|
|
from fastapi import APIRouter, HTTPException |
|
|
from fastapi.responses import FileResponse |
|
|
from models.tts import TTSRequest |
|
|
from services.tts_service import text_to_speech |
|
|
from pathlib import Path |
|
|
|
|
|
router = APIRouter(prefix="/tts", tags=["Text To Speech"]) |
|
|
|
|
|
@router.post("/") |
|
|
async def generate_tts(request: TTSRequest): |
|
|
""" |
|
|
Convert text to speech (English only) |
|
|
""" |
|
|
try: |
|
|
|
|
|
audio_path = text_to_speech( |
|
|
text=request.text, |
|
|
voice=request.voice, |
|
|
fmt=request.format |
|
|
) |
|
|
|
|
|
|
|
|
if not Path(audio_path).exists(): |
|
|
raise HTTPException(status_code=500, detail="Audio file generation failed") |
|
|
|
|
|
|
|
|
media_type = "audio/wav" if request.format == "wav" else "audio/mpeg" |
|
|
|
|
|
|
|
|
return FileResponse( |
|
|
path=audio_path, |
|
|
filename=f"speech.{request.format}", |
|
|
media_type=media_type, |
|
|
headers={ |
|
|
"Content-Disposition": f"attachment; filename=speech.{request.format}" |
|
|
} |
|
|
) |
|
|
|
|
|
except Exception as e: |
|
|
raise HTTPException(status_code=500, detail=str(e)) |