Spaces:
Running

axeronis commited on
Commit
e5f3f5b
·
1 Parent(s): 5805e03

feat(voice): replace Chatterbox with ElevenLabs TTS for faster voice generation

Browse files
backend/app/core/config.py CHANGED
@@ -116,8 +116,8 @@ 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
- # 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."""
 
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
+ # ElevenLabs TTS Service (replaces Chatterbox)
120
+ ELEVENLABS_API_KEY: Optional[str] = None # ElevenLabs API key for TTS
121
 
122
  def get_allowed_origins(self) -> List[str]:
123
  """Parse ALLOWED_ORIGINS from comma-separated string."""
backend/app/services/voice_service.py CHANGED
@@ -1,8 +1,8 @@
1
  """
2
- Voice Service - Chatterbox TTS Integration
3
 
4
- Uses Chatterbox TTS (free, emotional voices) with voice cloning support.
5
- Falls back to Edge TTS if Chatterbox is unavailable.
6
  """
7
 
8
  import httpx
@@ -13,55 +13,61 @@ from app.core.config import settings
13
  logger = logging.getLogger(__name__)
14
 
15
 
16
- # Available built-in voices
17
- AVAILABLE_VOICES = {
18
  "professional_male": {
 
19
  "name": "Professional (Male)",
20
  "description": "Confident business voice, works in Russian/English"
21
  },
22
  "friendly_male": {
 
23
  "name": "Friendly (Male)",
24
  "description": "Warm, approachable voice for building rapport"
25
  },
26
  "professional_female": {
 
27
  "name": "Professional (Female)",
28
  "description": "Clear, trustworthy female voice"
29
  }
30
  }
31
 
 
 
 
32
 
33
  class VoiceService:
34
  """
35
- Voice Service using Chatterbox TTS with voice cloning.
36
 
37
- Primary: Chatterbox (free, emotional, cloning)
38
  Fallback: Edge TTS (free, basic)
39
  """
40
 
41
  def __init__(self):
42
- self.chatterbox_url = getattr(settings, 'CHATTERBOX_API_URL', None)
43
  self.default_voice = "professional_male"
44
 
45
- if self.chatterbox_url:
46
- logger.info(f"✅ Chatterbox Voice Service initialized ({self.chatterbox_url})")
47
  else:
48
- logger.warning("⚠️ CHATTERBOX_API_URL not set, using Edge TTS fallback")
49
 
50
  async def generate_audio(
51
  self,
52
  text: str,
53
  voice: str = None,
54
- custom_voice_url: str = None,
55
- exaggeration: float = 0.5
56
  ) -> bytes:
57
  """
58
  Generate speech from text.
59
 
60
  Args:
61
  text: Text to synthesize
62
- voice: Voice ID (professional_male, friendly_male, professional_female, or custom)
63
- custom_voice_url: URL to custom voice audio for cloning
64
- exaggeration: Emotion intensity (0.0 - 1.0)
65
 
66
  Returns:
67
  bytes: Audio data (MP3)
@@ -71,47 +77,48 @@ class VoiceService:
71
 
72
  selected_voice = voice or self.default_voice
73
 
74
- # Try Chatterbox first
75
- if self.chatterbox_url:
76
  try:
77
- audio = await self._chatterbox_generate(
78
- text, selected_voice, exaggeration, custom_voice_url
79
- )
80
  if audio:
81
  return audio
82
  except Exception as e:
83
- logger.warning(f"⚠️ Chatterbox failed: {e}, falling back to Edge TTS")
84
 
85
  # Fallback to Edge TTS
86
  return await self._edge_tts_generate(text, selected_voice)
87
 
88
- async def _chatterbox_generate(
89
- self,
90
- text: str,
91
- voice: str,
92
- exaggeration: float,
93
- custom_voice_url: str = None
94
- ) -> bytes:
95
- """Generate audio using Chatterbox API with optional voice cloning."""
96
- async with httpx.AsyncClient(timeout=120.0) as client: # Longer timeout for CPU
97
- payload = {
98
- "text": text,
99
- "voice": voice,
100
- "exaggeration": exaggeration
 
 
 
 
 
 
 
 
101
  }
102
-
103
- # Add custom voice URL for cloning
104
- if custom_voice_url:
105
- payload["custom_voice_url"] = custom_voice_url
106
-
107
- response = await client.post(
108
- f"{self.chatterbox_url}/synthesize",
109
- json=payload
110
- )
111
  response.raise_for_status()
112
 
113
  audio_bytes = response.content
114
- logger.info(f"🎙️ Chatterbox generated {len(audio_bytes)} bytes (voice={voice})")
115
  return audio_bytes
116
 
117
  async def _edge_tts_generate(self, text: str, voice: str) -> bytes:
 
1
  """
2
+ Voice Service - ElevenLabs TTS Integration
3
 
4
+ Uses ElevenLabs TTS (fast, high-quality cloned voices).
5
+ Falls back to Edge TTS if ElevenLabs is unavailable.
6
  """
7
 
8
  import httpx
 
13
  logger = logging.getLogger(__name__)
14
 
15
 
16
+ # ElevenLabs Voice IDs (cloned from actors)
17
+ ELEVENLABS_VOICES = {
18
  "professional_male": {
19
+ "voice_id": "oSsVULelD3Y0OlgCgi7Y",
20
  "name": "Professional (Male)",
21
  "description": "Confident business voice, works in Russian/English"
22
  },
23
  "friendly_male": {
24
+ "voice_id": "sMVeMdZkTfhK3YCp2rUX",
25
  "name": "Friendly (Male)",
26
  "description": "Warm, approachable voice for building rapport"
27
  },
28
  "professional_female": {
29
+ "voice_id": "qYM4RQxhD1DdkQ3H0NuD",
30
  "name": "Professional (Female)",
31
  "description": "Clear, trustworthy female voice"
32
  }
33
  }
34
 
35
+ # For backward compatibility
36
+ AVAILABLE_VOICES = {k: {"name": v["name"], "description": v["description"]} for k, v in ELEVENLABS_VOICES.items()}
37
+
38
 
39
  class VoiceService:
40
  """
41
+ Voice Service using ElevenLabs TTS with cloned voices.
42
 
43
+ Primary: ElevenLabs (fast, high-quality cloned voices)
44
  Fallback: Edge TTS (free, basic)
45
  """
46
 
47
  def __init__(self):
48
+ self.elevenlabs_api_key = getattr(settings, 'ELEVENLABS_API_KEY', None)
49
  self.default_voice = "professional_male"
50
 
51
+ if self.elevenlabs_api_key:
52
+ logger.info(f"✅ ElevenLabs Voice Service initialized")
53
  else:
54
+ logger.warning("⚠️ ELEVENLABS_API_KEY not set, using Edge TTS fallback")
55
 
56
  async def generate_audio(
57
  self,
58
  text: str,
59
  voice: str = None,
60
+ custom_voice_url: str = None, # Kept for compatibility, not used with ElevenLabs
61
+ exaggeration: float = 0.5 # Kept for compatibility
62
  ) -> bytes:
63
  """
64
  Generate speech from text.
65
 
66
  Args:
67
  text: Text to synthesize
68
+ voice: Voice ID (professional_male, friendly_male, professional_female)
69
+ custom_voice_url: Not used with ElevenLabs (kept for compatibility)
70
+ exaggeration: Not used with ElevenLabs (kept for compatibility)
71
 
72
  Returns:
73
  bytes: Audio data (MP3)
 
77
 
78
  selected_voice = voice or self.default_voice
79
 
80
+ # Try ElevenLabs first
81
+ if self.elevenlabs_api_key:
82
  try:
83
+ audio = await self._elevenlabs_generate(text, selected_voice)
 
 
84
  if audio:
85
  return audio
86
  except Exception as e:
87
+ logger.warning(f"⚠️ ElevenLabs failed: {e}, falling back to Edge TTS")
88
 
89
  # Fallback to Edge TTS
90
  return await self._edge_tts_generate(text, selected_voice)
91
 
92
+ async def _elevenlabs_generate(self, text: str, voice: str) -> bytes:
93
+ """Generate audio using ElevenLabs API."""
94
+ voice_config = ELEVENLABS_VOICES.get(voice, ELEVENLABS_VOICES[self.default_voice])
95
+ voice_id = voice_config["voice_id"]
96
+
97
+ url = f"https://api.elevenlabs.io/v1/text-to-speech/{voice_id}"
98
+
99
+ headers = {
100
+ "Accept": "audio/mpeg",
101
+ "Content-Type": "application/json",
102
+ "xi-api-key": self.elevenlabs_api_key
103
+ }
104
+
105
+ payload = {
106
+ "text": text,
107
+ "model_id": "eleven_multilingual_v2", # Best for Russian
108
+ "voice_settings": {
109
+ "stability": 0.5,
110
+ "similarity_boost": 0.75,
111
+ "style": 0.0,
112
+ "use_speaker_boost": True
113
  }
114
+ }
115
+
116
+ async with httpx.AsyncClient(timeout=30.0) as client:
117
+ response = await client.post(url, json=payload, headers=headers)
 
 
 
 
 
118
  response.raise_for_status()
119
 
120
  audio_bytes = response.content
121
+ logger.info(f"🎙️ ElevenLabs generated {len(audio_bytes)} bytes (voice={voice})")
122
  return audio_bytes
123
 
124
  async def _edge_tts_generate(self, text: str, voice: str) -> bytes: