Spaces:
Sleeping
Sleeping
File size: 8,391 Bytes
d6efaed 5339570 d6efaed 5339570 d6efaed 5339570 d6efaed 880d450 d3ef2bc d6efaed 5339570 880d450 d6efaed c5a37fa 5339570 a685929 c5a37fa d6efaed 5339570 a685929 c5a37fa d6efaed 5339570 a685929 c5a37fa d6efaed 5339570 d6efaed d3ef2bc d6efaed d3ef2bc d6efaed 5339570 c5a37fa 5339570 d6efaed 5339570 d6efaed 5339570 d6efaed 5339570 d6efaed 5339570 d6efaed 5339570 c5a37fa d6efaed 5339570 c5a37fa 5339570 c5a37fa 5339570 d6efaed 5805e03 d6efaed 5805e03 d6efaed 5339570 d6efaed | 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 | """
Chatterbox TTS API Server
Free, emotional text-to-speech service using Resemble AI's Chatterbox.
Supports voice cloning with custom audio references.
"""
import io
import os
import logging
from typing import Optional
from fastapi import FastAPI, HTTPException, UploadFile, File, Form
from fastapi.responses import StreamingResponse
from pydantic import BaseModel
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Global model reference (set by run.py at startup)
_model = None
app = FastAPI(
title="Chatterbox TTS API",
description="Free emotional TTS with voice cloning",
version="1.2.0"
)
# Built-in voices (multilingual) with voice-specific settings
BUILTIN_VOICES = {
"professional_male": {
"name": "Professional (Male)",
"description": "Confident business voice, works well in Russian/English",
"reference_path": "voices/professional_male.mp3",
"exaggeration": 0.4, # Calm, controlled
"cfg_weight": 0.5
},
"friendly_male": {
"name": "Friendly (Male)",
"description": "Warm, approachable voice for building rapport",
"reference_path": "voices/friendly_male.mp3",
"exaggeration": 0.7, # More expressive
"cfg_weight": 0.4
},
"professional_female": {
"name": "Professional (Female)",
"description": "Clear, trustworthy female voice",
"reference_path": "voices/professional_female.mp3",
"exaggeration": 0.5, # Balanced
"cfg_weight": 0.5
}
}
# Custom voices storage
CUSTOM_VOICES_DIR = "custom_voices"
os.makedirs(CUSTOM_VOICES_DIR, exist_ok=True)
def get_model():
"""Get loaded model."""
global _model
if _model is None:
raise HTTPException(status_code=503, detail="Model not loaded yet")
return _model
class TTSRequest(BaseModel):
"""TTS synthesis request."""
text: str
voice: str = "professional_male" # Built-in or custom voice ID
exaggeration: Optional[float] = None # Override emotion intensity (0.0 - 1.0)
cfg_weight: Optional[float] = None # Classifier-free guidance (0.0 - 1.0)
custom_voice_url: Optional[str] = None # URL to custom voice audio
class VoiceInfo(BaseModel):
"""Voice information."""
id: str
name: str
description: str
is_custom: bool = False
@app.get("/health")
async def health_check():
"""Health check endpoint."""
return {"status": "healthy", "service": "chatterbox-tts"}
@app.get("/voices", response_model=list[VoiceInfo])
async def list_voices():
"""List available built-in voices."""
return [
VoiceInfo(id=vid, name=vinfo["name"], description=vinfo["description"], is_custom=False)
for vid, vinfo in BUILTIN_VOICES.items()
]
@app.post("/synthesize")
async def synthesize(request: TTSRequest):
"""
Synthesize speech from text.
Supports:
- Built-in voices (professional_male, friendly_male, professional_female)
- Custom voice via custom_voice_url (URL to audio file)
Returns MP3 audio stream.
"""
if not request.text or not request.text.strip():
raise HTTPException(status_code=400, detail="Text cannot be empty")
try:
model = get_model()
# Determine voice reference audio
voice_audio = None
if request.custom_voice_url:
# Download custom voice reference
import httpx
async with httpx.AsyncClient() as client:
resp = await client.get(request.custom_voice_url)
resp.raise_for_status()
voice_audio = resp.content
logger.info(f"π€ Using custom voice from URL ({len(voice_audio)} bytes)")
elif request.voice in BUILTIN_VOICES:
# Use built-in voice
ref_path = BUILTIN_VOICES[request.voice]["reference_path"]
if os.path.exists(ref_path):
with open(ref_path, "rb") as f:
voice_audio = f.read()
logger.info(f"π€ Using built-in voice: {request.voice}")
else:
logger.warning(f"β οΈ Voice reference not found: {ref_path}, using default")
# Check custom voice file
custom_path = f"{CUSTOM_VOICES_DIR}/{request.voice}.wav"
if voice_audio is None and os.path.exists(custom_path):
with open(custom_path, "rb") as f:
voice_audio = f.read()
logger.info(f"π€ Using custom voice file: {request.voice}")
# Get voice-specific parameters or use defaults
voice_config = BUILTIN_VOICES.get(request.voice, {})
exaggeration = request.exaggeration if request.exaggeration is not None else voice_config.get("exaggeration", 0.5)
cfg_weight = request.cfg_weight if request.cfg_weight is not None else voice_config.get("cfg_weight", 0.5)
logger.info(f"ποΈ Generating: voice={request.voice}, exaggeration={exaggeration}, cfg={cfg_weight}, text={request.text[:50]}...")
# Generate audio with or without reference
if voice_audio:
# Save temp file for reference
import tempfile
with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as tmp:
tmp.write(voice_audio)
tmp_path = tmp.name
wav = model.generate(
text=request.text,
audio_prompt_path=tmp_path,
exaggeration=exaggeration,
cfg_weight=cfg_weight
)
os.unlink(tmp_path) # Clean up temp file
else:
# No reference - use default voice
wav = model.generate(
text=request.text,
exaggeration=exaggeration,
cfg_weight=cfg_weight
)
# Convert to MP3
import torchaudio
import torch
# Ensure wav is 2D tensor (channels, samples)
if wav.dim() == 1:
wav = wav.unsqueeze(0) # Add channel dimension
elif wav.dim() == 3:
wav = wav.squeeze(0) # Remove batch dimension
audio_buffer = io.BytesIO()
torchaudio.save(audio_buffer, wav.cpu(), sample_rate=24000, format="mp3")
audio_buffer.seek(0)
logger.info(f"β
Generated {len(audio_buffer.getvalue())} bytes audio")
return StreamingResponse(
audio_buffer,
media_type="audio/mpeg",
headers={"Content-Disposition": "attachment; filename=speech.mp3"}
)
except Exception as e:
logger.error(f"β TTS generation failed: {e}")
raise HTTPException(status_code=500, detail=f"TTS generation failed: {str(e)}")
@app.post("/voices/upload")
async def upload_custom_voice(
voice_id: str = Form(...),
audio: UploadFile = File(...)
):
"""
Upload custom voice reference audio.
Requires 10-30 seconds of clear speech audio.
Supported formats: WAV, MP3, OGG.
"""
if not voice_id or not voice_id.strip():
raise HTTPException(status_code=400, detail="voice_id is required")
# Validate file size (max 10MB)
content = await audio.read()
if len(content) > 10 * 1024 * 1024:
raise HTTPException(status_code=400, detail="File too large (max 10MB)")
# Save file
save_path = f"{CUSTOM_VOICES_DIR}/{voice_id}.wav"
# Convert to WAV if needed
try:
from pydub import AudioSegment
audio_segment = AudioSegment.from_file(io.BytesIO(content))
audio_segment.export(save_path, format="wav")
logger.info(f"β
Custom voice saved: {voice_id} ({len(content)} bytes)")
except Exception as e:
logger.error(f"β Failed to process audio: {e}")
raise HTTPException(status_code=400, detail=f"Invalid audio format: {str(e)}")
return {
"status": "success",
"voice_id": voice_id,
"message": f"Voice '{voice_id}' uploaded successfully"
}
# OpenAI-compatible endpoint
@app.post("/v1/audio/speech")
async def openai_compatible_speech(request: TTSRequest):
"""OpenAI-compatible TTS endpoint."""
return await synthesize(request)
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8001)
|