# app.py - Simple FastAPI-only version for Hugging Face Spaces import os import logging import tempfile import subprocess from pathlib import Path import requests import uvicorn from fastapi import FastAPI, HTTPException, Request from fastapi.responses import FileResponse, HTMLResponse from fastapi.middleware.cors import CORSMiddleware # Configure logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) class PiperTTSSpaces: """Piper TTS for Hugging Face Spaces with FastAPI""" def __init__(self): self.model_path = self._setup_model() def _setup_model(self) -> str: """Download and setup Piper model for Spaces""" model_dir = Path("./models") model_dir.mkdir(exist_ok=True) model_file = model_dir / "en_US-lessac-medium.onnx" config_file = model_dir / "en_US-lessac-medium.onnx.json" # Download model if not exists if not model_file.exists(): logger.info("Downloading Piper model...") try: # Download model model_url = "https://huggingface.co/rhasspy/piper-voices/resolve/v1.0.0/en/en_US/lessac/medium/en_US-lessac-medium.onnx" response = requests.get(model_url, stream=True) response.raise_for_status() with open(model_file, 'wb') as f: for chunk in response.iter_content(chunk_size=8192): f.write(chunk) # Download config config_url = "https://huggingface.co/rhasspy/piper-voices/resolve/v1.0.0/en/en_US/lessac/medium/en_US-lessac-medium.onnx.json" response = requests.get(config_url) response.raise_for_status() with open(config_file, 'w') as f: f.write(response.text) logger.info("Model downloaded successfully") except Exception as e: logger.error(f"Failed to download model: {e}") raise return str(model_file) def synthesize_to_file(self, text: str) -> str: """Synthesize text to temporary WAV file""" try: # Create temporary file temp_file = tempfile.NamedTemporaryFile(suffix='.wav', delete=False) temp_file.close() # Prepare Piper command cmd = [ "python", "-m", "piper", "--model", self.model_path, "--output_file", temp_file.name ] logger.info(f"TTS request: '{text[:50]}...'") # Run Piper with text input process = subprocess.run( cmd, input=text.encode('utf-8'), capture_output=True, timeout=30 ) if process.returncode != 0: error_msg = process.stderr.decode() if process.stderr else "Unknown error" logger.error(f"Piper failed: {error_msg}") raise RuntimeError(f"TTS failed: {error_msg}") return temp_file.name except subprocess.TimeoutExpired: logger.error("TTS generation timed out") raise RuntimeError("TTS generation timed out") except Exception as e: logger.error(f"Synthesis failed: {e}") raise # Initialize TTS engine logger.info("Initializing TTS engine...") try: tts_engine = PiperTTSSpaces() logger.info("TTS engine initialized successfully") except Exception as e: logger.error(f"Failed to initialize TTS engine: {e}") tts_engine = None # Create FastAPI app app = FastAPI( title="Piper TTS API", description="High-quality neural TTS for digital companions", version="1.0.0" ) # Add CORS middleware app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) @app.get("/", response_class=HTMLResponse) async def root(): """Serve a simple HTML interface""" return HTMLResponse("""
High-quality neural text-to-speech for digital companions
Endpoint: POST /api/tts
Body: {"text": "Your text here"}
Response: WAV audio file
import requests
response = requests.post(
"https://eshwar06-piper-tts-server.hf.space/api/tts",
json={"text": "Hello from Python!"}
)
with open("speech.wav", "wb") as f:
f.write(response.content)
curl -X POST "https://eshwar06-piper-tts-server.hf.space/api/tts" \\
-H "Content-Type: application/json" \\
-d '{"text":"Hello world!"}' \\
--output speech.wav