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>
- 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(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
-
|
| 295 |
-
print(f"
|
|
|
|
|
|
|
|
|
|
| 296 |
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
result = json.loads(response)
|
| 300 |
|
| 301 |
-
print(f"π€ WebSocket STT:
|
|
|
|
|
|
|
| 302 |
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
|
|
|
| 307 |
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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:
|
|
|
|
|
|
|
|
|
|
| 323 |
continue
|
| 324 |
except Exception as ws_error:
|
| 325 |
-
print(f"π€ WebSocket STT:
|
|
|
|
|
|
|
|
|
|
| 326 |
continue
|
| 327 |
|
| 328 |
-
#
|
| 329 |
-
|
|
|
|
|
|
|
| 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:
|
| 336 |
-
|
|
|
|
|
|
|
|
|
|
| 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."""
|