---
description: Audio processing rules for src/services/**/*
alwaysApply: false
---
# Audio Processing Rule

## Core Principles
- **Download-First Architecture**: Download before processing
- **Standardized Format**: Convert to 16kHz mono WAV
- **M3 Optimization**: Use distil-large-v3 model
- **Complete File Processing**: No streaming to avoid interruptions

## Implementation Patterns

### Download-First Architecture
```python
# ✅ DO: Download media before processing
async def process_media(url: str) -> ProcessingResult:
    # First download the file
    local_path = await download_media(url)
    
    # Then process the downloaded file
    return await process_local_file(local_path)
```

### Audio Conversion
```python
# ✅ DO: Convert to standard format
def prepare_audio(input_path: Path) -> Path:
    """Convert audio to 16kHz mono WAV."""
    output_path = input_path.with_suffix('.wav')
    
    # Use ffmpeg to convert
    subprocess.run([
        "ffmpeg", "-i", str(input_path),
        "-ar", "16000",  # 16kHz sample rate
        "-ac", "1",      # Mono channel
        "-c:a", "pcm_s16le",  # 16-bit PCM
        str(output_path)
    ])
    
    return output_path
```

### Model Selection
```python
# ✅ DO: Use optimized models for M3
def load_transcription_model():
    """Load the optimal model for M3 MacBooks."""
    return whisper.load_model("distil-large-v3")
```

### Anti-Patterns
```python
# ❌ DON'T: Stream and process simultaneously
async def stream_and_process(url: str):
    # This can lead to interruptions and failures
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
            # Processing while streaming - WRONG!
            chunk = await response.content.read(1024)
            while chunk:
                process_chunk(chunk)  # Risky!
                chunk = await response.content.read(1024)
```

When working with audio files, ALWAYS follow the download-first architecture: download media to local storage before processing, never stream. Convert to 16kHz mono WAV format for processing. Use distil-large-v3 model for M3 optimization. Process complete files only - no streaming to avoid network interruption failures.