Spaces:
Running

michdubai commited on
Commit
35dbe8b
·
verified ·
1 Parent(s): eb421f2

Update backend/gemini/client.py

Browse files
Files changed (1) hide show
  1. backend/gemini/client.py +19 -28
backend/gemini/client.py CHANGED
@@ -32,7 +32,7 @@ class GeminiConnection:
32
  if not self.config:
33
  raise ValueError("Configuration required")
34
 
35
- # Build config per official documentation
36
  config = types.LiveConnectConfig(
37
  response_modalities=["AUDIO"],
38
  system_instruction=types.Content(
@@ -76,27 +76,28 @@ class GeminiConnection:
76
  return resumption_handle is not None
77
 
78
  async def _receive_loop(self):
79
- """Background task to receive messages"""
80
  try:
81
  async for msg in self.session.receive():
82
- # Check for session resumption update
83
  if hasattr(msg, 'session_resumption_update') and msg.session_resumption_update:
84
  update = msg.session_resumption_update
85
  if update.resumable and update.new_handle:
86
  self.resumption_handle = update.new_handle
87
  print(f"[DEBUG][{self.client_id}] 🔑 Session handle saved")
88
 
89
- await self._receive_queue.put(msg)
 
 
 
 
90
  except Exception as e:
91
  if "closed" not in str(e).lower():
92
  print(f"[DEBUG][{self.client_id}] Receive loop ended: {e}")
93
  await self._receive_queue.put(None)
94
 
95
  async def send_audio(self, data: str) -> None:
96
- """
97
- Send audio data with correct sampling rate.
98
- CRITICAL: Must specify rate=16000 in mime_type
99
- """
100
  if not self.session:
101
  return
102
  try:
@@ -104,7 +105,7 @@ class GeminiConnection:
104
  await self.session.send_realtime_input(
105
  audio=types.Blob(
106
  data=audio_bytes,
107
- mime_type="audio/pcm;rate=16000" # CRITICAL: Must specify sampling rate
108
  )
109
  )
110
  except Exception as e:
@@ -123,7 +124,7 @@ class GeminiConnection:
123
  print(f"[DEBUG][{self.client_id}] Send text error: {e}")
124
 
125
  async def send_image(self, data: str) -> None:
126
- """Send image data"""
127
  if not self.session:
128
  return
129
  try:
@@ -149,22 +150,17 @@ class GeminiConnection:
149
  print(f"[DEBUG][{self.client_id}] Send file error: {e}")
150
 
151
  async def receive(self) -> Optional[Dict]:
152
- """Get next message from Gemini with frontend-compatible structure"""
153
  if not self._receive_queue:
154
  return None
155
  try:
156
  msg = await self._receive_queue.get()
157
- if msg is None:
158
- return None
159
- return self._parse_message(msg)
160
- except Exception as e:
161
  return None
162
 
163
  def _parse_message(self, msg) -> Dict:
164
- """
165
- Convert SDK message to flat structure expected by frontend.
166
- Frontend expects {type: '...', ...} format.
167
- """
168
 
169
  # Check for GoAway notification first
170
  if hasattr(msg, 'go_away') and msg.go_away:
@@ -173,19 +169,14 @@ class GeminiConnection:
173
  "time_left": msg.go_away.time_left
174
  }
175
 
176
- # Check server content for flags that need immediate frontend events
177
  if hasattr(msg, 'server_content') and msg.server_content:
178
  sc = msg.server_content
179
 
180
- # Interruption - frontend should discard audio buffer
181
  if getattr(sc, 'interrupted', False):
182
  return {"type": "interrupted"}
183
-
184
- # Turn complete - frontend can update UI
185
  if getattr(sc, 'turn_complete', False):
186
  return {"type": "turn_complete"}
187
-
188
- # Generation complete - generation finished
189
  if getattr(sc, 'generation_complete', False):
190
  return {"type": "generation_complete"}
191
 
@@ -198,7 +189,7 @@ class GeminiConnection:
198
  "resumable": update.resumable
199
  }
200
 
201
- # Full server content with data
202
  if hasattr(msg, 'server_content') and msg.server_content:
203
  sc = msg.server_content
204
  result = {"type": "server_content"}
@@ -209,7 +200,7 @@ class GeminiConnection:
209
  if hasattr(sc, 'output_transcription') and sc.output_transcription:
210
  result["gemini_text"] = sc.output_transcription.text
211
 
212
- # Audio response
213
  if hasattr(sc, 'model_turn') and sc.model_turn:
214
  for part in sc.model_turn.parts:
215
  if hasattr(part, 'inline_data') and part.inline_data:
@@ -238,4 +229,4 @@ class GeminiConnection:
238
  finally:
239
  self._context = None
240
  self.session = None
241
- print(f"[DEBUG][{self.client_id}] 🧹 Connection closed") # Fixed syntax
 
32
  if not self.config:
33
  raise ValueError("Configuration required")
34
 
35
+ # Fix: Accept AUDIO and enable VIDEO input handling capabilities
36
  config = types.LiveConnectConfig(
37
  response_modalities=["AUDIO"],
38
  system_instruction=types.Content(
 
76
  return resumption_handle is not None
77
 
78
  async def _receive_loop(self):
79
+ """Background task to receive messages - parsed instantly to prevent keepalive drops"""
80
  try:
81
  async for msg in self.session.receive():
82
+ # Check for session resumption update instantly
83
  if hasattr(msg, 'session_resumption_update') and msg.session_resumption_update:
84
  update = msg.session_resumption_update
85
  if update.resumable and update.new_handle:
86
  self.resumption_handle = update.new_handle
87
  print(f"[DEBUG][{self.client_id}] 🔑 Session handle saved")
88
 
89
+ # Parse right away to clear the low-level buffer and minimize serialization weight in the queue
90
+ parsed_msg = self._parse_message(msg)
91
+ if parsed_msg:
92
+ await self._receive_queue.put(parsed_msg)
93
+
94
  except Exception as e:
95
  if "closed" not in str(e).lower():
96
  print(f"[DEBUG][{self.client_id}] Receive loop ended: {e}")
97
  await self._receive_queue.put(None)
98
 
99
  async def send_audio(self, data: str) -> None:
100
+ """Send audio data with correct sampling rate"""
 
 
 
101
  if not self.session:
102
  return
103
  try:
 
105
  await self.session.send_realtime_input(
106
  audio=types.Blob(
107
  data=audio_bytes,
108
+ mime_type="audio/pcm;rate=16000"
109
  )
110
  )
111
  except Exception as e:
 
124
  print(f"[DEBUG][{self.client_id}] Send text error: {e}")
125
 
126
  async def send_image(self, data: str) -> None:
127
+ """Send image data frame"""
128
  if not self.session:
129
  return
130
  try:
 
150
  print(f"[DEBUG][{self.client_id}] Send file error: {e}")
151
 
152
  async def receive(self) -> Optional[Dict]:
153
+ """Get pre-parsed message from the queue"""
154
  if not self._receive_queue:
155
  return None
156
  try:
157
  msg = await self._receive_queue.get()
158
+ return msg # Already safely parsed by the loop
159
+ except Exception:
 
 
160
  return None
161
 
162
  def _parse_message(self, msg) -> Dict:
163
+ """Convert SDK message to flat structure expected by frontend"""
 
 
 
164
 
165
  # Check for GoAway notification first
166
  if hasattr(msg, 'go_away') and msg.go_away:
 
169
  "time_left": msg.go_away.time_left
170
  }
171
 
172
+ # Check server content flags
173
  if hasattr(msg, 'server_content') and msg.server_content:
174
  sc = msg.server_content
175
 
 
176
  if getattr(sc, 'interrupted', False):
177
  return {"type": "interrupted"}
 
 
178
  if getattr(sc, 'turn_complete', False):
179
  return {"type": "turn_complete"}
 
 
180
  if getattr(sc, 'generation_complete', False):
181
  return {"type": "generation_complete"}
182
 
 
189
  "resumable": update.resumable
190
  }
191
 
192
+ # Full server content payloads
193
  if hasattr(msg, 'server_content') and msg.server_content:
194
  sc = msg.server_content
195
  result = {"type": "server_content"}
 
200
  if hasattr(sc, 'output_transcription') and sc.output_transcription:
201
  result["gemini_text"] = sc.output_transcription.text
202
 
203
+ # Audio media responses
204
  if hasattr(sc, 'model_turn') and sc.model_turn:
205
  for part in sc.model_turn.parts:
206
  if hasattr(part, 'inline_data') and part.inline_data:
 
229
  finally:
230
  self._context = None
231
  self.session = None
232
+ print(f"[DEBUG][{self.client_id}] 🧹 Connection closed")