Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI, Response
|
| 2 |
+
from fastapi.responses import StreamingResponse
|
| 3 |
+
from piper import PiperVoice
|
| 4 |
+
import io
|
| 5 |
+
import os
|
| 6 |
+
|
| 7 |
+
app = FastAPI()
|
| 8 |
+
|
| 9 |
+
# Path where models will be stored in the container
|
| 10 |
+
MODEL_DIR = "./models"
|
| 11 |
+
os.makedirs(MODEL_DIR, exist_ok=True)
|
| 12 |
+
|
| 13 |
+
# Cache for loaded models to avoid re-loading from disk every request
|
| 14 |
+
loaded_voices = {}
|
| 15 |
+
|
| 16 |
+
def get_voice(model_name: str):
|
| 17 |
+
if model_name not in loaded_voices:
|
| 18 |
+
# Assumes model files (onnx and json) are in MODEL_DIR
|
| 19 |
+
model_path = os.path.join(MODEL_DIR, f"{model_name}.onnx")
|
| 20 |
+
config_path = f"{model_path}.json"
|
| 21 |
+
|
| 22 |
+
if not os.path.exists(model_path):
|
| 23 |
+
raise FileNotFoundError(f"Model {model_name} not found.")
|
| 24 |
+
|
| 25 |
+
loaded_voices[model_name] = PiperVoice.load(model_path, config_path)
|
| 26 |
+
return loaded_voices[model_name]
|
| 27 |
+
|
| 28 |
+
@app.get("/tts")
|
| 29 |
+
async def tts(text: str, model: str = "en_US-lessac-medium"):
|
| 30 |
+
try:
|
| 31 |
+
voice = get_voice(model)
|
| 32 |
+
|
| 33 |
+
# Create an in-memory buffer for the WAV file
|
| 34 |
+
wav_buffer = io.BytesIO()
|
| 35 |
+
with io.BytesIO() as f:
|
| 36 |
+
voice.synthesize(text, f)
|
| 37 |
+
audio_data = f.getvalue()
|
| 38 |
+
|
| 39 |
+
return Response(content=audio_data, media_type="audio/wav")
|
| 40 |
+
except Exception as e:
|
| 41 |
+
return {"error": str(e)}
|
| 42 |
+
|
| 43 |
+
@app.get("/health")
|
| 44 |
+
def home():
|
| 45 |
+
return {"status": "Piper TTS is running"}
|
| 46 |
+
|
| 47 |
+
@app.get("/")
|
| 48 |
+
def home():
|
| 49 |
+
return {"status": "Piper TTS is running"}
|