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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
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import sys
import io
import os
import locale

# Comprehensive UTF-8 encoding setup for Windows
if sys.platform.startswith('win'):
    try:
        # Set locale to UTF-8
        try:
            locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
        except:
            try:
                locale.setlocale(locale.LC_ALL, 'C.UTF-8')
            except:
                pass
        
        # Set console to UTF-8 mode
        os.system('chcp 65001 > nul 2>&1')
        
        # Set environment variables for UTF-8
        os.environ['PYTHONIOENCODING'] = 'utf-8:replace'
        os.environ['PYTHONUTF8'] = '1'
        
        # Force UTF-8 encoding for stdout/stderr with error handling
        try:
            if hasattr(sys.stdout, 'reconfigure'):
                sys.stdout.reconfigure(encoding='utf-8', errors='replace')
                sys.stderr.reconfigure(encoding='utf-8', errors='replace')
            else:
                # Fallback for older Python versions
                sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='replace')
                sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8', errors='replace')
        except Exception:
            # Final fallback
            sys.stdout = io.TextIOWrapper(sys.stdout.detach(), encoding='utf-8', errors='replace')
            sys.stderr = io.TextIOWrapper(sys.stderr.detach(), encoding='utf-8', errors='replace')
        
    except Exception as e:
        # Silently continue if encoding setup fails
        pass

# Store original print function before any imports
import builtins
_original_print = builtins.print

def safe_print(*args, **kwargs):
    """Safe print function that handles UTF-8 encoding"""
    try:
        # Convert all arguments to strings first to avoid encoding issues
        safe_args = []
        for arg in args:
            if isinstance(arg, str):
                # Ensure string can be encoded/decoded properly
                try:
                    arg.encode('utf-8')
                    safe_args.append(arg)
                except UnicodeEncodeError:
                    safe_args.append(arg.encode('utf-8', errors='replace').decode('utf-8'))
            else:
                safe_args.append(str(arg))
        
        _original_print(*safe_args, **kwargs)
    except (UnicodeEncodeError, UnicodeDecodeError) as e:
        # Last resort: convert to ASCII with replacement
        ascii_args = []
        for arg in args:
            if isinstance(arg, str):
                ascii_args.append(arg.encode('ascii', errors='replace').decode('ascii'))
            else:
                ascii_args.append(str(arg).encode('ascii', errors='replace').decode('ascii'))
        _original_print(*ascii_args, **kwargs)
    except Exception:
        # Ultimate fallback
        _original_print("[Encoding Error in Print]")

# Override built-in print
builtins.print = safe_print
"""

Live Translation AI Agent - Two Person Mode

Real-time Cross-Translation between Person A & Person B

"""

import gradio as gr
import numpy as np
import librosa
import soundfile as sf
import tempfile
import os
import time
import logging
import json
from typing import Optional, Tuple, Dict, List
import asyncio
import threading
from pathlib import Path

# Load environment variables from .env file
try:
    from dotenv import load_dotenv
    load_dotenv()
    print("Environment variables loaded from .env file")
except ImportError:
    print("python-dotenv not available, using system environment variables")

# Google Gemini integration
try:
    import google.generativeai as genai
    GEMINI_AVAILABLE = True
    print("Google Gemini library loaded successfully")
except ImportError:
    GEMINI_AVAILABLE = False
    print("Google Gemini library not available")

# Google Speech Recognition integration
try:
    import speech_recognition as sr
    SPEECH_RECOGNITION_AVAILABLE = True
    print("SpeechRecognition library loaded successfully")
except ImportError:
    SPEECH_RECOGNITION_AVAILABLE = False
    print("SpeechRecognition library not available")

# Edge TTS for speech synthesis
try:
    import edge_tts
    EDGE_TTS_AVAILABLE = True
    print("Edge TTS loaded successfully")
except ImportError:
    EDGE_TTS_AVAILABLE = False
    print("Edge TTS not available")

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

class TranslationAIAgent:
    """Main AI Agent for translation tasks - Google Gemini Powered"""
    
    def __init__(self):
        # Enhanced language and voice options with country flags
        self.language_voice_options = {
            'en': {
                'name': 'English',
                'options': [
                    {'code': 'en-us', 'display': 'English (United States)', 'voice': 'en-US-JennyNeural', 'alt_voice': 'en-US-GuyNeural'},
                    {'code': 'en-gb', 'display': 'English (United Kingdom)', 'voice': 'en-GB-LibbyNeural', 'alt_voice': 'en-GB-RyanNeural'},
                ]
            },
            'es': {
                'name': 'Spanish',
                'options': [
                    {'code': 'es-es', 'display': 'Spanish (Spain)', 'voice': 'es-ES-ElviraNeural', 'alt_voice': 'es-ES-AlvaroNeural'},
                    {'code': 'es-mx', 'display': 'Spanish (Mexico)', 'voice': 'es-MX-DaliaNeural', 'alt_voice': 'es-MX-JorgeNeural'},
                ]
            },
            'fr': {
                'name': 'French',
                'options': [
                    {'code': 'fr-fr', 'display': 'French (France)', 'voice': 'fr-FR-DeniseNeural', 'alt_voice': 'fr-FR-HenriNeural'},
                    {'code': 'fr-ca', 'display': 'French (Canada)', 'voice': 'fr-CA-SylvieNeural', 'alt_voice': 'fr-CA-AntoineNeural'},
                ]
            },
            'de': {
                'name': 'German',
                'options': [
                    {'code': 'de-de', 'display': 'German (Germany)', 'voice': 'de-DE-KatjaNeural', 'alt_voice': 'de-DE-ConradNeural'},
                ]
            },
            'vi': {
                'name': 'Vietnamese',
                'options': [
                    {'code': 'vi-vn', 'display': 'Vietnamese (Vietnam)', 'voice': 'vi-VN-HoaiMyNeural', 'alt_voice': 'vi-VN-NamMinhNeural'}
                ]
            },
            'ja': {
                'name': 'Japanese',
                'options': [
                    {'code': 'ja-jp', 'display': 'Japanese (Japan)', 'voice': 'ja-JP-NanamiNeural', 'alt_voice': 'ja-JP-KeitaNeural'}
                ]
            },
            'zh': {
                'name': 'Chinese',
                'options': [
                    {'code': 'zh-cn', 'display': 'Chinese (Simplified)', 'voice': 'zh-CN-XiaoxiaoNeural', 'alt_voice': 'zh-CN-YunxiNeural'},
                ]
            }
        }
        
        # Create simple supported languages mapping for backward compatibility
        self.supported_languages = {
            lang_code: lang_info['name'] 
            for lang_code, lang_info in self.language_voice_options.items()
        }
        
        # Create default voice mapping for backward compatibility
        self.voice_map = {
            lang_code: lang_info['options'][0]['voice']
            for lang_code, lang_info in self.language_voice_options.items()
        }
        
        self.setup_gemini_client()
        self.setup_speech_recognizer()
    
    def setup_gemini_client(self):
        """Setup Google Gemini client for translation"""
        try:
            if not GEMINI_AVAILABLE:
                logger.error("Google Gemini library not available - please install: pip install google-generativeai")
                self.gemini_model = None
                self.gemini_configured = False
                return
            
            # Get Google API key from environment
            api_key = (
                os.environ.get("GOOGLE_API_KEY") or 
                os.environ.get("GEMINI_API_KEY") or
                os.getenv("GOOGLE_API_KEY")
            )
            
            if api_key and api_key.strip() and not api_key.strip().startswith("your-"):
                genai.configure(api_key=api_key.strip())
                self.gemini_model = genai.GenerativeModel('gemini-2.0-flash-exp')
                self.gemini_configured = True
                logger.info("[SUCCESS] Google Gemini client configured successfully - Real translation mode enabled")
            else:
                self.gemini_model = None
                self.gemini_configured = False
                logger.error("❌ Google API key not found or invalid in environment variables")
                logger.error("Please set GOOGLE_API_KEY in your .env file with a valid API key")
                
        except Exception as e:
            logger.error(f"Gemini setup failed: {e}")
            self.gemini_model = None
            self.gemini_configured = False

    def setup_speech_recognizer(self):
        """Setup speech recognizer for audio input"""
        try:
            if not SPEECH_RECOGNITION_AVAILABLE:
                logger.error("SpeechRecognition library not available - please install: pip install SpeechRecognition")
                self.recognizer = None
                self.speech_configured = False
                return
            
            self.recognizer = sr.Recognizer()
            # More conservative settings for better recognition
            self.recognizer.energy_threshold = 1000  # Lower threshold for processed audio
            self.recognizer.dynamic_energy_threshold = False  # More consistent
            self.recognizer.pause_threshold = 0.5  # Shorter pauses
            self.recognizer.operation_timeout = 15  # Longer timeout
            self.recognizer.phrase_threshold = 0.3  # More sensitive phrase detection
            self.recognizer.non_speaking_duration = 0.2  # Less aggressive silence detection
            self.speech_configured = True
            logger.info("[SUCCESS] Speech recognizer configured successfully")
            
        except Exception as e:
            logger.error(f"Speech recognizer setup failed: {e}")
            self.recognizer = None
            self.speech_configured = False

    def speech_to_text(self, audio_path: str, language: str = 'auto') -> tuple[str, str]:
        """Convert speech to text using Gemini Flash 2.0 with language detection or specified language"""
        try:
            if not self.gemini_configured:
                raise Exception("Gemini client not configured. Please check your API key.")
            
            if not os.path.exists(audio_path):
                raise Exception(f"Audio file not found: {audio_path}")
            
            # Load and preprocess audio with better error handling
            try:
                # Wait a bit to ensure file is fully written
                import time as time_module
                time_module.sleep(0.5)
                
                # Try to access the file multiple times if needed
                for attempt in range(3):
                    try:
                        y, sr_rate = librosa.load(audio_path, sr=16000, duration=30)
                        break
                    except Exception as e:
                        if attempt < 2:
                            logger.warning(f"Audio loading attempt {attempt + 1} failed: {e}, retrying...")
                            time_module.sleep(0.5)
                        else:
                            raise e
                
                if len(y) == 0:
                    return "No audio data found", "unknown"
                
                # Check for audio clipping and quality issues
                max_amplitude = np.max(np.abs(y))
                rms_level = np.sqrt(np.mean(y**2))
                
                logger.info(f"Audio quality check - Max: {max_amplitude:.4f}, RMS: {rms_level:.4f}, Duration: {len(y)/sr_rate:.2f}s")
                
                # Handle clipped audio (amplitude = 1.0 means clipping)
                if max_amplitude >= 0.99:
                    logger.warning("⚠️ Audio appears to be clipped - applying de-clipping")
                    # Apply soft clipping recovery
                    y = np.tanh(y * 0.8) * 0.9  # Soft compression to recover from clipping
                    max_amplitude = np.max(np.abs(y))
                
                # Check if audio is too quiet
                if rms_level < 0.01:
                    logger.warning("⚠️ Audio level very low - boosting signal")
                    # Boost quiet audio
                    y = y * (0.1 / rms_level)
                    y = np.clip(y, -0.95, 0.95)  # Prevent new clipping
                elif rms_level > 0.5:
                    logger.warning("⚠️ Audio level very high - reducing signal")
                    # Reduce loud audio
                    y = y * (0.3 / rms_level)
                
                # Final normalization to safe level
                if max_amplitude > 0.8:
                    y = y * (0.7 / max_amplitude)
                elif max_amplitude > 0:
                    y = y * (0.7 / max_amplitude)  # Normalize to 70% to avoid clipping
                
                logger.info(f"After processing - Max: {np.max(np.abs(y)):.4f}, RMS: {np.sqrt(np.mean(y**2)):.4f}")
                
                # Apply simple noise reduction
                if len(y) > sr_rate:  # Only if audio is longer than 1 second
                    # Calculate RMS energy
                    frame_length = int(0.025 * sr_rate)  # 25ms frames
                    hop_length = int(0.010 * sr_rate)    # 10ms hop
                    rms = librosa.feature.rms(y=y, frame_length=frame_length, hop_length=hop_length)[0]
                    
                    # Simple voice activity detection
                    rms_threshold = np.percentile(rms, 30)  # Bottom 30% is likely silence
                    
                    # Keep frames above threshold
                    frame_indices = np.where(rms > rms_threshold)[0]
                    if len(frame_indices) > 0:
                        start_frame = max(0, frame_indices[0] - 2)
                        end_frame = min(len(rms) - 1, frame_indices[-1] + 2)
                        
                        start_sample = start_frame * hop_length
                        end_sample = min(len(y), end_frame * hop_length + frame_length)
                        
                        y = y[start_sample:end_sample]
                
                # Save processed audio to temporary file with unique name
                temp_dir = tempfile.gettempdir()
                temp_audio = os.path.join(temp_dir, f"speech_audio_{os.getpid()}_{int(time.time() * 1000)}.wav")
                
                # Ensure we can write to the temp file
                try:
                    sf.write(temp_audio, y, sr_rate, format='WAV', subtype='PCM_16')
                    
                    # Verify file was written
                    if not os.path.exists(temp_audio) or os.path.getsize(temp_audio) == 0:
                        raise Exception("Failed to write temporary audio file")
                        
                except Exception as e:
                    logger.error(f"Failed to save temporary audio: {e}")
                    return f"Audio processing failed: {str(e)}", "unknown"
                
                # Give file system time to finish writing
                time_module.sleep(0.1)
                
                # Use Gemini Flash 2.0 for speech-to-text
                logger.info("🧠 Using Gemini Flash 2.0 for speech recognition...")
                
                try:
                    # Upload audio file to Gemini
                    import google.generativeai as genai
                    
                    # Upload the audio file
                    audio_file = genai.upload_file(temp_audio, mime_type="audio/wav")
                    logger.info(f"πŸ“€ Audio uploaded to Gemini: {audio_file.name}")
                    
                    # Create prompt based on language preference
                    if language == 'auto':
                        prompt = """Please transcribe this audio file. 

                        

Instructions:

1. Listen to the audio and transcribe exactly what is spoken

2. Detect the language automatically 

3. Provide the transcription in the original language

4. Return ONLY the transcribed text, no explanations

5. If you cannot understand the audio, respond with "RECOGNITION_FAILED"



Transcription:"""
                    else:
                        # Map language codes to language names
                        lang_name_map = {
                            'en-US': 'English', 'vi-VN': 'Vietnamese', 'es-ES': 'Spanish',
                            'fr-FR': 'French', 'de-DE': 'German', 'ja-JP': 'Japanese', 
                            'zh-CN': 'Chinese', 'ko-KR': 'Korean', 'it-IT': 'Italian',
                            'pt-PT': 'Portuguese', 'ru-RU': 'Russian', 'ar-SA': 'Arabic',
                            'hi-IN': 'Hindi', 'th-TH': 'Thai', 'tr-TR': 'Turkish'
                        }
                        expected_lang = lang_name_map.get(language, 'English')
                        
                        prompt = f"""Please transcribe this audio file in {expected_lang}.

                        

Instructions:

1. Listen to the audio and transcribe exactly what is spoken

2. The audio should be in {expected_lang}

3. Provide the transcription in {expected_lang}

4. Return ONLY the transcribed text, no explanations

5. If you cannot understand the audio, respond with "RECOGNITION_FAILED"



Transcription:"""
                    
                    # Generate transcription with Gemini (with timeout)
                    try:
                        response = self.gemini_model.generate_content(
                            [prompt, audio_file],
                            generation_config=genai.types.GenerationConfig(
                                candidate_count=1,
                                max_output_tokens=200,
                                temperature=0.1
                            )
                        )
                        transcription = response.text.strip()
                    except Exception as gen_error:
                        logger.error(f"Gemini generation failed: {gen_error}")
                        raise gen_error
                    
                    logger.info(f"🧠 Gemini transcription result: {transcription[:100]}...")
                    
                    # Clean up uploaded file
                    try:
                        genai.delete_file(audio_file.name)
                        logger.info("πŸ—‘οΈ Cleaned up uploaded file from Gemini")
                    except:
                        pass
                    
                    # Check if recognition failed
                    if transcription == "RECOGNITION_FAILED" or "cannot understand" in transcription.lower():
                        logger.warning("❌ Gemini could not understand the audio")
                        return "Could not understand speech - please try speaking more clearly or check your microphone", "unknown"
                    
                    # Detect language of transcription using Gemini
                    detected_language = self.detect_language_with_gemini(transcription)
                    
                    logger.info(f"βœ… Gemini transcription successful: {transcription[:50]}...")
                    logger.info(f"βœ… Detected language: {detected_language}")
                    
                    return transcription, detected_language
                    
                except Exception as gemini_error:
                    logger.error(f"❌ Gemini transcription failed: {gemini_error}")
                    return f"Gemini transcription failed: {str(gemini_error)}", "unknown"
                
                finally:
                    # Clean up temp file
                    try:
                        os.remove(temp_audio)
                    except Exception as e:
                        logger.warning(f"Failed to cleanup temp file: {e}")
                
            except Exception as audio_error:
                logger.error(f"Audio processing error: {audio_error}")
                return f"Audio processing failed: {str(audio_error)}", "unknown"
                
        except Exception as e:
            error_msg = str(e)
            logger.error(f"Speech recognition error: {error_msg}")
            raise Exception(f"Speech recognition failed: {error_msg}")
    
    def detect_language_with_gemini(self, text: str) -> str:
        """Use Gemini to detect language of text"""
        try:
            if not self.gemini_configured or not text.strip():
                return "English"
            
            prompt = f"""Analyze this text and identify the language. Respond with just the language name in English (e.g., "English", "Vietnamese", "Spanish", etc.):



{text[:200]}"""
            
            response = self.gemini_model.generate_content(prompt)
            detected_lang = response.text.strip()
            
            # Validate response
            valid_languages = ['English', 'Vietnamese', 'Spanish', 'French', 'German', 'Japanese', 'Chinese', 'Korean', 'Italian', 'Portuguese', 'Russian', 'Arabic', 'Hindi', 'Thai', 'Turkish']
            if detected_lang in valid_languages:
                return detected_lang
            else:
                return "English"
                
        except Exception as e:
            logger.warning(f"Gemini language detection failed: {e}")
            return "English"
    
    def get_audio_duration(self, audio_path: str) -> float:
        """Get duration of audio file"""
        try:
            y, sr = librosa.load(audio_path)
            return len(y) / sr
        except:
            return 0.0

    def translate_text(self, text: str, source_lang: str, target_lang: str) -> str:
        """Translate text using Google Gemini Flash 2.0"""
        try:
            if not self.gemini_configured:
                raise Exception("Google Gemini client not configured. Please check your API key.")
            
            # Create translation prompt
            source_name = self.supported_languages.get(source_lang, source_lang)
            target_name = self.supported_languages.get(target_lang, target_lang)
            
            prompt = f"""Translate the following {source_name} text to {target_name}. Provide only the translation, no explanations or additional text:



{text}"""
            
            response = self.gemini_model.generate_content(
                prompt,
                generation_config=genai.types.GenerationConfig(
                    candidate_count=1,
                    max_output_tokens=300,
                    temperature=0.2
                )
            )
            translated_text = response.text.strip()
            
            if translated_text:
                logger.info(f"Gemini Flash 2.0 translation successful: {translated_text[:100]}...")
                return translated_text
            else:
                raise Exception("Empty translation response from Gemini")
            
        except Exception as e:
            error_msg = str(e)
            logger.error(f"Translation error: {error_msg}")
            
            # Check for quota exceeded error
            if "429" in error_msg or "quota" in error_msg.lower() or "insufficient_quota" in error_msg.lower():
                logger.warning("[WARNING] Google Gemini API quota exceeded - using fallback translation")
                target_name = self.supported_languages.get(target_lang, target_lang)
                return f"[API Quota Exceeded] Please add credits to your Google account. Original text: {text}"
            
            raise Exception(f"Translation failed: {error_msg}")

    async def generate_speech_with_custom_voice(self, text: str, voice: str) -> str:
        """Generate speech using Edge TTS with custom voice"""
        try:
            if not EDGE_TTS_AVAILABLE:
                logger.warning("Edge TTS not available")
                return None
            
            # Create temporary output file
            temp_dir = tempfile.gettempdir()
            output_path = os.path.join(temp_dir, f"tts_output_{int(time.time())}.wav")
            
            # Generate speech with specific voice
            communicate = edge_tts.Communicate(text, voice)
            await communicate.save(output_path)
            
            if os.path.exists(output_path):
                logger.info(f"Edge TTS generated with {voice}: {output_path}")
                return output_path
            else:
                return None
                
        except Exception as e:
            logger.error(f"TTS Error: {e}")
            return None

    def process_audio_translation_with_voice(

        self, 

        audio_path: str, 

        target_lang: str,

        voice: str,

        input_language: str = 'auto'

    ) -> Tuple[str, str, str, Optional[str]]:
        """Complete audio translation pipeline with custom voice selection and input language option"""
        
        if not audio_path:
            return "Please upload an audio file", "", "", None
        
        input_desc = "auto-detection" if input_language == 'auto' else f"specified language ({input_language})"
        logger.info(f"Processing audio translation with {input_desc} -> {target_lang} (voice: {voice})")
        
        # Step 1: Speech to text with language detection or specified language
        logger.info(f"Step 1: Transcribing audio with {input_desc}...")
        transcribed_text, detected_language = self.speech_to_text(audio_path, input_language)
        
        if transcribed_text.startswith("Error"):
            return transcribed_text, "", "", None
        
        logger.info(f"Transcription: {transcribed_text[:100]}...")
        logger.info(f"Language: {detected_language}")
        
        # Step 2: Translate text with Gemini Flash 2.0 using detected/specified language
        logger.info("Step 2: Translating text...")
        # Map detected language name to code for translation
        lang_code_map = {
            'English': 'en', 'Vietnamese': 'vi', 'Spanish': 'es', 'French': 'fr',
            'German': 'de', 'Italian': 'it', 'Portuguese': 'pt', 'Russian': 'ru',
            'Japanese': 'ja', 'Korean': 'ko', 'Chinese': 'zh', 'Arabic': 'ar',
            'Hindi': 'hi', 'Thai': 'th', 'Turkish': 'tr'
        }
        
        detected_lang_code = lang_code_map.get(detected_language, 'en')
        translated_text = self.translate_text(transcribed_text, detected_lang_code, target_lang)
        
        if translated_text.startswith("[Translation Error]"):
            return transcribed_text, detected_language, translated_text, None
        
        logger.info(f"Translation: {translated_text[:100]}...")
        
        # Step 3: Generate speech with Edge TTS using custom voice
        logger.info(f"Step 3: Generating speech with voice: {voice}")
        audio_output = asyncio.run(self.generate_speech_with_custom_voice(translated_text, voice))
        
        if audio_output:
            logger.info("Complete translation pipeline successful!")
        else:
            logger.warning("TTS generation failed, returning text only")
        
        return transcribed_text, detected_language, translated_text, audio_output

# Initialize AI Agent
agent = TranslationAIAgent()

# Interface Functions
def get_country_options() -> List[str]:
    """Get country options with flags for target language"""
    choices = []
    for lang_code, lang_info in agent.language_voice_options.items():
        for option in lang_info['options']:
            choice = f"{option['code']} | {option['display']}"
            choices.append(choice)
    return sorted(choices)

def get_input_language_options() -> List[str]:
    """Get input language options for speech recognition"""
    choices = ["auto | Auto-detect Language (Recommended)"]
    
    # Add specific language options
    language_options = [
        ("en-US", "English (United States)"),
        ("vi-VN", "Vietnamese (Vietnam)"), 
        ("es-ES", "Spanish (Spain)"),
        ("fr-FR", "French (France)"),
        ("de-DE", "German (Germany)"),
        ("ja-JP", "Japanese (Japan)"),
        ("zh-CN", "Chinese (Simplified)"),
        ("ko-KR", "Korean (South Korea)"),
        ("it-IT", "Italian (Italy)"),
        ("pt-PT", "Portuguese (Portugal)"),
        ("ru-RU", "Russian (Russia)"),
        ("ar-SA", "Arabic (Saudi Arabia)"),
        ("hi-IN", "Hindi (India)"),
        ("th-TH", "Thai (Thailand)"),
        ("tr-TR", "Turkish (Turkey)")
    ]
    
    for code, display in language_options:
        choice = f"{code} | {display}"
        choices.append(choice)
    
    return choices

def get_voice_options_for_country(country_selection: str) -> List[str]:
    """Get voice options for selected country"""
    if not country_selection or '|' not in country_selection:
        return ["Jenny (Female)", "Guy (Male)"]
    
    code = country_selection.split(' | ')[0].strip()
    
    for lang_info in agent.language_voice_options.values():
        for option in lang_info['options']:
            if option['code'] == code:
                main_voice = option['voice'].replace('Neural', '').split('-')[-1]
                alt_voice = option['alt_voice'].replace('Neural', '').split('-')[-1]
                
                def get_gender(voice_name):
                    female_names = ['Jenny', 'Libby', 'Natasha', 'Clara', 'Elvira', 'Dalia', 'Denise', 'Sylvie', 'Katja', 'Elsa', 'Raquel', 'Francisca', 'Svetlana', 'Nanami', 'SunHi', 'Xiaoxiao', 'HoaiMy']
                    return "(Female)" if any(name in voice_name for name in female_names) else "(Male)"
                
                return [
                    f"{main_voice} {get_gender(main_voice)}",
                    f"{alt_voice} {get_gender(alt_voice)}"
                ]
    
    return ["Jenny (Female)", "Guy (Male)"]

def get_voice_code_from_selections(country_selection: str, voice_selection: str) -> str:
    """Get full voice code from country and voice selections"""
    if not country_selection or '|' not in country_selection:
        return 'en-US-JennyNeural'
    
    code = country_selection.split(' | ')[0].strip()
    voice_name = voice_selection.split(' (')[0].strip()
    
    for lang_info in agent.language_voice_options.values():
        for option in lang_info['options']:
            if option['code'] == code:
                main_voice_name = option['voice'].replace('Neural', '').split('-')[-1]
                alt_voice_name = option['alt_voice'].replace('Neural', '').split('-')[-1]
                
                if voice_name == main_voice_name:
                    return option['voice']
                elif voice_name == alt_voice_name:
                    return option['alt_voice']
    
    return 'en-US-JennyNeural'

def get_language_code_from_country(country_selection: str) -> str:
    """Extract language code from country selection"""
    if not country_selection or '|' not in country_selection:
        return 'en'
    
    code = country_selection.split(' | ')[0].strip()
    return code.split('-')[0]

def update_voice_options(country_selection: str) -> gr.Dropdown:
    """Update voice dropdown based on country selection"""
    voice_options = get_voice_options_for_country(country_selection)
    return gr.Dropdown(choices=voice_options, value=voice_options[0] if voice_options else "Jenny (Female)")

def get_input_language_code_from_selection(input_lang_selection: str) -> str:
    """Extract language code from input language selection"""
    if not input_lang_selection or '|' not in input_lang_selection:
        return 'auto'
    
    code = input_lang_selection.split(' | ')[0].strip()
    if code == 'auto':
        return 'auto'
    
    return code

# Global conversation and audio state
conversation_state = {
    "person_a_messages": [],
    "person_b_messages": [],
    "person_a_translations": [],
    "person_b_translations": [],
    "latest_audio_for_a": None,  # Audio that Person A should hear
    "latest_audio_for_b": None   # Audio that Person B should hear
}

# Recording state management
recording_state = {
    "person_a_recording": False,
    "person_b_recording": False,
    "person_a_audio": None,
    "person_b_audio": None
}

def add_message_to_conversation(person, original, detected_lang, translation, target_person):
    """Add message to global conversation state"""
    if original and translation:
        timestamp = time.strftime("%H:%M")
        
        if person == "A":
            conversation_state["person_a_messages"].append(f"[{timestamp}] Person A ({detected_lang}): {original}")
            conversation_state["person_b_translations"].append(f"[{timestamp}] -> Person B: {translation}")
        else:  # person == "B"
            conversation_state["person_b_messages"].append(f"[{timestamp}] Person B ({detected_lang}): {original}")
            conversation_state["person_a_translations"].append(f"[{timestamp}] -> Person A: {translation}")

def get_full_conversation():
    """Get complete conversation history for both tabs"""
    all_messages = []
    max_length = max(
        len(conversation_state["person_a_messages"]), 
        len(conversation_state["person_b_messages"]),
        len(conversation_state["person_a_translations"]),
        len(conversation_state["person_b_translations"])
    )
    
    for i in range(max_length):
        if i < len(conversation_state["person_a_messages"]):
            all_messages.append(conversation_state["person_a_messages"][i])
        if i < len(conversation_state["person_b_translations"]):
            all_messages.append(conversation_state["person_b_translations"][i])
        if i < len(conversation_state["person_b_messages"]):
            all_messages.append(conversation_state["person_b_messages"][i])
        if i < len(conversation_state["person_a_translations"]):
            all_messages.append(conversation_state["person_a_translations"][i])
    
    return "\n".join(all_messages[-10:])  # Show last 10 messages

def translate_person_a_to_b(audio_file, country_b: str, voice_b: str, input_lang_a: str) -> tuple[str, Optional[str]]:
    """Person A speaks -> results appear in Person B's tab"""
    if audio_file is None:
        return "", None
    
    try:
        print(f"[DEBUG] Person A recording: {audio_file}")
        tgt_code = get_language_code_from_country(country_b)
        selected_voice = get_voice_code_from_selections(country_b, voice_b)
        input_language = get_input_language_code_from_selection(input_lang_a)
        print(f"[DEBUG] Input Language: {input_language}, Target: {tgt_code}, Voice: {selected_voice}")
        
        original_text, detected_lang, translated_text, audio_output = agent.process_audio_translation_with_voice(
            audio_file, tgt_code, selected_voice, input_language
        )
        
        print(f"[DEBUG] Results: {original_text[:50]}... -> {translated_text[:50]}...")
        print(f"[DEBUG] Audio output: {audio_output}")
        
        # Add to conversation
        add_message_to_conversation("A", original_text, detected_lang, translated_text, "B")
        
        # Return conversation for Person B's tab and audio
        conversation_history = get_full_conversation()
        print(f"[DEBUG] Conversation length: {len(conversation_history)}")
        
        return conversation_history, audio_output
        
    except Exception as e:
        print(f"[ERROR] translate_person_a_to_b: {e}")
        return f"Error: {str(e)}", None

def translate_person_b_to_a(audio_file, country_a: str, voice_a: str, input_lang_b: str) -> tuple[str, Optional[str]]:
    """Person B speaks -> results appear in Person A's tab"""
    if audio_file is None:
        return "", None
    
    try:
        print(f"[DEBUG] Person B recording: {audio_file}")
        tgt_code = get_language_code_from_country(country_a)
        selected_voice = get_voice_code_from_selections(country_a, voice_a)
        input_language = get_input_language_code_from_selection(input_lang_b)
        print(f"[DEBUG] Input Language: {input_language}, Target: {tgt_code}, Voice: {selected_voice}")
        
        original_text, detected_lang, translated_text, audio_output = agent.process_audio_translation_with_voice(
            audio_file, tgt_code, selected_voice, input_language
        )
        
        print(f"[DEBUG] Results: {original_text[:50]}... -> {translated_text[:50]}...")
        print(f"[DEBUG] Audio output: {audio_output}")
        
        # Add to conversation
        add_message_to_conversation("B", original_text, detected_lang, translated_text, "A")
        
        # Return conversation for Person A's tab and audio
        conversation_history = get_full_conversation()
        print(f"[DEBUG] Conversation length: {len(conversation_history)}")
        
        return conversation_history, audio_output
        
    except Exception as e:
        print(f"[ERROR] translate_person_b_to_a: {e}")
        return f"Error: {str(e)}", None

def get_audio_for_person_a() -> Optional[str]:
    """Get latest audio that Person A should hear"""
    return conversation_state.get("latest_audio_for_a")

def get_audio_for_person_b() -> Optional[str]:
    """Get latest audio that Person B should hear"""
    return conversation_state.get("latest_audio_for_b")

def toggle_person_a_recording():
    """Toggle Person A recording state and return button updates"""
    if recording_state["person_a_recording"]:
        # Currently recording, stop it
        recording_state["person_a_recording"] = False
        return (
            gr.Button("🎀 Talk", elem_classes=["talk-button"]),
            "<div style='text-align: center; padding: 10px; color: #666;'>Ready to record</div>"
        )
    else:
        # Not recording, start it
        recording_state["person_a_recording"] = True
        # Clear previous audio
        recording_state["person_a_audio"] = None
        return (
            gr.Button("πŸ›‘ Stop", elem_classes=["stop-button"]),
            "<div style='text-align: center; padding: 10px; color: #f44336;'>πŸ”΄ Click Stop when done recording</div>"
        )

def toggle_person_b_recording():
    """Toggle Person B recording state and return button updates"""
    if recording_state["person_b_recording"]:
        # Currently recording, stop it
        recording_state["person_b_recording"] = False
        return (
            gr.Button("🎀 Talk", elem_classes=["talk-button"]),
            "<div style='text-align: center; padding: 10px; color: #666;'>Ready to record</div>"
        )
    else:
        # Not recording, start it
        recording_state["person_b_recording"] = True
        # Clear previous audio
        recording_state["person_b_audio"] = None
        return (
            gr.Button("πŸ›‘ Stop", elem_classes=["stop-button"]),
            "<div style='text-align: center; padding: 10px; color: #f44336;'>πŸ”΄ Click Stop when done recording</div>"
        )

def handle_person_a_audio_update(audio_file):
    """Handle audio update for Person A"""
    if audio_file and recording_state["person_a_recording"]:
        recording_state["person_a_audio"] = audio_file
        # Auto-stop recording when audio is received
        recording_state["person_a_recording"] = False
        return audio_file, "🎀 Talk", "talk-button"
    return None, "🎀 Talk", "talk-button"

def handle_person_b_audio_update(audio_file):
    """Handle audio update for Person B"""
    if audio_file and recording_state["person_b_recording"]:
        recording_state["person_b_audio"] = audio_file
        # Auto-stop recording when audio is received
        recording_state["person_b_recording"] = False
        return audio_file, "🎀 Talk", "talk-button"
    return None, "🎀 Talk", "talk-button"

def process_person_a_translation(country_b: str, voice_b: str, input_lang_a: str):
    """Process translation for Person A using stored audio"""
    audio_file = recording_state.get("person_a_audio")
    if not audio_file:
        return "", None
    
    try:
        print(f"[DEBUG] Person A processing stored audio: {audio_file}")
        tgt_code = get_language_code_from_country(country_b)
        selected_voice = get_voice_code_from_selections(country_b, voice_b)
        input_language = get_input_language_code_from_selection(input_lang_a)
        
        original_text, detected_lang, translated_text, audio_output = agent.process_audio_translation_with_voice(
            audio_file, tgt_code, selected_voice, input_language
        )
        
        # Add to conversation
        add_message_to_conversation("A", original_text, detected_lang, translated_text, "B")
        
        # Clear processed audio
        recording_state["person_a_audio"] = None
        
        # Return conversation for Person B's tab and audio
        conversation_history = get_full_conversation()
        return conversation_history, audio_output
        
    except Exception as e:
        print(f"[ERROR] process_person_a_translation: {e}")
        return f"Error: {str(e)}", None

def process_person_b_translation(country_a: str, voice_a: str, input_lang_b: str):
    """Process translation for Person B using stored audio"""
    audio_file = recording_state.get("person_b_audio")
    if not audio_file:
        return "", None
    
    try:
        print(f"[DEBUG] Person B processing stored audio: {audio_file}")
        tgt_code = get_language_code_from_country(country_a)
        selected_voice = get_voice_code_from_selections(country_a, voice_a)
        input_language = get_input_language_code_from_selection(input_lang_b)
        
        original_text, detected_lang, translated_text, audio_output = agent.process_audio_translation_with_voice(
            audio_file, tgt_code, selected_voice, input_language
        )
        
        # Add to conversation
        add_message_to_conversation("B", original_text, detected_lang, translated_text, "A")
        
        # Clear processed audio
        recording_state["person_b_audio"] = None
        
        # Return conversation for Person A's tab and audio
        conversation_history = get_full_conversation()
        return conversation_history, audio_output
        
    except Exception as e:
        print(f"[ERROR] process_person_b_translation: {e}")
        return f"Error: {str(e)}", None


# Create Two-Person Translation Interface
with gr.Blocks(
    title="πŸŽ™οΈ Two-Person Live Translation",
    theme=gr.themes.Soft(),
    css="""

    .gradio-container { max-width: 1400px !important; margin: 0 auto !important; }

    .header {

        text-align: center;

        background: linear-gradient(135deg, #4A90E2 0%, #FF6B9D 100%);

        color: white;

        padding: 20px;

        border-radius: 10px;

        margin-bottom: 20px;

    }

    .status-box {

        background: rgba(78, 205, 196, 0.1);

        border: 2px solid rgba(78, 205, 196, 0.3);

        border-radius: 10px;

        padding: 15px;

        text-align: center;

        margin: 15px 0;

    }

    .footer {

        text-align: center;

        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);

        color: white;

        padding: 20px;

        border-radius: 10px;

        margin-top: 30px;

        box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);

    }

    .guide-box {

        background: rgba(255, 255, 255, 0.05);

        border: 1px solid rgba(255, 255, 255, 0.2);

        border-radius: 10px;

        padding: 20px;

        margin: 15px 0;

    }

    .step-card {

        background: rgba(78, 205, 196, 0.1);

        border-left: 4px solid #4ECDCC;

        padding: 15px;

        margin: 10px 0;

        border-radius: 5px;

    }

    .tips-card {

        background: rgba(255, 193, 7, 0.1);

        border-left: 4px solid #FFC107;

        padding: 15px;

        margin: 10px 0;

        border-radius: 5px;

    }

    .talk-button {

        background: linear-gradient(135deg, #4CAF50 0%, #45a049 100%) !important;

        color: white !important;

        border: none !important;

        padding: 15px 30px !important;

        font-size: 18px !important;

        font-weight: bold !important;

        border-radius: 25px !important;

        cursor: pointer !important;

        transition: all 0.3s ease !important;

        box-shadow: 0 4px 8px rgba(76, 175, 80, 0.3) !important;

        min-height: 60px !important;

    }

    .talk-button:hover {

        transform: translateY(-2px) !important;

        box-shadow: 0 6px 12px rgba(76, 175, 80, 0.4) !important;

    }

    .stop-button {

        background: linear-gradient(135deg, #f44336 0%, #d32f2f 100%) !important;

        color: white !important;

        border: none !important;

        padding: 15px 30px !important;

        font-size: 18px !important;

        font-weight: bold !important;

        border-radius: 25px !important;

        cursor: pointer !important;

        transition: all 0.3s ease !important;

        box-shadow: 0 4px 8px rgba(244, 67, 54, 0.3) !important;

        min-height: 60px !important;

        animation: pulse 2s infinite !important;

    }

    .stop-button:hover {

        transform: translateY(-2px) !important;

        box-shadow: 0 6px 12px rgba(244, 67, 54, 0.4) !important;

    }

    @keyframes pulse {

        0% { box-shadow: 0 4px 8px rgba(244, 67, 54, 0.3); }

        50% { box-shadow: 0 6px 16px rgba(244, 67, 54, 0.6); }

        100% { box-shadow: 0 4px 8px rgba(244, 67, 54, 0.3); }

    }

    .hidden-audio {

        display: none !important;

    }

    """
) as demo:
    
    # Header
    api_status = "Ready" if agent.gemini_configured else "Missing API Key"
    edge_tts_status = "Ready" if EDGE_TTS_AVAILABLE else "Not Available"
    
    gr.HTML(f"""

    <div class="header">

        <h1>πŸŽ™οΈ Two-Person Live Translation</h1>

        <p>Real-time Cross-Translation between Person A & Person B</p>

        <div style="margin-top: 15px;">

            <span style="background: rgba(255,255,255,0.2); padding: 6px 12px; border-radius: 15px; margin: 0 5px;">

                <strong>Gemini:</strong> {api_status}

            </span>

            <span style="background: rgba(255,255,255,0.2); padding: 6px 12px; border-radius: 15px; margin: 0 5px;">

                <strong>Edge TTS:</strong> {edge_tts_status}

            </span>

        </div>

        <div style="margin-top: 10px;">🧠 <strong>Digitized Brains</strong></div>

    </div>

    """)

    # Status Box
    gr.HTML(f"""

    <div class="status-box">

        <h4>πŸ€– AI Pipeline Status</h4>

        <div style="display: flex; justify-content: center; gap: 20px; flex-wrap: wrap;">

            <span><strong>🧠 Gemini Speech Recognition:</strong> {'🟒 Ready' if agent.gemini_configured else 'πŸ”΄ Not Ready'}</span>

            <span><strong>🧠 Gemini Translation:</strong> {'🟒 Ready' if agent.gemini_configured else 'πŸ”΄ Not Ready'}</span>

            <span><strong>πŸ”Š Edge TTS:</strong> {'🟒 Ready' if EDGE_TTS_AVAILABLE else 'πŸ”΄ Not Ready'}</span>

        </div>

    </div>

    """)

    with gr.Tabs():
        # Person A Tab - Only shows translation FROM Person B
        with gr.TabItem("Person A View"):
            gr.Markdown("### Person A receives translations from Person B")
            
            # Conversation History for Person A
            conversation_display_a = gr.Textbox(
                label="Full Conversation",
                lines=8,
                interactive=False,
                placeholder="Conversation will appear here...",
                value=""
            )
            
            with gr.Row():
                with gr.Column(scale=2):
                    # Audio component with custom recording interface
                    mic_a = gr.Audio(
                        sources=["microphone"],
                        type="filepath",
                        label="Person A: Record Your Voice",
                        elem_id="mic_a"
                    )
                    
                    # Talk/Stop button for Person A
                    talk_button_a = gr.Button(
                        "🎀 Talk",
                        elem_classes=["talk-button"],
                        size="lg",
                        elem_id="talk_button_a"
                    )
                    
                    # Status display for Person A
                    status_a = gr.HTML(
                        "<div style='text-align: center; padding: 10px; color: #666;'>Ready to record</div>",
                        elem_id="status_a"
                    )
                    
                with gr.Column(scale=1):
                    # Person A's input language selection
                    input_lang_a = gr.Dropdown(
                        choices=get_input_language_options(),
                        label="Person A's Input Language",
                        value="auto | Auto-detect Language (Recommended)",
                        info="Select your speaking language or use auto-detect"
                    )
                    
                    # Person B's output settings
                    country_b_for_a = gr.Dropdown(
                        choices=get_country_options(),
                        label="Person B's Language",
                        value="vi-vn | Vietnamese (Vietnam)"
                    )
                    voice_b_for_a = gr.Dropdown(
                        choices=["HoaiMy (Female)", "NamMinh (Male)"],
                        label="Person B's Voice",
                        value="HoaiMy (Female)"
                    )
            
            # Only show audio FROM Person B (Person A hears this)
            audio_from_b = gr.Audio(
                label="πŸ”Š Translation Audio from Person B",
                interactive=False,
                value=None,
                autoplay=True
            )

        # Person B Tab - Only shows translation FROM Person A  
        with gr.TabItem("Person B View"):
            gr.Markdown("### Person B receives translations from Person A")
            
            # Conversation History for Person B
            conversation_display_b = gr.Textbox(
                label="Full Conversation",
                lines=8,
                interactive=False,
                placeholder="Conversation will appear here...",
                value=""
            )
            
            with gr.Row():
                with gr.Column(scale=2):
                    # Audio component with custom recording interface
                    mic_b = gr.Audio(
                        sources=["microphone"],
                        type="filepath",
                        label="Person B: Record Your Voice",
                        elem_id="mic_b"
                    )
                    
                    # Talk/Stop button for Person B
                    talk_button_b = gr.Button(
                        "🎀 Talk",
                        elem_classes=["talk-button"],
                        size="lg",
                        elem_id="talk_button_b"
                    )
                    
                    # Status display for Person B
                    status_b = gr.HTML(
                        "<div style='text-align: center; padding: 10px; color: #666;'>Ready to record</div>",
                        elem_id="status_b"
                    )
                    
                with gr.Column(scale=1):
                    # Person B's input language selection
                    input_lang_b = gr.Dropdown(
                        choices=get_input_language_options(),
                        label="Person B's Input Language",
                        value="auto | Auto-detect Language (Recommended)",
                        info="Select your speaking language or use auto-detect"
                    )
                    
                    # Person A's output settings
                    country_a_for_b = gr.Dropdown(
                        choices=get_country_options(),
                        label="Person A's Language",
                        value="en-us | English (United States)"
                    )
                    voice_a_for_b = gr.Dropdown(
                        choices=["Jenny (Female)", "Guy (Male)"],
                        label="Person A's Voice",
                        value="Jenny (Female)"
                    )
            
            # Only show audio FROM Person A (Person B hears this)
            audio_from_a = gr.Audio(
                label="πŸ”Š Translation Audio from Person A",
                interactive=False,
                value=None,
                autoplay=True
            )


        # User Guide Tab
        with gr.TabItem("πŸ“š User Guide"):
            gr.HTML("""

            <div class="guide-box">

                <h2 style="color: #4A90E2; margin-bottom: 20px;">πŸŽ™οΈ Two-Way Translation App User Guide</h2>

                <p style="font-size: 16px; margin-bottom: 20px;">This application enables two people to communicate in different languages through automatic translation.</p>

            </div>

            """)
            
            gr.HTML("""

            <div class="step-card">

                <h3>πŸš€ Step 1: Preparation</h3>

                <ul>

                    <li><strong>Check microphone:</strong> Ensure your microphone works properly</li>

                    <li><strong>Quiet environment:</strong> Find a location with minimal background noise</li>

                    <li><strong>Stable internet:</strong> Internet connection required for AI processing</li>

                    <li><strong>Speakers/headphones:</strong> To hear translated audio output</li>

                </ul>

            </div>

            """)
            
            gr.HTML("""

            <div class="step-card">

                <h3>πŸ‘₯ Step 2: Choose Your Tab</h3>

                <ul>

                    <li><strong>Person A View:</strong> For the first person</li>

                    <li><strong>Person B View:</strong> For the second person</li>

                    <li><strong>Each person only needs to focus on their own tab</strong></li>

                </ul>

            </div>

            """)
            
            gr.HTML("""

            <div class="step-card">

                <h3>πŸ—£οΈ Step 3: Language Setup</h3>

                <ul>

                    <li><strong>Input Language:</strong> Select the language you will speak (or Auto-detect)</li>

                    <li><strong>Target Language:</strong> Choose the language to translate to</li>

                    <li><strong>Voice:</strong> Select voice for translated audio output</li>

                    <li><strong>Recommendation:</strong> Choose specific language instead of Auto-detect for better accuracy</li>

                </ul>

            </div>

            """)
            
            gr.HTML("""

            <div class="step-card">

                <h3>🎀 Step 4: One-Click Talk Button Recording</h3>

                <ul>

                    <li><strong>Click "🎀 Talk"</strong> - Button turns green and starts recording automatically</li>

                    <li><strong>Speak clearly for 3-7 seconds</strong> - Button shows "πŸ›‘ Stop" with red pulse animation</li>

                    <li><strong>Click "πŸ›‘ Stop"</strong> - Automatically stops recording and processes translation</li>

                    <li><strong>Audio automatically plays</strong> - Translation appears in the other person's view</li>

                    <li><strong>Ready for next recording</strong> - System automatically resets for next conversation</li>

                </ul>

            </div>

            """)
            
            gr.HTML("""

            <div class="step-card">

                <h3>✨ Key Features</h3>

                <ul>

                    <li><strong>🎯 One-Click Operation:</strong> No need to manually start/stop recording - Talk button handles everything</li>

                    <li><strong>πŸ”„ Auto-Clear:</strong> System automatically clears previous recordings for seamless conversation flow</li>

                    <li><strong>🎡 Auto-Play:</strong> Translated audio plays immediately when ready</li>

                    <li><strong>🎨 Visual Feedback:</strong> Button colors and animations show current recording state</li>

                    <li><strong>πŸš€ Instant Translation:</strong> From speech to translation in one click</li>

                </ul>

            </div>

            """)
            
            gr.HTML("""

            <div class="tips-card">

                <h3>πŸ’‘ Tips for Best Results</h3>

                <ul>

                    <li><strong>🎀 Microphone:</strong> Speak close to mic, not too loud or quiet</li>

                    <li><strong>⏱️ Duration:</strong> 3-7 seconds is ideal (not too short/long)</li>

                    <li><strong>πŸ—£οΈ Speaking style:</strong> Clear, not too fast, natural punctuation</li>

                    <li><strong>πŸ”‡ Environment:</strong> Minimize background noise</li>

                    <li><strong>🌍 Language:</strong> Select correct input language instead of auto-detect</li>

                    <li><strong>πŸ”„ Retry:</strong> If unsuccessful, try again with different approach</li>

                </ul>

            </div>

            """)
            
            gr.HTML("""

            <div class="step-card">

                <h3>πŸ”§ Common Troubleshooting</h3>

                <ul>

                    <li><strong>"Could not understand speech":</strong> Speak more clearly, check microphone</li>

                    <li><strong>No audio output:</strong> Check speakers/headphones</li>

                    <li><strong>Incorrect translation:</strong> Select specific input language</li>

                    <li><strong>Slow processing:</strong> Check internet connection</li>

                </ul>

            </div>

            """)
            

    # JavaScript for controlling recording
    js_control_recording = """

    function(button_text, elem_classes) {

        // Get the button element and audio component

        const button = arguments[2];  // The button that was clicked

        const audio_component = document.querySelector('audio');

        

        if (button_text.includes('Talk')) {

            // Start recording

            if (audio_component) {

                const startButton = audio_component.querySelector('[aria-label="Record from microphone"]');

                if (startButton) startButton.click();

            }

            return ["πŸ›‘ Stop", "stop-button"];

        } else {

            // Stop recording  

            if (audio_component) {

                const stopButton = audio_component.querySelector('[aria-label="Stop recording"]');

                if (stopButton) stopButton.click();

            }

            return ["🎀 Talk", "talk-button"];

        }

    }

    """

    # Event Handlers
    # Voice options update
    country_b_for_a.change(
        fn=update_voice_options,
        inputs=[country_b_for_a],
        outputs=[voice_b_for_a]
    )
    
    country_a_for_b.change(
        fn=update_voice_options,
        inputs=[country_a_for_b],
        outputs=[voice_a_for_b]
    )
    
    # JavaScript-powered Talk/Stop button handlers
    def handle_person_a_recording():
        return None
    
    def handle_person_b_recording():
        return None
    
    talk_button_a.click(
        fn=handle_person_a_recording,
        js="""

        () => {

            console.log("🎀 Person A Talk button clicked");

            

            // Find Gradio's recording buttons (search globally after recording state changes)

            const micContainer = document.getElementById('mic_a');

            let recordBtn = micContainer.querySelector('.record-button');

            let stopBtn = micContainer.querySelector('.stop-button');

            

            // If not found in container, search globally (happens after recording)

            if (!recordBtn || !stopBtn) {

                const allRecordBtns = document.querySelectorAll('.record-button');

                const allStopBtns = document.querySelectorAll('.stop-button');

                

                // Find Person A buttons by checking parent containers

                for (let i = 0; i < allRecordBtns.length; i++) {

                    const btn = allRecordBtns[i];

                    const container = btn.closest('[id*="mic_a"]');

                    if (container && container.id === 'mic_a') {

                        recordBtn = btn;

                        stopBtn = allStopBtns[i];

                        console.log("πŸ” Found Person A buttons globally:", container.id);

                        break;

                    }

                }

                

                // Fallback to first button if specific search fails

                if (!recordBtn) {

                    recordBtn = allRecordBtns[0];

                    stopBtn = allStopBtns[0];

                    console.log("πŸ” Using fallback buttons");

                }

            }

            const statusEl = document.getElementById('status_a');

            const btn = document.getElementById('talk_button_a');

            

            // Initialize state if not exists

            if (!window.personARecording) {

                window.personARecording = { isRecording: false };

            }

            

            if (!window.personARecording.isRecording) {

                // Clear any existing audio first to restore record button

                const clearBtn = micContainer.querySelector('button[aria-label="Clear"]');

                if (clearBtn) {

                    console.log("🧹 Clearing existing audio for Person A");

                    clearBtn.click();

                    

                    // Wait a moment for UI to update, then find record button

                    setTimeout(() => {

                        const newRecordBtn = micContainer.querySelector('.record-button') || 

                                           document.querySelectorAll('.record-button')[0];

                        if (newRecordBtn) {

                            console.log("βœ… Clicking Gradio's Record button for Person A");

                            newRecordBtn.click();

                            window.personARecording.isRecording = true;

                            

                            // Update UI

                            if (btn) {

                                btn.textContent = 'πŸ›‘ Stop';

                                btn.className = btn.className.replace('talk-button', 'stop-button');

                            }

                            

                            if (statusEl) {

                                statusEl.innerHTML = '<div style="text-align: center; padding: 10px; color: #f44336;">πŸ”΄ Recording... Click Stop when done</div>';

                            }

                        }

                    }, 100);

                } else if (recordBtn) {

                    // No clear needed, record button available

                    console.log("βœ… Clicking Gradio's Record button for Person A");

                    recordBtn.click();

                    window.personARecording.isRecording = true;

                    

                    // Update UI

                    if (btn) {

                        btn.textContent = 'πŸ›‘ Stop';

                        btn.className = btn.className.replace('talk-button', 'stop-button');

                    }

                    

                    if (statusEl) {

                        statusEl.innerHTML = '<div style="text-align: center; padding: 10px; color: #f44336;">πŸ”΄ Recording... Click Stop when done</div>';

                    }

                }

                

            } else if (window.personARecording.isRecording && stopBtn) {

                // Stop recording by clicking Gradio's stop button

                console.log("⏹️ Clicking Gradio's Stop button for Person A");

                stopBtn.click();

                window.personARecording.isRecording = false;

                

                // Update UI

                if (btn) {

                    btn.textContent = '🎀 Talk';

                    btn.className = btn.className.replace('stop-button', 'talk-button');

                }

                

                if (statusEl) {

                    statusEl.innerHTML = '<div style="text-align: center; padding: 10px; color: #4CAF50;">βœ… Processing translation...</div>';

                }

            } else {

                console.error("❌ Gradio recording buttons not found");

                if (statusEl) {

                    statusEl.innerHTML = '<div style="color: red;">❌ Recording interface not available</div>';

                }

            }

        }

        """
    )
    
    talk_button_b.click(
        fn=handle_person_b_recording,
        js="""

        () => {

            console.log("🎀 Person B Talk button clicked");

            

            // Find Gradio's recording buttons (search globally after recording state changes)

            const micContainer = document.getElementById('mic_b');

            let recordBtn = micContainer.querySelector('.record-button');

            let stopBtn = micContainer.querySelector('.stop-button');

            

            // If not found in container, search globally (happens after recording)

            if (!recordBtn || !stopBtn) {

                const allRecordBtns = document.querySelectorAll('.record-button');

                const allStopBtns = document.querySelectorAll('.stop-button');

                

                // Find Person B buttons by checking parent containers

                for (let i = 0; i < allRecordBtns.length; i++) {

                    const btn = allRecordBtns[i];

                    const container = btn.closest('[id*="mic_b"]');

                    if (container && container.id === 'mic_b') {

                        recordBtn = btn;

                        stopBtn = allStopBtns[i];

                        console.log("πŸ” Found Person B buttons globally:", container.id);

                        break;

                    }

                }

                

                // Fallback to second button if specific search fails

                if (!recordBtn) {

                    recordBtn = allRecordBtns[1] || allRecordBtns[0];

                    stopBtn = allStopBtns[1] || allStopBtns[0];

                    console.log("πŸ” Using fallback buttons for Person B");

                }

            }

            const statusEl = document.getElementById('status_b');

            const btn = document.getElementById('talk_button_b');

            

            // Initialize state if not exists

            if (!window.personBRecording) {

                window.personBRecording = { isRecording: false };

            }

            

            if (!window.personBRecording.isRecording) {

                // Clear any existing audio first to restore record button

                const clearBtn = micContainer.querySelector('button[aria-label="Clear"]');

                if (clearBtn) {

                    console.log("🧹 Clearing existing audio for Person B");

                    clearBtn.click();

                    

                    // Wait a moment for UI to update, then find record button

                    setTimeout(() => {

                        const newRecordBtn = micContainer.querySelector('.record-button') || 

                                           document.querySelectorAll('.record-button')[1];

                        if (newRecordBtn) {

                            console.log("βœ… Clicking Gradio's Record button for Person B");

                            newRecordBtn.click();

                            window.personBRecording.isRecording = true;

                            

                            // Update UI

                            if (btn) {

                                btn.textContent = 'πŸ›‘ Stop';

                                btn.className = btn.className.replace('talk-button', 'stop-button');

                            }

                            

                            if (statusEl) {

                                statusEl.innerHTML = '<div style="text-align: center; padding: 10px; color: #f44336;">πŸ”΄ Recording... Click Stop when done</div>';

                            }

                        }

                    }, 100);

                } else if (recordBtn) {

                    // No clear needed, record button available

                    console.log("βœ… Clicking Gradio's Record button for Person B");

                    recordBtn.click();

                    window.personBRecording.isRecording = true;

                    

                    // Update UI

                    if (btn) {

                        btn.textContent = 'πŸ›‘ Stop';

                        btn.className = btn.className.replace('talk-button', 'stop-button');

                    }

                    

                    if (statusEl) {

                        statusEl.innerHTML = '<div style="text-align: center; padding: 10px; color: #f44336;">πŸ”΄ Recording... Click Stop when done</div>';

                    }

                }

                

            } else if (window.personBRecording.isRecording && stopBtn) {

                // Stop recording by clicking Gradio's stop button

                console.log("⏹️ Clicking Gradio's Stop button for Person B");

                stopBtn.click();

                window.personBRecording.isRecording = false;

                

                // Update UI

                if (btn) {

                    btn.textContent = '🎀 Talk';

                    btn.className = btn.className.replace('stop-button', 'talk-button');

                }

                

                if (statusEl) {

                    statusEl.innerHTML = '<div style="text-align: center; padding: 10px; color: #4CAF50;">βœ… Processing translation...</div>';

                }

            } else {

                console.error("❌ Gradio recording buttons not found");

                if (statusEl) {

                    statusEl.innerHTML = '<div style="color: red;">❌ Recording interface not available</div>';

                }

            }

        }

        """
    )
    
    # JavaScript to implement direct recording from Talk buttons
    gr.HTML("""

    <script>

    console.log("🎀 Setting up direct recording control...");

    

    let personARecording = false;

    let personBRecording = false;

    let personAMediaRecorder = null;

    let personBMediaRecorder = null;

    let personAStream = null;

    let personBStream = null;

    let personAAudioChunks = [];

    let personBAudioChunks = [];

    

    function findGradioAudioInputs() {

        // Find Gradio audio input components to send our recorded audio to

        console.log("πŸ” Finding Gradio audio inputs...");

        const audioInputA = document.querySelector('#mic_a input[type="file"]');

        const audioInputB = document.querySelector('#mic_b input[type="file"]');

        

        console.log("Audio Input A found:", !!audioInputA);

        console.log("Audio Input B found:", !!audioInputB);

        

        return { audioInputA, audioInputB };

    }

    

    function createAudioFile(audioBlob, filename) {

        // Create a File object from audio blob

        const file = new File([audioBlob], filename, {

            type: 'audio/wav',

            lastModified: Date.now()

        });

        return file;

    }

    

    function sendAudioToGradio(audioFile, audioInput) {

        // Send recorded audio file to Gradio's file input

        try {

            if (audioInput) {

                // Create a FileList-like object

                const fileList = {

                    0: audioFile,

                    length: 1,

                    item: (index) => index === 0 ? audioFile : null

                };

                

                // Set the files property

                Object.defineProperty(audioInput, 'files', {

                    value: fileList,

                    writable: false

                });

                

                // Trigger change event

                const event = new Event('change', { bubbles: true });

                audioInput.dispatchEvent(event);

                

                console.log("βœ… Audio file sent to Gradio:", audioFile.name);

                return true;

            }

        } catch (error) {

            console.error("❌ Failed to send audio to Gradio:", error);

        }

        return false;

    }

    

    function setupDirectRecording() {

        setTimeout(() => {

            const talkButtonA = document.getElementById('talk_button_a');

            const talkButtonB = document.getElementById('talk_button_b');

            const statusA = document.getElementById('status_a');

            const statusB = document.getElementById('status_b');

            

            console.log("Talk Button A found:", !!talkButtonA);

            console.log("Talk Button B found:", !!talkButtonB);

            

            // Find Gradio audio inputs

            const { audioInputA, audioInputB } = findGradioAudioInputs();

            

            // Setup Person A direct recording

            if (talkButtonA) {

                // Remove existing event listeners

                const newTalkButtonA = talkButtonA.cloneNode(true);

                talkButtonA.parentNode.replaceChild(newTalkButtonA, talkButtonA);

                

                newTalkButtonA.addEventListener('click', async function(e) {

                    e.preventDefault();

                    e.stopPropagation();

                    

                    console.log("🎀 Person A Talk button clicked, currently recording:", personARecording);

                    

                    if (!personARecording) {

                        // Start direct recording

                        try {

                            console.log("πŸ”΄ Starting Person A direct recording...");

                            

                            // Request microphone access

                            personAStream = await navigator.mediaDevices.getUserMedia({ 

                                audio: {

                                    sampleRate: 16000,

                                    channelCount: 1,

                                    echoCancellation: true,

                                    noiseSuppression: true

                                } 

                            });

                            

                            console.log("βœ… Microphone access granted");

                            

                            // Create MediaRecorder

                            personAMediaRecorder = new MediaRecorder(personAStream, {

                                mimeType: 'audio/webm;codecs=opus'

                            });

                            

                            personAAudioChunks = [];

                            

                            // Setup event handlers

                            personAMediaRecorder.ondataavailable = function(event) {

                                if (event.data.size > 0) {

                                    personAAudioChunks.push(event.data);

                                }

                            };

                            

                            personAMediaRecorder.onstop = function() {

                                console.log("🎡 Person A recording stopped, processing...");

                                

                                // Create audio blob

                                const audioBlob = new Blob(personAAudioChunks, { type: 'audio/webm' });

                                console.log("Audio blob created:", audioBlob.size, "bytes");

                                

                                // Convert to file and send to Gradio

                                const audioFile = createAudioFile(audioBlob, `person_a_recording_${Date.now()}.webm`);

                                

                                if (sendAudioToGradio(audioFile, audioInputA)) {

                                    console.log("βœ… Audio sent to Gradio successfully");

                                    if (statusA) {

                                        statusA.innerHTML = '<div style="text-align: center; padding: 10px; color: #4CAF50;">βœ… Processing translation...</div>';

                                    }

                                } else {

                                    console.error("❌ Failed to send audio to Gradio");

                                    if (statusA) {

                                        statusA.innerHTML = '<div style="text-align: center; padding: 10px; color: #f44336;">❌ Failed to process audio</div>';

                                    }

                                }

                                

                                // Cleanup

                                personAStream.getTracks().forEach(track => track.stop());

                                personAStream = null;

                                personAMediaRecorder = null;

                            };

                            

                            // Start recording

                            personAMediaRecorder.start();

                            personARecording = true;

                            

                            // Update status

                            if (statusA) {

                                statusA.innerHTML = '<div style="text-align: center; padding: 10px; color: #f44336;">πŸ”΄ Recording... Click Stop when done</div>';

                            }

                            

                            console.log("βœ… Person A recording started successfully");

                            

                        } catch (error) {

                            console.error("❌ Error starting Person A recording:", error);

                            if (statusA) {

                                statusA.innerHTML = '<div style="text-align: center; padding: 10px; color: #f44336;">❌ Microphone access denied or failed</div>';

                            }

                        }

                        

                    } else {

                        // Stop recording

                        console.log("⏹️ Stopping Person A recording...");

                        

                        if (personAMediaRecorder && personAMediaRecorder.state === 'recording') {

                            personAMediaRecorder.stop();

                            personARecording = false;

                            

                            if (statusA) {

                                statusA.innerHTML = '<div style="text-align: center; padding: 10px; color: #4CAF50;">βœ… Processing audio...</div>';

                            }

                        }

                    }

                });

            }

            

            // Setup Person B direct recording  

            if (talkButtonB) {

                // Remove existing event listeners

                const newTalkButtonB = talkButtonB.cloneNode(true);

                talkButtonB.parentNode.replaceChild(newTalkButtonB, talkButtonB);

                

                newTalkButtonB.addEventListener('click', async function(e) {

                    e.preventDefault();

                    e.stopPropagation();

                    

                    console.log("🎀 Person B Talk button clicked, currently recording:", personBRecording);

                    

                    if (!personBRecording) {

                        // Start direct recording

                        try {

                            console.log("πŸ”΄ Starting Person B direct recording...");

                            

                            // Request microphone access

                            personBStream = await navigator.mediaDevices.getUserMedia({ 

                                audio: {

                                    sampleRate: 16000,

                                    channelCount: 1,

                                    echoCancellation: true,

                                    noiseSuppression: true

                                } 

                            });

                            

                            console.log("βœ… Microphone access granted for Person B");

                            

                            // Create MediaRecorder

                            personBMediaRecorder = new MediaRecorder(personBStream, {

                                mimeType: 'audio/webm;codecs=opus'

                            });

                            

                            personBAudioChunks = [];

                            

                            // Setup event handlers

                            personBMediaRecorder.ondataavailable = function(event) {

                                if (event.data.size > 0) {

                                    personBAudioChunks.push(event.data);

                                }

                            };

                            

                            personBMediaRecorder.onstop = function() {

                                console.log("🎡 Person B recording stopped, processing...");

                                

                                // Create audio blob

                                const audioBlob = new Blob(personBAudioChunks, { type: 'audio/webm' });

                                console.log("Audio blob created:", audioBlob.size, "bytes");

                                

                                // Convert to file and send to Gradio

                                const audioFile = createAudioFile(audioBlob, `person_b_recording_${Date.now()}.webm`);

                                

                                if (sendAudioToGradio(audioFile, audioInputB)) {

                                    console.log("βœ… Audio sent to Gradio successfully");

                                    if (statusB) {

                                        statusB.innerHTML = '<div style="text-align: center; padding: 10px; color: #4CAF50;">βœ… Processing translation...</div>';

                                    }

                                } else {

                                    console.error("❌ Failed to send audio to Gradio");

                                    if (statusB) {

                                        statusB.innerHTML = '<div style="text-align: center; padding: 10px; color: #f44336;">❌ Failed to process audio</div>';

                                    }

                                }

                                

                                // Cleanup

                                personBStream.getTracks().forEach(track => track.stop());

                                personBStream = null;

                                personBMediaRecorder = null;

                            };

                            

                            // Start recording

                            personBMediaRecorder.start();

                            personBRecording = true;

                            

                            // Update status

                            if (statusB) {

                                statusB.innerHTML = '<div style="text-align: center; padding: 10px; color: #f44336;">πŸ”΄ Recording... Click Stop when done</div>';

                            }

                            

                            console.log("βœ… Person B recording started successfully");

                            

                        } catch (error) {

                            console.error("❌ Error starting Person B recording:", error);

                            if (statusB) {

                                statusB.innerHTML = '<div style="text-align: center; padding: 10px; color: #f44336;">❌ Microphone access denied or failed</div>';

                            }

                        }

                        

                    } else {

                        // Stop recording

                        console.log("⏹️ Stopping Person B recording...");

                        

                        if (personBMediaRecorder && personBMediaRecorder.state === 'recording') {

                            personBMediaRecorder.stop();

                            personBRecording = false;

                            

                            if (statusB) {

                                statusB.innerHTML = '<div style="text-align: center; padding: 10px; color: #4CAF50;">βœ… Processing audio...</div>';

                            }

                        }

                    }

                });

            }

            

            console.log("βœ… Direct recording setup complete");

            

        }, 3000); // Wait for Gradio to fully load

    }

    

    // Initialize with retry mechanism

    function initDirectRecording() {

        setupDirectRecording();

        

        // Retry in case interface isn't ready

        setTimeout(() => {

            console.log("πŸ”„ Retrying direct recording setup...");

            setupDirectRecording();

        }, 5000);

        

        setTimeout(() => {

            console.log("πŸ”„ Final retry for direct recording setup...");

            setupDirectRecording();

        }, 8000);

    }

    

    // Start initialization

    if (document.readyState === 'loading') {

        document.addEventListener('DOMContentLoaded', initDirectRecording);

    } else {

        initDirectRecording();

    }

    

    console.log("🎀 Direct recording script loaded");

    alert("🎀 Direct recording script loaded");

    

    </script>

    """)
    
    # Enhanced audio change handlers with JavaScript state sync
    def handle_person_a_audio_change(audio, country_b, voice_b, input_lang_a_val):
        # Always process audio when received (JavaScript controls when recording happens)
        if audio:
            # Process translation
            conversation, audio_output = translate_person_a_to_b(audio, country_b, voice_b, input_lang_a_val)
            # Reset recording state and button
            recording_state["person_a_recording"] = False
            reset_button = gr.Button("🎀 Talk", elem_classes=["talk-button"])
            reset_status = """<div style='text-align: center; padding: 10px; color: #4CAF50;'>βœ… Translation complete! Ready for next recording</div>

            <script>

            // Reset JavaScript state

            if (typeof personARecording !== 'undefined') {

                personARecording = false;

                console.log("πŸ”„ Person A recording state reset");

            }

            </script>"""
            return conversation, audio_output, reset_button, reset_status
        return "", None, gr.Button("🎀 Talk", elem_classes=["talk-button"]), "<div style='text-align: center; padding: 10px; color: #666;'>Ready to record</div>"

    def handle_person_b_audio_change(audio, country_a, voice_a, input_lang_b_val):
        # Always process audio when received (JavaScript controls when recording happens)
        if audio:
            # Process translation
            conversation, audio_output = translate_person_b_to_a(audio, country_a, voice_a, input_lang_b_val)
            # Reset recording state and button
            recording_state["person_b_recording"] = False
            reset_button = gr.Button("🎀 Talk", elem_classes=["talk-button"])
            reset_status = """<div style='text-align: center; padding: 10px; color: #4CAF50;'>βœ… Translation complete! Ready for next recording</div>

            <script>

            // Reset JavaScript state

            if (typeof personBRecording !== 'undefined') {

                personBRecording = false;

                console.log("πŸ”„ Person B recording state reset");

            }

            </script>"""
            return conversation, audio_output, reset_button, reset_status
        return "", None, gr.Button("🎀 Talk", elem_classes=["talk-button"]), "<div style='text-align: center; padding: 10px; color: #666;'>Ready to record</div>"

    mic_a.change(
        fn=handle_person_a_audio_change,
        inputs=[mic_a, country_b_for_a, voice_b_for_a, input_lang_a],
        outputs=[conversation_display_b, audio_from_a, talk_button_a, status_a]
    )
    
    mic_b.change(
        fn=handle_person_b_audio_change,
        inputs=[mic_b, country_a_for_b, voice_a_for_b, input_lang_b],
        outputs=[conversation_display_a, audio_from_b, talk_button_b, status_b]
    )

    # Footer
    gr.HTML("""

    <div class="footer">

        <div style="display: flex; align-items: center; justify-content: center; gap: 10px; margin-bottom: 10px;">

            <span style="font-size: 24px;">🧠</span>

            <h3 style="margin: 0; font-size: 20px; font-weight: 600; background: linear-gradient(45deg, #fff, #e0e0e0); -webkit-background-clip: text; -webkit-text-fill-color: transparent; background-clip: text;">

                Digitized Brains - AI Translation

            </h3>

        </div>

        <div style="height: 1px; background: linear-gradient(90deg, transparent, rgba(255,255,255,0.3), transparent); margin: 15px 0;"></div>

        <p style="margin: 0; font-size: 14px; opacity: 0.8; font-style: italic;">

            Intelligent Communication Solutions

        </p>

    </div>

    """)

if __name__ == "__main__":
    print("===== Two-Person Live Translation Startup =====")
    print("Starting Two-Person Live Translation with Google Gemini")
    print(f"Google Gemini API Status: {'Ready' if agent.gemini_configured else 'Missing - Set GOOGLE_API_KEY'}")
    print(f"Edge TTS Status: {'Ready' if EDGE_TTS_AVAILABLE else 'Not Available'}")
    
    if agent.gemini_configured:
        print("Production Mode - Full Gemini AI Translation enabled")
        print("Speech Recognition: Google Gemini Flash 2.0")
        print("Language Detection: Google Gemini Flash 2.0")  
        print("Translation Model: Google Gemini Flash 2.0")
        print("🧠 All AI processing powered by Gemini Flash 2.0!")
    else:
        print("Demo Mode - Configure GOOGLE_API_KEY for full functionality")
    
    # Use environment port or default (7860 is Hugging Face standard)
    port = int(os.environ.get("PORT", os.environ.get("GRADIO_SERVER_PORT", 7860)))
    demo.launch(
        server_name="0.0.0.0",
        server_port=port,
        share=False,
        show_error=True,
        ssr_mode=False,  # Disable SSR for better container compatibility
        show_api=False   # Reduce overhead
    )