Spaces:
Running

michdubai commited on
Commit
ae1da4e
·
verified ·
1 Parent(s): 52aa3da

Update backend/gemini/client.py

Browse files
Files changed (1) hide show
  1. backend/gemini/client.py +54 -33
backend/gemini/client.py CHANGED
@@ -58,7 +58,7 @@ class GeminiConnection:
58
  )
59
  )
60
 
61
- # IMPORTANT: connect() returns an async context manager, not a session directly
62
  self._context = self.client.aio.live.connect(
63
  model=self.model,
64
  config=config
@@ -93,12 +93,20 @@ class GeminiConnection:
93
  await self._receive_queue.put(None)
94
 
95
  async def send_audio(self, data: str) -> None:
96
- """Send audio data"""
 
 
 
97
  if not self.session:
98
  return
99
  try:
100
  audio_bytes = base64.b64decode(data) if isinstance(data, str) else data
101
- await self.session.send_realtime_input(audio=types.Blob(data=audio_bytes, mime_type="audio/pcm"))
 
 
 
 
 
102
  except Exception as e:
103
  if "closed" not in str(e).lower():
104
  print(f"[DEBUG][{self.client_id}] Send audio error: {e}")
@@ -120,7 +128,9 @@ class GeminiConnection:
120
  return
121
  try:
122
  image_bytes = base64.b64decode(data) if isinstance(data, str) else data
123
- await self.session.send_realtime_input(video=types.Blob(data=image_bytes, mime_type="image/jpeg"))
 
 
124
  except Exception as e:
125
  if "closed" not in str(e).lower():
126
  print(f"[DEBUG][{self.client_id}] Send image error: {e}")
@@ -139,7 +149,7 @@ class GeminiConnection:
139
  print(f"[DEBUG][{self.client_id}] Send file error: {e}")
140
 
141
  async def receive(self) -> Optional[Dict]:
142
- """Get next message from Gemini"""
143
  if not self._receive_queue:
144
  return None
145
  try:
@@ -151,55 +161,66 @@ class GeminiConnection:
151
  return None
152
 
153
  def _parse_message(self, msg) -> Dict:
154
- """Convert SDK message to JSON-serializable dict"""
155
- result = {}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
156
 
157
  # Session resumption update
158
  if hasattr(msg, 'session_resumption_update') and msg.session_resumption_update:
159
  update = msg.session_resumption_update
160
- result["session_resumption_update"] = {
 
161
  "new_handle": update.new_handle,
162
  "resumable": update.resumable
163
  }
164
 
165
- # GoAway notification
166
- if hasattr(msg, 'go_away') and msg.go_away:
167
- result["go_away"] = {"time_left": msg.go_away.time_left}
168
-
169
- # Server content
170
  if hasattr(msg, 'server_content') and msg.server_content:
171
  sc = msg.server_content
172
- result["server_content"] = {}
173
 
174
  # Transcriptions
175
  if hasattr(sc, 'input_transcription') and sc.input_transcription:
176
- result["server_content"]["input_transcription"] = {"text": sc.input_transcription.text}
177
  if hasattr(sc, 'output_transcription') and sc.output_transcription:
178
- result["server_content"]["output_transcription"] = {"text": sc.output_transcription.text}
179
 
180
  # Audio response
181
  if hasattr(sc, 'model_turn') and sc.model_turn:
182
- result["server_content"]["model_turn"] = {"parts": []}
183
  for part in sc.model_turn.parts:
184
  if hasattr(part, 'inline_data') and part.inline_data:
185
- result["server_content"]["model_turn"]["parts"].append({
186
- "inline_data": {
187
- "data": base64.b64encode(part.inline_data.data).decode('utf-8'),
188
- "mime_type": part.inline_data.mime_type
189
- }
190
- })
191
  elif hasattr(part, 'text') and part.text:
192
- result["server_content"]["model_turn"]["parts"].append({"text": part.text})
193
 
194
- # Status flags
195
- if hasattr(sc, 'interrupted') and sc.interrupted:
196
- result["server_content"]["interrupted"] = True
197
- if hasattr(sc, 'turn_complete') and sc.turn_complete:
198
- result["server_content"]["turn_complete"] = True
199
- if hasattr(sc, 'generation_complete') and sc.generation_complete:
200
- result["server_content"]["generation_complete"] = True
201
 
202
- return result
203
 
204
  async def check_connection(self) -> bool:
205
  return self.session is not None and self._receive_task is not None
@@ -217,4 +238,4 @@ class GeminiConnection:
217
  finally:
218
  self._context = None
219
  self.session = None
220
- print(f"[DEBUG][{self.client_id}] 🧹 Connection closed")
 
58
  )
59
  )
60
 
61
+ # Connect using async context manager
62
  self._context = self.client.aio.live.connect(
63
  model=self.model,
64
  config=config
 
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:
103
  audio_bytes = base64.b64decode(data) if isinstance(data, str) else data
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:
111
  if "closed" not in str(e).lower():
112
  print(f"[DEBUG][{self.client_id}] Send audio error: {e}")
 
128
  return
129
  try:
130
  image_bytes = base64.b64decode(data) if isinstance(data, str) else data
131
+ await self.session.send_realtime_input(
132
+ video=types.Blob(data=image_bytes, mime_type="image/jpeg")
133
+ )
134
  except Exception as e:
135
  if "closed" not in str(e).lower():
136
  print(f"[DEBUG][{self.client_id}] Send image error: {e}")
 
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:
 
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:
171
+ return {
172
+ "type": "go_away",
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
 
192
  # Session resumption update
193
  if hasattr(msg, 'session_resumption_update') and msg.session_resumption_update:
194
  update = msg.session_resumption_update
195
+ return {
196
+ "type": "session_resumption",
197
  "new_handle": update.new_handle,
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"}
205
 
206
  # Transcriptions
207
  if hasattr(sc, 'input_transcription') and sc.input_transcription:
208
+ result["user_text"] = sc.input_transcription.text
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:
216
+ result["audio"] = base64.b64encode(part.inline_data.data).decode('utf-8')
217
+ result["mime_type"] = part.inline_data.mime_type
 
 
 
 
218
  elif hasattr(part, 'text') and part.text:
219
+ result["gemini_text"] = part.text
220
 
221
+ return result
 
 
 
 
 
 
222
 
223
+ return {}
224
 
225
  async def check_connection(self) -> bool:
226
  return self.session is not None and self._receive_task is not None
 
238
  finally:
239
  self._context = None
240
  self.session = None
241
+ print(f"[DEBUG][self.client_id}] 🧹 Connection closed")