import logging from fastapi import APIRouter, File, Form, UploadFile, HTTPException from app.stt.sarvam_client import transcribe_audio, MAX_AUDIO_SIZE_BYTES from app.schemas.stt import TranscribeResponse router = APIRouter(prefix="/api/stt", tags=["stt"]) logger = logging.getLogger(__name__) @router.post("/transcribe", response_model=TranscribeResponse) async def transcribe( audio: UploadFile = File(..., description="Audio file (WebM/Opus, WAV, or MP3)"), language: str = Form(default="gu-In", description="Language hint: gu-In, hi-In, en-In"), ): """Receive audio from browser, transcribe via Sarvam AI Saaras v3.""" audio_bytes = await audio.read() if not audio_bytes: raise HTTPException(status_code=400, detail="No audio data received.") if len(audio_bytes) > MAX_AUDIO_SIZE_BYTES: raise HTTPException( status_code=413, detail=f"Audio file too large (max {MAX_AUDIO_SIZE_BYTES // 1024 // 1024} MB).", ) try: result = await transcribe_audio(audio_bytes=audio_bytes, language=language) except Exception as e: logger.error("STT transcription error: %s", e) raise HTTPException(status_code=502, detail=f"Sarvam AI API error: {str(e)}") if not result.get("transcript"): raise HTTPException(status_code=422, detail="Could not transcribe audio. Please try again.") return TranscribeResponse( transcript=result["transcript"], language_detected=result.get("language_detected"), )