Peter Michael Gits Claude commited on
Commit
3a3cbca
Β·
1 Parent(s): e9456c7

feat: Add comprehensive WebSocket STT debugging

Browse files

- Detailed debugging for audio file processing and format detection
- WebSocket connection state and parameter logging
- Message sending/receiving debugging with JSON parsing
- Enhanced error handling for different WebSocket exception types
- Connection timeout and failure tracking across multiple URLs
- Audio data validation and base64 encoding verification

Helps identify why WebSocket STT streaming isn't working properly.

πŸ€– Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

Files changed (1) hide show
  1. core/mcp_audio_handler.py +103 -30
core/mcp_audio_handler.py CHANGED
@@ -265,8 +265,10 @@ class MCPAudioHandler:
265
  import websockets
266
  import base64
267
  import json
 
268
 
269
  print(f"🎀 WebSocket STT: Processing {audio_file_path}")
 
270
 
271
  # Read audio file and encode for WebSocket transmission
272
  with open(audio_file_path, 'rb') as audio_file:
@@ -274,66 +276,137 @@ class MCPAudioHandler:
274
  audio_base64 = base64.b64encode(audio_data).decode('utf-8')
275
  print(f"πŸ” DEBUG: Audio file size: {len(audio_data)} bytes, path: {audio_file_path}")
276
  print(f"πŸ” DEBUG: First 20 bytes: {audio_data[:20].hex() if len(audio_data) >= 20 else 'N/A'}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
277
 
278
  # Try each WebSocket URL
279
- for ws_url in self.stt_websocket_urls:
280
  try:
281
- print(f"🎀 WebSocket STT: Connecting to {ws_url}")
282
 
283
  # Improved connection with better timeout handling to prevent spinning
284
- async with websockets.connect(ws_url, timeout=15, ping_interval=None) as websocket:
 
 
 
 
 
 
 
 
 
 
 
 
285
  # Send audio chunk with unmute.sh protocol
286
  message = {
287
  "type": "stt_audio_chunk",
288
  "audio_data": audio_base64,
289
- "language": "auto",
290
  "model_size": "base",
291
  "is_final": True # Use flush trick for best performance
292
  }
293
 
294
- await websocket.send(json.dumps(message))
295
- print(f"🎀 WebSocket STT: Sent audio data ({len(audio_data)} bytes)")
 
 
 
296
 
297
- # Wait for response with timeout to prevent hanging
298
- response = await asyncio.wait_for(websocket.recv(), timeout=30.0)
299
- result = json.loads(response)
300
 
301
- print(f"🎀 WebSocket STT: Received response: {result}")
 
 
302
 
303
- if result.get("type") == "stt_transcription" and result.get("text"):
304
- transcription = result["text"].strip()
305
- processing_time = result.get("processing_time", 0)
306
- rtf = result.get("real_time_factor", 0)
 
307
 
308
- print(f"🎀 WebSocket STT: SUCCESS - {transcription[:50]}... (RTF: {rtf:.2f}x)")
309
- return transcription
310
- elif result.get("type") == "stt_error":
311
- error_msg = result.get("message", "Unknown error")
312
- print(f"🎀 WebSocket STT: Service error - {error_msg}")
313
- continue # Try next URL
314
- else:
315
- print(f"🎀 WebSocket STT: Unexpected response format")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
316
  continue
317
 
318
- except websockets.exceptions.ConnectionClosed:
319
- print(f"🎀 WebSocket STT: Connection closed for {ws_url}")
 
 
 
 
 
 
 
 
 
 
320
  continue
321
  except asyncio.TimeoutError:
322
- print(f"🎀 WebSocket STT: Timeout for {ws_url}")
 
 
 
323
  continue
324
  except Exception as ws_error:
325
- print(f"🎀 WebSocket STT: Error with {ws_url}: {ws_error}")
 
 
 
326
  continue
327
 
328
- # If all WebSocket URLs failed
329
- return "Error: All WebSocket STT services failed"
 
 
330
 
331
  except ImportError:
332
  print("🎀 WebSocket STT: websockets library not available")
333
  return "Error: WebSocket support not available"
334
  except Exception as e:
335
- print(f"🎀 WebSocket STT: General error: {e}")
336
- return f"Error: WebSocket STT failed - {str(e)}"
 
 
 
337
 
338
  async def _call_mcp_stt_service(self, audio_file_path: str) -> str:
339
  """Call MCP STT service with HTTP fallback."""
 
265
  import websockets
266
  import base64
267
  import json
268
+ import os
269
 
270
  print(f"🎀 WebSocket STT: Processing {audio_file_path}")
271
+ print(f"πŸ” DEBUG: File exists: {os.path.exists(audio_file_path)}")
272
 
273
  # Read audio file and encode for WebSocket transmission
274
  with open(audio_file_path, 'rb') as audio_file:
 
276
  audio_base64 = base64.b64encode(audio_data).decode('utf-8')
277
  print(f"πŸ” DEBUG: Audio file size: {len(audio_data)} bytes, path: {audio_file_path}")
278
  print(f"πŸ” DEBUG: First 20 bytes: {audio_data[:20].hex() if len(audio_data) >= 20 else 'N/A'}")
279
+ print(f"πŸ” DEBUG: Base64 length: {len(audio_base64)} chars")
280
+
281
+ # Audio format detection
282
+ if audio_data.startswith(b'RIFF'):
283
+ print(f"πŸ” DEBUG: Audio format: WAV")
284
+ elif audio_data.startswith(b'\xff\xfb') or audio_data.startswith(b'ID3'):
285
+ print(f"πŸ” DEBUG: Audio format: MP3")
286
+ elif audio_data.startswith(b'OggS'):
287
+ print(f"πŸ” DEBUG: Audio format: OGG")
288
+ elif audio_data.startswith(b'\x1a\x45\xdf\xa3'):
289
+ print(f"πŸ” DEBUG: Audio format: WebM")
290
+ else:
291
+ print(f"πŸ” DEBUG: Audio format: Unknown - first 4 bytes: {audio_data[:4].hex()}")
292
+
293
+ print(f"πŸ” DEBUG: Available WebSocket URLs: {self.stt_websocket_urls}")
294
 
295
  # Try each WebSocket URL
296
+ for i, ws_url in enumerate(self.stt_websocket_urls):
297
  try:
298
+ print(f"🎀 WebSocket STT: Attempt {i+1}/{len(self.stt_websocket_urls)} - Connecting to {ws_url}")
299
 
300
  # Improved connection with better timeout handling to prevent spinning
301
+ async with websockets.connect(
302
+ ws_url,
303
+ timeout=15,
304
+ ping_interval=None,
305
+ max_size=10 * 1024 * 1024, # 10MB max message size
306
+ compression=None # Disable compression for audio
307
+ ) as websocket:
308
+ print(f"πŸ” DEBUG: WebSocket connected successfully to {ws_url}")
309
+
310
+ # Check WebSocket state
311
+ print(f"πŸ” DEBUG: WebSocket state: {websocket.state}")
312
+ print(f"πŸ” DEBUG: WebSocket ping interval: {websocket.ping_interval}")
313
+ print(f"πŸ” DEBUG: WebSocket timeout: {websocket.timeout}")
314
  # Send audio chunk with unmute.sh protocol
315
  message = {
316
  "type": "stt_audio_chunk",
317
  "audio_data": audio_base64,
318
+ "language": "auto",
319
  "model_size": "base",
320
  "is_final": True # Use flush trick for best performance
321
  }
322
 
323
+ print(f"πŸ” DEBUG: Preparing to send message with keys: {list(message.keys())}")
324
+ print(f"πŸ” DEBUG: Message type: {message['type']}")
325
+ print(f"πŸ” DEBUG: Audio data length: {len(message['audio_data'])}")
326
+ print(f"πŸ” DEBUG: Model size: {message['model_size']}")
327
+ print(f"πŸ” DEBUG: Is final: {message['is_final']}")
328
 
329
+ message_json = json.dumps(message)
330
+ print(f"πŸ” DEBUG: JSON message size: {len(message_json)} chars")
 
331
 
332
+ print(f"🎀 WebSocket STT: Sending message to {ws_url}...")
333
+ await websocket.send(message_json)
334
+ print(f"🎀 WebSocket STT: Message sent successfully - audio data ({len(audio_data)} bytes)")
335
 
336
+ print(f"🎀 WebSocket STT: Waiting for response (timeout: 30s)...")
337
+ # Wait for response with timeout to prevent hanging
338
+ try:
339
+ response = await asyncio.wait_for(websocket.recv(), timeout=30.0)
340
+ print(f"πŸ” DEBUG: Raw response received: {response[:500]}...") # First 500 chars
341
 
342
+ result = json.loads(response)
343
+ print(f"🎀 WebSocket STT: Parsed response: {result}")
344
+
345
+ if result.get("type") == "stt_transcription" and result.get("text"):
346
+ transcription = result["text"].strip()
347
+ processing_time = result.get("processing_time", 0)
348
+ rtf = result.get("real_time_factor", 0)
349
+
350
+ print(f"🎀 WebSocket STT: SUCCESS - {transcription[:50]}... (RTF: {rtf:.2f}x)")
351
+ return transcription
352
+ elif result.get("type") == "stt_error":
353
+ error_msg = result.get("message", "Unknown error")
354
+ print(f"🎀 WebSocket STT: Service error - {error_msg}")
355
+ print(f"πŸ” DEBUG: Full error response: {result}")
356
+ continue # Try next URL
357
+ else:
358
+ print(f"🎀 WebSocket STT: Unexpected response format")
359
+ print(f"πŸ” DEBUG: Response type: {result.get('type', 'NO_TYPE')}")
360
+ print(f"πŸ” DEBUG: Response keys: {list(result.keys()) if isinstance(result, dict) else 'NOT_DICT'}")
361
+ continue
362
+ except asyncio.TimeoutError:
363
+ print(f"🎀 WebSocket STT: Response timeout after 30s for {ws_url}")
364
+ continue
365
+ except json.JSONDecodeError as e:
366
+ print(f"🎀 WebSocket STT: Invalid JSON response from {ws_url}: {e}")
367
+ print(f"πŸ” DEBUG: Raw response that failed to parse: {response}")
368
  continue
369
 
370
+ except websockets.exceptions.ConnectionClosed as e:
371
+ print(f"🎀 WebSocket STT: Connection closed for {ws_url} - {e}")
372
+ print(f"πŸ” DEBUG: Connection close code: {e.code if hasattr(e, 'code') else 'N/A'}")
373
+ print(f"πŸ” DEBUG: Connection close reason: {e.reason if hasattr(e, 'reason') else 'N/A'}")
374
+ continue
375
+ except websockets.exceptions.InvalidStatusCode as e:
376
+ print(f"🎀 WebSocket STT: Invalid status code for {ws_url} - {e}")
377
+ print(f"πŸ” DEBUG: Status code: {e.status_code}")
378
+ continue
379
+ except websockets.exceptions.WebSocketException as e:
380
+ print(f"🎀 WebSocket STT: WebSocket exception for {ws_url} - {e}")
381
+ print(f"πŸ” DEBUG: Exception type: {type(e).__name__}")
382
  continue
383
  except asyncio.TimeoutError:
384
+ print(f"🎀 WebSocket STT: Connection timeout for {ws_url}")
385
+ continue
386
+ except ConnectionRefusedError as e:
387
+ print(f"🎀 WebSocket STT: Connection refused for {ws_url} - {e}")
388
  continue
389
  except Exception as ws_error:
390
+ print(f"🎀 WebSocket STT: Unexpected error for {ws_url}: {ws_error}")
391
+ print(f"πŸ” DEBUG: Exception type: {type(ws_error).__name__}")
392
+ import traceback
393
+ traceback.print_exc()
394
  continue
395
 
396
+ # All WebSocket URLs failed
397
+ print(f"🎀 WebSocket STT: All {len(self.stt_websocket_urls)} WebSocket URLs failed")
398
+ print(f"πŸ” DEBUG: URLs attempted: {self.stt_websocket_urls}")
399
+ return "Error: All WebSocket STT services unavailable"
400
 
401
  except ImportError:
402
  print("🎀 WebSocket STT: websockets library not available")
403
  return "Error: WebSocket support not available"
404
  except Exception as e:
405
+ print(f"🎀 WebSocket STT: Fatal error in _call_websocket_stt_service: {e}")
406
+ print(f"πŸ” DEBUG: Exception type: {type(e).__name__}")
407
+ import traceback
408
+ traceback.print_exc()
409
+ return f"Error: WebSocket STT fatal error - {str(e)}"
410
 
411
  async def _call_mcp_stt_service(self, audio_file_path: str) -> str:
412
  """Call MCP STT service with HTTP fallback."""