LangGraph_GAIA / tools /audio_transcribe.py
BiGuan's picture
Update tools/audio_transcribe.py
488705f verified
Raw
History Blame Contribute Delete
1.44 kB
import os
import requests
import tempfile
def audio_transcribe(audio_url: str) -> str:
"""
Transcribe an audio file from a URL to text using HuggingFace Whisper API.
Uses HF_TOKEN for authentication when downloading the file.
"""
try:
headers = {"Authorization": f"Bearer {os.getenv('HF_TOKEN')}"}
response = requests.get(audio_url, headers=headers, timeout=15)
response.raise_for_status()
with tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") as tmp:
tmp.write(response.content)
tmp_path = tmp.name
api_url = "https://api-inference.huggingface.co/models/openai/whisper-base"
api_headers = {"Authorization": f"Bearer {os.getenv('HF_TOKEN')}"}
with open(tmp_path, "rb") as f:
api_response = requests.post(api_url, headers=api_headers, data=f, timeout=30)
os.unlink(tmp_path)
if api_response.status_code == 200:
result = api_response.json()
transcript = result.get("text", "").strip()
return transcript if transcript else "No speech detected."
else:
return f"Transcription API error (HTTP {api_response.status_code}): {api_response.text}"
except requests.exceptions.RequestException as e:
return f"Failed to download audio file: {str(e)}"
except Exception as e:
return f"Transcription failed: {str(e)}"