Spaces:
Sleeping

File size: 9,716 Bytes
864ea97
 
 
41e47e8
864ea97
 
23e8911
eb2daf6
864ea97
 
 
 
 
41e47e8
 
 
 
 
eb2daf6
864ea97
 
 
3c8062c
41e47e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23e8911
864ea97
 
 
41e47e8
 
 
 
 
 
 
 
 
 
 
864ea97
 
 
 
41e47e8
864ea97
41e47e8
864ea97
23e8911
41e47e8
 
 
 
 
 
 
 
864ea97
 
 
 
41e47e8
864ea97
41e47e8
 
 
 
 
864ea97
3c8062c
 
 
864ea97
 
3c8062c
41e47e8
23e8911
3c8062c
41e47e8
 
 
 
 
 
 
 
864ea97
 
3c8062c
864ea97
 
 
23e8911
 
 
 
 
864ea97
41e47e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
864ea97
23e8911
41e47e8
864ea97
 
 
 
23e8911
41e47e8
3c8062c
 
 
 
864ea97
23e8911
41e47e8
 
 
864ea97
41e47e8
864ea97
 
41e47e8
 
 
 
 
 
 
 
 
 
 
 
864ea97
 
 
 
 
 
 
 
41e47e8
864ea97
41e47e8
 
 
 
864ea97
41e47e8
 
 
 
 
864ea97
 
 
 
 
41e47e8
 
 
 
 
 
 
 
 
 
 
864ea97
 
 
41e47e8
 
 
 
 
 
864ea97
 
 
 
41e47e8
864ea97
41e47e8
 
 
 
864ea97
 
 
 
 
 
41e47e8
864ea97
 
 
 
 
 
41e47e8
864ea97
41e47e8
864ea97
 
 
41e47e8
 
 
 
864ea97
 
 
 
 
 
 
 
 
 
41e47e8
864ea97
 
 
 
eb2daf6
864ea97
 
41e47e8
864ea97
 
 
 
41e47e8
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
#!/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
# ============================================================

@app.get("/")
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"
        }
    }

@app.get("/health")
async def health():
    return {"status": "healthy" if MODEL_LOADED else "unhealthy"}

@app.get("/status")
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)
    }

@app.post("/v1/audio/speech")
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))

@app.post("/upload_ref")
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)

@app.post("/set_default_voice")
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
    })