text_to_speech / app.py
sathish2352's picture
Update app.py
8b525a1 verified
raw
history blame contribute delete
734 Bytes
from fastapi import FastAPI, Request
from fastapi.responses import FileResponse
from gtts import gTTS
import os
import uuid
app = FastAPI()
UPLOAD_DIR = "/tmp/audio"
os.makedirs(UPLOAD_DIR, exist_ok=True)
@app.post("/echo")
async def echo(request: Request):
data = await request.json()
text = data.get("text", "")
if not text:
return {"error": "No 'text' provided in request."}
# Generate unique filename
filename = f"{uuid.uuid4().hex}.mp3"
filepath = os.path.join(UPLOAD_DIR, filename)
# Generate and save speech
tts = gTTS(text, lang='en')
tts.save(filepath)
# Return the audio file as response
return FileResponse(filepath, media_type="audio/mpeg", filename=filename)