malek-messaoudii
Refactor audio models and services for improved error handling and response streaming
9aa985d
raw
history blame
1.01 kB
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
# ======================
@router.post("/tts")
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
# ======================
@router.post("/stt")
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}