Hexa06 commited on
Commit
837f7c4
·
0 Parent(s):

Initial TTS service with Coqui XTTS-v2 and API key auth

Browse files
Files changed (2) hide show
  1. app.py +99 -0
  2. requirements.txt +7 -0
app.py ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, HTTPException, Header, File, UploadFile, Form
2
+ from fastapi.responses import FileResponse, JSONResponse
3
+ import gradio as gr
4
+ from TTS.api import TTS
5
+ import tempfile
6
+ import os
7
+ import secrets
8
+
9
+ # Your API key (set this as environment variable in HF Space settings)
10
+ API_KEY = os.getenv("API_KEY", "hexg-xbbss-demo-key") # Default for testing
11
+
12
+ print("🎤 Loading TTS model...")
13
+ # Use XTTS-v2 - high quality, works on CPU
14
+ tts = TTS("tts_models/multilingual/multi-dataset/xtts_v2")
15
+ print("✅ TTS model loaded!")
16
+
17
+ # FastAPI app
18
+ app = FastAPI(title="Studify TTS API")
19
+
20
+ def verify_api_key(x_api_key: str = Header(None)):
21
+ """Verify API key from header"""
22
+ if x_api_key != API_KEY:
23
+ raise HTTPException(status_code=401, detail="Invalid API key")
24
+ return True
25
+
26
+ @app.get("/")
27
+ def health():
28
+ return {"status": "healthy", "model": "xtts_v2"}
29
+
30
+ @app.post("/generate")
31
+ async def generate_tts(
32
+ text: str = Form(...),
33
+ language: str = Form("en"),
34
+ x_api_key: str = Header(None)
35
+ ):
36
+ """Generate TTS with API key authentication"""
37
+ verify_api_key(x_api_key)
38
+
39
+ try:
40
+ # Generate TTS
41
+ with tempfile.NamedTemporaryFile(suffix=".mp3", delete=False) as tmp:
42
+ tts.tts_to_file(
43
+ text=text,
44
+ language=language,
45
+ file_path=tmp.name
46
+ )
47
+ temp_path = tmp.name
48
+
49
+ return FileResponse(
50
+ temp_path,
51
+ media_type="audio/mpeg",
52
+ filename="tts.mp3",
53
+ background=lambda: os.unlink(temp_path) if os.path.exists(temp_path) else None
54
+ )
55
+ except Exception as e:
56
+ raise HTTPException(status_code=500, detail=str(e))
57
+
58
+ # Gradio UI (for testing without API key)
59
+ def generate_tts_gradio(text, language="en"):
60
+ """Gradio wrapper for web UI"""
61
+ try:
62
+ with tempfile.NamedTemporaryFile(suffix=".mp3", delete=False) as tmp:
63
+ tts.tts_to_file(text=text, language=language, file_path=tmp.name)
64
+ return tmp.name
65
+ except Exception as e:
66
+ return f"Error: {str(e)}"
67
+
68
+ gradio_app = gr.Interface(
69
+ fn=generate_tts_gradio,
70
+ inputs=[
71
+ gr.Textbox(label="Text", placeholder="Enter text to convert to speech"),
72
+ gr.Dropdown(["en", "es", "fr", "de", "it", "pt", "pl", "tr", "ru", "nl", "cs", "ar", "zh-cn", "ja", "hu", "ko"],
73
+ value="en", label="Language")
74
+ ],
75
+ outputs=gr.Audio(label="Generated Speech"),
76
+ title="🎤 Studify TTS Service",
77
+ description="High-quality Text-to-Speech powered by Coqui XTTS-v2. For API access, use the `/generate` endpoint with your API key.",
78
+ article="""
79
+ ### 📡 API Usage
80
+
81
+ ```bash
82
+ curl -X POST https://your-space.hf.space/generate \\
83
+ -H "X-API-Key: your-api-key" \\
84
+ -F "text=Hello world" \\
85
+ -F "language=en" \\
86
+ --output speech.mp3
87
+ ```
88
+
89
+ ### 🔑 API Key
90
+ Set your API key in Space settings as `API_KEY` environment variable.
91
+ """
92
+ )
93
+
94
+ # Mount Gradio to FastAPI
95
+ app = gr.mount_gradio_app(app, gradio_app, path="/")
96
+
97
+ if __name__ == "__main__":
98
+ import uvicorn
99
+ uvicorn.run(app, host="0.0.0.0", port=7860)
requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ TTS>=0.22.0
2
+ fastapi
3
+ uvicorn[standard]
4
+ python-multipart
5
+ numpy
6
+ scipy
7
+ pydub