File size: 50,787 Bytes
361b4a9
 
 
 
 
 
 
 
 
0304fae
 
361b4a9
 
 
19ac002
0304fae
361b4a9
 
d102321
361b4a9
 
 
 
 
d102321
361b4a9
d102321
361b4a9
d102321
361b4a9
 
 
 
 
 
 
 
 
 
 
0304fae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
361b4a9
 
 
 
d102321
361b4a9
 
 
 
 
 
 
 
 
 
 
 
 
 
d102321
361b4a9
 
 
d102321
 
361b4a9
0304fae
361b4a9
 
 
 
 
0304fae
 
 
 
361b4a9
 
 
 
d102321
 
 
 
0304fae
 
361b4a9
 
d102321
 
361b4a9
 
 
 
d102321
0304fae
 
 
 
 
 
 
 
d102321
 
361b4a9
d102321
361b4a9
 
 
 
d102321
 
361b4a9
 
d102321
 
 
 
361b4a9
 
 
d102321
0304fae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
361b4a9
 
 
 
 
 
 
d102321
361b4a9
 
19ac002
3bcab2c
19ac002
361b4a9
19ac002
d102321
835fc53
 
 
 
 
19ac002
 
 
 
3bcab2c
 
 
19ac002
d102321
 
 
361b4a9
3bcab2c
 
 
 
 
 
 
 
 
 
 
 
 
19ac002
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3bcab2c
19ac002
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3bcab2c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19ac002
3bcab2c
19ac002
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
361b4a9
19ac002
361b4a9
d102321
 
 
361b4a9
 
 
 
19ac002
0304fae
19ac002
 
 
 
361b4a9
 
 
d102321
361b4a9
d102321
 
19ac002
 
d102321
 
 
 
 
 
 
 
361b4a9
19ac002
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
835fc53
361b4a9
 
 
 
 
 
 
 
0304fae
361b4a9
 
 
 
 
 
0304fae
d102321
361b4a9
 
d102321
361b4a9
835fc53
 
 
 
 
361b4a9
d102321
835fc53
361b4a9
 
 
 
 
 
 
 
 
835fc53
 
 
 
 
361b4a9
 
0304fae
361b4a9
 
d102321
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0304fae
 
835fc53
 
 
0304fae
 
d102321
19ac002
d102321
 
 
835fc53
d102321
835fc53
19ac002
835fc53
d102321
835fc53
d102321
 
 
835fc53
d102321
 
 
988cb02
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
361b4a9
988cb02
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
361b4a9
 
 
 
988cb02
361b4a9
988cb02
361b4a9
 
 
988cb02
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
361b4a9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
988cb02
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
361b4a9
988cb02
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
361b4a9
988cb02
 
361b4a9
988cb02
 
 
361b4a9
 
 
 
 
 
988cb02
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
361b4a9
988cb02
 
 
 
 
 
 
 
 
 
 
 
361b4a9
 
988cb02
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
361b4a9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
988cb02
 
 
 
361b4a9
 
 
 
 
988cb02
361b4a9
 
 
 
 
 
 
 
 
 
 
988cb02
 
 
361b4a9
988cb02
 
361b4a9
 
988cb02
 
361b4a9
988cb02
 
 
 
 
 
361b4a9
 
 
 
988cb02
361b4a9
988cb02
 
 
361b4a9
 
988cb02
361b4a9
 
 
 
 
 
 
 
 
 
988cb02
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
361b4a9
988cb02
 
 
 
 
 
 
 
 
361b4a9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
988cb02
 
 
 
 
 
 
 
 
 
361b4a9
 
 
 
 
 
 
 
 
 
 
 
 
 
988cb02
361b4a9
 
 
 
 
 
988cb02
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
361b4a9
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
import io
import numpy as np
import soundfile as sf
import time
import traceback
import threading
import queue
import json
import os
import urllib.request
import zipfile
from vosk import Model, KaldiRecognizer
from groq import Groq
from typing import Optional, Dict, Any, Callable
from core.silero_vad import SileroVAD

class VoskStreamingASR:
    def __init__(self, model_path: str = None):
        """Khởi tạo VOSK ASR streaming với buffer"""
        self.model = None
        self.recognizer = None
        self.sample_rate = 16000
        self.is_streaming = False
        
        # Buffer để tích luỹ audio - QUAN TRỌNG
        self.audio_buffer = []
        self.buffer_size = 32000  # 2 giây audio
        
        # Tự động tải model nếu không có đường dẫn
        if model_path is None:
            model_path = self._download_vosk_model()
        
        if model_path and os.path.exists(model_path):
            print(f"🔄 Đang tải VOSK model từ: {model_path}")
            try:
                self.model = Model(model_path)
                print("✅ Đã tải VOSK model thành công")
            except Exception as e:
                print(f"❌ Lỗi khởi tạo VOSK model: {e}")
        else:
            print(f"❌ Không tìm thấy VOSK model")

    def _download_vosk_model(self):
        """Tải VOSK model tiếng Việt tự động"""
        try:
            model_url = "https://alphacephei.com/vosk/models/vosk-model-small-vn-0.4.zip"
            model_dir = "models/vosk-model-small-vn-0.4"
            zip_path = "models/vosk-model-small-vn-0.4.zip"
            
            # Tạo thư mục nếu chưa có
            os.makedirs("models", exist_ok=True)
            
            if not os.path.exists(model_dir):
                print("📥 Đang tải VOSK Vietnamese model...")
                urllib.request.urlretrieve(model_url, zip_path)
                
                with zipfile.ZipFile(zip_path, 'r') as zip_ref:
                    zip_ref.extractall("models/")
                
                if os.path.exists("models/vosk-model-small-vn-0.4"):
                    os.rename("models/vosk-model-small-vn-0.4", model_dir)
                
                if os.path.exists(zip_path):
                    os.remove(zip_path)
                print("✅ Đã tải VOSK model thành công")
            
            return model_dir if os.path.exists(model_dir) else None
            
        except Exception as e:
            print(f"❌ Lỗi tải VOSK model: {e}")
            return None

    def start_stream(self):
        """Bắt đầu stream mới"""
        if self.model is None:
            print("❌ VOSK model chưa được khởi tạo")
            return False
            
        try:
            self.recognizer = KaldiRecognizer(self.model, self.sample_rate)
            self.recognizer.SetWords(True)
            self.is_streaming = True
            self.audio_buffer = []  # reset buffer
            print("🎤 Đã khởi động VOSK stream")
            return True
        except Exception as e:
            print(f"❌ Lỗi khởi động VOSK stream: {e}")
            return False

    def process_audio_chunk(self, audio_chunk: np.ndarray, sample_rate: int = None) -> Dict[str, Any]:
        """Xử lý audio chunk với buffer - FIXED VERSION"""
        if self.recognizer is None or not self.is_streaming:
            return {"text": "", "partial": "", "is_final": False}
        
        start_time = time.time()
        
        try:
            # Resample nếu cần
            if sample_rate and sample_rate != self.sample_rate:
                audio_chunk = self._resample_audio(audio_chunk, sample_rate, self.sample_rate)
            
            # Đảm bảo là int16
            if audio_chunk.dtype != np.int16:
                if audio_chunk.dtype in [np.float32, np.float64]:
                    audio_chunk = (audio_chunk * 32767).astype(np.int16)
                else:
                    audio_chunk = audio_chunk.astype(np.int16)
            
            # THÊM VÀO BUFFER - QUAN TRỌNG
            self.audio_buffer.extend(audio_chunk)
            
            # Giữ buffer trong giới hạn
            if len(self.audio_buffer) > self.buffer_size:
                self.audio_buffer = self.audio_buffer[-self.buffer_size:]
            
            # Chỉ xử lý khi có đủ audio (ít nhất 1 giây)
            if len(self.audio_buffer) < 16000:
                return {"text": "", "partial": "Đang nghe...", "is_final": False}
            
            # Lấy audio từ buffer để xử lý
            process_audio = np.array(self.audio_buffer, dtype=np.int16)
            
            # Chuyển sang bytes
            audio_bytes = process_audio.tobytes()
            
            # Xử lý với VOSK - GỬI TOÀN BỘ BUFFER
            if self.recognizer.AcceptWaveform(audio_bytes):
                result_json = self.recognizer.Result()
                result = json.loads(result_json)
                text = result.get('text', '').strip()
                if text:
                    print(f"✅ VOSK Final: '{text}'")
                    # Reset buffer sau khi có kết quả
                    self.audio_buffer = []
                    processing_time = time.time() - start_time
                    return {"text": text, "partial": "", "is_final": True, "processing_time": processing_time}
            
            # Kiểm tra partial result - LUÔN CÓ KẾT QUẢ
            partial_json = self.recognizer.PartialResult()
            partial_result = json.loads(partial_json)
            partial_text = partial_result.get('partial', '').strip()
            
            processing_time = time.time() - start_time
            
            if partial_text:
                print(f"🎯 VOSK Partial: '{partial_text}'")
                return {"text": "", "partial": partial_text, "is_final": False, "processing_time": processing_time}
            else:
                # LUÔN trả về partial text để hiển thị
                return {"text": "", "partial": "🎤 Đang nghe... nói tiếp đi", "is_final": False, "processing_time": processing_time}
                
        except Exception as e:
            print(f"❌ Lỗi VOSK processing: {e}")
            return {"text": "", "partial": f"Lỗi: {e}", "is_final": False, "processing_time": 0}

    def _resample_audio(self, audio: np.ndarray, orig_sr: int, target_sr: int) -> np.ndarray:
        """Resample audio"""
        if orig_sr == target_sr:
            return audio
        try:
            from scipy import signal
            num_samples = int(len(audio) * target_sr / orig_sr)
            resampled_audio = signal.resample(audio, num_samples)
            return resampled_audio.astype(np.int16)
        except Exception as e:
            print(f"❌ Lỗi resample audio: {e}")
            return audio

    def stop_stream(self) -> str:
        """Kết thúc stream và lấy kết quả cuối"""
        if self.recognizer:
            try:
                result_json = self.recognizer.FinalResult()
                result = json.loads(result_json)
                text = result.get('text', '').strip()
                self.is_streaming = False
                print(f"🛑 VOSK Final: '{text}'")
                return text
            except Exception as e:
                print(f"❌ Lỗi khi dừng VOSK stream: {e}")
        return ""

class StreamingVoiceService:
    def __init__(self, groq_client: Groq, rag_system, tts_service):
        self.client = groq_client
        self.rag_system = rag_system
        self.tts_service = tts_service
        
        # Khởi tạo VOSK ASR
        print("🔄 Đang khởi tạo VOSK ASR...")
        self.vosk_asr = VoskStreamingASR()
        
        # Khởi tạo VAD
        self.vad_processor = SileroVAD()
        self.is_listening = False
        self.speech_callback = None
        
        # Conversation context
        self.conversation_history = []
        self.current_transcription = ""
        self.partial_transcription = ""
        
        # Response queue cho xử lý bất đồng bộ
        self.response_queue = queue.Queue()
        self.processing_active = False
        
        # Worker threads tracking
        self.worker_threads = 0
        
        # Latency tracking
        self.latency_metrics = {
            'asr': [], 'llm': [], 'tts': [], 'total': []
        }

    def get_conversation_state(self) -> dict:
        """Lấy trạng thái hội thoại - FIXED VERSION"""
        return {
            'is_listening': self.is_listening,
            'history_length': len(self.conversation_history),
            'current_transcription': self.current_transcription,
            'partial_transcription': self.partial_transcription,
            'queue_size': self.response_queue.qsize(),
            'worker_threads': self.worker_threads,  # THÊM KEY NÀY
            'vosk_active': self.vosk_asr.is_streaming if self.vosk_asr else False,
            'last_update': time.strftime("%H:%M:%S")
        }

    def start_listening(self, speech_callback: Callable) -> bool:
        """Bắt đầu lắng nghe với Silero VAD"""
        if self.is_listening:
            print("⚠️ Đã đang lắng nghe")
            return False
            
        self.speech_callback = speech_callback
        
        # Kiểm tra VOSK model
        if self.vosk_asr.model is None:
            print("❌ VOSK model không khả dụng")
            return False
        
        # Khởi động VOSK stream
        if not self.vosk_asr.start_stream():
            print("❌ Không thể khởi động VOSK stream")
            return False
            
        # Khởi động VAD với callback
        success = self.vad_processor.start_stream(self._on_speech_detected)
        
        if success:
            self.is_listening = True
            self.processing_active = True
            
            # Khởi động worker thread cho xử lý AI response
            worker_thread = threading.Thread(
                target=self._process_response_worker,
                daemon=True,
                name="AI-Response-Worker"
            )
            worker_thread.start()
            self.worker_threads = 1  # CẬP NHẬT SỐ LƯỢNG THREAD
            
            print("🎙️ Đã bắt đầu lắng nghe với Silero VAD")
            
            # Thông báo trạng thái
            if self.speech_callback:
                self.speech_callback({
                    'transcription': "Đã bắt đầu lắng nghe... Hãy nói gì đó",
                    'response': "",
                    'tts_audio': None,
                    'status': 'listening'
                })
                
            return True
            
        return False

    def stop_listening(self):
        """Dừng lắng nghe"""
        self.is_listening = False
        self.processing_active = False
        self.worker_threads = 0  # RESET SỐ THREAD
        self.vad_processor.stop_stream()
        if self.vosk_asr:
            self.vosk_asr.stop_stream()
        print("🛑 Đã dừng lắng nghe")

    def _process_response_worker(self):
        """Worker xử lý phản hồi AI từ queue"""
        while self.processing_active:
            try:
                # Lấy item từ queue với timeout
                item = self.response_queue.get(timeout=1.0)
                if item is None:  # Tín hiệu dừng
                    break
                    
                transcription = item['transcription']
                start_time = item['timestamp']
                
                print(f"🤖 Processing AI response for: '{transcription}'")
                
                # Tạo phản hồi AI với latency tracking
                llm_start_time = time.time()
                response = self._generate_ai_response(transcription)
                llm_time = time.time() - llm_start_time
                self.latency_metrics['llm'].append(llm_time)
                
                tts_start_time = time.time()
                tts_audio_path = self._text_to_speech(response)
                tts_time = time.time() - tts_start_time
                if tts_time > 0:
                    self.latency_metrics['tts'].append(tts_time)
                
                # Gửi kết quả về callback
                if self.speech_callback:
                    self.speech_callback({
                        'transcription': transcription,
                        'response': response,
                        'tts_audio': tts_audio_path,
                        'status': 'completed'
                    })
                
                # Đánh dấu task hoàn thành
                self.response_queue.task_done()
                
            except queue.Empty:
                continue
            except Exception as e:
                print(f"❌ Lỗi trong response worker: {e}")
                if self.speech_callback:
                    self.speech_callback({
                        'transcription': "Lỗi xử lý",
                        'response': f"Xin lỗi, có lỗi xảy ra: {str(e)}",
                        'tts_audio': None,
                        'status': 'error'
                    })

    # CÁC METHOD KHÁC GIỮ NGUYÊN...
    def _on_speech_detected(self, speech_audio: np.ndarray, sample_rate: int):
        """Callback khi Silero VAD phát hiện speech"""
        if not self.is_listening:
            return
            
        try:
            print(f"🎯 Silero VAD detected speech: {len(speech_audio)} samples")
            
            # Đảm bảo VOSK stream đang chạy
            if not self.vosk_asr.is_streaming:
                self.vosk_asr.start_stream()
            
            # Xử lý audio với VOSK
            result = self.vosk_asr.process_audio_chunk(speech_audio, sample_rate)
            
            # Xử lý kết quả
            if result['is_final'] and result['text']:
                print(f"✅ VOSK Final from VAD: '{result['text']}'")
                
                # Đưa vào queue để xử lý AI response
                try:
                    self.response_queue.put({
                        'transcription': result['text'],
                        'timestamp': time.time(),
                        'source': 'vad'
                    }, timeout=0.5)
                    
                    # Cập nhật UI ngay lập tức
                    if self.speech_callback:
                        self.speech_callback({
                            'transcription': result['text'],
                            'response': "Đang xử lý...",
                            'tts_audio': None,
                            'status': 'processing'
                        })
                        
                except queue.Full:
                    print("⚠️ Queue đầy, bỏ qua transcription")
                
                # Reset VOSK stream cho lần tiếp theo
                self.vosk_asr.start_stream()
                
            elif result['partial']:
                # Hiển thị partial text real-time
                if self.speech_callback:
                    self.speech_callback({
                        'transcription': result['partial'],
                        'response': "",
                        'tts_audio': None,
                        'status': 'partial'
                    })
                    
        except Exception as e:
            print(f"❌ Lỗi trong VAD speech detection: {e}")

    def process_streaming_audio(self, audio_data: tuple) -> Dict[str, Any]:
        """Xử lý audio streaming manual mode"""
        if not audio_data:
            return self._create_error_response("❌ Không có dữ liệu âm thanh")
        
        total_start_time = time.time()
        
        try:
            sample_rate, audio_array = audio_data
            
            print(f"🎤 Manual audio: {len(audio_array)} samples, {sample_rate}Hz")
            
            # Đưa audio vào VAD để xử lý (cho manual mode)
            self.vad_processor.process_stream(audio_array, sample_rate)
            
            # Đồng thời xử lý trực tiếp với VOSK để có kết quả real-time
            if not self.vosk_asr.is_streaming:
                self.vosk_asr.start_stream()
            
            asr_start_time = time.time()
            result = self.vosk_asr.process_audio_chunk(audio_array, sample_rate)
            asr_time = time.time() - asr_start_time
            
            # Cập nhật latency
            if 'processing_time' in result:
                self.latency_metrics['asr'].append(result['processing_time'])
            else:
                self.latency_metrics['asr'].append(asr_time)
            
            total_time = time.time() - total_start_time
            self.latency_metrics['total'].append(total_time)
            
            print(f"⏱️ ASR time: {asr_time:.3f}s, Total: {total_time:.3f}s")
            
            # Xử lý kết quả
            if result['is_final'] and result['text']:
                self.current_transcription = result['text']
                print(f"📝 Manual Final: '{result['text']}'")
                
                # Đưa vào queue để xử lý AI response
                try:
                    self.response_queue.put({
                        'transcription': result['text'],
                        'timestamp': time.time(),
                        'source': 'manual'
                    }, timeout=0.5)
                    
                    return {
                        'transcription': result['text'],
                        'response': "Đang xử lý...",
                        'tts_audio': None,
                        'status': 'processing'
                    }
                    
                except queue.Full:
                    return {
                        'transcription': result['text'],
                        'response': "Hệ thống bận, vui lòng thử lại",
                        'tts_audio': None,
                        'status': 'completed'
                    }
                    
            elif result['partial']:
                self.partial_transcription = result['partial']
                return {
                    'transcription': result['partial'],
                    'response': "",
                    'tts_audio': None,
                    'status': 'listening'
                }
            else:
                return {
                    'transcription': "🎤 Đang nghe... tiếp tục nói",
                    'response': "",
                    'tts_audio': None,
                    'status': 'listening'
                }
            
        except Exception as e:
            print(f"❌ Lỗi xử lý audio: {e}")
            return self._create_error_response(f"Lỗi: {e}")

    def _generate_ai_response(self, transcription: str) -> str:
        """Tạo phản hồi AI"""
        try:
            self.conversation_history.append({"role": "user", "content": transcription})
            
            if len(self.conversation_history) > 10:
                self.conversation_history = self.conversation_history[-10:]
            
            messages = [
                {"role": "system", "content": "Bạn là trợ lý AI. Trả lời ngắn gọn bằng tiếng Việt."},
                *self.conversation_history
            ]
            
            response = self.client.chat.completions.create(
                model="llama-3.1-8b-instant",
                messages=messages,
                max_tokens=100,
                temperature=0.7
            )
            
            ai_response = response.choices[0].message.content.strip()
            
            self.conversation_history.append({"role": "assistant", "content": ai_response})
            
            return ai_response
            
        except Exception as e:
            print(f"❌ Lỗi AI: {e}")
            return "Xin lỗi, tôi không thể trả lời ngay lúc này."

    def _text_to_speech(self, text: str) -> Optional[str]:
        """Chuyển văn bản thành giọng nói"""
        try:
            if not text:
                return None
                
            audio_path = self.tts_service.text_to_speech(
                text=text,
                language='vi',
                speed=1.0
            )
            
            return audio_path
            
        except Exception as e:
            print(f"❌ Lỗi TTS: {e}")
            return None

    def _create_error_response(self, message: str) -> Dict[str, Any]:
        return {
            'transcription': message,
            'response': "Vui lòng thử lại",
            'tts_audio': None,
            'status': 'error'
        }

    def clear_conversation(self):
        """Xóa lịch sử hội thoại"""
        self.conversation_history = []
        self.current_transcription = ""
        self.partial_transcription = ""
        print("🗑️ Đã xóa lịch sử hội thoại")

    def get_latency_stats(self) -> dict:
        """Lấy thống kê latency"""
        stats = {}
        for component, latencies in self.latency_metrics.items():
            if latencies and len(latencies) > 0:
                recent_latencies = latencies[-5:] if len(latencies) > 5 else latencies
                stats[component] = {
                    'avg': f"{sum(recent_latencies) / len(recent_latencies):.3f}s",
                    'min': f"{min(recent_latencies):.3f}s", 
                    'max': f"{max(recent_latencies):.3f}s",
                    'count': len(recent_latencies),
                    'recent': [f"{x:.3f}s" for x in recent_latencies]
                }
            else:
                stats[component] = {
                    'avg': "0.000s", 'min': "0.000s", 'max': "0.000s", 'count': 0, 'recent': []
                }
        
        return stats
# import io
# import numpy as np
# import soundfile as sf
# import time
# import traceback
# import threading
# import queue
# import json
# import os
# from vosk import Model, KaldiRecognizer
# from groq import Groq
# from typing import Optional, Dict, Any, Callable
# from config.settings import settings
# from core.rag_system import EnhancedRAGSystem
# from core.tts_service import EnhancedTTSService
# from core.silero_vad import SileroVAD

# class VoskStreamingASR:
#     def __init__(self, model_path: str = None):
#         """Khởi tạo VOSK ASR streaming với debug"""
#         self.model = None
#         self.recognizer = None
#         self.sample_rate = 16000
#         self.is_streaming = False
        
#         # Tự động tải model nếu không có đường dẫn
#         if model_path is None:
#             model_path = self._download_vosk_model()
        
#         if model_path and os.path.exists(model_path):
#             print(f"🔄 Đang tải VOSK model từ: {model_path}")
#             try:
#                 self.model = Model(model_path)
#                 self.recognizer = KaldiRecognizer(self.model, self.sample_rate)
#                 self.recognizer.SetWords(True)
#                 print("✅ Đã tải VOSK model thành công")
#             except Exception as e:
#                 print(f"❌ Lỗi khởi tạo VOSK model: {e}")
#         else:
#             print(f"❌ Không tìm thấy VOSK model tại: {model_path}")

#     def _download_vosk_model(self):
#         """Tải VOSK model tiếng Việt tự động"""
#         try:
#             import urllib.request
#             import zipfile
            
#             model_url = "https://alphacephei.com/vosk/models/vosk-model-small-vn-0.4.zip"
#             model_dir = "models/vosk-model-small-vn-0.4"
#             zip_path = "models/vosk-model-small-vn-0.4.zip"
            
#             # Tạo thư mục nếu chưa có
#             os.makedirs("models", exist_ok=True)
            
#             if not os.path.exists(model_dir):
#                 print("📥 Đang tải VOSK Vietnamese model...")
#                 urllib.request.urlretrieve(model_url, zip_path)
                
#                 with zipfile.ZipFile(zip_path, 'r') as zip_ref:
#                     zip_ref.extractall("models/")
                
#                 # Đảm bảo thư mục tồn tại
#                 if os.path.exists("models/vosk-model-small-vn-0.4"):
#                     os.rename("models/vosk-model-small-vn-0.4", model_dir)
                
#                 if os.path.exists(zip_path):
#                     os.remove(zip_path)
#                 print("✅ Đã tải VOSK model thành công")
            
#             return model_dir if os.path.exists(model_dir) else None
            
#         except Exception as e:
#             print(f"❌ Lỗi tải VOSK model: {e}")
#             return None

#     def start_stream(self):
#         """Bắt đầu stream mới"""
#         if self.model is None:
#             print("❌ VOSK model chưa được khởi tạo")
#             return False
            
#         try:
#             self.recognizer = KaldiRecognizer(self.model, self.sample_rate)
#             self.recognizer.SetWords(True)
#             self.is_streaming = True
#             print("🎤 Đã khởi động VOSK stream")
#             return True
#         except Exception as e:
#             print(f"❌ Lỗi khởi động VOSK stream: {e}")
#             return False

#     def process_audio_chunk(self, audio_chunk: np.ndarray, sample_rate: int = None) -> Dict[str, Any]:
#         """Xử lý audio chunk và trả về kết quả - FIXED VOLUME VERSION"""
#         if self.recognizer is None or not self.is_streaming:
#             return {"text": "", "partial": "", "is_final": False}
        
#         try:
#             # DEBUG: Thông tin audio chunk
#             print(f"🔊 Audio chunk: {len(audio_chunk)} samples, dtype: {audio_chunk.dtype}, max: {np.max(audio_chunk):.4f}")
            
#             # Chuẩn hóa audio - QUAN TRỌNG: VOSK cần audio ở dạng int16
#             if sample_rate and sample_rate != self.sample_rate:
#                 audio_chunk = self._resample_audio(audio_chunk, sample_rate, self.sample_rate)
            
#             # Đảm bảo là int16 với giá trị phù hợp
#             if audio_chunk.dtype != np.int16:
#                 if audio_chunk.dtype in [np.float32, np.float64]:
#                     # Audio float cần được scale về [-32768, 32767]
#                     audio_chunk = (audio_chunk * 32767).astype(np.int16)
#                 else:
#                     audio_chunk = audio_chunk.astype(np.int16)
            
#             # FIXED: Tăng cường âm lượng trước khi kiểm tra
#             audio_chunk = self._boost_audio_volume(audio_chunk)
            
#             # Kiểm tra âm lượng - GIẢM ngưỡng xuống
#             audio_rms = np.sqrt(np.mean(audio_chunk.astype(np.float32)**2)) / 32767.0
#             print(f"📊 Audio RMS: {audio_rms:.4f}, Max: {np.max(audio_chunk)}")
            
#             # FIXED: Giảm ngưỡng âm lượng từ 0.01 xuống 0.001
#             if audio_rms < 0.001:  # Giảm ngưỡng 10 lần
#                 print(f"⚠️ Âm lượng quá thấp (RMS: {audio_rms:.6f}), bỏ qua")
#                 return {"text": "", "partial": "", "is_final": False}
            
#             # Chuyển đổi sang bytes
#             audio_bytes = audio_chunk.tobytes()
            
#             # Xử lý với VOSK
#             if self.recognizer.AcceptWaveform(audio_bytes):
#                 # Kết quả cuối cùng
#                 result_json = self.recognizer.Result()
#                 result = json.loads(result_json)
#                 text = result.get('text', '').strip()
#                 print(f"✅ VOSK Final Result: '{text}'")
#                 if text:
#                     return {"text": text, "partial": "", "is_final": True}
#             else:
#                 # Kết quả tạm thời
#                 partial_json = self.recognizer.PartialResult()
#                 partial_result = json.loads(partial_json)
#                 partial_text = partial_result.get('partial', '').strip()
#                 if partial_text:
#                     print(f"🎯 VOSK Partial: '{partial_text}'")
#                     return {"text": "", "partial": partial_text, "is_final": False}
                
#         except Exception as e:
#             print(f"❌ Lỗi VOSK processing: {e}")
#             traceback.print_exc()
        
#         return {"text": "", "partial": "", "is_final": False}

#     def _boost_audio_volume(self, audio_chunk: np.ndarray, boost_factor: float = 5.0) -> np.ndarray:
#         """Tăng cường âm lượng audio"""
#         try:
#             # Chuyển sang float để xử lý
#             audio_float = audio_chunk.astype(np.float32) / 32768.0
            
#             # Tăng âm lượng
#             boosted_audio = audio_float * boost_factor
            
#             # Ngăn chặn clipping
#             boosted_audio = np.clip(boosted_audio, -1.0, 1.0)
            
#             # Chuyển lại sang int16
#             boosted_audio_int16 = (boosted_audio * 32767).astype(np.int16)
            
#             print(f"🔊 Volume boosted: {boost_factor}x, New max: {np.max(boosted_audio_int16)}")
#             return boosted_audio_int16
            
#         except Exception as e:
#             print(f"⚠️ Lỗi boost volume: {e}")
#             return audio_chunk
#     def stop_stream(self) -> str:
#         """Kết thúc stream và lấy kết quả cuối"""
#         if self.recognizer:
#             try:
#                 result_json = self.recognizer.FinalResult()
#                 result = json.loads(result_json)
#                 text = result.get('text', '').strip()
#                 self.is_streaming = False
#                 print(f"🛑 VOSK Final: '{text}'")
#                 return text
#             except Exception as e:
#                 print(f"❌ Lỗi khi dừng VOSK stream: {e}")
#         return ""

#     def _resample_audio(self, audio: np.ndarray, orig_sr: int, target_sr: int) -> np.ndarray:
#         """Resample audio với chất lượng tốt hơn"""
#         if orig_sr == target_sr:
#             return audio
#         try:
#             from scipy import signal
#             # Tính số sample mới
#             num_samples = int(len(audio) * target_sr / orig_sr)
#             resampled_audio = signal.resample(audio, num_samples)
#             return resampled_audio.astype(np.int16)
#         except Exception as e:
#             print(f"❌ Lỗi resample audio: {e}")
#             return audio

# class StreamingVoiceService:
#     def __init__(self, groq_client: Groq, rag_system, tts_service):
#         self.client = groq_client
#         self.rag_system = rag_system
#         self.tts_service = tts_service
        
#         # Khởi tạo VOSK ASR
#         print("🔄 Đang khởi tạo VOSK ASR...")
#         self.vosk_asr = VoskStreamingASR()
        
#         # Khởi tạo VAD
#         self.vad_processor = SileroVAD()
#         self.is_listening = False
#         self.speech_callback = None
#         self.is_processing = False
        
#         # Conversation context
#         self.conversation_history = []
#         self.current_transcription = ""
#         self.partial_transcription = ""
        
#         # Multi-thread processing
#         self.response_queue = queue.Queue()
#         self.processing_threads = []
#         self.max_workers = 2
        
#         # Streaming state - FIXED: Thêm các biến state mới
#         self.vosk_stream_active = False
#         self.last_voice_time = 0
#         self.silence_timeout = 3.0
        
#         # Audio buffer để cải thiện nhận diện
#         self.audio_buffer = []
#         self.buffer_duration = 1.0
#         self.max_buffer_samples = 16000
        
#         # Real-time processing
#         self.realtime_buffer = queue.Queue()
#         self.processing_active = False
        
#         # Latency tracking
#         self.latency_metrics = {
#             'asr': [], 'rag': [], 'llm': [], 'tts': [], 'total': [],
#             'vad_detection': [], 'queue_waiting': [], 'vosk_processing': []
#         }
        
#         self.current_callback = None

#     def start_listening(self, speech_callback: Callable) -> bool:
#         """Bắt đầu lắng nghe với VOSK streaming - FIXED VERSION"""
#         if self.is_listening:
#             print("⚠️ Đã đang lắng nghe")
#             return False
            
#         self.current_callback = speech_callback
        
#         # Kiểm tra VOSK model
#         if self.vosk_asr.model is None:
#             print("❌ VOSK model không khả dụng")
#             if self.current_callback:
#                 self.current_callback({
#                     'transcription': "Lỗi: VOSK model không khả dụng",
#                     'response': "Không thể khởi động nhận diện giọng nói",
#                     'tts_audio': None,
#                     'status': 'error'
#                 })
#             return False
        
#         # Khởi động VOSK stream
#         if not self.vosk_asr.start_stream():
#             print("❌ Không thể khởi động VOSK stream")
#             return False
            
#         # Khởi động VAD
#         success = self.vad_processor.start_stream(self._on_speech_detected)
        
#         if success:
#             self.is_listening = True
#             self.is_processing = False
#             self.vosk_stream_active = True
#             self.last_voice_time = time.time()
#             self.audio_buffer = []
#             self.processing_active = True
            
#             # Khởi động worker threads
#             if not self.processing_threads:
#                 for i in range(self.max_workers):
#                     thread = threading.Thread(
#                         target=self._process_response_worker,
#                         daemon=True,
#                         name=f"ASR-Worker-{i}"
#                     )
#                     thread.start()
#                     self.processing_threads.append(thread)
            
#             # Bắt đầu real-time processing thread
#             threading.Thread(target=self._realtime_processing_worker, daemon=True).start()
            
#             print("🎙️ Đã bắt đầu lắng nghe với VOSK ASR streaming")
            
#             # Thông báo trạng thái
#             if self.current_callback:
#                 self.current_callback({
#                     'transcription': "Đã bắt đầu lắng nghe... Hãy nói gì đó",
#                     'response': "",
#                     'tts_audio': None,
#                     'status': 'listening'
#                 })
                
#             return True
            
#         return False

#     def stop_listening(self):
#         """Dừng lắng nghe"""
#         self.is_listening = False
#         self.vosk_stream_active = False
#         self.processing_active = False
#         self.vad_processor.stop_stream()
#         print("🛑 Đã dừng lắng nghe")

#     def _on_speech_detected(self, speech_audio: np.ndarray, sample_rate: int):
#         """Callback khi VAD phát hiện speech - FIXED VERSION"""
#         if not self.vosk_stream_active or not self.is_listening:
#             return
            
#         try:
#             # Cập nhật thời gian có giọng nói
#             self.last_voice_time = time.time()
            
#             print(f"🎯 VAD detected: {len(speech_audio)} samples, {sample_rate}Hz")
            
#             # Xử lý real-time với VOSK
#             result = self.vosk_asr.process_audio_chunk(speech_audio, sample_rate)
#             self._handle_vosk_result(result)
            
#         except Exception as e:
#             print(f"❌ Lỗi trong speech detection: {e}")

#     def _handle_vosk_result(self, result: Dict[str, Any]):
#         """Xử lý kết quả từ VOSK - FIXED VERSION"""
#         try:
#             # Xử lý kết quả partial (real-time)
#             if result['partial'] and len(result['partial']) > 1:
#                 self.partial_transcription = result['partial']
#                 print(f"🎯 VOSK Partial: '{result['partial']}'")
                
#                 # Gửi partial result real-time
#                 if self.current_callback:
#                     self.current_callback({
#                         'transcription': result['partial'],
#                         'response': "",
#                         'tts_audio': None,
#                         'status': 'partial'
#                     })
            
#             # Xử lý kết quả final
#             if result['is_final'] and result['text'] and len(result['text']) > 1:
#                 print(f"✅ VOSK Final: '{result['text']}'")
                
#                 # Đưa vào queue để xử lý phản hồi AI
#                 try:
#                     self.response_queue.put({
#                         'transcription': result['text'],
#                         'timestamp': time.time()
#                     }, timeout=0.5)
#                     print(f"📦 Đã đưa vào queue: '{result['text']}'")
                    
#                     # Cập nhật UI ngay lập tức
#                     if self.current_callback:
#                         self.current_callback({
#                             'transcription': result['text'],
#                             'response': "Đang xử lý...",
#                             'tts_audio': None,
#                             'status': 'processing'
#                         })
                        
#                 except queue.Full:
#                     print("⚠️ Queue đầy, bỏ qua transcription")
                
#                 # Reset VOSK stream cho lần tiếp theo
#                 self.vosk_asr.start_stream()
                
#         except Exception as e:
#             print(f"❌ Lỗi xử lý VOSK result: {e}")

#     def _process_response_worker(self):
#         """Worker xử lý phản hồi AI từ queue"""
#         while self.processing_active:
#             try:
#                 # Lấy item từ queue với timeout
#                 item = self.response_queue.get(timeout=1.0)
#                 if item is None:  # Tín hiệu dừng
#                     break
                    
#                 transcription = item['transcription']
#                 start_time = item['timestamp']
                
#                 print(f"🤖 Processing AI response for: '{transcription}'")
                
#                 # Tạo phản hồi AI
#                 response = self._generate_ai_response_optimized(transcription)
#                 tts_audio_path = self._text_to_speech_optimized(response)
                
#                 # Gửi kết quả về callback
#                 if self.current_callback:
#                     self.current_callback({
#                         'transcription': transcription,
#                         'response': response,
#                         'tts_audio': tts_audio_path,
#                         'status': 'completed'
#                     })
                
#                 # Đánh dấu task hoàn thành
#                 self.response_queue.task_done()
                
#             except queue.Empty:
#                 continue
#             except Exception as e:
#                 print(f"❌ Lỗi trong response worker: {e}")
#                 if self.current_callback:
#                     self.current_callback({
#                         'transcription': "Lỗi xử lý",
#                         'response': f"Xin lỗi, có lỗi xảy ra: {str(e)}",
#                         'tts_audio': None,
#                         'status': 'error'
#                     })

#     def _realtime_processing_worker(self):
#         """Worker xử lý real-time để theo dõi timeout"""
#         while self.processing_active:
#             try:
#                 current_time = time.time()
#                 silence_duration = current_time - self.last_voice_time
                
#                 # Xử lý timeout nếu im lặng quá lâu và có partial text
#                 if (silence_duration > self.silence_timeout and 
#                     self.partial_transcription and 
#                     len(self.partial_transcription) > 2):
                    
#                     print(f"⏰ Silence timeout, xử lý: '{self.partial_transcription}'")
                    
#                     # Xử lý partial text như final
#                     try:
#                         self.response_queue.put({
#                             'transcription': self.partial_transcription,
#                             'timestamp': time.time()
#                         }, timeout=0.5)
#                     except queue.Full:
#                         print("⚠️ Queue đầy, bỏ qua timeout transcription")
                    
#                     # Reset
#                     self.partial_transcription = ""
#                     self.vosk_asr.start_stream()
                
#                 time.sleep(0.1)  # Giảm CPU usage
                
#             except Exception as e:
#                 print(f"❌ Lỗi real-time worker: {e}")
#                 time.sleep(0.5)

#     def process_streaming_audio(self, audio_data: tuple) -> Dict[str, Any]:
#         """Xử lý audio streaming manual mode với VOSK - FIXED VOLUME VERSION"""
#         if not audio_data:
#             return self._create_error_response("❌ Không có dữ liệu âm thanh")
        
#         try:
#             sample_rate, audio_array = audio_data
            
#             print(f"🎤 Manual audio: {len(audio_array)} samples, {sample_rate}Hz, Max: {np.max(audio_array)}")
            
#             # FIXED: Tăng cường âm lượng trước khi xử lý
#             audio_array = self._boost_input_volume(audio_array)
            
#             # Kiểm tra âm lượng với ngưỡng thấp hơn
#             if isinstance(audio_array, np.ndarray):
#                 if audio_array.dtype in [np.float32, np.float64]:
#                     audio_rms = np.sqrt(np.mean(audio_array**2))
#                 else:
#                     audio_rms = np.sqrt(np.mean(audio_array.astype(np.float32)**2)) / 32768.0
                    
#                 print(f"📊 Manual audio RMS: {audio_rms:.6f}, Max: {np.max(audio_array)}")
                
#                 # FIXED: Giảm ngưỡng âm lượng
#                 if audio_rms < 0.001:  # Giảm từ 0.01 xuống 0.001
#                     return {
#                         'transcription': f"Âm thanh quá nhỏ (RMS: {audio_rms:.6f}), hãy nói to hơn hoặc điều chỉnh microphone",
#                         'response': "",
#                         'tts_audio': None,
#                         'status': 'listening'
#                     }
            
#             # Khởi động VOSK stream tạm thời
#             if not self.vosk_asr.start_stream():
#                 return self._create_error_response("❌ Không thể khởi động VOSK")
            
#             # Xử lý audio với VOSK
#             result = self.vosk_asr.process_audio_chunk(audio_array, sample_rate)
            
#             if result['is_final'] and result['text'] and len(result['text']) > 1:
#                 transcription = result['text']
#                 print(f"📝 Manual Transcription: '{transcription}'")
                
#                 # Tạo phản hồi AI
#                 response = self._generate_ai_response_optimized(transcription)
#                 tts_audio_path = self._text_to_speech_optimized(response)
                
#                 return {
#                     'transcription': transcription,
#                     'response': response,
#                     'tts_audio': tts_audio_path,
#                     'status': 'completed'
#                 }
#             elif result['partial']:
#                 return {
#                     'transcription': result['partial'],
#                     'response': "",
#                     'tts_audio': None,
#                     'status': 'listening'
#                 }
#             else:
#                 return {
#                     'transcription': "Đang nghe... Hãy nói rõ hơn và gần microphone",
#                     'response': "",
#                     'tts_audio': None,
#                     'status': 'listening'
#                 }
            
#         except Exception as e:
#             print(f"❌ Lỗi xử lý streaming audio: {e}")
#             traceback.print_exc()
#             return self._create_error_response(f"❌ Lỗi: {str(e)}")
    
#     def _boost_input_volume(self, audio_array: np.ndarray, boost_factor: float = 10.0) -> np.ndarray:
#         """Tăng cường âm lượng input audio"""
#         try:
#             if audio_array.dtype in [np.float32, np.float64]:
#                 # Audio đã ở dạng float
#                 boosted = audio_array * boost_factor
#                 boosted = np.clip(boosted, -1.0, 1.0)
#             else:
#                 # Audio ở dạng int
#                 boosted = audio_array.astype(np.float32) * boost_factor
#                 max_val = np.iinfo(audio_array.dtype).max
#                 boosted = np.clip(boosted, -max_val, max_val).astype(audio_array.dtype)
            
#             print(f"🔊 Input volume boosted: {boost_factor}x")
#             return boosted
            
#         except Exception as e:
#             print(f"⚠️ Lỗi boost input volume: {e}")
#             return audio_array

#     def _generate_ai_response_optimized(self, transcription: str) -> str:
#         """Tạo phản hồi AI tối ưu hóa"""
#         try:
#             # Thêm vào lịch sử hội thoại
#             self.conversation_history.append({"role": "user", "content": transcription})
            
#             # Giới hạn lịch sử hội thoại
#             if len(self.conversation_history) > 10:
#                 self.conversation_history = self.conversation_history[-10:]
            
#             # Tạo prompt
#             messages = [
#                 {"role": "system", "content": "Bạn là trợ lý AI hữu ích. Hãy trả lời ngắn gọn, tự nhiên bằng tiếng Việt."},
#                 *self.conversation_history
#             ]
            
#             # Gọi Groq API
#             response = self.client.chat.completions.create(
#                 model="llama-3.1-8b-instant",
#                 messages=messages,
#                 max_tokens=150,
#                 temperature=0.7
#             )
            
#             ai_response = response.choices[0].message.content.strip()
            
#             # Thêm vào lịch sử
#             self.conversation_history.append({"role": "assistant", "content": ai_response})
            
#             return ai_response
            
#         except Exception as e:
#             print(f"❌ Lỗi tạo phản hồi AI: {e}")
#             return "Xin lỗi, tôi không thể xử lý yêu cầu ngay lúc này."

#     def _text_to_speech_optimized(self, text: str) -> Optional[str]:
#         """Chuyển văn bản thành giọng nói tối ưu hóa"""
#         try:
#             if not text or len(text.strip()) == 0:
#                 return None
                
#             # Sử dụng TTS service
#             audio_path = self.tts_service.text_to_speech(
#                 text=text,
#                 language='vi',
#                 speed=1.0
#             )
            
#             return audio_path
            
#         except Exception as e:
#             print(f"❌ Lỗi TTS: {e}")
#             return None

#     def _create_error_response(self, message: str) -> Dict[str, Any]:
#         """Tạo response lỗi chuẩn"""
#         return {
#             'transcription': message,
#             'response': "Vui lòng thử lại",
#             'tts_audio': None,
#             'status': 'error'
#         }

#     def get_conversation_state(self) -> dict:
#         """Lấy trạng thái hội thoại"""
#         return {
#             'is_listening': self.is_listening,
#             'is_processing': self.is_processing,
#             'history_length': len(self.conversation_history),
#             'current_transcription': self.current_transcription,
#             'partial_transcription': self.partial_transcription,
#             'queue_size': self.response_queue.qsize(),
#             'worker_threads': len([t for t in self.processing_threads if t.is_alive()]),
#             'vosk_active': self.vosk_stream_active,
#             'last_voice_time': time.strftime("%H:%M:%S", time.localtime(self.last_voice_time)),
#             'last_update': time.strftime("%H:%M:%S")
#         }

#     def clear_conversation(self):
#         """Xóa lịch sử hội thoại"""
#         self.conversation_history = []
#         self.current_transcription = ""
#         self.partial_transcription = ""
#         print("🗑️ Đã xóa lịch sử hội thoại")

#     def get_latency_stats(self) -> dict:
#         """Lấy thống kê latency"""
#         stats = {}
#         for component, latencies in self.latency_metrics.items():
#             if latencies:
#                 recent_latencies = latencies[-10:]
#                 stats[component] = {
#                     'avg': sum(latencies) / len(latencies),
#                     'min': min(latencies),
#                     'max': max(latencies),
#                     'count': len(latencies),
#                     'recent_avg': sum(recent_latencies) / len(recent_latencies),
#                     'recent_min': min(recent_latencies),
#                     'recent_max': max(recent_latencies)
#                 }
#             else:
#                 stats[component] = {
#                     'avg': 0, 'min': 0, 'max': 0, 'count': 0, 
#                     'recent_avg': 0, 'recent_min': 0, 'recent_max': 0
#                 }
#         return stats