from fastapi import APIRouter, WebSocket, WebSocketDisconnect, Depends, Query from app.api.deps import get_current_user from app.core.security import decode_access_token from app.services.voice_manager import voice_manager, VoiceSession from uuid import uuid4 import logging import json router = APIRouter() logger = logging.getLogger(__name__) @router.websocket("/stream") async def voice_stream( websocket: WebSocket, token: str = Query(...) ): """ Real-time voice streaming endpoint. Client sends audio chunks (binary). Server sends audio chunks (binary) + metadata (text). """ await websocket.accept() # Authenticate via Token (since WS headers are hard in standard JS WebSocket) try: payload = decode_access_token(token) user_id = payload.get("sub") # In a real app we'd fetch the user and tenant object here. # For speed: decode tenant_id if available or assume 'default' for now. # But we need tenant_id for context. # For MVP: Use a dummy tenant or extract from token if custom claim. session_id = str(uuid4()) # Mock tenant ID - assume single tenant demo or extracted properly tenant_id = "demo-tenant" session = VoiceSession(session_id, tenant_id) logger.info(f"🔌 WS Connected: {user_id} (Session {session_id})") await websocket.send_text(json.dumps({"status": "connected", "session_id": session_id})) except Exception as e: logger.error(f"WS Auth failed: {e}") await websocket.close(code=4003) return try: while True: # Receive message (can be bytes or text) message = await websocket.receive() if "bytes" in message: chunk = message["bytes"] # Process audio chunk (VAD, buffer) # Currently returns None until turn complete (mock VAD) # If we want streaming VAD, we'd check here. # For MVP, assume client sends small chunks. # VoiceManager currently adds to buffer. await voice_manager.process_audio_chunk(session, chunk) elif "text" in message: data = json.loads(message["text"]) msg_type = data.get("type") # Explicit "Turn Finished" signal from client VAD if msg_type == "commit": logger.info("🎤 Client committed turn.") # Force process await websocket.send_text(json.dumps({"status": "thinking"})) audio_response = await voice_manager.process_turn(session) if audio_response: await websocket.send_text(json.dumps({"status": "speaking"})) # Send audio as binary await websocket.send_bytes(audio_response) await websocket.send_text(json.dumps({"status": "listening"})) else: await websocket.send_text(json.dumps({"status": "error", "message": "No response"})) await websocket.send_text(json.dumps({"status": "listening"})) elif msg_type == "ping": await websocket.send_text(json.dumps({"type": "pong"})) except WebSocketDisconnect: logger.info(f"🔌 WS Disconnected: {session_id}") except Exception as e: logger.error(f"WS Error: {e}") try: await websocket.close() except: pass