Update services/streaming_voice_service.py
Browse files- services/streaming_voice_service.py +775 -216
services/streaming_voice_service.py
CHANGED
|
@@ -461,6 +461,511 @@
|
|
| 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 = []
|
|
@@ -472,14 +977,130 @@ 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 |
-
|
| 480 |
-
|
| 481 |
-
|
| 482 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 483 |
|
| 484 |
class StreamingVoiceService:
|
| 485 |
def __init__(self, groq_client: Groq, rag_system, tts_service):
|
|
@@ -487,6 +1108,9 @@ class StreamingVoiceService:
|
|
| 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
|
|
@@ -497,13 +1121,19 @@ class StreamingVoiceService:
|
|
| 497 |
# Conversation context
|
| 498 |
self.conversation_history = []
|
| 499 |
self.current_transcription = ""
|
|
|
|
| 500 |
|
| 501 |
-
# Multi-thread processing
|
| 502 |
self.response_queue = queue.Queue()
|
| 503 |
self.processing_threads = []
|
| 504 |
self.max_workers = 2
|
| 505 |
|
| 506 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 507 |
self.latency_metrics = {
|
| 508 |
'asr': [],
|
| 509 |
'rag': [],
|
|
@@ -511,26 +1141,33 @@ class StreamingVoiceService:
|
|
| 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
|
| 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 |
-
#
|
| 534 |
if not self.processing_threads:
|
| 535 |
for i in range(self.max_workers):
|
| 536 |
thread = threading.Thread(
|
|
@@ -541,18 +1178,27 @@ class StreamingVoiceService:
|
|
| 541 |
thread.start()
|
| 542 |
self.processing_threads.append(thread)
|
| 543 |
|
| 544 |
-
|
|
|
|
|
|
|
|
|
|
| 545 |
return True
|
| 546 |
return False
|
| 547 |
|
| 548 |
def stop_listening(self):
|
| 549 |
-
"""Dừng lắng nghe
|
| 550 |
self.vad_processor.stop_stream()
|
| 551 |
self.is_listening = False
|
| 552 |
self.is_processing = False
|
|
|
|
| 553 |
self.current_callback = None
|
| 554 |
|
| 555 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 556 |
while not self.response_queue.empty():
|
| 557 |
try:
|
| 558 |
self.response_queue.get_nowait()
|
|
@@ -562,37 +1208,94 @@ class StreamingVoiceService:
|
|
| 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 -
|
| 567 |
vad_start = time.time()
|
| 568 |
-
audio_duration = len(speech_audio) / sample_rate
|
| 569 |
|
| 570 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 571 |
vad_latency = time.time() - vad_start
|
| 572 |
self._add_latency_sample('vad_detection', vad_latency)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 573 |
|
| 574 |
-
|
| 575 |
-
|
| 576 |
-
# FIXED: Thêm vào queue với timeout
|
| 577 |
try:
|
| 578 |
-
self.response_queue.put(
|
| 579 |
except queue.Full:
|
| 580 |
-
print("⚠️ Queue đầy, bỏ qua
|
| 581 |
|
| 582 |
def _process_response_worker(self):
|
| 583 |
-
"""Worker thread xử lý
|
| 584 |
while self.is_listening:
|
| 585 |
try:
|
| 586 |
-
# FIXED: Thêm queue waiting latency tracking
|
| 587 |
queue_start = time.time()
|
| 588 |
-
|
| 589 |
queue_latency = time.time() - queue_start
|
| 590 |
self._add_latency_sample('queue_waiting', queue_latency)
|
| 591 |
|
| 592 |
-
# Xử lý
|
| 593 |
-
self.
|
| 594 |
|
| 595 |
-
# Đánh dấu task hoàn thành
|
| 596 |
self.response_queue.task_done()
|
| 597 |
|
| 598 |
except queue.Empty:
|
|
@@ -601,29 +1304,17 @@ class StreamingVoiceService:
|
|
| 601 |
print(f"❌ Lỗi trong worker thread: {e}")
|
| 602 |
continue
|
| 603 |
|
| 604 |
-
def
|
| 605 |
-
"""Xử lý
|
| 606 |
total_start_time = time.time()
|
| 607 |
|
| 608 |
try:
|
| 609 |
-
# 1.
|
| 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 |
-
#
|
| 627 |
tts_start = time.time()
|
| 628 |
tts_audio_path = self._text_to_speech_optimized(response)
|
| 629 |
tts_latency = time.time() - tts_start
|
|
@@ -632,13 +1323,12 @@ class StreamingVoiceService:
|
|
| 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 |
-
#
|
| 642 |
if self.current_callback:
|
| 643 |
result = {
|
| 644 |
'transcription': transcription,
|
|
@@ -650,122 +1340,19 @@ class StreamingVoiceService:
|
|
| 650 |
self.current_callback(result)
|
| 651 |
|
| 652 |
except Exception as e:
|
| 653 |
-
print(f"❌ Lỗi xử lý
|
| 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':
|
| 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
|
| 769 |
llm_start = time.time()
|
| 770 |
try:
|
| 771 |
# Thêm vào lịch sử
|
|
@@ -785,7 +1372,6 @@ Thông tin tham khảo:
|
|
| 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()
|
|
@@ -806,7 +1392,6 @@ Thông tin tham khảo:
|
|
| 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 |
|
|
@@ -832,8 +1417,6 @@ Thông tin tham khảo:
|
|
| 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:
|
|
@@ -841,55 +1424,40 @@ Thông tin tham khảo:
|
|
| 841 |
return None
|
| 842 |
|
| 843 |
def process_streaming_audio(self, audio_data: tuple) -> Dict[str, Any]:
|
| 844 |
-
"""Xử lý audio streaming manual mode
|
| 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 |
-
|
| 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 |
-
#
|
| 885 |
-
|
| 886 |
|
| 887 |
-
|
| 888 |
-
|
| 889 |
-
|
| 890 |
-
|
| 891 |
-
|
| 892 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 893 |
|
| 894 |
except Exception as e:
|
| 895 |
print(f"❌ Lỗi xử lý streaming audio: {e}")
|
|
@@ -904,27 +1472,15 @@ Thông tin tham khảo:
|
|
| 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
|
| 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
|
| 928 |
for key, value in latencies.items():
|
| 929 |
self._add_latency_sample(key, value)
|
| 930 |
|
|
@@ -933,11 +1489,11 @@ Thông tin tham khảo:
|
|
| 933 |
print(f" {component.upper()}: {latency:.2f}s")
|
| 934 |
|
| 935 |
def get_latency_stats(self) -> dict:
|
| 936 |
-
"""Lấy thống kê latency
|
| 937 |
stats = {}
|
| 938 |
for component, latencies in self.latency_metrics.items():
|
| 939 |
if latencies:
|
| 940 |
-
recent_latencies = latencies[-10:]
|
| 941 |
stats[component] = {
|
| 942 |
'avg': sum(latencies) / len(latencies),
|
| 943 |
'min': min(latencies),
|
|
@@ -955,14 +1511,16 @@ Thông tin tham khảo:
|
|
| 955 |
return stats
|
| 956 |
|
| 957 |
def get_conversation_state(self) -> dict:
|
| 958 |
-
"""Lấy trạng thái hội thoại
|
| 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 |
|
|
@@ -970,4 +1528,5 @@ Thông tin tham khảo:
|
|
| 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")
|
|
|
|
| 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 = []
|
|
|
|
| 977 |
import time
|
| 978 |
import traceback
|
| 979 |
import threading
|
|
|
|
| 980 |
import queue
|
| 981 |
+
import json
|
| 982 |
+
import os
|
| 983 |
+
from vosk import Model, KaldiRecognizer
|
| 984 |
+
from groq import Groq
|
| 985 |
from typing import Optional, Dict, Any, Callable
|
| 986 |
from config.settings import settings
|
| 987 |
+
|
| 988 |
+
class VoskStreamingASR:
|
| 989 |
+
def __init__(self, model_path: str = None):
|
| 990 |
+
"""Khởi tạo VOSK ASR streaming"""
|
| 991 |
+
self.model = None
|
| 992 |
+
self.recognizer = None
|
| 993 |
+
self.sample_rate = 16000
|
| 994 |
+
self.is_streaming = False
|
| 995 |
+
self.partial_results = []
|
| 996 |
+
|
| 997 |
+
# Tự động tải model nếu không có đường dẫn
|
| 998 |
+
if model_path is None:
|
| 999 |
+
model_path = self._download_vosk_model()
|
| 1000 |
+
|
| 1001 |
+
if os.path.exists(model_path):
|
| 1002 |
+
print("🔄 Đang tải VOSK model...")
|
| 1003 |
+
self.model = Model(model_path)
|
| 1004 |
+
self.recognizer = KaldiRecognizer(self.model, self.sample_rate)
|
| 1005 |
+
print("✅ Đã tải VOSK model thành công")
|
| 1006 |
+
else:
|
| 1007 |
+
print(f"❌ Không tìm thấy VOSK model tại: {model_path}")
|
| 1008 |
+
|
| 1009 |
+
def _download_vosk_model(self):
|
| 1010 |
+
"""Tải VOSK model tiếng Việt tự động"""
|
| 1011 |
+
import urllib.request
|
| 1012 |
+
import zipfile
|
| 1013 |
+
|
| 1014 |
+
model_url = "https://alphacephei.com/vosk/models/vosk-model-vi-0.5.zip"
|
| 1015 |
+
model_dir = "models/vosk-model-vi"
|
| 1016 |
+
zip_path = "models/vosk-model-vi.zip"
|
| 1017 |
+
|
| 1018 |
+
# Tạo thư mục nếu chưa có
|
| 1019 |
+
os.makedirs("models", exist_ok=True)
|
| 1020 |
+
|
| 1021 |
+
if not os.path.exists(model_dir):
|
| 1022 |
+
print("📥 Đang tải VOSK Vietnamese model...")
|
| 1023 |
+
try:
|
| 1024 |
+
urllib.request.urlretrieve(model_url, zip_path)
|
| 1025 |
+
|
| 1026 |
+
with zipfile.ZipFile(zip_path, 'r') as zip_ref:
|
| 1027 |
+
zip_ref.extractall("models/")
|
| 1028 |
+
|
| 1029 |
+
os.rename("models/vosk-model-vi-0.5", model_dir)
|
| 1030 |
+
os.remove(zip_path)
|
| 1031 |
+
print("✅ Đã tải VOSK model thành công")
|
| 1032 |
+
except Exception as e:
|
| 1033 |
+
print(f"❌ Lỗi tải VOSK model: {e}")
|
| 1034 |
+
return None
|
| 1035 |
+
|
| 1036 |
+
return model_dir
|
| 1037 |
+
|
| 1038 |
+
def start_stream(self):
|
| 1039 |
+
"""Bắt đầu stream mới"""
|
| 1040 |
+
if self.model is None:
|
| 1041 |
+
return False
|
| 1042 |
+
|
| 1043 |
+
self.recognizer = KaldiRecognizer(self.model, self.sample_rate)
|
| 1044 |
+
self.recognizer.SetWords(True)
|
| 1045 |
+
self.is_streaming = True
|
| 1046 |
+
self.partial_results = []
|
| 1047 |
+
return True
|
| 1048 |
+
|
| 1049 |
+
def process_audio_chunk(self, audio_chunk: np.ndarray, sample_rate: int = None) -> Dict[str, Any]:
|
| 1050 |
+
"""Xử lý audio chunk và trả về kết quả"""
|
| 1051 |
+
if self.recognizer is None or not self.is_streaming:
|
| 1052 |
+
return {"text": "", "partial": "", "is_final": False}
|
| 1053 |
+
|
| 1054 |
+
try:
|
| 1055 |
+
# Chuẩn hóa audio
|
| 1056 |
+
if sample_rate and sample_rate != self.sample_rate:
|
| 1057 |
+
audio_chunk = self._resample_audio(audio_chunk, sample_rate, self.sample_rate)
|
| 1058 |
+
|
| 1059 |
+
if audio_chunk.dtype != np.int16:
|
| 1060 |
+
audio_chunk = (audio_chunk * 32767).astype(np.int16)
|
| 1061 |
+
|
| 1062 |
+
# Chuyển đổi sang bytes
|
| 1063 |
+
audio_bytes = audio_chunk.tobytes()
|
| 1064 |
+
|
| 1065 |
+
# Xử lý với VOSK
|
| 1066 |
+
if self.recognizer.AcceptWaveform(audio_bytes):
|
| 1067 |
+
# Kết quả cuối cùng
|
| 1068 |
+
result = json.loads(self.recognizer.Result())
|
| 1069 |
+
text = result.get('text', '').strip()
|
| 1070 |
+
if text:
|
| 1071 |
+
return {"text": text, "partial": "", "is_final": True}
|
| 1072 |
+
else:
|
| 1073 |
+
# Kết quả tạm thời
|
| 1074 |
+
partial_result = json.loads(self.recognizer.PartialResult())
|
| 1075 |
+
partial_text = partial_result.get('partial', '').strip()
|
| 1076 |
+
return {"text": "", "partial": partial_text, "is_final": False}
|
| 1077 |
+
|
| 1078 |
+
except Exception as e:
|
| 1079 |
+
print(f"❌ Lỗi VOSK processing: {e}")
|
| 1080 |
+
|
| 1081 |
+
return {"text": "", "partial": "", "is_final": False}
|
| 1082 |
+
|
| 1083 |
+
def stop_stream(self) -> str:
|
| 1084 |
+
"""Kết thúc stream và lấy kết quả cuối"""
|
| 1085 |
+
if self.recognizer:
|
| 1086 |
+
result = json.loads(self.recognizer.FinalResult())
|
| 1087 |
+
text = result.get('text', '').strip()
|
| 1088 |
+
self.is_streaming = False
|
| 1089 |
+
return text
|
| 1090 |
+
return ""
|
| 1091 |
+
|
| 1092 |
+
def _resample_audio(self, audio: np.ndarray, orig_sr: int, target_sr: int) -> np.ndarray:
|
| 1093 |
+
"""Resample audio"""
|
| 1094 |
+
if orig_sr == target_sr:
|
| 1095 |
+
return audio
|
| 1096 |
+
try:
|
| 1097 |
+
from scipy import signal
|
| 1098 |
+
duration = len(audio) / orig_sr
|
| 1099 |
+
new_length = int(duration * target_sr)
|
| 1100 |
+
resampled_audio = signal.resample(audio, new_length)
|
| 1101 |
+
return resampled_audio.astype(np.int16)
|
| 1102 |
+
except Exception:
|
| 1103 |
+
return audio
|
| 1104 |
|
| 1105 |
class StreamingVoiceService:
|
| 1106 |
def __init__(self, groq_client: Groq, rag_system, tts_service):
|
|
|
|
| 1108 |
self.rag_system = rag_system
|
| 1109 |
self.tts_service = tts_service
|
| 1110 |
|
| 1111 |
+
# Khởi tạo VOSK ASR thay vì Whisper
|
| 1112 |
+
self.vosk_asr = VoskStreamingASR()
|
| 1113 |
+
|
| 1114 |
# Khởi tạo VAD
|
| 1115 |
self.vad_processor = SileroVAD()
|
| 1116 |
self.is_listening = False
|
|
|
|
| 1121 |
# Conversation context
|
| 1122 |
self.conversation_history = []
|
| 1123 |
self.current_transcription = ""
|
| 1124 |
+
self.partial_transcription = ""
|
| 1125 |
|
| 1126 |
+
# Multi-thread processing
|
| 1127 |
self.response_queue = queue.Queue()
|
| 1128 |
self.processing_threads = []
|
| 1129 |
self.max_workers = 2
|
| 1130 |
|
| 1131 |
+
# VOSK streaming state
|
| 1132 |
+
self.vosk_stream_active = False
|
| 1133 |
+
self.last_voice_time = 0
|
| 1134 |
+
self.silence_timeout = 2.0 # 2 giây im lặng thì kết thúc câu
|
| 1135 |
+
|
| 1136 |
+
# Latency tracking
|
| 1137 |
self.latency_metrics = {
|
| 1138 |
'asr': [],
|
| 1139 |
'rag': [],
|
|
|
|
| 1141 |
'tts': [],
|
| 1142 |
'total': [],
|
| 1143 |
'vad_detection': [],
|
| 1144 |
+
'queue_waiting': [],
|
| 1145 |
+
'vosk_processing': []
|
| 1146 |
}
|
| 1147 |
|
|
|
|
| 1148 |
self.current_callback = None
|
| 1149 |
|
| 1150 |
def start_listening(self, speech_callback: Callable) -> bool:
|
| 1151 |
+
"""Bắt đầu lắng nghe với VOSK streaming"""
|
| 1152 |
if self.is_listening:
|
| 1153 |
return False
|
| 1154 |
|
|
|
|
| 1155 |
self.current_callback = speech_callback
|
| 1156 |
+
|
| 1157 |
+
# Khởi động VOSK stream
|
| 1158 |
+
if not self.vosk_asr.start_stream():
|
| 1159 |
+
print("❌ Không thể khởi động VOSK ASR")
|
| 1160 |
+
return False
|
| 1161 |
+
|
| 1162 |
success = self.vad_processor.start_stream(self._on_speech_detected)
|
| 1163 |
|
| 1164 |
if success:
|
| 1165 |
self.is_listening = True
|
| 1166 |
self.is_processing = False
|
| 1167 |
+
self.vosk_stream_active = True
|
| 1168 |
+
self.last_voice_time = time.time()
|
| 1169 |
|
| 1170 |
+
# Khởi động worker threads
|
| 1171 |
if not self.processing_threads:
|
| 1172 |
for i in range(self.max_workers):
|
| 1173 |
thread = threading.Thread(
|
|
|
|
| 1178 |
thread.start()
|
| 1179 |
self.processing_threads.append(thread)
|
| 1180 |
|
| 1181 |
+
# Bắt đầu thread theo dõi VOSK streaming
|
| 1182 |
+
threading.Thread(target=self._vosk_streaming_monitor, daemon=True).start()
|
| 1183 |
+
|
| 1184 |
+
print("🎙️ Đã bắt đầu lắng nghe với VOSK ASR streaming")
|
| 1185 |
return True
|
| 1186 |
return False
|
| 1187 |
|
| 1188 |
def stop_listening(self):
|
| 1189 |
+
"""Dừng lắng nghe"""
|
| 1190 |
self.vad_processor.stop_stream()
|
| 1191 |
self.is_listening = False
|
| 1192 |
self.is_processing = False
|
| 1193 |
+
self.vosk_stream_active = False
|
| 1194 |
self.current_callback = None
|
| 1195 |
|
| 1196 |
+
# Dừng VOSK stream
|
| 1197 |
+
final_text = self.vosk_asr.stop_stream()
|
| 1198 |
+
if final_text and len(final_text) > 1:
|
| 1199 |
+
self._process_final_transcription(final_text)
|
| 1200 |
+
|
| 1201 |
+
# Clear queue
|
| 1202 |
while not self.response_queue.empty():
|
| 1203 |
try:
|
| 1204 |
self.response_queue.get_nowait()
|
|
|
|
| 1208 |
|
| 1209 |
print("🛑 Đã dừng lắng nghe")
|
| 1210 |
|
| 1211 |
+
def _vosk_streaming_monitor(self):
|
| 1212 |
+
"""Theo dõi VOSK streaming và xử lý kết quả real-time"""
|
| 1213 |
+
while self.is_listening and self.vosk_stream_active:
|
| 1214 |
+
try:
|
| 1215 |
+
# Kiểm tra timeout im lặng
|
| 1216 |
+
current_time = time.time()
|
| 1217 |
+
silence_duration = current_time - self.last_voice_time
|
| 1218 |
+
|
| 1219 |
+
if silence_duration > self.silence_timeout and self.partial_transcription:
|
| 1220 |
+
# Im lặng quá lâu, xử lý transcription hiện tại
|
| 1221 |
+
print(f"⏰ Silence timeout, xử lý: {self.partial_transcription}")
|
| 1222 |
+
self._process_final_transcription(self.partial_transcription)
|
| 1223 |
+
self.partial_transcription = ""
|
| 1224 |
+
self.vosk_asr.start_stream() # Bắt đầu stream mới
|
| 1225 |
+
|
| 1226 |
+
time.sleep(0.1) # Giảm CPU usage
|
| 1227 |
+
|
| 1228 |
+
except Exception as e:
|
| 1229 |
+
print(f"❌ Lỗi VOSK monitor: {e}")
|
| 1230 |
+
break
|
| 1231 |
+
|
| 1232 |
def _on_speech_detected(self, speech_audio: np.ndarray, sample_rate: int):
|
| 1233 |
+
"""Callback khi VAD phát hiện speech - sử dụng VOSK real-time"""
|
| 1234 |
vad_start = time.time()
|
|
|
|
| 1235 |
|
| 1236 |
+
if not self.vosk_stream_active:
|
| 1237 |
+
return
|
| 1238 |
+
|
| 1239 |
+
# Cập nhật thời gian có giọng nói
|
| 1240 |
+
self.last_voice_time = time.time()
|
| 1241 |
+
|
| 1242 |
+
# Xử lý với VOSK
|
| 1243 |
+
vosk_start = time.time()
|
| 1244 |
+
result = self.vosk_asr.process_audio_chunk(speech_audio, sample_rate)
|
| 1245 |
+
vosk_latency = time.time() - vosk_start
|
| 1246 |
+
|
| 1247 |
+
self._add_latency_sample('vosk_processing', vosk_latency)
|
| 1248 |
+
|
| 1249 |
+
# Xử lý kết quả partial
|
| 1250 |
+
if result['partial'] and len(result['partial']) > 1:
|
| 1251 |
+
self.partial_transcription = result['partial']
|
| 1252 |
+
print(f"🎯 VOSK Partial: {result['partial']}")
|
| 1253 |
+
|
| 1254 |
+
# Gửi partial result real-time
|
| 1255 |
+
if self.current_callback:
|
| 1256 |
+
self.current_callback({
|
| 1257 |
+
'transcription': result['partial'],
|
| 1258 |
+
'response': "",
|
| 1259 |
+
'tts_audio': None,
|
| 1260 |
+
'status': 'partial'
|
| 1261 |
+
})
|
| 1262 |
+
|
| 1263 |
+
# Xử lý kết quả final
|
| 1264 |
+
if result['is_final'] and result['text'] and len(result['text']) > 1:
|
| 1265 |
+
print(f"✅ VOSK Final: {result['text']}")
|
| 1266 |
+
self._process_final_transcription(result['text'])
|
| 1267 |
+
self.partial_transcription = ""
|
| 1268 |
+
self.vosk_asr.start_stream() # Bắt đầu stream mới
|
| 1269 |
+
|
| 1270 |
vad_latency = time.time() - vad_start
|
| 1271 |
self._add_latency_sample('vad_detection', vad_latency)
|
| 1272 |
+
|
| 1273 |
+
def _process_final_transcription(self, transcription: str):
|
| 1274 |
+
"""Xử lý transcription cuối cùng"""
|
| 1275 |
+
if not transcription or len(transcription.strip()) < 2:
|
| 1276 |
+
return
|
| 1277 |
+
|
| 1278 |
+
print(f"📝 Final Transcription: {transcription}")
|
| 1279 |
+
self.current_transcription = transcription
|
| 1280 |
|
| 1281 |
+
# Đưa vào queue để xử lý
|
|
|
|
|
|
|
| 1282 |
try:
|
| 1283 |
+
self.response_queue.put(transcription, timeout=0.5)
|
| 1284 |
except queue.Full:
|
| 1285 |
+
print("⚠️ Queue đầy, bỏ qua transcription")
|
| 1286 |
|
| 1287 |
def _process_response_worker(self):
|
| 1288 |
+
"""Worker thread xử lý transcriptions"""
|
| 1289 |
while self.is_listening:
|
| 1290 |
try:
|
|
|
|
| 1291 |
queue_start = time.time()
|
| 1292 |
+
transcription = self.response_queue.get(timeout=1.0)
|
| 1293 |
queue_latency = time.time() - queue_start
|
| 1294 |
self._add_latency_sample('queue_waiting', queue_latency)
|
| 1295 |
|
| 1296 |
+
# Xử lý AI response
|
| 1297 |
+
self._process_ai_response(transcription)
|
| 1298 |
|
|
|
|
| 1299 |
self.response_queue.task_done()
|
| 1300 |
|
| 1301 |
except queue.Empty:
|
|
|
|
| 1304 |
print(f"❌ Lỗi trong worker thread: {e}")
|
| 1305 |
continue
|
| 1306 |
|
| 1307 |
+
def _process_ai_response(self, transcription: str):
|
| 1308 |
+
"""Xử lý phản hồi AI cho transcription"""
|
| 1309 |
total_start_time = time.time()
|
| 1310 |
|
| 1311 |
try:
|
| 1312 |
+
# 1. AI Response Generation
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1313 |
rag_start = time.time()
|
| 1314 |
response = self._generate_ai_response_optimized(transcription)
|
| 1315 |
rag_latency = time.time() - rag_start
|
| 1316 |
|
| 1317 |
+
# 2. TTS Conversion
|
| 1318 |
tts_start = time.time()
|
| 1319 |
tts_audio_path = self._text_to_speech_optimized(response)
|
| 1320 |
tts_latency = time.time() - tts_start
|
|
|
|
| 1323 |
|
| 1324 |
# Log latency metrics
|
| 1325 |
self._log_latency_metrics({
|
|
|
|
| 1326 |
'rag': rag_latency,
|
| 1327 |
'tts': tts_latency,
|
| 1328 |
'total': total_latency
|
| 1329 |
})
|
| 1330 |
|
| 1331 |
+
# Gọi callback
|
| 1332 |
if self.current_callback:
|
| 1333 |
result = {
|
| 1334 |
'transcription': transcription,
|
|
|
|
| 1340 |
self.current_callback(result)
|
| 1341 |
|
| 1342 |
except Exception as e:
|
| 1343 |
+
print(f"❌ Lỗi xử lý AI response: {e}")
|
| 1344 |
traceback.print_exc()
|
| 1345 |
|
|
|
|
| 1346 |
if self.current_callback:
|
| 1347 |
self.current_callback({
|
| 1348 |
+
'transcription': transcription,
|
| 1349 |
+
'response': f"Xin lỗi, có lỗi xảy ra: {str(e)}",
|
| 1350 |
'tts_audio': None,
|
| 1351 |
'status': 'error'
|
| 1352 |
})
|
| 1353 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1354 |
def _generate_ai_response_optimized(self, user_input: str) -> str:
|
| 1355 |
+
"""Sinh phản hồi AI với tối ưu hiệu suất"""
|
| 1356 |
llm_start = time.time()
|
| 1357 |
try:
|
| 1358 |
# Thêm vào lịch sử
|
|
|
|
| 1372 |
"""
|
| 1373 |
|
| 1374 |
messages = [{"role": "system", "content": system_prompt}]
|
|
|
|
| 1375 |
messages.extend(self.conversation_history[-6:])
|
| 1376 |
|
| 1377 |
llm_inference_start = time.time()
|
|
|
|
| 1392 |
if len(self.conversation_history) > 12:
|
| 1393 |
self.conversation_history = self.conversation_history[-12:]
|
| 1394 |
|
|
|
|
| 1395 |
self._add_latency_sample('llm', total_llm_latency)
|
| 1396 |
self._add_latency_sample('rag', rag_latency)
|
| 1397 |
|
|
|
|
| 1417 |
|
| 1418 |
if tts_bytes:
|
| 1419 |
audio_path = self.tts_service.save_audio_to_file(tts_bytes)
|
|
|
|
|
|
|
| 1420 |
self._add_latency_sample('tts', tts_latency)
|
| 1421 |
return audio_path
|
| 1422 |
except Exception as e:
|
|
|
|
| 1424 |
return None
|
| 1425 |
|
| 1426 |
def process_streaming_audio(self, audio_data: tuple) -> Dict[str, Any]:
|
| 1427 |
+
"""Xử lý audio streaming manual mode với VOSK"""
|
| 1428 |
if not audio_data:
|
| 1429 |
return self._create_error_response("❌ Không có dữ liệu âm thanh")
|
| 1430 |
|
| 1431 |
try:
|
| 1432 |
sample_rate, audio_array = audio_data
|
| 1433 |
|
| 1434 |
+
# Khởi động VOSK stream tạm thời
|
| 1435 |
+
self.vosk_asr.start_stream()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1436 |
|
| 1437 |
+
# Xử lý audio với VOSK
|
| 1438 |
+
result = self.vosk_asr.process_audio_chunk(audio_array, sample_rate)
|
| 1439 |
|
| 1440 |
+
if result['is_final'] and result['text']:
|
| 1441 |
+
transcription = result['text']
|
| 1442 |
+
print(f"📝 Manual Transcription: {transcription}")
|
| 1443 |
+
|
| 1444 |
+
# Tạo phản hồi AI
|
| 1445 |
+
response = self._generate_ai_response_optimized(transcription)
|
| 1446 |
+
tts_audio_path = self._text_to_speech_optimized(response)
|
| 1447 |
+
|
| 1448 |
+
return {
|
| 1449 |
+
'transcription': transcription,
|
| 1450 |
+
'response': response,
|
| 1451 |
+
'tts_audio': tts_audio_path,
|
| 1452 |
+
'status': 'completed'
|
| 1453 |
+
}
|
| 1454 |
+
else:
|
| 1455 |
+
return {
|
| 1456 |
+
'transcription': result['partial'] or "Đang nghe...",
|
| 1457 |
+
'response': "",
|
| 1458 |
+
'tts_audio': None,
|
| 1459 |
+
'status': 'listening'
|
| 1460 |
+
}
|
| 1461 |
|
| 1462 |
except Exception as e:
|
| 1463 |
print(f"❌ Lỗi xử lý streaming audio: {e}")
|
|
|
|
| 1472 |
'status': 'error'
|
| 1473 |
}
|
| 1474 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1475 |
def _add_latency_sample(self, component: str, latency: float):
|
| 1476 |
+
"""Thêm mẫu latency"""
|
| 1477 |
if component in self.latency_metrics:
|
| 1478 |
self.latency_metrics[component].append(latency)
|
|
|
|
| 1479 |
if len(self.latency_metrics[component]) > 100:
|
| 1480 |
self.latency_metrics[component] = self.latency_metrics[component][-100:]
|
| 1481 |
|
| 1482 |
def _log_latency_metrics(self, latencies: dict):
|
| 1483 |
+
"""Log và theo dõi latency metrics"""
|
| 1484 |
for key, value in latencies.items():
|
| 1485 |
self._add_latency_sample(key, value)
|
| 1486 |
|
|
|
|
| 1489 |
print(f" {component.upper()}: {latency:.2f}s")
|
| 1490 |
|
| 1491 |
def get_latency_stats(self) -> dict:
|
| 1492 |
+
"""Lấy thống kê latency"""
|
| 1493 |
stats = {}
|
| 1494 |
for component, latencies in self.latency_metrics.items():
|
| 1495 |
if latencies:
|
| 1496 |
+
recent_latencies = latencies[-10:]
|
| 1497 |
stats[component] = {
|
| 1498 |
'avg': sum(latencies) / len(latencies),
|
| 1499 |
'min': min(latencies),
|
|
|
|
| 1511 |
return stats
|
| 1512 |
|
| 1513 |
def get_conversation_state(self) -> dict:
|
| 1514 |
+
"""Lấy trạng thái hội thoại"""
|
| 1515 |
return {
|
| 1516 |
'is_listening': self.is_listening,
|
| 1517 |
'is_processing': self.is_processing,
|
| 1518 |
'history_length': len(self.conversation_history),
|
| 1519 |
'current_transcription': self.current_transcription,
|
| 1520 |
+
'partial_transcription': self.partial_transcription,
|
| 1521 |
'queue_size': self.response_queue.qsize(),
|
| 1522 |
'worker_threads': len(self.processing_threads),
|
| 1523 |
+
'vosk_active': self.vosk_stream_active,
|
| 1524 |
'last_update': time.strftime("%H:%M:%S")
|
| 1525 |
}
|
| 1526 |
|
|
|
|
| 1528 |
"""Xóa lịch sử hội thoại"""
|
| 1529 |
self.conversation_history = []
|
| 1530 |
self.current_transcription = ""
|
| 1531 |
+
self.partial_transcription = ""
|
| 1532 |
print("🗑️ Đã xóa lịch sử hội thoại")
|