# 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(""" 🎙️ Piper TTS API

🎙️ Piper TTS API

High-quality neural text-to-speech for digital companions

🚀 API Integration

Endpoint: POST /api/tts

Body: {"text": "Your text here"}

Response: WAV audio file

Python Example:

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 Example:

curl -X POST "https://eshwar06-piper-tts-server.hf.space/api/tts" \\
     -H "Content-Type: application/json" \\
     -d '{"text":"Hello world!"}' \\
     --output speech.wav
""") @app.post("/api/tts") async def generate_tts(request: dict): """ Generate TTS from text Body: {"text": "Your text here"} Returns: WAV audio file """ text = request.get("text", "") if not text or not text.strip(): raise HTTPException(status_code=400, detail="Text is required") if len(text) > 1000: raise HTTPException(status_code=400, detail="Text too long (max 1000 characters)") if not tts_engine: raise HTTPException(status_code=503, detail="TTS engine not available") try: audio_file = tts_engine.synthesize_to_file(text) return FileResponse( audio_file, media_type="audio/wav", filename="speech.wav", background=lambda: os.unlink(audio_file) if os.path.exists(audio_file) else None ) except Exception as e: logger.error(f"TTS failed: {e}") raise HTTPException(status_code=500, detail=str(e)) @app.get("/api/health") async def health_check(): """Health check endpoint""" return { "status": "healthy" if tts_engine else "tts_engine_unavailable", "service": "Piper TTS", "model_loaded": tts_engine is not None, "version": "1.0.0" } @app.get("/docs-redirect") async def docs_redirect(): """Redirect to API docs""" return {"message": "Visit /docs for interactive API documentation"} # Health check for Spaces @app.get("/health") async def health_alias(): """Alternative health endpoint""" return await health_check() if __name__ == "__main__": # Run the FastAPI app uvicorn.run( app, host="0.0.0.0", port=7860, # Spaces default port log_level="info" )