Spaces:
Running

axeronis
fix(chatterbox): fix tensor dimension handling for audio output
5805e03
Raw History Blame Contribute Delete
8.39 kB
"""
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)