anuj-exe/coqui-test-api
0
1import os2import time3import shutil4from fastapi import FastAPI, UploadFile, File, Form5from fastapi.responses import FileResponse, JSONResponse6from TTS.api import TTS7 8os.environ["COQUI_TOS_AGREED"] = "1"9 10app = FastAPI()11 12tts = TTS("tts_models/multilingual/multi-dataset/xtts_v2", gpu=False)13 14DEFAULT_SPEAKER = "speakers/speaker_reference.wav"15 16SUPPORTED_LANGUAGES = [17 "en","es","fr","de","it","pt","pl","tr","ru","nl",18 "cs","ar","zh-cn","hu","ko","ja","hi"19]20 21 22@app.post("/generate")23async def generate_audio(24 text: str = Form(...),25 language: str = Form("en"),26 speaker: UploadFile = File(None)27):28 # ๐ด Validate input29 if not text.strip():30 return JSONResponse({"error": "Text is empty"}, status_code=400)31 32 if language not in SUPPORTED_LANGUAGES:33 return JSONResponse({34 "error": f"Unsupported language '{language}'",35 "supported_languages": SUPPORTED_LANGUAGES36 }, status_code=400)37 38 # ๐ค Handle speaker39 speaker_path = None40 speaker_used = "none"41 42 try:43 if speaker:44 speaker_path = f"/tmp/{speaker.filename}"45 with open(speaker_path, "wb") as buffer:46 shutil.copyfileobj(speaker.file, buffer)47 speaker_used = "uploaded"48 49 elif os.path.exists(DEFAULT_SPEAKER):50 speaker_path = DEFAULT_SPEAKER51 speaker_used = "default"52 53 # Unique output54 output_path = f"/tmp/output_{int(time.time())}.wav"55 56 start = time.time()57 58 # ๐ฅ Critical section (wrap this!)59 tts.tts_to_file(60 text=text,61 speaker_wav=speaker_path,62 language=language,63 file_path=output_path64 )65 66 duration = round(time.time() - start, 2)67 68 return {69 "meta": {70 "time_sec": duration,71 "language": language,72 "speaker": speaker_used73 },74 "audio_url": f"/audio?path={output_path}"75 }76 77 except AssertionError as e:78 return JSONResponse({79 "error": "TTS model assertion error",80 "details": str(e)81 }, status_code=400)82 83 except Exception as e:84 return JSONResponse({85 "error": "Internal server error",86 "details": str(e)87 }, status_code=500)88 89 90@app.get("/audio")91def get_audio(path: str):92 if not os.path.exists(path):93 return JSONResponse({"error": "File not found"}, status_code=404)94 95 return FileResponse(path, media_type="audio/wav", filename="output.wav")