import os import uuid from pathlib import Path from typing import Optional from fastapi import FastAPI, File, UploadFile, HTTPException from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import FileResponse from pydantic import BaseModel from TTS.api import TTS import soundfile as sf import numpy as np # ---------- Paths ---------- BASE_DIR = Path(__file__).parent VOICES_DIR = BASE_DIR / "voices" OUTPUTS_DIR = BASE_DIR / "outputs" VOICES_DIR.mkdir(exist_ok=True) OUTPUTS_DIR.mkdir(exist_ok=True) # ---------- FastAPI app ---------- app = FastAPI(title="Meshcraft Voice Clone Backend") # Allow calls from any origin (your site will call this) app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) # ---------- TTS model ---------- # You can change this to another Coqui model if you prefer. TTS_MODEL_NAME = os.getenv( "TTS_MODEL_NAME", "tts_models/multilingual/multi-dataset/xtts_v2", ) _tts: Optional[TTS] = None def get_tts() -> TTS: global _tts if _tts is None: _tts = TTS(TTS_MODEL_NAME, gpu=False) return _tts # ---------- Schemas ---------- class GenerateRequest(BaseModel): voice_id: str text: str # ---------- Helpers ---------- def validate_audio_duration(path: Path, min_sec: int = 30, max_sec: int = 300): try: data, sr = sf.read(str(path)) except Exception: raise HTTPException( status_code=400, detail="Could not read audio file. Please upload a valid WAV/MP3 file.", ) if data.ndim > 1: data = np.mean(data, axis=1) duration_sec = len(data) / float(sr) if duration_sec < min_sec: raise HTTPException( status_code=400, detail=f"Audio is too short ({duration_sec:.1f}s). Use at least {min_sec} seconds of speech.", ) if duration_sec > max_sec: raise HTTPException( status_code=400, detail=f"Audio is too long ({duration_sec:.1f}s). Limit is {max_sec} seconds.", ) # ---------- Endpoints ---------- @app.post("/api/upload-voice") async def upload_voice(file: UploadFile = File(...)): if not file.filename: raise HTTPException(status_code=400, detail="No file uploaded.") ext = Path(file.filename).suffix.lower() if ext not in {".wav", ".mp3"}: raise HTTPException( status_code=400, detail="Unsupported file type. Please upload WAV or MP3.", ) voice_id = str(uuid.uuid4()) dest_path = VOICES_DIR / f"{voice_id}{ext}" with dest_path.open("wb") as f: f.write(await file.read()) # Validate basic duration constraints validate_audio_duration(dest_path) return {"voice_id": voice_id} @app.post("/api/generate") async def generate_audio(payload: GenerateRequest): text = payload.text.strip() if not text: raise HTTPException(status_code=400, detail="Text cannot be empty.") if len(text) > 500: raise HTTPException(status_code=400, detail="Text is limited to 500 characters.") # Find voice file candidates = list(VOICES_DIR.glob(f"{payload.voice_id}.*")) if not candidates: raise HTTPException(status_code=404, detail="Voice profile not found.") ref_audio_path = candidates[0] tts = get_tts() out_path = OUTPUTS_DIR / f"{uuid.uuid4()}.wav" # Generate conditioned on reference voice tts.tts_to_file( text=text, file_path=str(out_path), speaker_wav=str(ref_audio_path), language="en", ) # HF Spaces will serve static files from the app; return relative URL audio_url = f"/outputs/{out_path.name}" return {"audio_url": audio_url} @app.delete("/api/voices/{voice_id}") async def delete_voice(voice_id: str): deleted = False for p in VOICES_DIR.glob(f"{voice_id}.*"): try: p.unlink() deleted = True except Exception: pass # Also delete any generated outputs that start with this voice_id if you choose # (here we keep outputs independent, so just succeed even if nothing deleted). return {"deleted": deleted} @app.get("/") async def root(): return {"status": "ok", "message": "Meshcraft voice clone backend running."}