Spaces:
Running

File size: 3,724 Bytes
20ee727
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
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