Spaces:
Running

axeronis commited on
Commit
a0c82c7
Β·
1 Parent(s): b3457ad

Implement Voice Message Recognition for WhatsApp and Telegram

Browse files
backend/app/api/telegram_webhook.py CHANGED
@@ -10,6 +10,7 @@ from app.models.tenant import Tenant
10
  from app.models.lead import Lead, Message, Conversation
11
  from app.services.ai_core import get_ai_core
12
  from app.core.logging import get_logger
 
13
 
14
  logger = get_logger(__name__)
15
  router = APIRouter(prefix="/webhook/telegram", tags=["Telegram Webhooks"])
@@ -36,12 +37,13 @@ async def handle_telegram_webhook(
36
  message_data = data["message"]
37
  chat_id = str(message_data.get("chat", {}).get("id"))
38
  text = message_data.get("text", "")
 
39
  user_data = message_data.get("from", {})
40
  username = user_data.get("username", "")
41
  first_name = user_data.get("first_name", "")
42
 
43
- if not text:
44
- return {"status": "no_text"}
45
 
46
  # Process in background
47
  background_tasks.add_task(
@@ -49,6 +51,7 @@ async def handle_telegram_webhook(
49
  tenant_id=tenant_id,
50
  chat_id=chat_id,
51
  text=text,
 
52
  username=username,
53
  first_name=first_name
54
  )
@@ -59,6 +62,7 @@ async def process_telegram_message(
59
  tenant_id: UUID,
60
  chat_id: str,
61
  text: str,
 
62
  username: str,
63
  first_name: str
64
  ):
@@ -86,6 +90,41 @@ async def process_telegram_message(
86
  logger.error(f"No Telegram token found for tenant {tenant_id}")
87
  return
88
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89
  # 2. Find/Create Lead
90
  stmt = select(Lead).where(
91
  Lead.tenant_id == tenant_id,
 
10
  from app.models.lead import Lead, Message, Conversation
11
  from app.services.ai_core import get_ai_core
12
  from app.core.logging import get_logger
13
+ import httpx
14
 
15
  logger = get_logger(__name__)
16
  router = APIRouter(prefix="/webhook/telegram", tags=["Telegram Webhooks"])
 
37
  message_data = data["message"]
38
  chat_id = str(message_data.get("chat", {}).get("id"))
39
  text = message_data.get("text", "")
40
+ voice = message_data.get("voice", {}) # Voice message
41
  user_data = message_data.get("from", {})
42
  username = user_data.get("username", "")
43
  first_name = user_data.get("first_name", "")
44
 
45
+ if not text and not voice:
46
+ return {"status": "no_text_or_voice"}
47
 
48
  # Process in background
49
  background_tasks.add_task(
 
51
  tenant_id=tenant_id,
52
  chat_id=chat_id,
53
  text=text,
54
+ voice_file_id=voice.get("file_id"), # Pass file_id if voice
55
  username=username,
56
  first_name=first_name
57
  )
 
62
  tenant_id: UUID,
63
  chat_id: str,
64
  text: str,
65
+ voice_file_id: str | None,
66
  username: str,
67
  first_name: str
68
  ):
 
90
  logger.error(f"No Telegram token found for tenant {tenant_id}")
91
  return
92
 
93
+ # --- VOICE TRANSCRIPTION START ---
94
+ if voice_file_id:
95
+ try:
96
+ logger.info("🎀 Telegram Voice Message Detected. Fetching file...")
97
+ async with httpx.AsyncClient() as client:
98
+ # 1. Get File Path
99
+ file_res = await client.get(f"https://api.telegram.org/bot{bot_token}/getFile?file_id={voice_file_id}")
100
+ file_data = file_res.json()
101
+ if not file_data.get("ok"):
102
+ logger.error(f"Failed to get file path: {file_data}")
103
+ return
104
+
105
+ file_path = file_data["result"]["file_path"]
106
+ download_url = f"https://api.telegram.org/file/bot{bot_token}/{file_path}"
107
+
108
+ # 2. Download File
109
+ logger.info(f"⬇️ Downloading voice from {download_url}")
110
+ audio_res = await client.get(download_url)
111
+ audio_res.raise_for_status()
112
+ audio_bytes = audio_res.content
113
+
114
+ # 3. Transcribe
115
+ from app.services.llm_client import get_llm_client
116
+ gc = get_llm_client()
117
+ logger.info("🧠 Transcribing with Gemini...")
118
+ transcription = await gc.transcribe_audio(audio_bytes, mime_type="audio/ogg")
119
+
120
+ logger.info(f"βœ… Transcription: {transcription}")
121
+ text = f"[Voice Message] {transcription}" # Prefix to indicate source
122
+
123
+ except Exception as e:
124
+ logger.error(f"❌ Voice processing failed: {e}")
125
+ text = "[Voice Message] (НС ΡƒΠ΄Π°Π»ΠΎΡΡŒ Ρ€Π°ΡΠΏΠΎΠ·Π½Π°Ρ‚ΡŒ Π°ΡƒΠ΄ΠΈΠΎ)"
126
+ # --- VOICE TRANSCRIPTION END ---
127
+
128
  # 2. Find/Create Lead
129
  stmt = select(Lead).where(
130
  Lead.tenant_id == tenant_id,
backend/app/services/llm_client.py CHANGED
@@ -217,26 +217,62 @@ class GeminiLLMClient:
217
  """
218
 
219
  # Use simple generation
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
220
  try:
221
  model = genai.GenerativeModel(self.default_model_name)
222
- # Native JSON mode
 
 
 
 
 
 
 
 
 
223
  response = await asyncio.to_thread(
224
  model.generate_content,
225
- prompt,
226
- generation_config=genai.GenerationConfig(
227
- response_mime_type="application/json",
228
- temperature=0.1
229
- )
230
  )
231
- data = json.loads(response.text)
232
- return AISummary(**data).model_dump()
 
233
  except Exception as e:
234
- logger.error(f"Summary failed: {e}")
235
- # Return fallback (same as before)
236
- return {
237
- "intent": "Error", "heat_score": 50, "recommendation": "Manual review needed",
238
- "pain_points": [], "objections": [], "draft_reply": "Error"
239
- } # Simplified fallback
240
 
241
  @lru_cache()
242
  def get_llm_client():
 
217
  """
218
 
219
  # Use simple generation
220
+ try:
221
+ # Native JSON mode
222
+ model = genai.GenerativeModel(self.default_model_name)
223
+ response = await asyncio.to_thread(
224
+ model.generate_content,
225
+ prompt,
226
+ generation_config=genai.GenerationConfig(
227
+ response_mime_type="application/json",
228
+ temperature=0.1
229
+ )
230
+ )
231
+ data = json.loads(response.text)
232
+ return AISummary(**data).model_dump()
233
+ except Exception as e:
234
+ logger.error(f"Summary failed: {e}")
235
+ # Return fallback (same as before)
236
+ return {
237
+ "intent": "Error", "heat_score": 50, "recommendation": "Manual review needed",
238
+ "pain_points": [], "objections": [], "draft_reply": "Error"
239
+ } # Simplified fallback
240
+
241
+ async def transcribe_audio(self, audio_bytes: bytes, mime_type: str = "audio/ogg") -> str:
242
+ """
243
+ Transcribe audio using Gemini Multimodal capabilities.
244
+
245
+ Args:
246
+ audio_bytes: Raw audio data
247
+ mime_type: Mime type (e.g. audio/ogg, audio/mp3)
248
+
249
+ Returns:
250
+ str: Transcribed text
251
+ """
252
+ prompt = "Listen to this audio and provide a verbatim transcription of what is being said. Return ONLY the transcription text, nothing else."
253
+
254
  try:
255
  model = genai.GenerativeModel(self.default_model_name)
256
+
257
+ # Create content part with inline data
258
+ content = [
259
+ prompt,
260
+ {
261
+ "mime_type": mime_type,
262
+ "data": audio_bytes
263
+ }
264
+ ]
265
+
266
  response = await asyncio.to_thread(
267
  model.generate_content,
268
+ content
 
 
 
 
269
  )
270
+
271
+ return response.text.strip()
272
+
273
  except Exception as e:
274
+ logger.error(f"Transcription failed: {e}")
275
+ raise LLMAPIError(f"Transcription failed: {e}")
 
 
 
 
276
 
277
  @lru_cache()
278
  def get_llm_client():
verify_webhook_endpoint.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import httpx
3
+ import uuid
4
+
5
+ async def test_webhook():
6
+ # Use a valid UUID to avoid 422 if validation is strict
7
+ tenant_id = str(uuid.uuid4())
8
+ url = f"http://localhost:8000/api/v1/webhook/evolution/{tenant_id}"
9
+
10
+ print(f"Testing URL: {url}")
11
+
12
+ try:
13
+ async with httpx.AsyncClient() as client:
14
+ # Send an empty JSON or minimal payload
15
+ response = await client.post(url, json={"type": "test"})
16
+
17
+ print(f"Status Code: {response.status_code}")
18
+ print(f"Response: {response.text}")
19
+
20
+ if response.status_code == 404:
21
+ print("❌ Endpoint NOT FOUND (404)")
22
+ elif response.status_code == 405:
23
+ print("❌ Method Not Allowed (405) - Check if POST is correct")
24
+ elif response.status_code == 400:
25
+ print("βœ… Endpoint exists (400 Bad Request is expected for invalid payload)")
26
+ elif response.status_code == 422:
27
+ print("βœ… Endpoint exists (422 validation error is expected)")
28
+ elif response.status_code == 200:
29
+ print("βœ… Endpoint works!")
30
+ else:
31
+ print(f"⚠️ Unexpected status: {response.status_code}")
32
+
33
+ except Exception as e:
34
+ print(f"❌ Connection failed: {e}")
35
+
36
+ if __name__ == "__main__":
37
+ asyncio.run(test_webhook())