malek-messaoudii
Refactor audio models and services for improved error handling and response streaming
9aa985d
| from fastapi import APIRouter, UploadFile, File, HTTPException | |
| from services.tts_service import generate_tts | |
| from services.stt_service import speech_to_text | |
| from fastapi.responses import StreamingResponse | |
| import io | |
| router = APIRouter(prefix="/audio", tags=["Audio"]) | |
| # ====================== | |
| # TEXT TO SPEECH | |
| # ====================== | |
| async def tts(text: str): | |
| try: | |
| audio_bytes = await generate_tts(text) | |
| except Exception as e: | |
| raise HTTPException(status_code=500, detail=str(e)) | |
| # Return as streaming response without saving file | |
| return StreamingResponse(io.BytesIO(audio_bytes), media_type="audio/wav") | |
| # ====================== | |
| # SPEECH TO TEXT | |
| # ====================== | |
| async def stt(file: UploadFile = File(...)): | |
| try: | |
| audio_bytes = await file.read() | |
| text = await speech_to_text(audio_bytes) | |
| except Exception as e: | |
| raise HTTPException(status_code=500, detail=str(e)) | |
| return {"text": text} | |