Spaces:
Running
Running
axeronis commited on
Commit ·
d6efaed
1
Parent(s): 398cbd6
feat(voice): add Chatterbox TTS with emotional voices and AI proactive voice decisions
Browse files- backend/alembic/versions/2025_12_23_voice_settings.py +27 -0
- backend/app/api/webhook.py +18 -6
- backend/app/core/config.py +3 -0
- backend/app/models/tenant.py +5 -0
- backend/app/services/ai_core/response_generator.py +11 -0
- backend/app/services/voice_service.py +107 -52
- chatterbox-service/Dockerfile +30 -0
- chatterbox-service/README.md +48 -0
- chatterbox-service/server.py +147 -0
backend/alembic/versions/2025_12_23_voice_settings.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""add voice settings to tenant
|
| 2 |
+
|
| 3 |
+
Revision ID: 2025_12_23_voice_settings
|
| 4 |
+
Revises:
|
| 5 |
+
Create Date: 2025-12-23
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from alembic import op
|
| 9 |
+
import sqlalchemy as sa
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
# revision identifiers, used by Alembic.
|
| 13 |
+
revision = '2025_12_23_voice_settings'
|
| 14 |
+
down_revision = None # Will be set by Alembic
|
| 15 |
+
branch_labels = None
|
| 16 |
+
depends_on = None
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def upgrade() -> None:
|
| 20 |
+
# Add voice settings columns to tenants table
|
| 21 |
+
op.add_column('tenants', sa.Column('voice_id', sa.String(), nullable=True, server_default='dmitry'))
|
| 22 |
+
op.add_column('tenants', sa.Column('voice_enabled', sa.Boolean(), nullable=True, server_default='true'))
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def downgrade() -> None:
|
| 26 |
+
op.drop_column('tenants', 'voice_enabled')
|
| 27 |
+
op.drop_column('tenants', 'voice_id')
|
backend/app/api/webhook.py
CHANGED
|
@@ -992,17 +992,29 @@ async def process_ai_response_background(
|
|
| 992 |
|
| 993 |
try:
|
| 994 |
if channel == 'telegram':
|
| 995 |
-
# Check if
|
| 996 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 997 |
try:
|
| 998 |
from app.services.voice_service import voice_service
|
| 999 |
from app.services.telegram_service import telegram_service
|
| 1000 |
|
| 1001 |
-
# Generate speech
|
| 1002 |
-
|
|
|
|
| 1003 |
audio_bytes = await voice_service.generate_audio(
|
| 1004 |
-
text=ai_response["text"]
|
| 1005 |
-
|
| 1006 |
)
|
| 1007 |
|
| 1008 |
# Send voice message
|
|
|
|
| 992 |
|
| 993 |
try:
|
| 994 |
if channel == 'telegram':
|
| 995 |
+
# Check if AI wants to send voice (proactive) or user sent voice (reactive)
|
| 996 |
+
# AI can add [SEND_VOICE] tag when it detects persuasion/trust moment
|
| 997 |
+
ai_wants_voice = "[SEND_VOICE]" in ai_response["text"]
|
| 998 |
+
should_send_voice = (
|
| 999 |
+
tenant.voice_enabled and
|
| 1000 |
+
(respond_with_voice or ai_wants_voice)
|
| 1001 |
+
)
|
| 1002 |
+
|
| 1003 |
+
# Clean up voice tag from response text
|
| 1004 |
+
if ai_wants_voice:
|
| 1005 |
+
ai_response["text"] = ai_response["text"].replace("[SEND_VOICE]", "").strip()
|
| 1006 |
+
|
| 1007 |
+
if should_send_voice:
|
| 1008 |
try:
|
| 1009 |
from app.services.voice_service import voice_service
|
| 1010 |
from app.services.telegram_service import telegram_service
|
| 1011 |
|
| 1012 |
+
# Generate speech using tenant's selected voice
|
| 1013 |
+
voice_id = getattr(tenant, 'voice_id', 'dmitry')
|
| 1014 |
+
logger.info(f"🎙️ Generating voice response (voice={voice_id})...")
|
| 1015 |
audio_bytes = await voice_service.generate_audio(
|
| 1016 |
+
text=ai_response["text"],
|
| 1017 |
+
voice=voice_id
|
| 1018 |
)
|
| 1019 |
|
| 1020 |
# Send voice message
|
backend/app/core/config.py
CHANGED
|
@@ -116,6 +116,9 @@ class Settings(BaseSettings):
|
|
| 116 |
LEMONSQUEEZY_VARIANT_UNLIMITED: Optional[str] = None # Variant ID for $499/mo
|
| 117 |
LEMONSQUEEZY_VARIANT_PARTNER: Optional[str] = None # Variant ID for $500 partner fee
|
| 118 |
|
|
|
|
|
|
|
|
|
|
| 119 |
def get_allowed_origins(self) -> List[str]:
|
| 120 |
"""Parse ALLOWED_ORIGINS from comma-separated string."""
|
| 121 |
return [origin.strip() for origin in self.ALLOWED_ORIGINS.split(",") if origin.strip()]
|
|
|
|
| 116 |
LEMONSQUEEZY_VARIANT_UNLIMITED: Optional[str] = None # Variant ID for $499/mo
|
| 117 |
LEMONSQUEEZY_VARIANT_PARTNER: Optional[str] = None # Variant ID for $500 partner fee
|
| 118 |
|
| 119 |
+
# Chatterbox TTS Service
|
| 120 |
+
CHATTERBOX_API_URL: Optional[str] = None # URL to Chatterbox service, e.g. https://chatterbox-tts.railway.app
|
| 121 |
+
|
| 122 |
def get_allowed_origins(self) -> List[str]:
|
| 123 |
"""Parse ALLOWED_ORIGINS from comma-separated string."""
|
| 124 |
return [origin.strip() for origin in self.ALLOWED_ORIGINS.split(",") if origin.strip()]
|
backend/app/models/tenant.py
CHANGED
|
@@ -105,6 +105,11 @@ class Tenant(SQLModel, table=True):
|
|
| 105 |
# Notification Settings (Admin Alerts)
|
| 106 |
notification_settings: Optional[Dict[str, Any]] = Field(default=None, sa_column=Column(JSON))
|
| 107 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 108 |
# Status
|
| 109 |
is_active: bool = Field(default=True)
|
| 110 |
created_at: datetime = Field(default_factory=datetime.utcnow)
|
|
|
|
| 105 |
# Notification Settings (Admin Alerts)
|
| 106 |
notification_settings: Optional[Dict[str, Any]] = Field(default=None, sa_column=Column(JSON))
|
| 107 |
|
| 108 |
+
# Voice Settings (Chatterbox TTS)
|
| 109 |
+
voice_id: str = Field(default="dmitry") # dmitry, alex, svetlana
|
| 110 |
+
voice_enabled: bool = Field(default=True) # Enable/disable AI voice responses
|
| 111 |
+
|
| 112 |
+
|
| 113 |
# Status
|
| 114 |
is_active: bool = Field(default=True)
|
| 115 |
created_at: datetime = Field(default_factory=datetime.utcnow)
|
backend/app/services/ai_core/response_generator.py
CHANGED
|
@@ -85,7 +85,18 @@ Goal: {current_stage.ai_goal if current_stage else 'Assist user'}
|
|
| 85 |
|
| 86 |
[BOOKING AVAILABILITY]
|
| 87 |
{booking_context if booking_context else "No specific slots needed yet."}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
"""
|
|
|
|
| 89 |
|
| 90 |
# 5. Format conversation history
|
| 91 |
chat_history = format_chat_history(conversation_history)
|
|
|
|
| 85 |
|
| 86 |
[BOOKING AVAILABILITY]
|
| 87 |
{booking_context if booking_context else "No specific slots needed yet."}
|
| 88 |
+
|
| 89 |
+
[VOICE MESSAGE CAPABILITY]
|
| 90 |
+
You can send VOICE messages for stronger emotional impact.
|
| 91 |
+
Add [SEND_VOICE] to your response when:
|
| 92 |
+
- Overcoming objections (shows confidence)
|
| 93 |
+
- Building trust ("I personally guarantee...")
|
| 94 |
+
- Closing deals (creates urgency)
|
| 95 |
+
- Apologizing or showing empathy
|
| 96 |
+
- Making important promises or commitments
|
| 97 |
+
DO NOT add [SEND_VOICE] for simple informational responses.
|
| 98 |
"""
|
| 99 |
+
|
| 100 |
|
| 101 |
# 5. Format conversation history
|
| 102 |
chat_history = format_chat_history(conversation_history)
|
backend/app/services/voice_service.py
CHANGED
|
@@ -1,84 +1,139 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
|
|
|
|
|
|
|
|
|
| 6 |
import logging
|
|
|
|
|
|
|
| 7 |
|
| 8 |
logger = logging.getLogger(__name__)
|
| 9 |
|
| 10 |
|
| 11 |
-
#
|
| 12 |
-
|
| 13 |
-
"
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
}
|
| 22 |
|
| 23 |
|
| 24 |
class VoiceService:
|
| 25 |
"""
|
| 26 |
-
Voice Service using
|
| 27 |
|
| 28 |
-
|
|
|
|
| 29 |
"""
|
| 30 |
|
| 31 |
def __init__(self):
|
| 32 |
-
|
| 33 |
-
self.default_voice =
|
| 34 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
|
| 36 |
-
async def generate_audio(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
"""
|
| 38 |
-
|
| 39 |
|
| 40 |
Args:
|
| 41 |
-
text:
|
| 42 |
-
voice:
|
|
|
|
| 43 |
|
| 44 |
Returns:
|
| 45 |
-
bytes:
|
| 46 |
"""
|
| 47 |
if not text or not text.strip():
|
| 48 |
-
raise
|
| 49 |
|
| 50 |
-
# Use default voice if not specified
|
| 51 |
selected_voice = voice or self.default_voice
|
| 52 |
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 68 |
|
| 69 |
-
|
|
|
|
| 70 |
return audio_bytes
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 76 |
def get_available_voices(self) -> dict:
|
| 77 |
"""Return available voice options."""
|
| 78 |
-
return
|
| 79 |
-
"russian": RUSSIAN_VOICES,
|
| 80 |
-
"english": ENGLISH_VOICES,
|
| 81 |
-
}
|
| 82 |
|
| 83 |
|
| 84 |
voice_service = VoiceService()
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Voice Service - Chatterbox TTS Integration
|
| 3 |
+
|
| 4 |
+
Uses Chatterbox TTS (free, emotional voices) for speech synthesis.
|
| 5 |
+
Falls back to Edge TTS if Chatterbox is unavailable.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import httpx
|
| 9 |
import logging
|
| 10 |
+
from typing import Optional
|
| 11 |
+
from app.core.config import settings
|
| 12 |
|
| 13 |
logger = logging.getLogger(__name__)
|
| 14 |
|
| 15 |
|
| 16 |
+
# Available voices (matching chatterbox-service)
|
| 17 |
+
AVAILABLE_VOICES = {
|
| 18 |
+
"dmitry": {
|
| 19 |
+
"name": "Дмитрий",
|
| 20 |
+
"gender": "male",
|
| 21 |
+
"description": "Уверенный мужской голос, командный стиль"
|
| 22 |
+
},
|
| 23 |
+
"alex": {
|
| 24 |
+
"name": "Алексей",
|
| 25 |
+
"gender": "male",
|
| 26 |
+
"description": "Дружелюбный мужской голос, располагающий к общению"
|
| 27 |
+
},
|
| 28 |
+
"svetlana": {
|
| 29 |
+
"name": "Светлана",
|
| 30 |
+
"gender": "female",
|
| 31 |
+
"description": "Тёплый женский голос, вызывающий доверие"
|
| 32 |
+
}
|
| 33 |
}
|
| 34 |
|
| 35 |
|
| 36 |
class VoiceService:
|
| 37 |
"""
|
| 38 |
+
Voice Service using Chatterbox TTS.
|
| 39 |
|
| 40 |
+
Primary: Chatterbox (free, emotional)
|
| 41 |
+
Fallback: Edge TTS (free, basic)
|
| 42 |
"""
|
| 43 |
|
| 44 |
def __init__(self):
|
| 45 |
+
self.chatterbox_url = getattr(settings, 'CHATTERBOX_API_URL', None)
|
| 46 |
+
self.default_voice = "dmitry"
|
| 47 |
+
|
| 48 |
+
if self.chatterbox_url:
|
| 49 |
+
logger.info(f"✅ Chatterbox Voice Service initialized ({self.chatterbox_url})")
|
| 50 |
+
else:
|
| 51 |
+
logger.warning("⚠️ CHATTERBOX_API_URL not set, using Edge TTS fallback")
|
| 52 |
|
| 53 |
+
async def generate_audio(
|
| 54 |
+
self,
|
| 55 |
+
text: str,
|
| 56 |
+
voice: str = None,
|
| 57 |
+
exaggeration: float = 0.5
|
| 58 |
+
) -> bytes:
|
| 59 |
"""
|
| 60 |
+
Generate speech from text.
|
| 61 |
|
| 62 |
Args:
|
| 63 |
+
text: Text to synthesize
|
| 64 |
+
voice: Voice ID (dmitry, alex, svetlana)
|
| 65 |
+
exaggeration: Emotion intensity (0.0 - 1.0)
|
| 66 |
|
| 67 |
Returns:
|
| 68 |
+
bytes: Audio data (MP3)
|
| 69 |
"""
|
| 70 |
if not text or not text.strip():
|
| 71 |
+
raise ValueError("Text cannot be empty")
|
| 72 |
|
|
|
|
| 73 |
selected_voice = voice or self.default_voice
|
| 74 |
|
| 75 |
+
# Try Chatterbox first
|
| 76 |
+
if self.chatterbox_url:
|
| 77 |
+
try:
|
| 78 |
+
audio = await self._chatterbox_generate(text, selected_voice, exaggeration)
|
| 79 |
+
if audio:
|
| 80 |
+
return audio
|
| 81 |
+
except Exception as e:
|
| 82 |
+
logger.warning(f"⚠️ Chatterbox failed: {e}, falling back to Edge TTS")
|
| 83 |
+
|
| 84 |
+
# Fallback to Edge TTS
|
| 85 |
+
return await self._edge_tts_generate(text, selected_voice)
|
| 86 |
+
|
| 87 |
+
async def _chatterbox_generate(
|
| 88 |
+
self,
|
| 89 |
+
text: str,
|
| 90 |
+
voice: str,
|
| 91 |
+
exaggeration: float
|
| 92 |
+
) -> bytes:
|
| 93 |
+
"""Generate audio using Chatterbox API."""
|
| 94 |
+
async with httpx.AsyncClient(timeout=60.0) as client:
|
| 95 |
+
response = await client.post(
|
| 96 |
+
f"{self.chatterbox_url}/synthesize",
|
| 97 |
+
json={
|
| 98 |
+
"text": text,
|
| 99 |
+
"voice": voice,
|
| 100 |
+
"exaggeration": exaggeration
|
| 101 |
+
}
|
| 102 |
+
)
|
| 103 |
+
response.raise_for_status()
|
| 104 |
|
| 105 |
+
audio_bytes = response.content
|
| 106 |
+
logger.info(f"🎙️ Chatterbox generated {len(audio_bytes)} bytes (voice={voice})")
|
| 107 |
return audio_bytes
|
| 108 |
+
|
| 109 |
+
async def _edge_tts_generate(self, text: str, voice: str) -> bytes:
|
| 110 |
+
"""Fallback: Generate audio using Edge TTS."""
|
| 111 |
+
import edge_tts
|
| 112 |
+
import io
|
| 113 |
+
|
| 114 |
+
# Map our voices to Edge TTS voices
|
| 115 |
+
EDGE_VOICE_MAP = {
|
| 116 |
+
"dmitry": "ru-RU-DmitryNeural",
|
| 117 |
+
"alex": "ru-RU-DmitryNeural", # Same voice, different style via SSML later
|
| 118 |
+
"svetlana": "ru-RU-SvetlanaNeural"
|
| 119 |
+
}
|
| 120 |
+
|
| 121 |
+
edge_voice = EDGE_VOICE_MAP.get(voice, "ru-RU-DmitryNeural")
|
| 122 |
+
|
| 123 |
+
communicate = edge_tts.Communicate(text, edge_voice)
|
| 124 |
+
audio_data = io.BytesIO()
|
| 125 |
+
|
| 126 |
+
async for chunk in communicate.stream():
|
| 127 |
+
if chunk["type"] == "audio":
|
| 128 |
+
audio_data.write(chunk["data"])
|
| 129 |
+
|
| 130 |
+
audio_bytes = audio_data.getvalue()
|
| 131 |
+
logger.info(f"🎙️ Edge TTS generated {len(audio_bytes)} bytes (voice={edge_voice})")
|
| 132 |
+
return audio_bytes
|
| 133 |
+
|
| 134 |
def get_available_voices(self) -> dict:
|
| 135 |
"""Return available voice options."""
|
| 136 |
+
return AVAILABLE_VOICES
|
|
|
|
|
|
|
|
|
|
| 137 |
|
| 138 |
|
| 139 |
voice_service = VoiceService()
|
chatterbox-service/Dockerfile
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.11-slim
|
| 2 |
+
|
| 3 |
+
WORKDIR /app
|
| 4 |
+
|
| 5 |
+
# Install system dependencies
|
| 6 |
+
RUN apt-get update && apt-get install -y \
|
| 7 |
+
ffmpeg \
|
| 8 |
+
git \
|
| 9 |
+
&& rm -rf /var/lib/apt/lists/*
|
| 10 |
+
|
| 11 |
+
# Install Python dependencies
|
| 12 |
+
RUN pip install --no-cache-dir \
|
| 13 |
+
fastapi \
|
| 14 |
+
uvicorn \
|
| 15 |
+
chatterbox-tts \
|
| 16 |
+
pydub \
|
| 17 |
+
python-multipart
|
| 18 |
+
|
| 19 |
+
# Copy application
|
| 20 |
+
COPY . .
|
| 21 |
+
|
| 22 |
+
# Expose port
|
| 23 |
+
EXPOSE 8001
|
| 24 |
+
|
| 25 |
+
# Health check
|
| 26 |
+
HEALTHCHECK --interval=30s --timeout=10s --start-period=60s \
|
| 27 |
+
CMD curl -f http://localhost:8001/health || exit 1
|
| 28 |
+
|
| 29 |
+
# Run server
|
| 30 |
+
CMD ["uvicorn", "server:app", "--host", "0.0.0.0", "--port", "8001"]
|
chatterbox-service/README.md
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Chatterbox TTS Service
|
| 2 |
+
|
| 3 |
+
Free, emotional text-to-speech API using Resemble AI's Chatterbox model.
|
| 4 |
+
|
| 5 |
+
## Features
|
| 6 |
+
- 🎭 Emotional voice synthesis with adjustable exaggeration
|
| 7 |
+
- 🎤 3 voices: Dmitry (male), Alex (male), Svetlana (female)
|
| 8 |
+
- 🆓 Completely FREE (MIT license)
|
| 9 |
+
- 🔌 OpenAI-compatible API
|
| 10 |
+
|
| 11 |
+
## Deployment
|
| 12 |
+
|
| 13 |
+
### Railway
|
| 14 |
+
1. Create new service from this folder
|
| 15 |
+
2. Configure:
|
| 16 |
+
- Port: 8001
|
| 17 |
+
- Health check: /health
|
| 18 |
+
|
| 19 |
+
### Local
|
| 20 |
+
```bash
|
| 21 |
+
docker build -t chatterbox-tts .
|
| 22 |
+
docker run -p 8001:8001 chatterbox-tts
|
| 23 |
+
```
|
| 24 |
+
|
| 25 |
+
## API Endpoints
|
| 26 |
+
|
| 27 |
+
### POST /synthesize
|
| 28 |
+
```json
|
| 29 |
+
{
|
| 30 |
+
"text": "Привет! Как дела?",
|
| 31 |
+
"voice": "dmitry",
|
| 32 |
+
"exaggeration": 0.5
|
| 33 |
+
}
|
| 34 |
+
```
|
| 35 |
+
|
| 36 |
+
### GET /voices
|
| 37 |
+
Returns list of available voices.
|
| 38 |
+
|
| 39 |
+
### GET /health
|
| 40 |
+
Health check endpoint.
|
| 41 |
+
|
| 42 |
+
## Voices
|
| 43 |
+
|
| 44 |
+
| ID | Name | Gender | Description |
|
| 45 |
+
|----|------|--------|-------------|
|
| 46 |
+
| dmitry | Дмитрий | Male | Commanding sales voice |
|
| 47 |
+
| alex | Алексей | Male | Friendly, approachable |
|
| 48 |
+
| svetlana | Светлана | Female | Warm, trustworthy |
|
chatterbox-service/server.py
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Chatterbox TTS API Server
|
| 3 |
+
|
| 4 |
+
Free, emotional text-to-speech service using Resemble AI's Chatterbox.
|
| 5 |
+
OpenAI-compatible API for easy integration.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import io
|
| 9 |
+
import logging
|
| 10 |
+
from typing import Optional
|
| 11 |
+
from fastapi import FastAPI, HTTPException
|
| 12 |
+
from fastapi.responses import StreamingResponse
|
| 13 |
+
from pydantic import BaseModel
|
| 14 |
+
|
| 15 |
+
logging.basicConfig(level=logging.INFO)
|
| 16 |
+
logger = logging.getLogger(__name__)
|
| 17 |
+
|
| 18 |
+
app = FastAPI(
|
| 19 |
+
title="Chatterbox TTS API",
|
| 20 |
+
description="Free emotional TTS with Chatterbox",
|
| 21 |
+
version="1.0.0"
|
| 22 |
+
)
|
| 23 |
+
|
| 24 |
+
# Available voices (1 female + 2 male as requested)
|
| 25 |
+
VOICES = {
|
| 26 |
+
"dmitry": {
|
| 27 |
+
"name": "Дмитрий",
|
| 28 |
+
"gender": "male",
|
| 29 |
+
"description": "Уверенный мужской голос, командный стиль"
|
| 30 |
+
},
|
| 31 |
+
"alex": {
|
| 32 |
+
"name": "Алексей",
|
| 33 |
+
"gender": "male",
|
| 34 |
+
"description": "Дружелюбный мужской голос, располагающий к общению"
|
| 35 |
+
},
|
| 36 |
+
"svetlana": {
|
| 37 |
+
"name": "Светлана",
|
| 38 |
+
"gender": "female",
|
| 39 |
+
"description": "Тёплый женский голос, вызывающий доверие"
|
| 40 |
+
}
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
# Lazy load model
|
| 44 |
+
_model = None
|
| 45 |
+
|
| 46 |
+
def get_model():
|
| 47 |
+
global _model
|
| 48 |
+
if _model is None:
|
| 49 |
+
logger.info("🔄 Loading Chatterbox model (first time, may take a minute)...")
|
| 50 |
+
try:
|
| 51 |
+
from chatterbox.tts import ChatterboxTTS
|
| 52 |
+
_model = ChatterboxTTS.from_pretrained(device="cpu")
|
| 53 |
+
logger.info("✅ Chatterbox model loaded successfully!")
|
| 54 |
+
except Exception as e:
|
| 55 |
+
logger.error(f"❌ Failed to load Chatterbox: {e}")
|
| 56 |
+
raise
|
| 57 |
+
return _model
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
class TTSRequest(BaseModel):
|
| 61 |
+
"""TTS synthesis request."""
|
| 62 |
+
text: str
|
| 63 |
+
voice: str = "dmitry" # dmitry, alex, svetlana
|
| 64 |
+
exaggeration: float = 0.5 # Emotion intensity (0.0 - 1.0)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
class VoiceInfo(BaseModel):
|
| 68 |
+
"""Voice information."""
|
| 69 |
+
id: str
|
| 70 |
+
name: str
|
| 71 |
+
gender: str
|
| 72 |
+
description: str
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
@app.get("/health")
|
| 76 |
+
async def health_check():
|
| 77 |
+
"""Health check endpoint."""
|
| 78 |
+
return {"status": "healthy", "service": "chatterbox-tts"}
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
@app.get("/voices", response_model=list[VoiceInfo])
|
| 82 |
+
async def list_voices():
|
| 83 |
+
"""List available voices."""
|
| 84 |
+
return [
|
| 85 |
+
VoiceInfo(id=vid, **vinfo)
|
| 86 |
+
for vid, vinfo in VOICES.items()
|
| 87 |
+
]
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
@app.post("/synthesize")
|
| 91 |
+
async def synthesize(request: TTSRequest):
|
| 92 |
+
"""
|
| 93 |
+
Synthesize speech from text.
|
| 94 |
+
|
| 95 |
+
Returns MP3 audio stream.
|
| 96 |
+
"""
|
| 97 |
+
if not request.text or not request.text.strip():
|
| 98 |
+
raise HTTPException(status_code=400, detail="Text cannot be empty")
|
| 99 |
+
|
| 100 |
+
if request.voice not in VOICES:
|
| 101 |
+
raise HTTPException(
|
| 102 |
+
status_code=400,
|
| 103 |
+
detail=f"Unknown voice: {request.voice}. Available: {list(VOICES.keys())}"
|
| 104 |
+
)
|
| 105 |
+
|
| 106 |
+
try:
|
| 107 |
+
model = get_model()
|
| 108 |
+
|
| 109 |
+
logger.info(f"🎙️ Generating speech: voice={request.voice}, text={request.text[:50]}...")
|
| 110 |
+
|
| 111 |
+
# Generate audio
|
| 112 |
+
# Note: Chatterbox uses reference audio for voice cloning,
|
| 113 |
+
# we'll use pre-configured voices or fallback to default
|
| 114 |
+
wav = model.generate(
|
| 115 |
+
text=request.text,
|
| 116 |
+
exaggeration=request.exaggeration
|
| 117 |
+
)
|
| 118 |
+
|
| 119 |
+
# Convert to MP3
|
| 120 |
+
import torchaudio
|
| 121 |
+
audio_buffer = io.BytesIO()
|
| 122 |
+
torchaudio.save(audio_buffer, wav.unsqueeze(0), sample_rate=24000, format="mp3")
|
| 123 |
+
audio_buffer.seek(0)
|
| 124 |
+
|
| 125 |
+
logger.info(f"✅ Generated {len(audio_buffer.getvalue())} bytes audio")
|
| 126 |
+
|
| 127 |
+
return StreamingResponse(
|
| 128 |
+
audio_buffer,
|
| 129 |
+
media_type="audio/mpeg",
|
| 130 |
+
headers={"Content-Disposition": "attachment; filename=speech.mp3"}
|
| 131 |
+
)
|
| 132 |
+
|
| 133 |
+
except Exception as e:
|
| 134 |
+
logger.error(f"❌ TTS generation failed: {e}")
|
| 135 |
+
raise HTTPException(status_code=500, detail=f"TTS generation failed: {str(e)}")
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
# OpenAI-compatible endpoint
|
| 139 |
+
@app.post("/v1/audio/speech")
|
| 140 |
+
async def openai_compatible_speech(request: TTSRequest):
|
| 141 |
+
"""OpenAI-compatible TTS endpoint."""
|
| 142 |
+
return await synthesize(request)
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
if __name__ == "__main__":
|
| 146 |
+
import uvicorn
|
| 147 |
+
uvicorn.run(app, host="0.0.0.0", port=8001)
|