Update services/streaming_voice_service.py
Browse files
services/streaming_voice_service.py
CHANGED
|
@@ -1,976 +1,4 @@
|
|
| 1 |
|
| 2 |
-
# import io
|
| 3 |
-
# import numpy as np
|
| 4 |
-
# import soundfile as sf
|
| 5 |
-
# import time
|
| 6 |
-
# import traceback
|
| 7 |
-
# import threading
|
| 8 |
-
# from groq import Groq
|
| 9 |
-
# import queue
|
| 10 |
-
# from typing import Optional, Dict, Any, Callable
|
| 11 |
-
# from config.settings import settings
|
| 12 |
-
# from core.rag_system import EnhancedRAGSystem
|
| 13 |
-
# from core.tts_service import EnhancedTTSService
|
| 14 |
-
# 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, 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 = SileroVAD()
|
| 25 |
-
# self.is_listening = False
|
| 26 |
-
# self.speech_callback = None
|
| 27 |
-
# self.is_processing = False
|
| 28 |
-
# self.processing_lock = threading.Lock()
|
| 29 |
-
|
| 30 |
-
# # Conversation context
|
| 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 |
-
|
| 57 |
-
# self.speech_callback = speech_callback
|
| 58 |
-
# success = self.vad_processor.start_stream(self._on_speech_detected)
|
| 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):
|
| 77 |
-
# """Dừng lắng nghe"""
|
| 78 |
-
# self.vad_processor.stop_stream()
|
| 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ử lý 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
|
| 112 |
-
# self.response_queue.task_done()
|
| 113 |
-
|
| 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
|
| 133 |
-
|
| 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,
|
| 152 |
-
# 'rag': rag_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, có 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 |
-
|
| 194 |
-
# # Resample nếu cần
|
| 195 |
-
# target_sample_rate = 16000
|
| 196 |
-
# if sample_rate != target_sample_rate:
|
| 197 |
-
# audio_data = self._resample_audio(audio_data, sample_rate, target_sample_rate)
|
| 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
|
| 209 |
-
# buffer = io.BytesIO()
|
| 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(
|
| 217 |
-
# model=settings.WHISPER_MODEL,
|
| 218 |
-
# file=("speech.wav", buffer.read(), "audio/wav"),
|
| 219 |
-
# response_format="text",
|
| 220 |
-
# language="vi",
|
| 221 |
-
# temperature=0.0,
|
| 222 |
-
# )
|
| 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()
|
| 232 |
-
# elif isinstance(transcription, str):
|
| 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.
|
| 292 |
-
# Hãy trả lời ngắn gọn, tự nhiên và hữu ích (dưới 100 từ).
|
| 293 |
-
# Thông tin tham khảo:
|
| 294 |
-
# {context_text}
|
| 295 |
-
# """
|
| 296 |
-
|
| 297 |
-
# messages = [{"role": "system", "content": system_prompt}]
|
| 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"):
|
| 334 |
-
# return None
|
| 335 |
-
|
| 336 |
-
# tts_bytes = self.tts_service.text_to_speech(text, 'vi')
|
| 337 |
-
# tts_latency = time.time() - tts_start
|
| 338 |
-
|
| 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:
|
| 414 |
-
# from scipy import signal
|
| 415 |
-
# duration = len(audio_data) / orig_sr
|
| 416 |
-
# new_length = int(duration * target_sr)
|
| 417 |
-
# resampled_audio = signal.resample(audio_data, new_length)
|
| 418 |
-
# return np.clip(resampled_audio, -32768, 32767).astype(np.int16)
|
| 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():
|
| 425 |
-
# if key in self.latency_metrics:
|
| 426 |
-
# self.latency_metrics[key].append(value)
|
| 427 |
-
|
| 428 |
-
# # Giữ chỉ 100 mẫu gần nhất
|
| 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"""
|
| 438 |
-
# stats = {}
|
| 439 |
-
# for component, latencies in self.latency_metrics.items():
|
| 440 |
-
# if latencies:
|
| 441 |
-
# stats[component] = {
|
| 442 |
-
# 'avg': sum(latencies) / len(latencies),
|
| 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 {
|
| 455 |
-
# 'is_listening': self.is_listening,
|
| 456 |
-
# 'is_processing': self.is_processing,
|
| 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")
|
| 469 |
-
# import io
|
| 470 |
-
# import numpy as np
|
| 471 |
-
# import soundfile as sf
|
| 472 |
-
# import time
|
| 473 |
-
# import traceback
|
| 474 |
-
# import threading
|
| 475 |
-
# from groq import Groq
|
| 476 |
-
# import queue
|
| 477 |
-
# from typing import Optional, Dict, Any, Callable
|
| 478 |
-
# from config.settings import settings
|
| 479 |
-
# from core.rag_system import EnhancedRAGSystem
|
| 480 |
-
# from core.tts_service import EnhancedTTSService
|
| 481 |
-
# from core.speechbrain_vad import SpeechBrainVAD
|
| 482 |
-
# from core.silero_vad import SileroVAD
|
| 483 |
-
|
| 484 |
-
# class StreamingVoiceService:
|
| 485 |
-
# def __init__(self, groq_client: Groq, rag_system, tts_service):
|
| 486 |
-
# self.client = groq_client
|
| 487 |
-
# self.rag_system = rag_system
|
| 488 |
-
# self.tts_service = tts_service
|
| 489 |
-
|
| 490 |
-
# # Khởi tạo VAD
|
| 491 |
-
# self.vad_processor = SileroVAD()
|
| 492 |
-
# self.is_listening = False
|
| 493 |
-
# self.speech_callback = None
|
| 494 |
-
# self.is_processing = False
|
| 495 |
-
# self.processing_lock = threading.Lock()
|
| 496 |
-
|
| 497 |
-
# # Conversation context
|
| 498 |
-
# self.conversation_history = []
|
| 499 |
-
# self.current_transcription = ""
|
| 500 |
-
|
| 501 |
-
# # Multi-thread processing - FIXED: Khởi tạo queue đúng cách
|
| 502 |
-
# self.response_queue = queue.Queue()
|
| 503 |
-
# self.processing_threads = []
|
| 504 |
-
# self.max_workers = 2
|
| 505 |
-
|
| 506 |
-
# # Latency tracking - FIXED: Thêm các metrics còn thiếu
|
| 507 |
-
# self.latency_metrics = {
|
| 508 |
-
# 'asr': [],
|
| 509 |
-
# 'rag': [],
|
| 510 |
-
# 'llm': [],
|
| 511 |
-
# 'tts': [],
|
| 512 |
-
# 'total': [],
|
| 513 |
-
# 'vad_detection': [],
|
| 514 |
-
# 'queue_waiting': []
|
| 515 |
-
# }
|
| 516 |
-
|
| 517 |
-
# # FIXED: Thêm biến để track callback function
|
| 518 |
-
# self.current_callback = None
|
| 519 |
-
|
| 520 |
-
# def start_listening(self, speech_callback: Callable) -> bool:
|
| 521 |
-
# """Bắt đầu lắng nghe với multi-thread processing - FIXED VERSION"""
|
| 522 |
-
# if self.is_listening:
|
| 523 |
-
# return False
|
| 524 |
-
|
| 525 |
-
# # FIXED: Lưu callback function
|
| 526 |
-
# self.current_callback = speech_callback
|
| 527 |
-
# success = self.vad_processor.start_stream(self._on_speech_detected)
|
| 528 |
-
|
| 529 |
-
# if success:
|
| 530 |
-
# self.is_listening = True
|
| 531 |
-
# self.is_processing = False
|
| 532 |
-
|
| 533 |
-
# # FIXED: Khởi động worker threads chỉ khi chưa có
|
| 534 |
-
# if not self.processing_threads:
|
| 535 |
-
# for i in range(self.max_workers):
|
| 536 |
-
# thread = threading.Thread(
|
| 537 |
-
# target=self._process_response_worker,
|
| 538 |
-
# daemon=True,
|
| 539 |
-
# name=f"ASR-Worker-{i}"
|
| 540 |
-
# )
|
| 541 |
-
# thread.start()
|
| 542 |
-
# self.processing_threads.append(thread)
|
| 543 |
-
|
| 544 |
-
# print("🎙️ Đã bắt đầu lắng nghe với multi-thread processing")
|
| 545 |
-
# return True
|
| 546 |
-
# return False
|
| 547 |
-
|
| 548 |
-
# def stop_listening(self):
|
| 549 |
-
# """Dừng lắng nghe - FIXED VERSION"""
|
| 550 |
-
# self.vad_processor.stop_stream()
|
| 551 |
-
# self.is_listening = False
|
| 552 |
-
# self.is_processing = False
|
| 553 |
-
# self.current_callback = None
|
| 554 |
-
|
| 555 |
-
# # FIXED: Clear queue đúng cách
|
| 556 |
-
# while not self.response_queue.empty():
|
| 557 |
-
# try:
|
| 558 |
-
# self.response_queue.get_nowait()
|
| 559 |
-
# self.response_queue.task_done()
|
| 560 |
-
# except queue.Empty:
|
| 561 |
-
# break
|
| 562 |
-
|
| 563 |
-
# print("🛑 Đã dừng lắng nghe")
|
| 564 |
-
|
| 565 |
-
# def _on_speech_detected(self, speech_audio: np.ndarray, sample_rate: int):
|
| 566 |
-
# """Callback khi VAD phát hiện speech - FIXED: Thêm latency tracking"""
|
| 567 |
-
# vad_start = time.time()
|
| 568 |
-
# audio_duration = len(speech_audio) / sample_rate
|
| 569 |
-
|
| 570 |
-
# # FIXED: Đo lường VAD detection latency
|
| 571 |
-
# vad_latency = time.time() - vad_start
|
| 572 |
-
# self._add_latency_sample('vad_detection', vad_latency)
|
| 573 |
-
|
| 574 |
-
# print(f"🎯 VAD phát hiện speech: {audio_duration:.2f}s - Đưa vào queue")
|
| 575 |
-
|
| 576 |
-
# # FIXED: Thêm vào queue với timeout
|
| 577 |
-
# try:
|
| 578 |
-
# self.response_queue.put((speech_audio, sample_rate), timeout=0.5)
|
| 579 |
-
# except queue.Full:
|
| 580 |
-
# print("⚠️ Queue đầy, bỏ qua audio segment")
|
| 581 |
-
|
| 582 |
-
# def _process_response_worker(self):
|
| 583 |
-
# """Worker thread xử lý speech segments - FIXED VERSION"""
|
| 584 |
-
# while self.is_listening:
|
| 585 |
-
# try:
|
| 586 |
-
# # FIXED: Thêm queue waiting latency tracking
|
| 587 |
-
# queue_start = time.time()
|
| 588 |
-
# speech_audio, sample_rate = self.response_queue.get(timeout=1.0)
|
| 589 |
-
# queue_latency = time.time() - queue_start
|
| 590 |
-
# self._add_latency_sample('queue_waiting', queue_latency)
|
| 591 |
-
|
| 592 |
-
# # Xử lý speech segment
|
| 593 |
-
# self._process_speech_segment(speech_audio, sample_rate)
|
| 594 |
-
|
| 595 |
-
# # Đánh dấu task hoàn thành
|
| 596 |
-
# self.response_queue.task_done()
|
| 597 |
-
|
| 598 |
-
# except queue.Empty:
|
| 599 |
-
# continue
|
| 600 |
-
# except Exception as e:
|
| 601 |
-
# print(f"❌ Lỗi trong worker thread: {e}")
|
| 602 |
-
# continue
|
| 603 |
-
|
| 604 |
-
# def _process_speech_segment(self, speech_audio: np.ndarray, sample_rate: int):
|
| 605 |
-
# """Xử lý speech segment - FIXED: Sử dụng callback đúng cách"""
|
| 606 |
-
# total_start_time = time.time()
|
| 607 |
-
|
| 608 |
-
# try:
|
| 609 |
-
# # 1. ASR Transcription
|
| 610 |
-
# asr_start = time.time()
|
| 611 |
-
# transcription = self._transcribe_audio_optimized(speech_audio, sample_rate)
|
| 612 |
-
# asr_latency = time.time() - asr_start
|
| 613 |
-
|
| 614 |
-
# if not transcription or len(transcription.strip()) < 2:
|
| 615 |
-
# print("⚠️ Transcription quá ngắn hoặc trống")
|
| 616 |
-
# return
|
| 617 |
-
|
| 618 |
-
# print(f"📝 Transcription: {transcription}")
|
| 619 |
-
# self.current_transcription = transcription
|
| 620 |
-
|
| 621 |
-
# # 2. AI Response Generation
|
| 622 |
-
# rag_start = time.time()
|
| 623 |
-
# response = self._generate_ai_response_optimized(transcription)
|
| 624 |
-
# rag_latency = time.time() - rag_start
|
| 625 |
-
|
| 626 |
-
# # 3. TTS Conversion
|
| 627 |
-
# tts_start = time.time()
|
| 628 |
-
# tts_audio_path = self._text_to_speech_optimized(response)
|
| 629 |
-
# tts_latency = time.time() - tts_start
|
| 630 |
-
|
| 631 |
-
# total_latency = time.time() - total_start_time
|
| 632 |
-
|
| 633 |
-
# # Log latency metrics
|
| 634 |
-
# self._log_latency_metrics({
|
| 635 |
-
# 'asr': asr_latency,
|
| 636 |
-
# 'rag': rag_latency,
|
| 637 |
-
# 'tts': tts_latency,
|
| 638 |
-
# 'total': total_latency
|
| 639 |
-
# })
|
| 640 |
-
|
| 641 |
-
# # FIXED: Sử dụng callback đã lưu
|
| 642 |
-
# if self.current_callback:
|
| 643 |
-
# result = {
|
| 644 |
-
# 'transcription': transcription,
|
| 645 |
-
# 'response': response,
|
| 646 |
-
# 'tts_audio': tts_audio_path,
|
| 647 |
-
# 'status': 'completed',
|
| 648 |
-
# 'latency': total_latency
|
| 649 |
-
# }
|
| 650 |
-
# self.current_callback(result)
|
| 651 |
-
|
| 652 |
-
# except Exception as e:
|
| 653 |
-
# print(f"❌ Lỗi xử lý speech segment: {e}")
|
| 654 |
-
# traceback.print_exc()
|
| 655 |
-
|
| 656 |
-
# # FIXED: Gọi callback ngay cả khi có lỗi
|
| 657 |
-
# if self.current_callback:
|
| 658 |
-
# self.current_callback({
|
| 659 |
-
# 'transcription': f"Lỗi: {str(e)}",
|
| 660 |
-
# 'response': "Xin lỗi, có lỗi xảy ra",
|
| 661 |
-
# 'tts_audio': None,
|
| 662 |
-
# 'status': 'error'
|
| 663 |
-
# })
|
| 664 |
-
|
| 665 |
-
# def _transcribe_audio_optimized(self, audio_data: np.ndarray, sample_rate: int) -> Optional[str]:
|
| 666 |
-
# """Chuyển audio -> text với tối ưu hiệu suất - FIXED VERSION"""
|
| 667 |
-
# asr_start = time.time()
|
| 668 |
-
# try:
|
| 669 |
-
# # Chuẩn hóa audio data
|
| 670 |
-
# if audio_data.dtype != np.int16:
|
| 671 |
-
# if audio_data.dtype in [np.float32, np.float64]:
|
| 672 |
-
# audio_data = (audio_data * 32767).astype(np.int16)
|
| 673 |
-
# else:
|
| 674 |
-
# audio_data = audio_data.astype(np.int16)
|
| 675 |
-
|
| 676 |
-
# if audio_data.ndim > 1:
|
| 677 |
-
# audio_data = np.mean(audio_data, axis=1).astype(np.int16)
|
| 678 |
-
|
| 679 |
-
# # Resample nếu cần
|
| 680 |
-
# target_sample_rate = 16000
|
| 681 |
-
# if sample_rate != target_sample_rate:
|
| 682 |
-
# audio_data = self._resample_audio(audio_data, sample_rate, target_sample_rate)
|
| 683 |
-
# sample_rate = target_sample_rate
|
| 684 |
-
|
| 685 |
-
# # Giới hạn độ dài audio
|
| 686 |
-
# max_duration = 30
|
| 687 |
-
# max_samples = sample_rate * max_duration
|
| 688 |
-
# if len(audio_data) > max_samples:
|
| 689 |
-
# audio_data = audio_data[:max_samples]
|
| 690 |
-
|
| 691 |
-
# print(f"🔊 Gửi audio đến Whisper: {len(audio_data)} samples, {sample_rate}Hz")
|
| 692 |
-
|
| 693 |
-
# # Tạo temporary file trong memory
|
| 694 |
-
# buffer = io.BytesIO()
|
| 695 |
-
# sf.write(buffer, audio_data, sample_rate, format='wav', subtype='PCM_16')
|
| 696 |
-
# buffer.seek(0)
|
| 697 |
-
|
| 698 |
-
# # Gọi API Whisper với timeout
|
| 699 |
-
# api_start = time.time()
|
| 700 |
-
# try:
|
| 701 |
-
# # FIXED: Sửa lỗi buffer - đọc lại buffer sau khi seek
|
| 702 |
-
# audio_buffer_content = buffer.getvalue()
|
| 703 |
-
# transcription = self.client.audio.transcriptions.create(
|
| 704 |
-
# model=settings.WHISPER_MODEL,
|
| 705 |
-
# file=("speech.wav", audio_buffer_content, "audio/wav"),
|
| 706 |
-
# response_format="text",
|
| 707 |
-
# language="vi",
|
| 708 |
-
# temperature=0.0,
|
| 709 |
-
# )
|
| 710 |
-
# except Exception as e:
|
| 711 |
-
# print(f"❌ Lỗi Whisper API: {e}")
|
| 712 |
-
# return None
|
| 713 |
-
|
| 714 |
-
# api_latency = time.time() - api_start
|
| 715 |
-
|
| 716 |
-
# # Xử lý response
|
| 717 |
-
# if hasattr(transcription, 'text'):
|
| 718 |
-
# result = transcription.text.strip()
|
| 719 |
-
# elif isinstance(transcription, str):
|
| 720 |
-
# result = transcription.strip()
|
| 721 |
-
# else:
|
| 722 |
-
# result = str(transcription).strip()
|
| 723 |
-
|
| 724 |
-
# total_asr_latency = time.time() - asr_start
|
| 725 |
-
# print(f"✅ ASR Latency: {total_asr_latency:.2f}s (API: {api_latency:.2f}s)")
|
| 726 |
-
|
| 727 |
-
# # Kiểm tra chất lượng transcription
|
| 728 |
-
# if self._is_valid_transcription(result):
|
| 729 |
-
# return result
|
| 730 |
-
# else:
|
| 731 |
-
# print(f"⚠️ Transcription không hợp lệ: '{result}'")
|
| 732 |
-
# return None
|
| 733 |
-
|
| 734 |
-
# except Exception as e:
|
| 735 |
-
# print(f"❌ Lỗi transcription: {e}")
|
| 736 |
-
# traceback.print_exc()
|
| 737 |
-
# return None
|
| 738 |
-
|
| 739 |
-
# def _is_valid_transcription(self, text: str) -> bool:
|
| 740 |
-
# """Kiểm tra tính hợp lệ của transcription"""
|
| 741 |
-
# if not text or len(text.strip()) == 0:
|
| 742 |
-
# return False
|
| 743 |
-
|
| 744 |
-
# # Danh sách từ ngắn được chấp nhận
|
| 745 |
-
# short_responses = {
|
| 746 |
-
# 'ừ', 'um', 'à', 'ờ', 'ê', 'ô',
|
| 747 |
-
# 'có', 'không', 'đúng', 'sai', 'ok', 'okay', 'ừm',
|
| 748 |
-
# 'vâng', 'dạ', 'ạ', 'được', 'tốt', 'hay', 'ừ ừ',
|
| 749 |
-
# 'yes', 'no', 'yeah', 'yep', 'nope'
|
| 750 |
-
# }
|
| 751 |
-
|
| 752 |
-
# normalized_text = text.lower().strip()
|
| 753 |
-
|
| 754 |
-
# # Loại bỏ dấu câu và khoảng trắng thừa
|
| 755 |
-
# import re
|
| 756 |
-
# normalized_text = re.sub(r'[^\w\s]', '', normalized_text)
|
| 757 |
-
# normalized_text = re.sub(r'\s+', ' ', normalized_text).strip()
|
| 758 |
-
|
| 759 |
-
# # Nếu là từ ngắn thông dụng, chấp nhận
|
| 760 |
-
# if normalized_text in short_responses:
|
| 761 |
-
# return True
|
| 762 |
-
|
| 763 |
-
# # Kiểm tra độ dài tối thiểu cho các từ khác
|
| 764 |
-
# min_length = 2
|
| 765 |
-
# return len(normalized_text) >= min_length
|
| 766 |
-
|
| 767 |
-
# def _generate_ai_response_optimized(self, user_input: str) -> str:
|
| 768 |
-
# """Sinh phản hồi AI với tối ưu hiệu suất - FIXED: Thêm LLM latency tracking"""
|
| 769 |
-
# llm_start = time.time()
|
| 770 |
-
# try:
|
| 771 |
-
# # Thêm vào lịch sử
|
| 772 |
-
# self.conversation_history.append({"role": "user", "content": user_input})
|
| 773 |
-
|
| 774 |
-
# # Tìm kiếm RAG
|
| 775 |
-
# rag_start = time.time()
|
| 776 |
-
# rag_results = self.rag_system.semantic_search(user_input, top_k=2) if self.rag_system else []
|
| 777 |
-
# rag_latency = time.time() - rag_start
|
| 778 |
-
|
| 779 |
-
# context_text = "\n".join([f"- {result.get('text', str(result))}" for result in rag_results]) if rag_results else ""
|
| 780 |
-
|
| 781 |
-
# system_prompt = f"""Bạn là trợ lý AI thông minh chuyên về tiếng Việt.
|
| 782 |
-
# Hãy trả lời ngắn gọn, tự nhiên và hữu ích (dưới 100 từ).
|
| 783 |
-
# Thông tin tham khảo:
|
| 784 |
-
# {context_text}
|
| 785 |
-
# """
|
| 786 |
-
|
| 787 |
-
# messages = [{"role": "system", "content": system_prompt}]
|
| 788 |
-
# # Giữ lại 6 tin nhắn gần nhất
|
| 789 |
-
# messages.extend(self.conversation_history[-6:])
|
| 790 |
-
|
| 791 |
-
# llm_inference_start = time.time()
|
| 792 |
-
# completion = self.client.chat.completions.create(
|
| 793 |
-
# model=settings.MULTILINGUAL_LLM_MODEL,
|
| 794 |
-
# messages=messages,
|
| 795 |
-
# max_tokens=300,
|
| 796 |
-
# temperature=0.7
|
| 797 |
-
# )
|
| 798 |
-
# ttft = time.time() - llm_inference_start
|
| 799 |
-
|
| 800 |
-
# response = completion.choices[0].message.content
|
| 801 |
-
# self.conversation_history.append({"role": "assistant", "content": response})
|
| 802 |
-
|
| 803 |
-
# total_llm_latency = time.time() - llm_start
|
| 804 |
-
|
| 805 |
-
# # Giới hạn lịch sử
|
| 806 |
-
# if len(self.conversation_history) > 12:
|
| 807 |
-
# self.conversation_history = self.conversation_history[-12:]
|
| 808 |
-
|
| 809 |
-
# # FIXED: Thêm LLM latency tracking
|
| 810 |
-
# self._add_latency_sample('llm', total_llm_latency)
|
| 811 |
-
# self._add_latency_sample('rag', rag_latency)
|
| 812 |
-
|
| 813 |
-
# print(f"✅ RAG Latency: {rag_latency:.2f}s")
|
| 814 |
-
# print(f"✅ LLM TTFT: {ttft:.2f}s")
|
| 815 |
-
# print(f"✅ Total LLM Latency: {total_llm_latency:.2f}s")
|
| 816 |
-
|
| 817 |
-
# return response
|
| 818 |
-
|
| 819 |
-
# except Exception as e:
|
| 820 |
-
# print(f"❌ Lỗi tạo AI response: {e}")
|
| 821 |
-
# return "Xin lỗi, tôi gặp lỗi khi tạo phản hồi. Vui lòng thử lại."
|
| 822 |
-
|
| 823 |
-
# def _text_to_speech_optimized(self, text: str) -> Optional[str]:
|
| 824 |
-
# """Chuyển văn bản thành giọng nói với tối ưu"""
|
| 825 |
-
# tts_start = time.time()
|
| 826 |
-
# try:
|
| 827 |
-
# if not text or text.startswith("❌") or text.startswith("Xin lỗi"):
|
| 828 |
-
# return None
|
| 829 |
-
|
| 830 |
-
# tts_bytes = self.tts_service.text_to_speech(text, 'vi')
|
| 831 |
-
# tts_latency = time.time() - tts_start
|
| 832 |
-
|
| 833 |
-
# if tts_bytes:
|
| 834 |
-
# audio_path = self.tts_service.save_audio_to_file(tts_bytes)
|
| 835 |
-
# print(f"✅ TTS Latency: {tts_latency:.2f}s")
|
| 836 |
-
# # FIXED: Thêm TTS latency tracking
|
| 837 |
-
# self._add_latency_sample('tts', tts_latency)
|
| 838 |
-
# return audio_path
|
| 839 |
-
# except Exception as e:
|
| 840 |
-
# print(f"❌ Lỗi TTS: {e}")
|
| 841 |
-
# return None
|
| 842 |
-
|
| 843 |
-
# def process_streaming_audio(self, audio_data: tuple) -> Dict[str, Any]:
|
| 844 |
-
# """Xử lý audio streaming manual mode - FIXED VERSION"""
|
| 845 |
-
# if not audio_data:
|
| 846 |
-
# return self._create_error_response("❌ Không có dữ liệu âm thanh")
|
| 847 |
-
|
| 848 |
-
# try:
|
| 849 |
-
# sample_rate, audio_array = audio_data
|
| 850 |
-
|
| 851 |
-
# print(f"🎯 Nhận audio manual: {len(audio_array)} samples, SR: {sample_rate}")
|
| 852 |
-
|
| 853 |
-
# # Kiểm tra và chuyển đổi kiểu dữ liệu
|
| 854 |
-
# if isinstance(audio_array, np.ndarray):
|
| 855 |
-
# if audio_array.dtype == np.float32 or audio_array.dtype == np.float64:
|
| 856 |
-
# audio_array = (audio_array * 32767).astype(np.int16)
|
| 857 |
-
|
| 858 |
-
# if len(audio_array) == 0:
|
| 859 |
-
# return self._create_error_response("❌ Âm thanh trống")
|
| 860 |
-
|
| 861 |
-
# # Kiểm tra âm lượng
|
| 862 |
-
# audio_abs = np.abs(audio_array.astype(np.float32))
|
| 863 |
-
# audio_rms = np.sqrt(np.mean(audio_abs**2)) / 32767.0
|
| 864 |
-
|
| 865 |
-
# if audio_rms < 0.005:
|
| 866 |
-
# return self._create_error_response("❌ Âm thanh quá yếu")
|
| 867 |
-
|
| 868 |
-
# # Sử dụng VAD để kiểm tra speech
|
| 869 |
-
# if not self.vad_processor.is_speech(audio_array, sample_rate):
|
| 870 |
-
# return self._create_error_response("❌ Không phát hiện giọng nói")
|
| 871 |
-
|
| 872 |
-
# # Chuyển đổi thành văn bản
|
| 873 |
-
# transcription = self._transcribe_audio_optimized(audio_array, sample_rate)
|
| 874 |
-
|
| 875 |
-
# if not transcription:
|
| 876 |
-
# return self._create_error_response("❌ Không nghe rõ")
|
| 877 |
-
|
| 878 |
-
# print(f"📝 Đã chuyển đổi: {transcription}")
|
| 879 |
-
# self.current_transcription = transcription
|
| 880 |
-
|
| 881 |
-
# # Tạo phản hồi AI
|
| 882 |
-
# response = self._generate_ai_response_optimized(transcription)
|
| 883 |
-
|
| 884 |
-
# # Tạo TTS
|
| 885 |
-
# tts_audio_path = self._text_to_speech_optimized(response)
|
| 886 |
-
|
| 887 |
-
# return {
|
| 888 |
-
# 'transcription': transcription,
|
| 889 |
-
# 'response': response,
|
| 890 |
-
# 'tts_audio': tts_audio_path,
|
| 891 |
-
# 'status': 'completed'
|
| 892 |
-
# }
|
| 893 |
-
|
| 894 |
-
# except Exception as e:
|
| 895 |
-
# print(f"❌ Lỗi xử lý streaming audio: {e}")
|
| 896 |
-
# return self._create_error_response(f"❌ Lỗi: {str(e)}")
|
| 897 |
-
|
| 898 |
-
# def _create_error_response(self, message: str) -> Dict[str, Any]:
|
| 899 |
-
# """Tạo response lỗi chuẩn"""
|
| 900 |
-
# return {
|
| 901 |
-
# 'transcription': message,
|
| 902 |
-
# 'response': "Vui lòng thử lại",
|
| 903 |
-
# 'tts_audio': None,
|
| 904 |
-
# 'status': 'error'
|
| 905 |
-
# }
|
| 906 |
-
|
| 907 |
-
# def _resample_audio(self, audio_data: np.ndarray, orig_sr: int, target_sr: int) -> np.ndarray:
|
| 908 |
-
# """Resample audio"""
|
| 909 |
-
# try:
|
| 910 |
-
# from scipy import signal
|
| 911 |
-
# duration = len(audio_data) / orig_sr
|
| 912 |
-
# new_length = int(duration * target_sr)
|
| 913 |
-
# resampled_audio = signal.resample(audio_data, new_length)
|
| 914 |
-
# return np.clip(resampled_audio, -32768, 32767).astype(np.int16)
|
| 915 |
-
# except Exception:
|
| 916 |
-
# return audio_data
|
| 917 |
-
|
| 918 |
-
# def _add_latency_sample(self, component: str, latency: float):
|
| 919 |
-
# """Thêm mẫu latency - FIXED VERSION"""
|
| 920 |
-
# if component in self.latency_metrics:
|
| 921 |
-
# self.latency_metrics[component].append(latency)
|
| 922 |
-
# # Giữ chỉ 100 mẫu gần nhất
|
| 923 |
-
# if len(self.latency_metrics[component]) > 100:
|
| 924 |
-
# self.latency_metrics[component] = self.latency_metrics[component][-100:]
|
| 925 |
-
|
| 926 |
-
# def _log_latency_metrics(self, latencies: dict):
|
| 927 |
-
# """Log và theo dõi latency metrics - FIXED VERSION"""
|
| 928 |
-
# for key, value in latencies.items():
|
| 929 |
-
# self._add_latency_sample(key, value)
|
| 930 |
-
|
| 931 |
-
# print("📊 LATENCY REPORT:")
|
| 932 |
-
# for component, latency in latencies.items():
|
| 933 |
-
# print(f" {component.upper()}: {latency:.2f}s")
|
| 934 |
-
|
| 935 |
-
# def get_latency_stats(self) -> dict:
|
| 936 |
-
# """Lấy thống kê latency - FIXED VERSION"""
|
| 937 |
-
# stats = {}
|
| 938 |
-
# for component, latencies in self.latency_metrics.items():
|
| 939 |
-
# if latencies:
|
| 940 |
-
# recent_latencies = latencies[-10:] # Lấy 10 mẫu gần nhất
|
| 941 |
-
# stats[component] = {
|
| 942 |
-
# 'avg': sum(latencies) / len(latencies),
|
| 943 |
-
# 'min': min(latencies),
|
| 944 |
-
# 'max': max(latencies),
|
| 945 |
-
# 'count': len(latencies),
|
| 946 |
-
# 'recent_avg': sum(recent_latencies) / len(recent_latencies),
|
| 947 |
-
# 'recent_min': min(recent_latencies),
|
| 948 |
-
# 'recent_max': max(recent_latencies)
|
| 949 |
-
# }
|
| 950 |
-
# else:
|
| 951 |
-
# stats[component] = {
|
| 952 |
-
# 'avg': 0, 'min': 0, 'max': 0, 'count': 0,
|
| 953 |
-
# 'recent_avg': 0, 'recent_min': 0, 'recent_max': 0
|
| 954 |
-
# }
|
| 955 |
-
# return stats
|
| 956 |
-
|
| 957 |
-
# def get_conversation_state(self) -> dict:
|
| 958 |
-
# """Lấy trạng thái h���i thoại - FIXED VERSION"""
|
| 959 |
-
# return {
|
| 960 |
-
# 'is_listening': self.is_listening,
|
| 961 |
-
# 'is_processing': self.is_processing,
|
| 962 |
-
# 'history_length': len(self.conversation_history),
|
| 963 |
-
# 'current_transcription': self.current_transcription,
|
| 964 |
-
# 'queue_size': self.response_queue.qsize(),
|
| 965 |
-
# 'worker_threads': len(self.processing_threads),
|
| 966 |
-
# 'last_update': time.strftime("%H:%M:%S")
|
| 967 |
-
# }
|
| 968 |
-
|
| 969 |
-
# def clear_conversation(self):
|
| 970 |
-
# """Xóa lịch sử hội thoại"""
|
| 971 |
-
# self.conversation_history = []
|
| 972 |
-
# self.current_transcription = ""
|
| 973 |
-
# print("🗑️ Đã xóa lịch sử hội thoại")
|
| 974 |
import io
|
| 975 |
import numpy as np
|
| 976 |
import soundfile as sf
|
|
|
|
| 1 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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