datbkpro commited on
Commit
995e5f1
·
verified ·
1 Parent(s): 27b3d88

Update ui/tabs.py

Browse files
Files changed (1) hide show
  1. ui/tabs.py +71 -176
ui/tabs.py CHANGED
@@ -60,22 +60,22 @@ def create_gemini_realtime_tab():
60
 
61
  with gr.Blocks() as gemini_tab:
62
  gr.Markdown("""
63
- # 🎯 Gemini Realtime API
64
- **Audio Streaming Thời Gian Thực với Google Gemini**
65
  """)
66
 
67
  with gr.Row():
68
  with gr.Column(scale=1):
69
  # Connection controls
70
  with gr.Group():
71
- gr.Markdown("### 🔗 Kết nối Audio")
72
 
73
  api_key = gr.Textbox(
74
  label="Gemini API Key",
75
  type="password",
76
  placeholder="Nhập API key của bạn...",
77
  value=os.getenv("GEMINI_API_KEY", ""),
78
- info="Cần cho Audio Streaming"
79
  )
80
 
81
  voice_select = gr.Dropdown(
@@ -106,31 +106,17 @@ def create_gemini_realtime_tab():
106
  )
107
 
108
  with gr.Column(scale=2):
109
- # Chat interface
110
- with gr.Group():
111
- gr.Markdown("### 💬 Hội thoại")
112
-
113
- chatbot = gr.Chatbot(
114
- label="Gemini Chat",
115
- type="messages",
116
- height=300,
117
- show_copy_button=True,
118
- value=[]
119
- )
120
-
121
  # Audio Streaming Interface
122
  with gr.Group():
123
  gr.Markdown("### 🎤 Audio Streaming")
124
 
125
- with gr.Row():
126
- start_audio_btn = gr.Button("🎙️ Bắt đầu nói", variant="primary")
127
- stop_audio_btn = gr.Button("⏹️ Dừng nói", variant="secondary")
128
-
129
- transcription_display = gr.Textbox(
130
- label="Bạn nói",
131
- interactive=False,
132
- lines=2,
133
- placeholder="Văn bản nhận diện sẽ hiển thị ở đây..."
134
  )
135
 
136
  # Audio output for Gemini responses
@@ -140,24 +126,22 @@ def create_gemini_realtime_tab():
140
  autoplay=True
141
  )
142
 
143
- # Audio input for user
144
- audio_input = gr.Audio(
145
- label="🎤 Micro của bạn",
146
- sources=["microphone"],
147
- type="numpy",
148
- interactive=True
149
  )
150
 
151
  # State management
152
  connection_state = gr.State(value=False)
153
- audio_streaming_state = gr.State(value=False)
154
  gemini_service_state = gr.State(value=None)
155
 
156
- async def connect_gemini(api_key, voice_name, current_chat):
157
  """Kết nối Gemini Audio Streaming"""
158
  try:
159
  if not api_key:
160
- return False, "❌ Vui lòng nhập API Key", "Chưa kết nối", current_chat, None
161
 
162
  service = GeminiRealtimeService(api_key)
163
 
@@ -165,18 +149,10 @@ def create_gemini_realtime_tab():
165
  async def handle_gemini_callback(data):
166
  if data['type'] == 'status':
167
  gr.Info(data['message'])
168
- return data['message'], data['message'], current_chat
169
  elif data['type'] == 'text':
170
- # Cập nhật transcription
171
- new_chat = current_chat + [{"role": "assistant", "content": data['content']}]
172
- return f"📝 {data['content']}", data['content'], new_chat
173
- elif data['type'] == 'audio':
174
- # Xử lý audio stream (sẽ được xử lý trong audio output)
175
- return "🔊 Đang nhận audio...", "audio_received", current_chat
176
  elif data['type'] == 'error':
177
  gr.Warning(data['message'])
178
- return f"❌ {data['message']}", data['message'], current_chat
179
- return "Unknown", "unknown", current_chat
180
 
181
  success = await service.start_session(
182
  voice_name=voice_name,
@@ -184,166 +160,82 @@ def create_gemini_realtime_tab():
184
  )
185
 
186
  if success:
187
- welcome_msg = f"Xin chào! Tôi Gemini với giọng {voice_name}. Hãy bắt đầu nói chuyện!"
188
- new_chat = current_chat + [{"role": "assistant", "content": welcome_msg}]
189
- info_msg = f"Đã kết nối audio streaming - Giọng: {voice_name}"
190
- return True, "✅ Đã kết nối Audio Streaming", info_msg, new_chat, service
191
  else:
192
- return False, "❌ Không thể kết nối audio", "Lỗi kết nối", current_chat, None
193
 
194
  except Exception as e:
195
  error_msg = f"❌ Lỗi kết nối: {str(e)}"
196
- return False, error_msg, f"Lỗi: {str(e)}", current_chat, None
197
 
198
- async def disconnect_gemini(current_chat, service):
199
  """Ngắt kết nối"""
200
  if service:
201
  await service.close()
202
-
203
- new_chat = current_chat + [{"role": "assistant", "content": "Đã ngắt kết nối audio streaming."}]
204
- return False, "🔌 Đã ngắt kết nối", "Ngắt kết nối", new_chat, None
205
-
206
- async def start_audio_stream(service, audio_state):
207
- """Bắt đầu stream audio"""
208
- if not service or not service.is_active:
209
- return False, "❌ Chưa kết nối. Vui lòng kết nối trước."
210
-
211
- return True, "🎙️ Đang nghe... Hãy bắt đầu nói!"
212
-
213
- async def stop_audio_stream(service, audio_state):
214
- """Dừng stream audio"""
215
- return False, "⏹️ Đã dừng thu âm"
216
 
217
- async def process_audio_input(audio_data, sample_rate, service, current_chat):
218
- """Xử lý audio input từ user"""
219
  if not service or not service.is_active:
220
- return current_chat, "❌ Chưa kết nối audio", current_chat
221
 
222
  if audio_data is None:
223
- return current_chat, "⚠️ Không có audio input", current_chat
224
 
225
  try:
226
  # Gửi audio đến Gemini
227
  success = await service.send_audio_chunk(audio_data, sample_rate)
228
 
229
- if success:
230
- # Nhận audio response từ Gemini
 
 
 
 
 
 
231
  audio_response = await service.receive_audio()
 
 
 
 
 
 
232
 
233
- if audio_response:
234
- resp_sample_rate, resp_audio_data = audio_response
235
- # Lưu audio response để phát
236
- audio_path = f"gemini_response_{int(asyncio.get_event_loop().time())}.wav"
237
  import scipy.io.wavfile as wavfile
238
- wavfile.write(audio_path, resp_sample_rate, resp_audio_data)
239
-
240
- info_msg = "🔊 Đã nhận phản hồi audio từ Gemini"
241
- return current_chat, info_msg, audio_path
242
- else:
243
- info_msg = "⏳ Đang chờ phản hồi audio..."
244
- return current_chat, info_msg, None
245
  else:
246
- return current_chat, " Lỗi gửi audio", current_chat
247
 
248
  except Exception as e:
249
  error_msg = f"❌ Lỗi xử lý audio: {str(e)}"
250
- return current_chat, error_msg, current_chat
251
-
252
- async def send_text_message(message, current_chat, service):
253
- """Gửi tin nhắn text (fallback)"""
254
- if not service or not service.is_active:
255
- error_msg = "❌ Chưa kết nối. Vui lòng kết nối trước."
256
- new_chat = current_chat + [{"role": "user", "content": message}, {"role": "assistant", "content": error_msg}]
257
- return new_chat, "Lỗi kết nối", new_chat
258
-
259
- if not message.strip():
260
- return current_chat, "⚠️ Vui lòng nhập tin nhắn", current_chat
261
-
262
- try:
263
- # Hiển thị tin nhắn user
264
- new_chat = current_chat + [{"role": "user", "content": message}]
265
-
266
- # Gửi text
267
- response = await service.send_text(message)
268
-
269
- # Cập nhật response
270
- new_chat = new_chat + [{"role": "assistant", "content": response}]
271
-
272
- return new_chat, f"✅ Đã nhận phản hồi ({len(response)} ký tự)", new_chat
273
-
274
- except Exception as e:
275
- error_msg = f"❌ Lỗi: {str(e)}"
276
- new_chat = current_chat + [{"role": "user", "content": message}, {"role": "assistant", "content": error_msg}]
277
- return new_chat, error_msg, new_chat
278
-
279
- def clear_chat():
280
- """Xóa chat"""
281
- return [], "🧹 Đã xóa chat", []
282
-
283
- # Thêm text input
284
- with gr.Row():
285
- text_input = gr.Textbox(
286
- label="Hoặc nhập tin nhắn text",
287
- placeholder="Nhập tin nhắn text và nhấn Enter...",
288
- scale=4
289
- )
290
- send_text_btn = gr.Button("📤 Gửi text", scale=1)
291
 
292
  # Event handlers
293
  connect_btn.click(
294
  connect_gemini,
295
- inputs=[api_key, voice_select, chatbot],
296
- outputs=[connection_state, status_display, connection_info, chatbot, gemini_service_state]
297
  )
298
 
299
  disconnect_btn.click(
300
  disconnect_gemini,
301
- inputs=[chatbot, gemini_service_state],
302
- outputs=[connection_state, status_display, connection_info, chatbot, gemini_service_state]
303
- )
304
-
305
- start_audio_btn.click(
306
- start_audio_stream,
307
- inputs=[gemini_service_state, audio_streaming_state],
308
- outputs=[audio_streaming_state, transcription_display]
309
- )
310
-
311
- stop_audio_btn.click(
312
- stop_audio_stream,
313
- inputs=[gemini_service_state, audio_streaming_state],
314
- outputs=[audio_streaming_state, transcription_display]
315
  )
316
 
317
- # Audio input processing
318
  audio_input.stop_recording(
319
  process_audio_input,
320
- inputs=[audio_input, audio_input, gemini_service_state, chatbot],
321
- outputs=[chatbot, connection_info, audio_output]
322
- )
323
-
324
- # Text message handling
325
- send_text_btn.click(
326
- send_text_message,
327
- inputs=[text_input, chatbot, gemini_service_state],
328
- outputs=[chatbot, connection_info, chatbot]
329
- ).then(
330
- lambda: "",
331
- outputs=[text_input]
332
- )
333
-
334
- text_input.submit(
335
- send_text_message,
336
- inputs=[text_input, chatbot, gemini_service_state],
337
- outputs=[chatbot, connection_info, chatbot]
338
- ).then(
339
- lambda: "",
340
- outputs=[text_input]
341
- )
342
-
343
- clear_btn = gr.Button("🧹 Xóa chat", variant="secondary")
344
- clear_btn.click(
345
- clear_chat,
346
- outputs=[chatbot, connection_info, chatbot]
347
  )
348
 
349
  # Hướng dẫn sử dụng
@@ -357,17 +249,14 @@ def create_gemini_realtime_tab():
357
  - Nhấn **"Kết nối Audio"**
358
 
359
  2. **Trò chuyện bằng giọng nói**:
360
- - Nhấn **"Bắt đầu nói"**
361
- - Nói vào micro
362
- - Gemini sẽ trả lời bằng audio ngay lập tức
 
363
 
364
- 3. **Hoặc chat bằng text**:
365
- - Nhập tin nhắn trong ô text
366
- - Nhấn Enter hoặc **"Gửi text"**
367
-
368
- ### 🔊 Tính năng Audio Streaming:
369
  - 🎙️ Real-time voice recognition
370
- - 🔊 Real-time audio response
371
  - ⚡ Ultra low latency
372
  - 🎯 Multiple voice options
373
 
@@ -375,6 +264,12 @@ def create_gemini_realtime_tab():
375
  - Sử dụng headset để chất lượng tốt hơn
376
  - Nói rõ ràng, không nói quá nhanh
377
  - Môi trường yên tĩnh cho kết quả tốt nhất
 
 
 
 
 
 
378
  """)
379
 
380
  return gemini_tab
 
60
 
61
  with gr.Blocks() as gemini_tab:
62
  gr.Markdown("""
63
+ # 🎯 Gemini Audio Streaming
64
+ **Trò chuyện thời gian thực bằng giọng nói với Google Gemini**
65
  """)
66
 
67
  with gr.Row():
68
  with gr.Column(scale=1):
69
  # Connection controls
70
  with gr.Group():
71
+ gr.Markdown("### 🔗 Kết nối")
72
 
73
  api_key = gr.Textbox(
74
  label="Gemini API Key",
75
  type="password",
76
  placeholder="Nhập API key của bạn...",
77
  value=os.getenv("GEMINI_API_KEY", ""),
78
+ info="Lấy từ https://aistudio.google.com/"
79
  )
80
 
81
  voice_select = gr.Dropdown(
 
106
  )
107
 
108
  with gr.Column(scale=2):
 
 
 
 
 
 
 
 
 
 
 
 
109
  # Audio Streaming Interface
110
  with gr.Group():
111
  gr.Markdown("### 🎤 Audio Streaming")
112
 
113
+ # Audio input for user
114
+ audio_input = gr.Audio(
115
+ label="🎤 Nhấn để nói chuyện với Gemini",
116
+ sources=["microphone"],
117
+ type="numpy",
118
+ interactive=True,
119
+ show_download_button=False
 
 
120
  )
121
 
122
  # Audio output for Gemini responses
 
126
  autoplay=True
127
  )
128
 
129
+ transcription_display = gr.Textbox(
130
+ label="💬 Nội dung hội thoại",
131
+ interactive=False,
132
+ lines=3,
133
+ placeholder="Nội dung cuộc trò chuyện sẽ hiển thị ở đây..."
 
134
  )
135
 
136
  # State management
137
  connection_state = gr.State(value=False)
 
138
  gemini_service_state = gr.State(value=None)
139
 
140
+ async def connect_gemini(api_key, voice_name):
141
  """Kết nối Gemini Audio Streaming"""
142
  try:
143
  if not api_key:
144
+ return False, "❌ Vui lòng nhập API Key", "Chưa kết nối", None
145
 
146
  service = GeminiRealtimeService(api_key)
147
 
 
149
  async def handle_gemini_callback(data):
150
  if data['type'] == 'status':
151
  gr.Info(data['message'])
 
152
  elif data['type'] == 'text':
153
+ gr.Info(f"Gemini: {data['content']}")
 
 
 
 
 
154
  elif data['type'] == 'error':
155
  gr.Warning(data['message'])
 
 
156
 
157
  success = await service.start_session(
158
  voice_name=voice_name,
 
160
  )
161
 
162
  if success:
163
+ info_msg = f" Đã kết nối Audio Streaming\nGiọng: {voice_name}\nHãy sử dụng micro để trò chuyện"
164
+ return True, "✅ Đã kết nối Audio", info_msg, service
 
 
165
  else:
166
+ return False, "❌ Không thể kết nối audio", "Lỗi kết nối", None
167
 
168
  except Exception as e:
169
  error_msg = f"❌ Lỗi kết nối: {str(e)}"
170
+ return False, error_msg, f"Lỗi: {str(e)}", None
171
 
172
+ async def disconnect_gemini(service):
173
  """Ngắt kết nối"""
174
  if service:
175
  await service.close()
176
+ return False, "🔌 Đã ngắt kết nối", "Đã ngắt kết nối audio streaming", None
 
 
 
 
 
 
 
 
 
 
 
 
 
177
 
178
+ async def process_audio_input(audio_data, sample_rate, service):
179
+ """Xử lý audio input từ user và trả lời bằng audio"""
180
  if not service or not service.is_active:
181
+ return None, "❌ Chưa kết nối. Vui lòng kết nối audio trước.", "Chưa kết nối"
182
 
183
  if audio_data is None:
184
+ return None, "⚠️ Không có audio input", "Không có audio"
185
 
186
  try:
187
  # Gửi audio đến Gemini
188
  success = await service.send_audio_chunk(audio_data, sample_rate)
189
 
190
+ if not success:
191
+ return None, "❌ Lỗi gửi audio đến Gemini", "Lỗi gửi audio"
192
+
193
+ # Chờ và nhận audio response từ Gemini
194
+ audio_response = None
195
+ max_attempts = 50 # Chờ tối đa 5 giây
196
+
197
+ for attempt in range(max_attempts):
198
  audio_response = await service.receive_audio()
199
+ if audio_response is not None:
200
+ break
201
+ await asyncio.sleep(0.1) # Chờ 100ms giữa các lần thử
202
+
203
+ if audio_response:
204
+ resp_sample_rate, resp_audio_data = audio_response
205
 
206
+ # Lưu audio response vào file tạm
207
+ with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as f:
 
 
208
  import scipy.io.wavfile as wavfile
209
+ wavfile.write(f.name, resp_sample_rate, resp_audio_data)
210
+ audio_path = f.name
211
+
212
+ info_msg = f"✅ Đã nhận phản hồi audio từ Gemini ({(len(resp_audio_data) / resp_sample_rate):.1f}s)"
213
+ return audio_path, info_msg, "Thành công"
 
 
214
  else:
215
+ return None, " Không nhận được phản hồi audio từ Gemini", "Timeout"
216
 
217
  except Exception as e:
218
  error_msg = f"❌ Lỗi xử lý audio: {str(e)}"
219
+ return None, error_msg, f"Lỗi: {str(e)}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
220
 
221
  # Event handlers
222
  connect_btn.click(
223
  connect_gemini,
224
+ inputs=[api_key, voice_select],
225
+ outputs=[connection_state, status_display, connection_info, gemini_service_state]
226
  )
227
 
228
  disconnect_btn.click(
229
  disconnect_gemini,
230
+ inputs=[gemini_service_state],
231
+ outputs=[connection_state, status_display, connection_info, gemini_service_state]
 
 
 
 
 
 
 
 
 
 
 
 
232
  )
233
 
234
+ # Xử lý audio input
235
  audio_input.stop_recording(
236
  process_audio_input,
237
+ inputs=[audio_input, audio_input, gemini_service_state],
238
+ outputs=[audio_output, connection_info, transcription_display]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
239
  )
240
 
241
  # Hướng dẫn sử dụng
 
249
  - Nhấn **"Kết nối Audio"**
250
 
251
  2. **Trò chuyện bằng giọng nói**:
252
+ - Nhấn nút **Micro** để bắt đầu ghi âm
253
+ - Nói câu hỏi của bạn
254
+ - Nhấn **Dừng** để kết thúc ghi âm
255
+ - Gemini sẽ trả lời bằng giọng nói ngay lập tức
256
 
257
+ ### 🔊 Tính năng:
 
 
 
 
258
  - 🎙️ Real-time voice recognition
259
+ - 🔊 Real-time audio response
260
  - ⚡ Ultra low latency
261
  - 🎯 Multiple voice options
262
 
 
264
  - Sử dụng headset để chất lượng tốt hơn
265
  - Nói rõ ràng, không nói quá nhanh
266
  - Môi trường yên tĩnh cho kết quả tốt nhất
267
+ - Mỗi lần ghi âm nên ngắn hơn 30 giây
268
+
269
+ ### 🔧 Lưu ý kỹ thuật:
270
+ - Cần API Key Gemini có quyền Realtime API
271
+ - Audio được stream real-time đến Gemini
272
+ - Phản hồi audio được stream về và phát tự động
273
  """)
274
 
275
  return gemini_tab