Spaces:
Sleeping
Sleeping
Download server.py from michdubai/mossttsnano: direct link, hf CLI and curl.
- Browser
- Download file 9.72 kB
-
https://huggingface.co/spaces/michdubai/mossttsnano/resolve/main/server.py
- Command line
-
hf download hf://spaces/michdubai/mossttsnano/server.py
-
curl -L -o server.py https://huggingface.co/spaces/michdubai/mossttsnano/resolve/main/server.py
9.72 kB
| #!/usr/bin/env python3 | |
| """ | |
| MossTTS-Nano OpenAI-Compatible API Server | |
| With improved error handling and debugging | |
| """ | |
| import ctypes | |
| import os | |
| import tempfile | |
| from fastapi import FastAPI, Response, HTTPException, UploadFile, File, Form | |
| from fastapi.responses import JSONResponse | |
| from pydantic import BaseModel | |
| from typing import Optional | |
| import logging | |
| # Set up logging | |
| logging.basicConfig(level=logging.INFO) | |
| logger = logging.getLogger(__name__) | |
| # ============================================================ | |
| # Load the compiled C library | |
| # ============================================================ | |
| LIB_PATH = "./libnanotts.so" | |
| C_LIB_LOADED = False | |
| if os.path.exists(LIB_PATH): | |
| try: | |
| lib = ctypes.CDLL(LIB_PATH) | |
| C_LIB_LOADED = True | |
| logger.info("C library loaded successfully") | |
| except Exception as e: | |
| logger.error(f"Failed to load C library: {e}") | |
| lib = None | |
| else: | |
| logger.error(f"C library not found at {LIB_PATH}") | |
| lib = None | |
| if C_LIB_LOADED: | |
| try: | |
| lib.load_model.restype = ctypes.c_int | |
| lib.free_model.restype = None | |
| lib.generate_wav_from_ref.argtypes = [ | |
| ctypes.c_char_p, | |
| ctypes.c_char_p, | |
| ctypes.POINTER(ctypes.POINTER(ctypes.c_float)), | |
| ctypes.POINTER(ctypes.c_int), | |
| ctypes.POINTER(ctypes.c_int), | |
| ctypes.POINTER(ctypes.c_int), | |
| ctypes.c_int, | |
| ] | |
| lib.generate_wav_from_ref.restype = ctypes.c_int | |
| lib.save_wav.argtypes = [ | |
| ctypes.c_char_p, | |
| ctypes.POINTER(ctypes.c_float), | |
| ctypes.c_int, | |
| ctypes.c_int, | |
| ctypes.c_int | |
| ] | |
| lib.save_wav.restype = ctypes.c_int | |
| logger.info("C library configured successfully") | |
| except Exception as e: | |
| logger.error(f"Failed to configure C library: {e}") | |
| C_LIB_LOADED = False | |
| lib = None | |
| # ============================================================ | |
| # Initialize the model | |
| # ============================================================ | |
| MODEL_LOADED = False | |
| if C_LIB_LOADED: | |
| try: | |
| init_status = lib.load_model() | |
| if init_status == 0: | |
| MODEL_LOADED = True | |
| logger.info("Model loaded successfully") | |
| else: | |
| logger.error(f"Failed to load model. Error code: {init_status}") | |
| except Exception as e: | |
| logger.error(f"Exception during model loading: {e}") | |
| # ============================================================ | |
| # FastAPI App | |
| # ============================================================ | |
| app = FastAPI(title="MossTTS-Nano API") | |
| # Default reference voice path | |
| DEFAULT_REF_PATH = "default_ref.wav" | |
| # Try to import pydub, provide fallback if not available | |
| try: | |
| from pydub import AudioSegment | |
| PYDUB_AVAILABLE = True | |
| except ImportError: | |
| PYDUB_AVAILABLE = False | |
| logger.warning("pydub not available, WAV output only") | |
| class TTSRequest(BaseModel): | |
| input: str | |
| model: str = "tts-1" | |
| voice: str = "default" | |
| response_format: str = "wav" # Default to WAV to avoid conversion issues | |
| def preprocess_audio(input_path: str): | |
| """Convert audio to format expected by C engine""" | |
| if not PYDUB_AVAILABLE: | |
| return input_path # Skip processing if pydub not available | |
| output_path = tempfile.mktemp(suffix=".wav") | |
| try: | |
| audio = AudioSegment.from_file(input_path) | |
| audio = audio.set_frame_rate(48000).set_channels(1).set_sample_width(2) | |
| audio.export(output_path, format="wav") | |
| return output_path | |
| except Exception as e: | |
| logger.error(f"Audio preprocessing error: {e}") | |
| return None | |
| def synthesize_with_clone(text: str, ref_audio_path: str, output_format: str = "wav") -> bytes: | |
| """Synthesize speech using voice cloning""" | |
| if not MODEL_LOADED or not C_LIB_LOADED: | |
| raise Exception(f"Model not loaded (C_LIB: {C_LIB_LOADED}, MODEL: {MODEL_LOADED})") | |
| if not os.path.exists(ref_audio_path): | |
| raise Exception(f"Reference audio not found: {ref_audio_path}") | |
| # Preprocess reference audio | |
| clean_ref = preprocess_audio(ref_audio_path) | |
| if not clean_ref: | |
| raise Exception("Failed to process reference audio file") | |
| # Prepare pointers for C output | |
| wav_ptr = ctypes.POINTER(ctypes.c_float)() | |
| samples = ctypes.c_int() | |
| channels = ctypes.c_int() | |
| sr = ctypes.c_int() | |
| # Call the C engine | |
| try: | |
| result = lib.generate_wav_from_ref( | |
| clean_ref.encode('utf-8'), | |
| text.encode('utf-8'), | |
| ctypes.byref(wav_ptr), | |
| ctypes.byref(samples), | |
| ctypes.byref(channels), | |
| ctypes.byref(sr), | |
| 1 | |
| ) | |
| except Exception as e: | |
| raise Exception(f"C library call failed: {e}") | |
| # Clean up temporary file | |
| if os.path.exists(clean_ref): | |
| os.unlink(clean_ref) | |
| if result != 0: | |
| raise Exception(f"C Engine error code: {result}") | |
| # Save to temporary WAV file | |
| tmp_wav = tempfile.mktemp(suffix=".wav") | |
| lib.save_wav(tmp_wav.encode('utf-8'), wav_ptr, samples, channels, sr) | |
| # Free memory | |
| try: | |
| libc = ctypes.CDLL("libc.so.6") | |
| libc.free(wav_ptr) | |
| except: | |
| pass | |
| # Read audio bytes | |
| with open(tmp_wav, "rb") as f: | |
| audio_bytes = f.read() | |
| # Clean up | |
| os.unlink(tmp_wav) | |
| # Convert to MP3 if requested and pydub is available | |
| if output_format == "mp3" and PYDUB_AVAILABLE: | |
| try: | |
| audio = AudioSegment.from_wav(tmp_wav) | |
| from io import BytesIO | |
| mp3_io = BytesIO() | |
| audio.export(mp3_io, format="mp3") | |
| audio_bytes = mp3_io.getvalue() | |
| except Exception as e: | |
| logger.warning(f"MP3 conversion failed, returning WAV: {e}") | |
| return audio_bytes | |
| # ============================================================ | |
| # API Endpoints | |
| # ============================================================ | |
| async def root(): | |
| return { | |
| "status": "ok" if MODEL_LOADED else "degraded", | |
| "service": "MossTTS-Nano", | |
| "c_library_loaded": C_LIB_LOADED, | |
| "model_loaded": MODEL_LOADED, | |
| "pydub_available": PYDUB_AVAILABLE, | |
| "default_ref_exists": os.path.exists(DEFAULT_REF_PATH), | |
| "endpoints": { | |
| "POST /v1/audio/speech": "OpenAI-compatible TTS", | |
| "POST /upload_ref": "Upload reference voice", | |
| "POST /set_default_voice": "Set default voice", | |
| "GET /health": "Health check", | |
| "GET /status": "Detailed status" | |
| } | |
| } | |
| async def health(): | |
| return {"status": "healthy" if MODEL_LOADED else "unhealthy"} | |
| async def status(): | |
| return { | |
| "c_library_loaded": C_LIB_LOADED, | |
| "model_loaded": MODEL_LOADED, | |
| "pydub_available": PYDUB_AVAILABLE, | |
| "default_ref_exists": os.path.exists(DEFAULT_REF_PATH), | |
| "lib_path_exists": os.path.exists(LIB_PATH) | |
| } | |
| async def tts_openai(request: TTSRequest): | |
| """OpenAI-compatible TTS endpoint""" | |
| logger.info(f"TTS request received: text length={len(request.input)}") | |
| if not MODEL_LOADED: | |
| raise HTTPException(status_code=503, detail=f"Model not loaded (status: C_LIB={C_LIB_LOADED}, MODEL={MODEL_LOADED})") | |
| text = request.input.strip() | |
| if not text: | |
| raise HTTPException(status_code=400, detail="Text input is required") | |
| # Check for default reference voice | |
| if not os.path.exists(DEFAULT_REF_PATH): | |
| raise HTTPException( | |
| status_code=400, | |
| detail=f"Default reference voice not found. Please upload one via POST /set_default_voice" | |
| ) | |
| try: | |
| audio_bytes = synthesize_with_clone(text, DEFAULT_REF_PATH, request.response_format) | |
| content_type = "audio/mpeg" if request.response_format == "mp3" else "audio/wav" | |
| return Response(content=audio_bytes, media_type=content_type) | |
| except Exception as e: | |
| logger.error(f"Synthesis error: {e}") | |
| raise HTTPException(status_code=500, detail=str(e)) | |
| async def upload_reference_audio( | |
| file: UploadFile = File(...), | |
| text: str = Form(...), | |
| response_format: str = Form("wav") | |
| ): | |
| """Upload reference voice and synthesize text""" | |
| if not text.strip(): | |
| raise HTTPException(status_code=400, detail="Text is required") | |
| if not MODEL_LOADED: | |
| raise HTTPException(status_code=503, detail="Model not loaded") | |
| # Save uploaded file | |
| with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as tmp_ref: | |
| content = await file.read() | |
| tmp_ref.write(content) | |
| tmp_ref_path = tmp_ref.name | |
| try: | |
| audio_bytes = synthesize_with_clone(text, tmp_ref_path, response_format) | |
| content_type = "audio/mpeg" if response_format == "mp3" else "audio/wav" | |
| return Response(content=audio_bytes, media_type=content_type) | |
| except Exception as e: | |
| logger.error(f"Upload ref error: {e}") | |
| raise HTTPException(status_code=500, detail=str(e)) | |
| finally: | |
| if os.path.exists(tmp_ref_path): | |
| os.unlink(tmp_ref_path) | |
| async def set_default_voice(file: UploadFile = File(...)): | |
| """Upload a default reference voice""" | |
| content = await file.read() | |
| with open(DEFAULT_REF_PATH, "wb") as f: | |
| f.write(content) | |
| return JSONResponse({ | |
| "status": "ok", | |
| "message": f"Default voice saved. Size: {len(content)} bytes", | |
| "path": DEFAULT_REF_PATH | |
| }) |