ssasio commited on
Commit
5b28cbe
·
verified ·
1 Parent(s): eb4be33

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +80 -0
app.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import uuid
3
+ from pathlib import Path
4
+
5
+ from fastapi import FastAPI, HTTPException
6
+ from fastapi.responses import FileResponse, JSONResponse
7
+ from pydantic import BaseModel
8
+ import edge_tts
9
+
10
+ app = FastAPI(title="Edge TTS API")
11
+
12
+ TMP_DIR = Path("/tmp/edge_tts_api")
13
+ TMP_DIR.mkdir(parents=True, exist_ok=True)
14
+
15
+
16
+ class TTSRequest(BaseModel):
17
+ text: str
18
+ voice: str = "bg-BG-BorislavNeural"
19
+ rate: str = "+0%"
20
+ volume: str = "+0%"
21
+ pitch: str = "+0Hz"
22
+
23
+
24
+ @app.get("/")
25
+ async def root():
26
+ return {
27
+ "ok": True,
28
+ "service": "Edge TTS API",
29
+ "routes": {
30
+ "health": "/health",
31
+ "voices": "/voices",
32
+ "tts": "/tts"
33
+ }
34
+ }
35
+
36
+
37
+ @app.get("/health")
38
+ async def health():
39
+ return {"status": "ok"}
40
+
41
+
42
+ @app.get("/voices")
43
+ async def voices():
44
+ try:
45
+ voices_data = await edge_tts.list_voices()
46
+ voices_data = sorted(voices_data, key=lambda v: v.get("ShortName", ""))
47
+ return JSONResponse(content=voices_data)
48
+ except Exception as e:
49
+ raise HTTPException(status_code=500, detail=f"Failed to fetch voices: {str(e)}")
50
+
51
+
52
+ @app.post("/tts")
53
+ async def tts(req: TTSRequest):
54
+ text = req.text.strip()
55
+
56
+ if not text:
57
+ raise HTTPException(status_code=400, detail="Text is empty")
58
+
59
+ output_file = TMP_DIR / f"{uuid.uuid4().hex}.mp3"
60
+
61
+ try:
62
+ communicate = edge_tts.Communicate(
63
+ text=text,
64
+ voice=req.voice,
65
+ rate=req.rate,
66
+ volume=req.volume,
67
+ pitch=req.pitch
68
+ )
69
+ await communicate.save(str(output_file))
70
+
71
+ if not output_file.exists():
72
+ raise HTTPException(status_code=500, detail="Audio file was not created")
73
+
74
+ return FileResponse(
75
+ path=str(output_file),
76
+ media_type="audio/mpeg",
77
+ filename="speech.mp3"
78
+ )
79
+ except Exception as e:
80
+ raise HTTPException(status_code=500, detail=f"TTS generation failed: {str(e)}")