Spaces:
Runtime error
Runtime error
Create app/main.py
Browse files- app/main.py +36 -0
app/main.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI, Request, HTTPException
|
| 2 |
+
from fastapi.responses import StreamingResponse
|
| 3 |
+
from gradio_client import Client
|
| 4 |
+
import httpx
|
| 5 |
+
|
| 6 |
+
app = FastAPI()
|
| 7 |
+
tts = Client("mrfakename/MeloTTS") # one-time init, O(1)
|
| 8 |
+
|
| 9 |
+
async def synth_stream(text: str):
|
| 10 |
+
# 1) simple stubbed chatbot logic, O(1)
|
| 11 |
+
reply = "Hello! You said: " + text
|
| 12 |
+
|
| 13 |
+
# 2) request TTS (blocking inside predict, but typically <100 ms)
|
| 14 |
+
audio_path = tts.predict(
|
| 15 |
+
text=reply,
|
| 16 |
+
speaker="EN_INDIA",
|
| 17 |
+
speed=0.95,
|
| 18 |
+
language="EN",
|
| 19 |
+
api_name="/synthesize"
|
| 20 |
+
)
|
| 21 |
+
url = f"https://mrfakename-melotts.hf.space/file={audio_path}"
|
| 22 |
+
|
| 23 |
+
# 3) async stream from upstream, O(L) for L bytes
|
| 24 |
+
async with httpx.AsyncClient(timeout=None) as client:
|
| 25 |
+
async with client.stream("GET", url) as resp:
|
| 26 |
+
resp.raise_for_status()
|
| 27 |
+
async for chunk in resp.aiter_bytes(1024):
|
| 28 |
+
yield chunk
|
| 29 |
+
|
| 30 |
+
@app.post("/chat")
|
| 31 |
+
async def chat(request: Request):
|
| 32 |
+
data = await request.json()
|
| 33 |
+
text = data.get("text", "").strip()
|
| 34 |
+
if not text:
|
| 35 |
+
raise HTTPException(400, "`text` required")
|
| 36 |
+
return StreamingResponse(synth_stream(text), media_type="audio/mpeg")
|