# Audio Transcription with Whisper

This guide demonstrates how to use OpenAI's **Whisper**, a robust open-source speech recognition model. It allows you to transcribe audio files into text locally on your machine, supporting multiple languages and accents.

**Modules Used:**
*   `openai-whisper`: The Python library for the Whisper model.
*   [[programming/python/modules/argparse-module|argparse]]: To handle command-line arguments.
*   `os`: For file path handling.

## Prerequisites

You must have **FFmpeg** installed on your system.
*   **Windows**: `winget install ffmpeg`
*   **macOS**: `brew install ffmpeg`
*   **Linux**: `sudo apt install ffmpeg`

## Installation

```bash
pip install openai-whisper
```

## The Code

Save this as `transcriber.py`.

```python
import whisper
import argparse
import os
import warnings

# Suppress FP16 warning on CPU-only machines
warnings.filterwarnings("ignore")

def transcribe(audio_path, model_size, output_file):
    if not os.path.exists(audio_path):
        print(f"Error: File '{audio_path}' not found.")
        return

    print(f"Loading Whisper model ('{model_size}')...")
    try:
        # Models: tiny, base, small, medium, large
        # The first run will download the model weights
        model = whisper.load_model(model_size)
    except Exception as e:
        print(f"Error loading model: {e}")
        return

    print(f"Transcribing '{audio_path}'... (This may take time)")
    try:
        # Transcribe
        result = model.transcribe(audio_path)
        text = result["text"]

        # Output
        if output_file:
            with open(output_file, "w", encoding="utf-8") as f:
                f.write(text.strip())
            print(f"Success! Saved to '{output_file}'")
        else:
            print("\n--- Transcription ---")
            print(text.strip())
            print("---------------------")

    except Exception as e:
        print(f"Error during transcription: {e}")

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Whisper Audio Transcriber")
    parser.add_argument("audio", help="Path to the audio file (mp3, wav, m4a, etc.)")
    parser.add_argument("--model", default="base", choices=["tiny", "base", "small", "medium", "large"], help="Model size (default: base)")
    parser.add_argument("-o", "--output", help="Output text filename")
    
    args = parser.parse_args()
    
    transcribe(args.audio, args.model, args.output)
```

## Usage

```bash
# Transcribe and print to console
python transcriber.py meeting.mp3

# Use a larger model and save to file
python transcriber.py interview.wav --model medium -o interview.txt
```

[[programming/python/python]]