Certainly! Below is a comprehensive Python script that fulfills your requirements. This script provides an advanced command-line interface (CLI) for transcribing audio files or live recordings. It automatically detects the language of the audio and transcribes it both in the detected language and in English. The rich module is utilized for enhanced terminal presentation. The script adheres strictly to PEP-8 standards, includes type hints, and implements robust error handling to ensure maintainability and scalability.
Dependencies
Before running the script, ensure you have the necessary Python packages installed. You can install them using pip:
pip install openai-whisper rich sounddevice numpy
openai-whisper: For transcription and language detection.
rich: For enhanced terminal output.
sounddevice and numpy: For capturing live audio recordings.
Python Script
#!/usr/bin/env python3
"""
Advanced Command-Line Interface for Audio Transcription
This script allows users to transcribe audio files or live recordings using OpenAI's Whisper model.
It automatically detects the language of the audio and provides transcriptions in both the detected
language and English. The `rich` module is used for enhanced terminal presentation.
Usage:
python transcribe.py --file path/to/audio.mp3
python transcribe.py --live
"""
import argparse
import sys
from typing import Optional, Tuple
import numpy as np
import sounddevice as sd
import whisper
from rich.console import Console
from rich.panel import Panel
from rich.text import Text
# Initialize Rich console for enhanced output
console = Console()
def load_model(model_size: str = "base") -> whisper.Whisper:
"""
Load the Whisper model.
Args:
model_size (str): Size of the Whisper model to load.
Returns:
whisper.Whisper: The loaded Whisper model.
"""
try:
model = whisper.load_model(model_size)
return model
except Exception as e:
console.print(f"[red]Error loading Whisper model: {e}[/red]")
sys.exit(1)
def transcribe_audio(
model: whisper.Whisper, audio_path: Optional[str] = None, duration: int = 10
) -> Tuple[str, str]:
"""
Transcribe audio from a file or live recording.
Args:
model (whisper.Whisper): Loaded Whisper model.
audio_path (Optional[str]): Path to the audio file. If None, record live audio.
duration (int): Duration in seconds for live recording.
Returns:
Tuple[str, str]: Transcriptions in detected language and English.
"""
try:
if audio_path:
audio = whisper.load_audio(audio_path)
console.print(f"[green]Loaded audio file: {audio_path}[/green]")
else:
console.print(f"[blue]Recording live audio for {duration} seconds...[/blue]")
audio = record_audio(duration)
console.print("[green]Recording complete.[/green]")
audio = whisper.pad_or_trim(audio)
mel = whisper.log_mel_spectrogram(audio).to(model.device)
# Detect language
_, probs = model.detect_language(mel)
detected_lang = max(probs, key=probs.get)
console.print(f"[yellow]Detected language: {detected_lang}[/yellow]")
# Decode in detected language
options_detected = whisper.DecodingOptions(language=detected_lang)
result_detected = whisper.decode(model, mel, options_detected)
# Decode in English
options_english = whisper.DecodingOptions(language="en")
result_english = whisper.decode(model, mel, options_english)
return result_detected.text, result_english.text
except Exception as e:
console.print(f"[red]Error during transcription: {e}[/red]")
sys.exit(1)
def record_audio(duration: int = 10, samplerate: int = 16000) -> np.ndarray:
"""
Record audio from the microphone.
Args:
duration (int): Duration to record in seconds.
samplerate (int): Sampling rate.
Returns:
np.ndarray: Recorded audio as a NumPy array.
"""
try:
console.print("[blue]Initializing audio recording...[/blue]")
audio = sd.rec(int(duration * samplerate), samplerate=samplerate, channels=1, dtype="float32")
sd.wait() # Wait until recording is finished
return audio.flatten()
except Exception as e:
console.print(f"[red]Error recording audio: {e}[/red]")
sys.exit(1)
def display_transcriptions(
detected_text: str, english_text: str, detected_lang: str
) -> None:
"""
Display the transcriptions using Rich panels.
Args:
detected_text (str): Transcription in the detected language.
english_text (str): Transcription in English.
detected_lang (str): Detected language code.
"""
try:
panel_detected = Panel(
Text(detected_text, style="cyan"),
title=f"Transcription [{detected_lang}]",
subtitle="Detected Language",
expand=False,
)
panel_english = Panel(
Text(english_text, style="magenta"),
title="Transcription [en]",
subtitle="English",
expand=False,
)
console.print(panel_detected)
console.print(panel_english)
except Exception as e:
console.print(f"[red]Error displaying transcriptions: {e}[/red]")
sys.exit(1)
def parse_arguments() -> argparse.Namespace:
"""
Parse command-line arguments.
Returns:
argparse.Namespace: Parsed arguments.
"""
parser = argparse.ArgumentParser(
description="Advanced Audio Transcription CLI using Whisper."
)
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument(
"--file",
type=str,
help="Path to the audio file for transcription.",
)
group.add_argument(
"--live",
action="store_true",
help="Record live audio for transcription.",
)
parser.add_argument(
"--duration",
type=int,
default=10,
help="Duration in seconds for live recording (default: 10).",
)
parser.add_argument(
"--model",
type=str,
default="base",
choices=["tiny", "base", "small", "medium", "large"],
help="Size of the Whisper model to use (default: base).",
)
return parser.parse_args()
def main() -> None:
"""
Main function to execute the transcription CLI.
"""
args = parse_arguments()
model = load_model(args.model)
if args.file:
detected_text, english_text = transcribe_audio(model, audio_path=args.file)
else:
detected_text, english_text = transcribe_audio(model, duration=args.duration)
# Detect language code for display purposes
_, probs = model.detect_language(whisper.log_mel_spectrogram(
whisper.pad_or_trim(
whisper.load_audio(args.file) if args.file else record_audio(args.duration)
)
).to(model.device))
detected_lang = max(probs, key=probs.get)
display_transcriptions(detected_text, english_text, detected_lang)
if __name__ == "__main__":
main()
Explanation of the Script
-
Imports and Initialization
- Standard Libraries:
argparse for CLI argument parsing, sys for exiting the program gracefully, and typing for type hints.
- Third-Party Libraries:
whisper for transcription and language detection.
rich for enhanced terminal output.
sounddevice and numpy for capturing and handling live audio recordings.
- Rich Console: Initialized for colored and formatted terminal output.
-
Function Definitions
load_model: Loads the specified Whisper model and handles errors related to model loading.
transcribe_audio: Handles both file-based and live audio transcription. It processes the audio, detects the language, and performs transcriptions in both the detected language and English.
record_audio: Captures live audio from the microphone for a specified duration. It ensures that the microphone is accessible and handles any recording errors.
display_transcriptions: Utilizes the rich module to display the transcriptions in organized panels with appropriate colors and titles.
parse_arguments: Uses argparse to define and parse CLI arguments, ensuring that users provide either a file path or opt for live recording.
main: The entry point of the script that orchestrates loading the model, transcribing the audio, and displaying the results.
-
Error Handling
- Each function includes try-except blocks to catch and report errors gracefully using
rich console messages. The script exits gracefully if any critical error occurs.
-
Type Hints and PEP-8 Compliance
- All functions include type hints for better code clarity and maintainability.
- The script adheres to PEP-8 standards regarding naming conventions, indentation, and line lengths.
-
Usage Instructions
Additional Notes
-
Model Selection: Whisper offers various model sizes (tiny, base, small, medium, large). Larger models are more accurate but require more computational resources. You can specify the model size using the --model argument.
python transcribe.py --file audio.mp3 --model large
-
Supported Audio Formats: Whisper supports multiple audio formats such as WAV, MP3, M4A, etc. Ensure that the audio file provided is in a supported format.
-
Live Recording Requirements: Ensure that your system has a functioning microphone. The sounddevice library is cross-platform but may require additional setup on some operating systems.
-
Performance Considerations: Processing large audio files or using larger models may increase transcription time and resource usage. Ensure that your system meets the necessary requirements for the selected model size.
-
Extensibility: The script is designed to be easily extensible. You can integrate additional features such as saving transcriptions to a file, supporting more languages, or enhancing the CLI interface further.
Conclusion
This script provides a robust, efficient, and user-friendly CLI tool for transcribing audio using OpenAI's Whisper model. By adhering to best practices and leveraging powerful Python libraries, it ensures maintainability, scalability, and excellent performance.