Spaces:
Running

axeronis commited on
Commit
c918691
·
1 Parent(s): 1fee233

feat(tts): switch to free Edge TTS + proper voice message format

Browse files
backend/Dockerfile CHANGED
@@ -6,6 +6,7 @@ WORKDIR /app
6
  RUN apt-get update && apt-get install -y \
7
  gcc \
8
  postgresql-client \
 
9
  && rm -rf /var/lib/apt/lists/*
10
 
11
  # Copy requirements
 
6
  RUN apt-get update && apt-get install -y \
7
  gcc \
8
  postgresql-client \
9
+ ffmpeg \
10
  && rm -rf /var/lib/apt/lists/*
11
 
12
  # Copy requirements
backend/app/services/telegram_service.py CHANGED
@@ -96,41 +96,75 @@ class TelegramService:
96
  """
97
  Send voice message to Telegram chat.
98
 
99
- Note: Telegram sendVoice expects OGG/OPUS format, but OpenAI TTS returns MP3.
100
- We use sendAudio instead which accepts MP3.
101
 
102
  Args:
103
  token: Bot token
104
  chat_id: Chat ID to send to
105
- audio_bytes: Audio file bytes (MP3 format from OpenAI TTS)
106
- caption: Optional caption for the audio message
107
  """
108
  if not token:
109
  logger.error("Telegram token not provided")
110
  return False
 
 
 
 
 
111
 
112
- # Use sendAudio instead of sendVoice because OpenAI TTS returns MP3
113
- url = self._get_url(token, "sendAudio")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
114
 
115
  try:
116
  async with httpx.AsyncClient(timeout=30.0) as client:
117
- # Send as multipart form data (file upload)
118
- files = {"audio": ("voice.mp3", audio_bytes, "audio/mpeg")}
119
  data = {"chat_id": chat_id}
120
 
121
  if caption:
122
- data["caption"] = caption[:1024] # Telegram caption limit
123
 
124
  response = await client.post(url, files=files, data=data)
125
 
126
  if response.status_code == 200:
127
- logger.info(f"🎤 Audio message sent to chat {chat_id}")
128
  return True
129
  else:
130
- logger.error(f"Telegram sendAudio failed: {response.text}")
131
- return False
 
132
  except Exception as e:
133
- logger.error(f"Telegram sendAudio error: {e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
134
  return False
135
 
136
  # Singleton
 
96
  """
97
  Send voice message to Telegram chat.
98
 
99
+ Converts MP3 to OGG format for proper voice message display in Telegram.
 
100
 
101
  Args:
102
  token: Bot token
103
  chat_id: Chat ID to send to
104
+ audio_bytes: Audio file bytes (MP3 format from Edge TTS)
105
+ caption: Optional caption for the voice message
106
  """
107
  if not token:
108
  logger.error("Telegram token not provided")
109
  return False
110
+
111
+ try:
112
+ # Convert MP3 to OGG for proper Telegram voice message
113
+ from pydub import AudioSegment
114
+ import io
115
 
116
+ # Load MP3 from bytes
117
+ audio = AudioSegment.from_mp3(io.BytesIO(audio_bytes))
118
+
119
+ # Export as OGG (Telegram voice format)
120
+ ogg_buffer = io.BytesIO()
121
+ audio.export(ogg_buffer, format="ogg", codec="libopus")
122
+ ogg_bytes = ogg_buffer.getvalue()
123
+
124
+ logger.info(f"🔄 Converted MP3 ({len(audio_bytes)} bytes) → OGG ({len(ogg_bytes)} bytes)")
125
+
126
+ except Exception as conv_err:
127
+ logger.warning(f"⚠️ OGG conversion failed: {conv_err}, trying MP3 directly")
128
+ # Fallback: try sending MP3 as audio
129
+ return await self._send_audio_fallback(token, chat_id, audio_bytes)
130
+
131
+ url = self._get_url(token, "sendVoice")
132
 
133
  try:
134
  async with httpx.AsyncClient(timeout=30.0) as client:
135
+ # Send as voice message (OGG format)
136
+ files = {"voice": ("voice.ogg", ogg_bytes, "audio/ogg")}
137
  data = {"chat_id": chat_id}
138
 
139
  if caption:
140
+ data["caption"] = caption[:1024]
141
 
142
  response = await client.post(url, files=files, data=data)
143
 
144
  if response.status_code == 200:
145
+ logger.info(f"🎤 Voice message sent to chat {chat_id}")
146
  return True
147
  else:
148
+ logger.error(f"Telegram sendVoice failed: {response.text}")
149
+ # Fallback to audio
150
+ return await self._send_audio_fallback(token, chat_id, audio_bytes)
151
  except Exception as e:
152
+ logger.error(f"Telegram sendVoice error: {e}")
153
+ return False
154
+
155
+ async def _send_audio_fallback(self, token: str, chat_id: str, audio_bytes: bytes) -> bool:
156
+ """Fallback: send as audio file if voice fails."""
157
+ url = self._get_url(token, "sendAudio")
158
+ try:
159
+ async with httpx.AsyncClient(timeout=30.0) as client:
160
+ files = {"audio": ("voice.mp3", audio_bytes, "audio/mpeg")}
161
+ data = {"chat_id": chat_id}
162
+ response = await client.post(url, files=files, data=data)
163
+ if response.status_code == 200:
164
+ logger.info(f"🎵 Audio fallback sent to chat {chat_id}")
165
+ return True
166
+ return False
167
+ except:
168
  return False
169
 
170
  # Singleton
backend/app/services/voice_service.py CHANGED
@@ -1,43 +1,84 @@
1
- from openai import AsyncOpenAI
 
 
2
  from app.core.config import settings
3
  from fastapi import HTTPException
4
  import logging
5
 
6
  logger = logging.getLogger(__name__)
7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
  class VoiceService:
 
 
 
 
 
 
9
  def __init__(self):
10
- self.api_key = settings.OPENAI_API_KEY
11
- if self.api_key:
12
- self.client = AsyncOpenAI(api_key=self.api_key)
13
- else:
14
- self.client = None
15
- logger.warning("OPENAI_API_KEY not found. Voice generation will be disabled.")
16
-
17
- async def generate_audio(self, text: str, voice: str = "onyx") -> bytes:
18
  """
19
- Generates audio from text using OpenAI's TTS API.
20
 
21
  Args:
22
  text: The text to convert to speech.
23
- voice: The voice ID to use (onyx, alloy, echo, fable, nova, shimmer).
24
 
25
  Returns:
26
  bytes: The binary audio content (MP3).
27
  """
28
- if not self.client:
29
- raise HTTPException(status_code=503, detail="Voice service is not configured (Missing OpenAI Key)")
30
-
 
 
 
31
  try:
32
- # "onyx" is best for the "Aggressive/Command Center" persona
33
- response = await self.client.audio.speech.create(
34
- model="tts-1",
35
- voice=voice,
36
- input=text
37
- )
38
- return response.content
 
 
 
 
 
 
 
 
 
 
 
39
  except Exception as e:
40
  logger.error(f"Voice generation failed: {str(e)}")
41
  raise HTTPException(status_code=500, detail=f"Voice generation failed: {str(e)}")
 
 
 
 
 
 
 
 
42
 
43
  voice_service = VoiceService()
 
1
+ import edge_tts
2
+ import asyncio
3
+ import io
4
  from app.core.config import settings
5
  from fastapi import HTTPException
6
  import logging
7
 
8
  logger = logging.getLogger(__name__)
9
 
10
+
11
+ # Russian voices available in Edge TTS
12
+ RUSSIAN_VOICES = {
13
+ "male": "ru-RU-DmitryNeural", # Male Russian voice
14
+ "female": "ru-RU-SvetlanaNeural", # Female Russian voice
15
+ }
16
+
17
+ # English voices
18
+ ENGLISH_VOICES = {
19
+ "male": "en-US-GuyNeural",
20
+ "female": "en-US-JennyNeural",
21
+ }
22
+
23
+
24
  class VoiceService:
25
+ """
26
+ Voice Service using Microsoft Edge TTS (FREE).
27
+
28
+ Replaces OpenAI TTS ($15/1M chars) with Edge TTS (free).
29
+ """
30
+
31
  def __init__(self):
32
+ # Default voice - Russian male for sales persona
33
+ self.default_voice = RUSSIAN_VOICES["male"]
34
+ logger.info(f"✅ Edge TTS Voice Service initialized (voice: {self.default_voice})")
35
+
36
+ async def generate_audio(self, text: str, voice: str = None) -> bytes:
 
 
 
37
  """
38
+ Generates audio from text using Microsoft Edge TTS (FREE).
39
 
40
  Args:
41
  text: The text to convert to speech.
42
+ voice: The voice ID to use (default: Russian male).
43
 
44
  Returns:
45
  bytes: The binary audio content (MP3).
46
  """
47
+ if not text or not text.strip():
48
+ raise HTTPException(status_code=400, detail="Text cannot be empty")
49
+
50
+ # Use default voice if not specified
51
+ selected_voice = voice or self.default_voice
52
+
53
  try:
54
+ # Create TTS communicate object
55
+ communicate = edge_tts.Communicate(text, selected_voice)
56
+
57
+ # Collect audio data into memory
58
+ audio_data = io.BytesIO()
59
+
60
+ async for chunk in communicate.stream():
61
+ if chunk["type"] == "audio":
62
+ audio_data.write(chunk["data"])
63
+
64
+ audio_bytes = audio_data.getvalue()
65
+
66
+ if not audio_bytes:
67
+ raise HTTPException(status_code=500, detail="No audio data generated")
68
+
69
+ logger.info(f"🎙️ Edge TTS generated {len(audio_bytes)} bytes for {len(text)} chars")
70
+ return audio_bytes
71
+
72
  except Exception as e:
73
  logger.error(f"Voice generation failed: {str(e)}")
74
  raise HTTPException(status_code=500, detail=f"Voice generation failed: {str(e)}")
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()
backend/requirements.txt CHANGED
@@ -61,6 +61,7 @@ google-api-python-client>=2.111.0
61
 
62
  # Voice / Audio Processing
63
  pydub==0.25.1
 
64
 
65
  # Testing
66
  pytest==7.4.3
 
61
 
62
  # Voice / Audio Processing
63
  pydub==0.25.1
64
+ edge-tts>=6.1.0 # Free Microsoft Edge TTS
65
 
66
  # Testing
67
  pytest==7.4.3