datbkpro commited on
Commit
97e1995
·
verified ·
1 Parent(s): 01c964f

Update services/streaming_voice_service.py

Browse files
Files changed (1) hide show
  1. services/streaming_voice_service.py +196 -261
services/streaming_voice_service.py CHANGED
@@ -15,13 +15,13 @@ from core.speechbrain_vad import SpeechBrainVAD
15
  from core.silero_vad import SileroVAD
16
 
17
  class StreamingVoiceService:
18
- def __init__(self, groq_client: Groq, rag_system: EnhancedRAGSystem, tts_service: EnhancedTTSService):
19
  self.client = groq_client
20
  self.rag_system = rag_system
21
  self.tts_service = tts_service
22
 
23
- # Khởi tạo VAD tối ưu
24
- self.vad_processor = SileroVAD()
25
  self.is_listening = False
26
  self.speech_callback = None
27
  self.is_processing = False
@@ -31,25 +31,26 @@ class StreamingVoiceService:
31
  self.conversation_history = []
32
  self.current_transcription = ""
33
 
34
- # Audio buffer
35
- self.audio_buffer = []
36
- self.buffer_lock = threading.Lock()
37
-
38
- # Response queue để quản lý thứ tự xử lý
39
  self.response_queue = queue.Queue()
40
- self.current_task = None
41
-
42
- #Latency
 
43
  self.latency_metrics = {
44
  'asr': [],
45
- 'rag' : [],
46
- 'llm' : [],
47
- 'tts' : [],
48
- 'total' : []
49
  }
 
 
 
 
50
 
51
  def start_listening(self, speech_callback: Callable) -> bool:
52
- """Bắt đầu lắng nghe với VAD tối ưu"""
53
  if self.is_listening:
54
  return False
55
 
@@ -58,8 +59,18 @@ class StreamingVoiceService:
58
  if success:
59
  self.is_listening = True
60
  self.is_processing = False
61
- threading.Thread(target=self._process_response_queue, daemon=True).start()
62
- print("🎙️ Đã bắt đầu lắng nghe với VAD tối ưu")
 
 
 
 
 
 
 
 
 
 
63
  return success
64
 
65
  def stop_listening(self):
@@ -68,24 +79,33 @@ class StreamingVoiceService:
68
  self.is_listening = False
69
  self.is_processing = False
70
  self.speech_callback = None
71
- with self.buffer_lock:
72
- self.audio_buffer = []
 
 
 
 
 
 
 
73
  print("🛑 Đã dừng lắng nghe")
74
 
75
  def _on_speech_detected(self, speech_audio: np.ndarray, sample_rate: int):
76
- """Callback khi VAD phát hiện speech - TỐI ƯU HÓA"""
77
- print(f"🎯 VAD phát hiện speech: {len(speech_audio)/sample_rate:.2f}s")
 
78
 
 
79
  self.response_queue.put((speech_audio, sample_rate))
80
 
81
- def _process_response_queue(self):
82
- """Xử tuần tự các request từ queue"""
83
  while self.is_listening:
84
  try:
85
  # Chờ item từ queue với timeout
86
  speech_audio, sample_rate = self.response_queue.get(timeout=1.0)
87
 
88
- # Xử lý speech
89
  self._process_speech_segment(speech_audio, sample_rate)
90
 
91
  # Đánh dấu task hoàn thành
@@ -94,25 +114,19 @@ class StreamingVoiceService:
94
  except queue.Empty:
95
  continue
96
  except Exception as e:
97
- print(f"❌ Lỗi trong response queue: {e}")
98
  continue
99
 
100
  def _process_speech_segment(self, speech_audio: np.ndarray, sample_rate: int):
101
- """Xử lý speech segment - TỐI ƯU HÓA"""
102
- # Kiểm tra nếu đang xử lý
103
- if self.is_processing:
104
- print("⚠️ Bỏ qua speech segment - đang xử lý request trước")
105
- return
106
-
107
- with self.processing_lock:
108
- self.is_processing = True
109
  total_start_time = time.time()
 
110
  try:
111
- # Chuyển đổi speech thành text
112
- # 1. ASR
113
  asr_start = time.time()
114
- transcription = self._transcribe_audio(speech_audio, sample_rate)
115
  asr_latency = time.time() - asr_start
 
116
  if not transcription or len(transcription.strip()) < 2:
117
  print("⚠️ Transcription quá ngắn hoặc trống")
118
  return
@@ -120,15 +134,18 @@ class StreamingVoiceService:
120
  print(f"📝 Transcription: {transcription}")
121
  self.current_transcription = transcription
122
 
123
- # Tạo phản hồi AI
124
  rag_start = time.time()
125
- response = self._generate_ai_response(transcription)
126
  rag_latency = time.time() - rag_start
127
- # Tạo TTS
 
128
  tts_start = time.time()
129
- tts_audio_path = self._text_to_speech(response)
130
  tts_latency = time.time() - tts_start
 
131
  total_latency = time.time() - total_start_time
 
132
  # Log latency metrics
133
  self._log_latency_metrics({
134
  'asr': asr_latency,
@@ -136,183 +153,41 @@ class StreamingVoiceService:
136
  'tts': tts_latency,
137
  'total': total_latency
138
  })
 
139
  # Gửi kết quả đến callback
140
  if self.speech_callback:
141
- self.speech_callback({
142
  'transcription': transcription,
143
  'response': response,
144
  'tts_audio': tts_audio_path,
145
- 'status': 'completed'
146
- })
 
 
147
 
148
  except Exception as e:
149
  print(f"❌ Lỗi xử lý speech segment: {e}")
150
  traceback.print_exc()
151
- finally:
152
- with self.processing_lock:
153
- self.is_processing = False
154
-
155
- def process_streaming_audio(self, audio_data: tuple) -> Dict[str, Any]:
156
- """Xử lý audio streaming (phương thức cũ cho compatibility với Gradio)"""
157
- if not audio_data:
158
- return {
159
- 'transcription': "❌ Không có dữ liệu âm thanh",
160
- 'response': "Vui lòng nói lại",
161
- 'tts_audio': None,
162
- 'status': 'error'
163
- }
164
-
165
- # Nếu đang xử lý VAD, trả về trạng thái processing
166
- if self.is_processing:
167
- return {
168
- 'transcription': "Đang xử lý...",
169
- 'response': "",
170
- 'tts_audio': None,
171
- 'status': 'processing'
172
- }
173
-
174
- try:
175
- # Lấy dữ liệu audio từ Gradio
176
- sample_rate, audio_array = audio_data
177
-
178
- print(f"🎯 Nhận audio manual: {len(audio_array)} samples, SR: {sample_rate}")
179
-
180
- # Kiểm tra kiểu dữ liệu và chuyển đổi nếu cần
181
- if isinstance(audio_array, np.ndarray):
182
- if audio_array.dtype == np.float32 or audio_array.dtype == np.float64:
183
- # Chuyển từ float sang int16
184
- audio_array = (audio_array * 32767).astype(np.int16)
185
-
186
- # Kiểm tra audio có dữ liệu không
187
- if len(audio_array) == 0:
188
- return {
189
- 'transcription': "❌ Âm thanh trống",
190
- 'response': "Vui lòng nói lại",
191
- 'tts_audio': None,
192
- 'status': 'error'
193
- }
194
-
195
- # Tính toán âm lượng
196
- audio_abs = np.abs(audio_array.astype(np.float32))
197
- audio_rms = np.sqrt(np.mean(audio_abs**2)) / 32767.0
198
- print(f"📊 Âm lượng RMS: {audio_rms:.4f}")
199
-
200
- if audio_rms < 0.005:
201
- return {
202
- 'transcription': "❌ Âm thanh quá yếu",
203
- 'response': "Xin vui lòng nói to hơn",
204
- 'tts_audio': None,
205
- 'status': 'error'
206
- }
207
 
208
- # Sử dụng VAD để kiểm tra speech
209
- if not self.vad_processor.is_speech(audio_array, sample_rate):
210
- return {
211
- 'transcription': " Không phát hiện giọng nói",
212
- 'response': "Vui lòng nói rõ hơn",
213
- 'tts_audio': None,
214
- 'status': 'error'
215
- }
216
-
217
- # Chuyển đổi thành văn bản
218
- transcription = self._transcribe_audio(audio_array, sample_rate)
219
-
220
- if not transcription or len(transcription.strip()) == 0:
221
- return {
222
- 'transcription': "❌ Không nghe rõ",
223
- 'response': "Xin vui lòng nói lại rõ hơn",
224
- 'tts_audio': None,
225
- 'status': 'error'
226
- }
227
-
228
- # Kiểm tra nếu transcription quá ngắn
229
- if len(transcription.strip()) < 2:
230
- return {
231
- 'transcription': "❌ Câu nói quá ngắn",
232
- 'response': "Xin vui lòng nói câu dài hơn",
233
  'tts_audio': None,
234
  'status': 'error'
235
- }
236
-
237
- print(f"📝 Đã chuyển đổi: {transcription}")
238
-
239
- # Cập nhật transcription hiện tại
240
- self.current_transcription = transcription
241
-
242
- # Tạo phản hồi AI
243
- response = self._generate_ai_response(transcription)
244
-
245
- # Tạo TTS
246
- tts_audio_path = self._text_to_speech(response)
247
-
248
- return {
249
- 'transcription': transcription,
250
- 'response': response,
251
- 'tts_audio': tts_audio_path,
252
- 'status': 'completed'
253
- }
254
-
255
- except Exception as e:
256
- print(f"❌ Lỗi xử lý streaming audio: {e}")
257
- print(f"Chi tiết lỗi: {traceback.format_exc()}")
258
- return {
259
- 'transcription': f"❌ Lỗi: {str(e)}",
260
- 'response': "Xin lỗi, có lỗi xảy ra trong quá trình xử lý",
261
- 'tts_audio': None,
262
- 'status': 'error'
263
- }
264
- def process_audio_chunk(self, audio_data: tuple) -> Dict[str, Any]:
265
- """Xử lý audio chunk với VAD"""
266
- if not audio_data or not self.is_listening:
267
- return {
268
- 'transcription': "Đang lắng nghe...",
269
- 'response': "",
270
- 'tts_audio': None,
271
- 'status': 'listening'
272
- }
273
-
274
- try:
275
- sample_rate, audio_array = audio_data
276
-
277
- # Thêm vào buffer và xử lý với VAD
278
- with self.buffer_lock:
279
- self.audio_buffer.extend(audio_array)
280
- # Giới hạn buffer
281
- max_buffer_samples = sample_rate * 15 # 15 giây
282
- if len(self.audio_buffer) > max_buffer_samples:
283
- self.audio_buffer = self.audio_buffer[-max_buffer_samples:]
284
-
285
- # Xử lý với VAD
286
- self.vad_processor.process_stream(audio_array, sample_rate)
287
-
288
- return {
289
- 'transcription': "Đang lắng nghe...",
290
- 'response': "",
291
- 'tts_audio': None,
292
- 'status': 'listening'
293
- }
294
-
295
- except Exception as e:
296
- print(f"❌ Lỗi xử lý audio chunk: {e}")
297
- return {
298
- 'transcription': "",
299
- 'response': "",
300
- 'tts_audio': None,
301
- 'status': 'error'
302
- }
303
 
304
- def _transcribe_audio(self, audio_data: np.ndarray, sample_rate: int) -> Optional[str]:
305
- """Chuyển audio -> text với xử cải tiến"""
306
  asr_start = time.time()
307
  try:
308
- # Đảm bảo kiểu dữ liệu và chuẩn hóa
309
  if audio_data.dtype != np.int16:
310
  if audio_data.dtype in [np.float32, np.float64]:
311
  audio_data = (audio_data * 32767).astype(np.int16)
312
  else:
313
  audio_data = audio_data.astype(np.int16)
314
 
315
- # Chuẩn hóa audio data
316
  if audio_data.ndim > 1:
317
  audio_data = np.mean(audio_data, axis=1).astype(np.int16)
318
 
@@ -323,18 +198,11 @@ class StreamingVoiceService:
323
  sample_rate = target_sample_rate
324
 
325
  # Giới hạn độ dài audio
326
- max_duration = 30 # giây
327
  max_samples = sample_rate * max_duration
328
  if len(audio_data) > max_samples:
329
  audio_data = audio_data[:max_samples]
330
 
331
- # Đảm bảo audio đủ dài
332
- min_duration = 2 # giây
333
- min_samples = int(sample_rate * min_duration)
334
- if len(audio_data) < min_samples:
335
- padding = np.zeros(min_samples - len(audio_data), dtype=np.int16)
336
- audio_data = np.concatenate([audio_data, padding])
337
-
338
  print(f"🔊 Gửi audio đến Whisper: {len(audio_data)} samples, {sample_rate}Hz")
339
 
340
  # Tạo temporary file trong memory
@@ -342,8 +210,7 @@ class StreamingVoiceService:
342
  sf.write(buffer, audio_data, sample_rate, format='wav', subtype='PCM_16')
343
  buffer.seek(0)
344
 
345
-
346
- # Gọi API Whisper
347
  api_start = time.time()
348
  try:
349
  transcription = self.client.audio.transcriptions.create(
@@ -356,7 +223,9 @@ class StreamingVoiceService:
356
  except Exception as e:
357
  print(f"❌ Lỗi Whisper API: {e}")
358
  return None
 
359
  api_latency = time.time() - api_start
 
360
  # Xử lý response
361
  if hasattr(transcription, 'text'):
362
  result = transcription.text.strip()
@@ -364,49 +233,59 @@ class StreamingVoiceService:
364
  result = transcription.strip()
365
  else:
366
  result = str(transcription).strip()
367
- short_responses = {
368
- 'ừ', 'um', 'à', 'ờ', 'ê', 'ô',
369
- 'có', 'không', 'đúng', 'sai', 'ok', 'okay', 'ừm',
370
- 'vâng', 'dạ', 'ạ', 'được', 'tốt', 'hay', 'ừ ừ',
371
- 'yes', 'no', 'yeah', 'yep', 'nope'
372
- }
373
 
374
  total_asr_latency = time.time() - asr_start
375
  print(f"✅ ASR Latency: {total_asr_latency:.2f}s (API: {api_latency:.2f}s)")
376
- # Chuẩn hóa text để so sánh
377
- normalized_text = result.lower().strip()
378
 
379
- # Loại bỏ dấu câu và khoảng trắng thừa
380
- import re
381
- normalized_text = re.sub(r'[^\w\s]', '', normalized_text)
382
-
383
- # Nếu là từ ngắn thông dụng, vẫn chấp nhận
384
- if normalized_text in short_responses:
385
- print(f"✅ Nhận diện phản hồi ngắn: '{result}'")
386
  return result
387
- # Kiểm tra độ dài tối thiểu cho các từ khác
388
- min_length = 2 # Ít nhất 2 ký tự cho các từ không trong danh sách ngắn
389
- if len(normalized_text) < min_length and normalized_text not in short_responses:
390
- print(f"⚠️ Bỏ qua transcription quá ngắn: '{result}'")
391
  return None
392
- print(f"✅ Transcription: '{result}'")
393
- return result
394
 
395
  except Exception as e:
396
  print(f"❌ Lỗi transcription: {e}")
397
  return None
398
 
399
- def _generate_ai_response(self, user_input: str) -> str:
400
- """Sinh phản hồi AI với xử lý lỗi"""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
401
  llm_start = time.time()
402
  try:
403
  # Thêm vào lịch sử
404
  self.conversation_history.append({"role": "user", "content": user_input})
405
 
406
- # Tìm kiếm RAG
407
  rag_start = time.time()
408
- rag_results = self.rag_system.semantic_search(user_input, top_k=2)
409
  rag_latency = time.time() - rag_start
 
410
  context_text = "\n".join([f"- {result.get('text', str(result))}" for result in rag_results]) if rag_results else ""
411
 
412
  system_prompt = f"""Bạn là trợ lý AI thông minh chuyên về tiếng Việt.
@@ -419,30 +298,36 @@ Thông tin tham khảo:
419
  # Giữ lại 6 tin nhắn gần nhất
420
  messages.extend(self.conversation_history[-6:])
421
 
 
422
  completion = self.client.chat.completions.create(
423
  model=settings.MULTILINGUAL_LLM_MODEL,
424
  messages=messages,
425
  max_tokens=300,
426
  temperature=0.7
427
  )
428
- ttft = time.time() - llm_inference_start # Time To First Token
 
429
  response = completion.choices[0].message.content
430
  self.conversation_history.append({"role": "assistant", "content": response})
 
431
  total_llm_latency = time.time() - llm_start
 
432
  # Giới hạn lịch sử
433
  if len(self.conversation_history) > 12:
434
  self.conversation_history = self.conversation_history[-12:]
 
435
  print(f"✅ RAG Latency: {rag_latency:.2f}s")
436
  print(f"✅ LLM TTFT: {ttft:.2f}s")
437
  print(f"✅ Total LLM Latency: {total_llm_latency:.2f}s")
 
438
  return response
439
 
440
  except Exception as e:
441
  print(f"❌ Lỗi tạo AI response: {e}")
442
  return "Xin lỗi, tôi gặp lỗi khi tạo phản hồi. Vui lòng thử lại."
443
 
444
- def _text_to_speech(self, text: str) -> Optional[str]:
445
- """Chuyển văn bản thành giọng nói với latency tracking"""
446
  tts_start = time.time()
447
  try:
448
  if not text or text.startswith("❌") or text.startswith("Xin lỗi"):
@@ -454,12 +339,75 @@ Thông tin tham khảo:
454
  if tts_bytes:
455
  audio_path = self.tts_service.save_audio_to_file(tts_bytes)
456
  print(f"✅ TTS Latency: {tts_latency:.2f}s")
457
- print(f"✅ Đã tạo TTS: {audio_path}")
458
  return audio_path
459
  except Exception as e:
460
  print(f"❌ Lỗi TTS: {e}")
461
  return None
462
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
463
  def _resample_audio(self, audio_data: np.ndarray, orig_sr: int, target_sr: int) -> np.ndarray:
464
  """Resample audio"""
465
  try:
@@ -471,11 +419,6 @@ Thông tin tham khảo:
471
  except Exception:
472
  return audio_data
473
 
474
- def clear_conversation(self):
475
- """Xóa lịch sử hội thoại"""
476
- self.conversation_history = []
477
- self.current_transcription = ""
478
- print("🗑️ Đã xóa lịch sử hội thoại")
479
  def _log_latency_metrics(self, latencies: dict):
480
  """Log và theo dõi latency metrics"""
481
  for key, value in latencies.items():
@@ -486,25 +429,9 @@ Thông tin tham khảo:
486
  if len(self.latency_metrics[key]) > 100:
487
  self.latency_metrics[key] = self.latency_metrics[key][-100:]
488
 
489
- # Log tổng hợp
490
  print("📊 LATENCY REPORT:")
491
- print(f" ASR: {latencies['asr']:.2f}s")
492
- print(f" RAG: {latencies['rag']:.2f}s")
493
- print(f" TTS: {latencies['tts']:.2f}s")
494
- print(f" TOTAL: {latencies['total']:.2f}s")
495
-
496
- # Tính toán và hiển thị latency trung bình
497
- self._print_average_latencies()
498
-
499
- def _print_average_latencies(self):
500
- """In ra latency trung bình"""
501
- if len(self.latency_metrics['total']) > 0:
502
- print("📈 AVERAGE LATENCIES (last 10 requests):")
503
- for component in ['asr', 'rag', 'tts', 'total']:
504
- recent_latencies = self.latency_metrics[component][-10:]
505
- if recent_latencies:
506
- avg = sum(recent_latencies) / len(recent_latencies)
507
- print(f" {component.upper()}: {avg:.2f}s")
508
 
509
  def get_latency_stats(self) -> dict:
510
  """Lấy thống kê latency"""
@@ -516,11 +443,12 @@ Thông tin tham khảo:
516
  'min': min(latencies),
517
  'max': max(latencies),
518
  'count': len(latencies),
519
- 'recent_avg': sum(latencies[-10:]) / min(10, len(latencies)) if latencies else 0
520
  }
521
  else:
522
  stats[component] = {'avg': 0, 'min': 0, 'max': 0, 'count': 0, 'recent_avg': 0}
523
  return stats
 
524
  def get_conversation_state(self) -> dict:
525
  """Lấy trạng thái hội thoại"""
526
  return {
@@ -529,5 +457,12 @@ Thông tin tham khảo:
529
  'history_length': len(self.conversation_history),
530
  'current_transcription': self.current_transcription,
531
  'queue_size': self.response_queue.qsize(),
 
532
  'last_update': time.strftime("%H:%M:%S")
533
- }
 
 
 
 
 
 
 
15
  from core.silero_vad import SileroVAD
16
 
17
  class StreamingVoiceService:
18
+ def __init__(self, groq_client: Groq, rag_system, tts_service):
19
  self.client = groq_client
20
  self.rag_system = rag_system
21
  self.tts_service = tts_service
22
 
23
+ # Khởi tạo VAD tối ưu với double buffer
24
+ self.vad_processor = OptimizedSileroVAD()
25
  self.is_listening = False
26
  self.speech_callback = None
27
  self.is_processing = False
 
31
  self.conversation_history = []
32
  self.current_transcription = ""
33
 
34
+ # Multi-thread processing
 
 
 
 
35
  self.response_queue = queue.Queue()
36
+ self.processing_threads = []
37
+ self.max_workers = 2 # Số lượng thread xử lý song song
38
+
39
+ # Latency tracking
40
  self.latency_metrics = {
41
  'asr': [],
42
+ 'rag': [],
43
+ 'llm': [],
44
+ 'tts': [],
45
+ 'total': []
46
  }
47
+
48
+ # Audio buffer management
49
+ self.pending_audio_segments = []
50
+ self.segment_lock = threading.Lock()
51
 
52
  def start_listening(self, speech_callback: Callable) -> bool:
53
+ """Bắt đầu lắng nghe với multi-thread processing"""
54
  if self.is_listening:
55
  return False
56
 
 
59
  if success:
60
  self.is_listening = True
61
  self.is_processing = False
62
+
63
+ # Khởi động worker threads
64
+ for i in range(self.max_workers):
65
+ thread = threading.Thread(
66
+ target=self._process_response_worker,
67
+ daemon=True,
68
+ name=f"ASR-Worker-{i}"
69
+ )
70
+ thread.start()
71
+ self.processing_threads.append(thread)
72
+
73
+ print("🎙️ Đã bắt đầu lắng nghe với multi-thread processing")
74
  return success
75
 
76
  def stop_listening(self):
 
79
  self.is_listening = False
80
  self.is_processing = False
81
  self.speech_callback = None
82
+
83
+ # Clear queue
84
+ while not self.response_queue.empty():
85
+ try:
86
+ self.response_queue.get_nowait()
87
+ self.response_queue.task_done()
88
+ except queue.Empty:
89
+ break
90
+
91
  print("🛑 Đã dừng lắng nghe")
92
 
93
  def _on_speech_detected(self, speech_audio: np.ndarray, sample_rate: int):
94
+ """Callback khi VAD phát hiện speech - không blocking"""
95
+ audio_duration = len(speech_audio) / sample_rate
96
+ print(f"🎯 VAD phát hiện speech: {audio_duration:.2f}s - Đưa vào queue")
97
 
98
+ # Đưa vào queue mà không chờ đợi
99
  self.response_queue.put((speech_audio, sample_rate))
100
 
101
+ def _process_response_worker(self):
102
+ """Worker thread xử speech segments"""
103
  while self.is_listening:
104
  try:
105
  # Chờ item từ queue với timeout
106
  speech_audio, sample_rate = self.response_queue.get(timeout=1.0)
107
 
108
+ # Xử lý speech segment
109
  self._process_speech_segment(speech_audio, sample_rate)
110
 
111
  # Đánh dấu task hoàn thành
 
114
  except queue.Empty:
115
  continue
116
  except Exception as e:
117
+ print(f"❌ Lỗi trong worker thread: {e}")
118
  continue
119
 
120
  def _process_speech_segment(self, speech_audio: np.ndarray, sample_rate: int):
121
+ """Xử lý speech segment - optimized version"""
 
 
 
 
 
 
 
122
  total_start_time = time.time()
123
+
124
  try:
125
+ # 1. ASR Transcription
 
126
  asr_start = time.time()
127
+ transcription = self._transcribe_audio_optimized(speech_audio, sample_rate)
128
  asr_latency = time.time() - asr_start
129
+
130
  if not transcription or len(transcription.strip()) < 2:
131
  print("⚠️ Transcription quá ngắn hoặc trống")
132
  return
 
134
  print(f"📝 Transcription: {transcription}")
135
  self.current_transcription = transcription
136
 
137
+ # 2. AI Response Generation
138
  rag_start = time.time()
139
+ response = self._generate_ai_response_optimized(transcription)
140
  rag_latency = time.time() - rag_start
141
+
142
+ # 3. TTS Conversion
143
  tts_start = time.time()
144
+ tts_audio_path = self._text_to_speech_optimized(response)
145
  tts_latency = time.time() - tts_start
146
+
147
  total_latency = time.time() - total_start_time
148
+
149
  # Log latency metrics
150
  self._log_latency_metrics({
151
  'asr': asr_latency,
 
153
  'tts': tts_latency,
154
  'total': total_latency
155
  })
156
+
157
  # Gửi kết quả đến callback
158
  if self.speech_callback:
159
+ result = {
160
  'transcription': transcription,
161
  'response': response,
162
  'tts_audio': tts_audio_path,
163
+ 'status': 'completed',
164
+ 'latency': total_latency
165
+ }
166
+ self.speech_callback(result)
167
 
168
  except Exception as e:
169
  print(f"❌ Lỗi xử lý speech segment: {e}")
170
  traceback.print_exc()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
171
 
172
+ if self.speech_callback:
173
+ self.speech_callback({
174
+ 'transcription': f"Lỗi: {str(e)}",
175
+ 'response': "Xin lỗi, lỗi xảy ra",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
176
  'tts_audio': None,
177
  'status': 'error'
178
+ })
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
179
 
180
+ def _transcribe_audio_optimized(self, audio_data: np.ndarray, sample_rate: int) -> Optional[str]:
181
+ """Chuyển audio -> text với tối ưu hiệu suất"""
182
  asr_start = time.time()
183
  try:
184
+ # Chuẩn hóa audio data
185
  if audio_data.dtype != np.int16:
186
  if audio_data.dtype in [np.float32, np.float64]:
187
  audio_data = (audio_data * 32767).astype(np.int16)
188
  else:
189
  audio_data = audio_data.astype(np.int16)
190
 
 
191
  if audio_data.ndim > 1:
192
  audio_data = np.mean(audio_data, axis=1).astype(np.int16)
193
 
 
198
  sample_rate = target_sample_rate
199
 
200
  # Giới hạn độ dài audio
201
+ max_duration = 30
202
  max_samples = sample_rate * max_duration
203
  if len(audio_data) > max_samples:
204
  audio_data = audio_data[:max_samples]
205
 
 
 
 
 
 
 
 
206
  print(f"🔊 Gửi audio đến Whisper: {len(audio_data)} samples, {sample_rate}Hz")
207
 
208
  # Tạo temporary file trong memory
 
210
  sf.write(buffer, audio_data, sample_rate, format='wav', subtype='PCM_16')
211
  buffer.seek(0)
212
 
213
+ # Gọi API Whisper với timeout
 
214
  api_start = time.time()
215
  try:
216
  transcription = self.client.audio.transcriptions.create(
 
223
  except Exception as e:
224
  print(f"❌ Lỗi Whisper API: {e}")
225
  return None
226
+
227
  api_latency = time.time() - api_start
228
+
229
  # Xử lý response
230
  if hasattr(transcription, 'text'):
231
  result = transcription.text.strip()
 
233
  result = transcription.strip()
234
  else:
235
  result = str(transcription).strip()
 
 
 
 
 
 
236
 
237
  total_asr_latency = time.time() - asr_start
238
  print(f"✅ ASR Latency: {total_asr_latency:.2f}s (API: {api_latency:.2f}s)")
 
 
239
 
240
+ # Kiểm tra chất lượng transcription
241
+ if self._is_valid_transcription(result):
 
 
 
 
 
242
  return result
243
+ else:
 
 
 
244
  return None
 
 
245
 
246
  except Exception as e:
247
  print(f"❌ Lỗi transcription: {e}")
248
  return None
249
 
250
+ def _is_valid_transcription(self, text: str) -> bool:
251
+ """Kiểm tra tính hợp lệ của transcription"""
252
+ if not text or len(text.strip()) == 0:
253
+ return False
254
+
255
+ # Danh sách từ ngắn được chấp nhận
256
+ short_responses = {
257
+ 'ừ', 'um', 'à', 'ờ', 'ê', 'ô',
258
+ 'có', 'không', 'đúng', 'sai', 'ok', 'okay', 'ừm',
259
+ 'vâng', 'dạ', 'ạ', 'được', 'tốt', 'hay', 'ừ ừ',
260
+ 'yes', 'no', 'yeah', 'yep', 'nope'
261
+ }
262
+
263
+ normalized_text = text.lower().strip()
264
+
265
+ # Loại bỏ dấu câu và khoảng trắng thừa
266
+ import re
267
+ normalized_text = re.sub(r'[^\w\s]', '', normalized_text)
268
+
269
+ # Nếu là từ ngắn thông dụng, chấp nhận
270
+ if normalized_text in short_responses:
271
+ return True
272
+
273
+ # Kiểm tra độ dài tối thiểu cho các từ khác
274
+ min_length = 2
275
+ return len(normalized_text) >= min_length
276
+
277
+ def _generate_ai_response_optimized(self, user_input: str) -> str:
278
+ """Sinh phản hồi AI với tối ưu hiệu suất"""
279
  llm_start = time.time()
280
  try:
281
  # Thêm vào lịch sử
282
  self.conversation_history.append({"role": "user", "content": user_input})
283
 
284
+ # Tìm kiếm RAG (có thể bỏ qua nếu cần tốc độ)
285
  rag_start = time.time()
286
+ rag_results = self.rag_system.semantic_search(user_input, top_k=2) if self.rag_system else []
287
  rag_latency = time.time() - rag_start
288
+
289
  context_text = "\n".join([f"- {result.get('text', str(result))}" for result in rag_results]) if rag_results else ""
290
 
291
  system_prompt = f"""Bạn là trợ lý AI thông minh chuyên về tiếng Việt.
 
298
  # Giữ lại 6 tin nhắn gần nhất
299
  messages.extend(self.conversation_history[-6:])
300
 
301
+ llm_inference_start = time.time()
302
  completion = self.client.chat.completions.create(
303
  model=settings.MULTILINGUAL_LLM_MODEL,
304
  messages=messages,
305
  max_tokens=300,
306
  temperature=0.7
307
  )
308
+ ttft = time.time() - llm_inference_start
309
+
310
  response = completion.choices[0].message.content
311
  self.conversation_history.append({"role": "assistant", "content": response})
312
+
313
  total_llm_latency = time.time() - llm_start
314
+
315
  # Giới hạn lịch sử
316
  if len(self.conversation_history) > 12:
317
  self.conversation_history = self.conversation_history[-12:]
318
+
319
  print(f"✅ RAG Latency: {rag_latency:.2f}s")
320
  print(f"✅ LLM TTFT: {ttft:.2f}s")
321
  print(f"✅ Total LLM Latency: {total_llm_latency:.2f}s")
322
+
323
  return response
324
 
325
  except Exception as e:
326
  print(f"❌ Lỗi tạo AI response: {e}")
327
  return "Xin lỗi, tôi gặp lỗi khi tạo phản hồi. Vui lòng thử lại."
328
 
329
+ def _text_to_speech_optimized(self, text: str) -> Optional[str]:
330
+ """Chuyển văn bản thành giọng nói với tối ưu"""
331
  tts_start = time.time()
332
  try:
333
  if not text or text.startswith("❌") or text.startswith("Xin lỗi"):
 
339
  if tts_bytes:
340
  audio_path = self.tts_service.save_audio_to_file(tts_bytes)
341
  print(f"✅ TTS Latency: {tts_latency:.2f}s")
 
342
  return audio_path
343
  except Exception as e:
344
  print(f"❌ Lỗi TTS: {e}")
345
  return None
346
 
347
+ def process_streaming_audio(self, audio_data: tuple) -> Dict[str, Any]:
348
+ """Xử lý audio streaming manual mode"""
349
+ if not audio_data:
350
+ return self._create_error_response("❌ Không có dữ liệu âm thanh")
351
+
352
+ try:
353
+ sample_rate, audio_array = audio_data
354
+
355
+ print(f"🎯 Nhận audio manual: {len(audio_array)} samples, SR: {sample_rate}")
356
+
357
+ # Kiểm tra và chuyển đổi kiểu dữ liệu
358
+ if isinstance(audio_array, np.ndarray):
359
+ if audio_array.dtype == np.float32 or audio_array.dtype == np.float64:
360
+ audio_array = (audio_array * 32767).astype(np.int16)
361
+
362
+ if len(audio_array) == 0:
363
+ return self._create_error_response("❌ Âm thanh trống")
364
+
365
+ # Kiểm tra âm lượng
366
+ audio_abs = np.abs(audio_array.astype(np.float32))
367
+ audio_rms = np.sqrt(np.mean(audio_abs**2)) / 32767.0
368
+
369
+ if audio_rms < 0.005:
370
+ return self._create_error_response("❌ Âm thanh quá yếu")
371
+
372
+ # Sử dụng VAD để kiểm tra speech
373
+ if not self.vad_processor.is_speech(audio_array, sample_rate):
374
+ return self._create_error_response("❌ Không phát hiện giọng nói")
375
+
376
+ # Chuyển đổi thành văn bản
377
+ transcription = self._transcribe_audio_optimized(audio_array, sample_rate)
378
+
379
+ if not transcription:
380
+ return self._create_error_response("❌ Không nghe rõ")
381
+
382
+ print(f"📝 Đã chuyển đổi: {transcription}")
383
+ self.current_transcription = transcription
384
+
385
+ # Tạo phản hồi AI
386
+ response = self._generate_ai_response_optimized(transcription)
387
+
388
+ # Tạo TTS
389
+ tts_audio_path = self._text_to_speech_optimized(response)
390
+
391
+ return {
392
+ 'transcription': transcription,
393
+ 'response': response,
394
+ 'tts_audio': tts_audio_path,
395
+ 'status': 'completed'
396
+ }
397
+
398
+ except Exception as e:
399
+ print(f"❌ Lỗi xử lý streaming audio: {e}")
400
+ return self._create_error_response(f"❌ Lỗi: {str(e)}")
401
+
402
+ def _create_error_response(self, message: str) -> Dict[str, Any]:
403
+ """Tạo response lỗi chuẩn"""
404
+ return {
405
+ 'transcription': message,
406
+ 'response': "Vui lòng thử lại",
407
+ 'tts_audio': None,
408
+ 'status': 'error'
409
+ }
410
+
411
  def _resample_audio(self, audio_data: np.ndarray, orig_sr: int, target_sr: int) -> np.ndarray:
412
  """Resample audio"""
413
  try:
 
419
  except Exception:
420
  return audio_data
421
 
 
 
 
 
 
422
  def _log_latency_metrics(self, latencies: dict):
423
  """Log và theo dõi latency metrics"""
424
  for key, value in latencies.items():
 
429
  if len(self.latency_metrics[key]) > 100:
430
  self.latency_metrics[key] = self.latency_metrics[key][-100:]
431
 
 
432
  print("📊 LATENCY REPORT:")
433
+ for component, latency in latencies.items():
434
+ print(f" {component.upper()}: {latency:.2f}s")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
435
 
436
  def get_latency_stats(self) -> dict:
437
  """Lấy thống kê latency"""
 
443
  'min': min(latencies),
444
  'max': max(latencies),
445
  'count': len(latencies),
446
+ 'recent_avg': sum(latencies[-10:]) / min(10, len(latencies))
447
  }
448
  else:
449
  stats[component] = {'avg': 0, 'min': 0, 'max': 0, 'count': 0, 'recent_avg': 0}
450
  return stats
451
+
452
  def get_conversation_state(self) -> dict:
453
  """Lấy trạng thái hội thoại"""
454
  return {
 
457
  'history_length': len(self.conversation_history),
458
  'current_transcription': self.current_transcription,
459
  'queue_size': self.response_queue.qsize(),
460
+ 'worker_threads': len(self.processing_threads),
461
  'last_update': time.strftime("%H:%M:%S")
462
+ }
463
+
464
+ def clear_conversation(self):
465
+ """Xóa lịch sử hội thoại"""
466
+ self.conversation_history = []
467
+ self.current_transcription = ""
468
+ print("🗑️ Đã xóa lịch sử hội thoại")