| """Audio transcription using OpenAI Whisper API.""" | |
| import os | |
| from openai import OpenAI | |
| def get_openai_client() -> OpenAI: | |
| """Get OpenAI client with API key from environment.""" | |
| api_key = os.getenv("OPENAI_API_KEY") | |
| if not api_key: | |
| raise ValueError("OPENAI_API_KEY environment variable not set") | |
| return OpenAI(api_key=api_key) | |
| def transcribe_audio(audio_path: str) -> str: | |
| """ | |
| Transcribe audio file using OpenAI Whisper API. | |
| Args: | |
| audio_path: Path to audio file (mp3, wav, webm, etc.) | |
| Returns: | |
| Transcribed text | |
| """ | |
| client = get_openai_client() | |
| with open(audio_path, "rb") as audio_file: | |
| transcription = client.audio.transcriptions.create( | |
| model="whisper-1", | |
| file=audio_file, | |
| response_format="text" | |
| ) | |
| return transcription | |
| def transcribe_audio_chunk(audio_data: bytes, filename: str = "audio.webm") -> str: | |
| """ | |
| Transcribe audio data directly from bytes. | |
| Args: | |
| audio_data: Raw audio bytes | |
| filename: Filename hint for format detection | |
| Returns: | |
| Transcribed text | |
| """ | |
| client = get_openai_client() | |
| transcription = client.audio.transcriptions.create( | |
| model="whisper-1", | |
| file=(filename, audio_data), | |
| response_format="text" | |
| ) | |
| return transcription | |