Spaces:
michdubai
/
Sleeping

michdubai commited on
Commit
96cf686
·
verified ·
1 Parent(s): ac98860

Update backend/routes/websocket.py

Browse files
Files changed (1) hide show
  1. backend/routes/websocket.py +78 -42
backend/routes/websocket.py CHANGED
@@ -5,123 +5,159 @@ from typing import Dict
5
 
6
  from gemini.client import GeminiConnection
7
 
 
8
  router = APIRouter()
 
 
9
  connections: Dict[str, GeminiConnection] = {}
10
 
11
  @router.websocket("/ws/{client_id}")
12
  async def websocket_endpoint(websocket: WebSocket, client_id: str):
 
 
 
13
  await websocket.accept()
14
  print(f"Client connected: {client_id}")
15
 
 
16
  gemini = GeminiConnection()
17
  connections[client_id] = gemini
18
 
19
  try:
 
20
  initial_msg = await websocket.receive_json()
21
  if initial_msg.get("type") != "config":
22
  raise ValueError("First WebSocket message must be configuration.")
23
 
 
24
  config_data = initial_msg.get("config", {})
25
  gemini.set_config(config_data)
 
26
 
 
27
  await gemini.connect()
 
28
 
 
29
  receive_task = asyncio.create_task(receive_from_client(websocket, gemini))
30
  send_task = asyncio.create_task(send_to_frontend(websocket, gemini))
31
 
 
32
  done, pending = await asyncio.wait(
33
  [receive_task, send_task],
34
  return_when=asyncio.FIRST_EXCEPTION
35
  )
36
 
 
37
  for task in pending:
38
  task.cancel()
39
 
 
40
  for task in done:
41
  if task.exception():
42
  raise task.exception()
43
 
44
  except WebSocketDisconnect:
45
- print(f"Client disconnected: {client_id}")
 
 
 
 
 
 
46
  except Exception as e:
47
- print(f"Error in WebSocket instance {client_id}: {e}")
48
  try:
49
  await websocket.send_json({"type": "error", "message": f"Server error: {str(e)}"})
50
  except:
51
  pass
52
  finally:
 
53
  await gemini.close()
54
  if client_id in connections:
55
  del connections[client_id]
 
 
56
 
57
  async def receive_from_client(websocket: WebSocket, gemini: GeminiConnection):
58
- """Process incoming audio chunks or parameters sent by the client browser"""
 
 
59
  while True:
60
  try:
 
61
  message = await websocket.receive()
 
 
62
  if message["type"] == "websocket.disconnect":
 
63
  return
64
 
 
65
  content = json.loads(message["text"])
66
- msg_type = content["type"]
67
 
 
68
  if msg_type == "audio":
69
  await gemini.send_audio(content["data"])
70
  elif msg_type == "image":
71
  await gemini.send_image(content["data"])
72
  elif msg_type == "text":
73
  await gemini.send_text(content["data"])
 
 
74
 
 
 
 
 
75
  except Exception as e:
76
- print(f"Error processing client request channel: {e}")
77
  break
78
 
 
79
  async def send_to_frontend(websocket: WebSocket, gemini: GeminiConnection):
80
- """Extract and forward dialogue transcripts downstream to the client interface"""
 
 
81
  while True:
82
  try:
 
83
  msg = await gemini.receive()
84
  if not msg:
85
  continue
86
 
 
87
  response = json.loads(msg)
 
88
 
89
- # The API returns transcript parameters directly inside the core response frame
90
- if "inputTranscription" in response:
91
- user_text = response["inputTranscription"].get("text", "")
92
- if user_text:
93
- await websocket.send_json({"type": "user_text", "text": user_text})
94
-
95
- if "outputTranscription" in response:
96
- gemini_text = response["outputTranscription"].get("text", "")
97
- if gemini_text:
98
- await websocket.send_json({"type": "gemini_text", "text": gemini_text})
99
-
100
- if "serverContent" in response:
101
- server_content = response["serverContent"]
102
-
103
- # Fallback matching structure for streaming content
104
- if "inputTranscription" in server_content:
105
- user_text = server_content["inputTranscription"].get("text", "")
106
- if user_text:
107
- await websocket.send_json({"type": "user_text", "text": user_text})
108
-
109
- if "outputTranscription" in server_content:
110
- gemini_text = server_content["outputTranscription"].get("text", "")
111
- if gemini_text:
112
- await websocket.send_json({"type": "gemini_text", "text": gemini_text})
113
-
114
- if "modelTurn" in server_content:
115
- parts = server_content["modelTurn"].get("parts", [])
116
- for part in parts:
117
- if "inlineData" in part:
118
- await websocket.send_json({"type": "audio", "data": part["inlineData"]["data"]})
119
- elif "text" in part:
120
- await websocket.send_json({"type": "text", "text": part["text"]})
121
-
122
- if server_content.get("turnComplete"):
123
- await websocket.send_json({"type": "turn_complete", "data": True})
124
 
125
  except Exception as e:
126
- print(f"Error handling Gemini socket message output frame: {e}")
127
  break
 
5
 
6
  from gemini.client import GeminiConnection
7
 
8
+ # Create router
9
  router = APIRouter()
10
+
11
+ # Store active connections
12
  connections: Dict[str, GeminiConnection] = {}
13
 
14
  @router.websocket("/ws/{client_id}")
15
  async def websocket_endpoint(websocket: WebSocket, client_id: str):
16
+ """
17
+ WebSocket endpoint for real-time communication with Gemini API
18
+ """
19
  await websocket.accept()
20
  print(f"Client connected: {client_id}")
21
 
22
+ # Create Gemini connection for this client
23
  gemini = GeminiConnection()
24
  connections[client_id] = gemini
25
 
26
  try:
27
+ # 1) The first message from front-end must be "config"
28
  initial_msg = await websocket.receive_json()
29
  if initial_msg.get("type") != "config":
30
  raise ValueError("First WebSocket message must be configuration.")
31
 
32
+ # Extract and apply configuration
33
  config_data = initial_msg.get("config", {})
34
  gemini.set_config(config_data)
35
+ print(f"Received config for client {client_id}")
36
 
37
+ # 2) Connect to Gemini (sends 'setup' message)
38
  await gemini.connect()
39
+ print(f"Gemini connected for client {client_id}")
40
 
41
+ # 3) Start tasks: reading from client and reading from Gemini
42
  receive_task = asyncio.create_task(receive_from_client(websocket, gemini))
43
  send_task = asyncio.create_task(send_to_frontend(websocket, gemini))
44
 
45
+ # Wait for either task to complete (or fail)
46
  done, pending = await asyncio.wait(
47
  [receive_task, send_task],
48
  return_when=asyncio.FIRST_EXCEPTION
49
  )
50
 
51
+ # Cancel any pending tasks
52
  for task in pending:
53
  task.cancel()
54
 
55
+ # Re-raise exceptions from completed tasks
56
  for task in done:
57
  if task.exception():
58
  raise task.exception()
59
 
60
  except WebSocketDisconnect:
61
+ print(f"Client disconnected smoothly: {client_id}")
62
+ except ValueError as e:
63
+ print(f"Validation error for client {client_id}: {e}")
64
+ try:
65
+ await websocket.send_json({"type": "error", "message": str(e)})
66
+ except:
67
+ pass
68
  except Exception as e:
69
+ print(f"Error in WebSocket handler for client {client_id}: {e}")
70
  try:
71
  await websocket.send_json({"type": "error", "message": f"Server error: {str(e)}"})
72
  except:
73
  pass
74
  finally:
75
+ # Clean up resources
76
  await gemini.close()
77
  if client_id in connections:
78
  del connections[client_id]
79
+ print(f"Connection closed for client {client_id}")
80
+
81
 
82
  async def receive_from_client(websocket: WebSocket, gemini: GeminiConnection):
83
+ """
84
+ Process incoming messages from the client browser
85
+ """
86
  while True:
87
  try:
88
+ # Receive WebSocket message
89
  message = await websocket.receive()
90
+
91
+ # Handle disconnection
92
  if message["type"] == "websocket.disconnect":
93
+ print("Client disconnected.")
94
  return
95
 
96
+ # Parse the message content
97
  content = json.loads(message["text"])
98
+ msg_type = content.get("type")
99
 
100
+ # Route to appropriate handler based on message type
101
  if msg_type == "audio":
102
  await gemini.send_audio(content["data"])
103
  elif msg_type == "image":
104
  await gemini.send_image(content["data"])
105
  elif msg_type == "text":
106
  await gemini.send_text(content["data"])
107
+ else:
108
+ print(f"Unknown message type from client: {msg_type}")
109
 
110
+ except json.JSONDecodeError:
111
+ print("Received invalid JSON from client")
112
+ except KeyError as e:
113
+ print(f"Missing required field in client message: {e}")
114
  except Exception as e:
115
+ print(f"Error processing client message: {e}")
116
  break
117
 
118
+
119
  async def send_to_frontend(websocket: WebSocket, gemini: GeminiConnection):
120
+ """
121
+ Forward Gemini responses to the client browser with proper type grouping
122
+ """
123
  while True:
124
  try:
125
+ # Get next message from Gemini
126
  msg = await gemini.receive()
127
  if not msg:
128
  continue
129
 
130
+ # Parse response
131
  response = json.loads(msg)
132
+ server_content = response.get("serverContent", {})
133
 
134
+ # 1. Capture User Speech-to-Text Transcription Echoes
135
+ if "userTurn" in server_content:
136
+ parts = server_content["userTurn"].get("parts", [])
137
+ for part in parts:
138
+ if "text" in part:
139
+ await websocket.send_json({
140
+ "type": "user_text",
141
+ "text": part["text"]
142
+ })
143
+
144
+ # 2. Capture Gemini output payload frames (audio and text tokens)
145
+ if "modelTurn" in server_content:
146
+ parts = server_content["modelTurn"].get("parts", [])
147
+ for part in parts:
148
+ if "inlineData" in part:
149
+ # Audio data from Gemini (base64 PCM)
150
+ audio_data = part["inlineData"]["data"]
151
+ await websocket.send_json({"type": "audio", "data": audio_data})
152
+ elif "text" in part:
153
+ # Text tokens belonging explicitly to Gemini
154
+ text_data = part["text"]
155
+ await websocket.send_json({"type": "gemini_text", "text": text_data})
156
+
157
+ # 3. Handle global round-trip turn completions
158
+ if server_content.get("turnComplete"):
159
+ await websocket.send_json({"type": "turn_complete", "data": True})
 
 
 
 
 
 
 
 
 
160
 
161
  except Exception as e:
162
+ print(f"Error processing Gemini response: {e}")
163
  break