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

FAST_HTTP_SESSION = requests.Session()
adapter = requests.adapters.HTTPAdapter(pool_connections=20, pool_maxsize=20)
FAST_HTTP_SESSION.mount('https://', adapter)
FAST_HTTP_SESSION.mount('http://', adapter)

sys.stdout.reconfigure(encoding='utf-8')

CACHE_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "audio_cache")
os.makedirs(CACHE_DIR, exist_ok=True)

GEMINI_KEY_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), ".gemini_key")
MAX_REQUEST_BYTES = 25 * 1024 * 1024  # 25 MB is plenty for a voice clip


def get_gemini_key(user_key=""):
    """Gemini key: from the request, else the GEMINI_API_KEY env var, else the private .gemini_key file.
    The key is never written in the code, so it is never sent to browsers or uploaded anywhere."""
    if user_key and user_key.strip():
        return user_key.strip()
    env_key = os.environ.get("GEMINI_API_KEY", "").strip()
    if env_key:
        return env_key
    try:
        with open(GEMINI_KEY_FILE, "r", encoding="utf-8") as f:
            return f.read().strip()
    except Exception:
        return ""

def sanitize_kurdish_sorani(text):
    """Ensures authentic Sorani Kurdish greeting 'سڵاو' is always preserved and never converted to 'سلاڤ',
    and converts unnatural literal possessives into native Sorani Kurdish."""
    if not text:
        return text

    # Sorani Kurdish Greeting normalization
    text = re.sub(r'(?<!\w)سلاڤ(?!\w)', 'سڵاو', text)
    text = re.sub(r'(?<!\w)سلاڤان(?!\w)', 'سڵاوان', text)
    text = re.sub(r'(?<!\w)سلاو(?!\w)', 'سڵاو', text)
    text = re.sub(r'\b[sS]ilav\b', 'سڵاو', text)
    text = re.sub(r'\b[sS]lav\b', 'سڵاو', text)
    text = re.sub(r'\b[sS]law\b', 'سڵاو', text)

    # Convert unnatural literal possessives (فارسی/عەرەبی دەقاودەق) to authentic Sorani Kurdish
    text = re.sub(r'(?<!\w)برای\s+من(?!\w)', 'برام', text)
    text = re.sub(r'(?<!\w)براکەی\s+من(?!\w)', 'براکەم', text)
    text = re.sub(r'(?<!\w)خوشکی\s+من(?!\w)', 'خوشکم', text)
    text = re.sub(r'(?<!\w)خوشکەکەی\s+من(?!\w)', 'خوشکەکەم', text)
    text = re.sub(r'(?<!\w)هاو[ڕر]ێی\s+من(?!\w)', 'هاوڕێکەم', text)
    text = re.sub(r'(?<!\w)هاو[ڕر]ێکەی\s+من(?!\w)', 'هاوڕێکەم', text)
    text = re.sub(r'(?<!\w)دایکی\s+من(?!\w)', 'دایکم', text)
    text = re.sub(r'(?<!\w)باوکی\s+من(?!\w)', 'باوکم', text)
    text = re.sub(r'(?<!\w)ماڵی\s+من(?!\w)', 'ماڵم', text)
    text = re.sub(r'(?<!\w)ماڵەکەی\s+من(?!\w)', 'ماڵەکەم', text)
    text = re.sub(r'(?<!\w)ناوی\s+من(?!\w)', 'ناوم', text)
    text = re.sub(r'(?<!\w)کاری\s+من(?!\w)', 'کارم', text)
    text = re.sub(r'(?<!\w)کتێبی\s+من(?!\w)', 'کتێبەکەم', text)
    text = re.sub(r'(?<!\w)تۆ\s+چۆنیت(?!\w)', 'چۆنیت', text)
    try:
        text = normalize_kurdish_numbers(text)
    except Exception:
        pass
    return text

def normalize_kurdish_for_neural(text, dialect="sorani"):
    """
    Normalizes Kurdish text for the neural speech engine so every phoneme
    and dialect is articulated with true human naturalness and native vocabulary.
    """
    if not text:
        return ""
    s = text.strip()

    # Normalize Kurdish ligatures & punctuation
    s = s.replace("،", " , ").replace("؟", " ? ").replace("؛", " ; ")
    s = s.replace("«", '"').replace("»", '"').replace("ـ", "")

    # For Badini dialect, adapt typical Badini vocabulary and pronunciation
    if dialect == "badini":
        badini_map = [
            (r'\bچۆنی\b', 'چەوانی'),
            (r'\bچۆنن\b', 'چەوانن'),
            (r'\bبەخێربێیت\b', 'ب خێر هاتی'),
            (r'\bبەخێربێن\b', 'ب خێر هاتن'),
            (r'\bتکایە\b', 'هیڤیدارم'),
            (r'\bئەمڕۆ\b', 'ئەڤرۆ'),
            (r'\bئێستا\b', 'نوکە'),
            (r'\bبەیانی باش\b', 'سپێدە باش'),
            (r'\bشەو باش\b', 'شەڤ باش'),
            (r'\bڕۆژ باش\b', 'ڕۆژ باش'),
            (r'\bزۆر\b', 'گەلەک'),
            (r'\bسوپاس\b', 'دەستخۆش'),
            (r'\bهەموو\b', 'هەمی'),
            (r'\bباشی\b', 'ساخی'),
            (r'\bباشیت\b', 'باشی'),
            (r'\bخۆشەویست\b', 'خۆشتڤی'),
            (r'\bدەچم\b', 'دچم'),
            (r'\bدێم\b', 'دهێم'),
            (r'\bخواردن\b', 'خوارن'),
            (r'\bخەوتن\b', 'نڤستن'),
            (r'\bدەزانم\b', 'دزانم'),
            (r'\bنازانم\b', 'نزانم'),
            (r'\bدەستپێک\b', 'دەسپێک'),
        ]
        for pat, rep in badini_map:
            s = re.sub(pat, rep, s)

    elif dialect == "kurmanji":
        kurmanji_map = [
            (r'\bچۆنی\b', 'چاوانی'),
            (r'\bچۆنن\b', 'چەوانن'),
            (r'\bبەخێربێیت\b', 'ب خێر هاتی'),
            (r'\bبەخێربێن\b', 'ب خێر هاتن'),
            (r'\bتکایە\b', 'تکایە'),
            (r'\bئەمڕۆ\b', 'ئیرۆ'),
            (r'\bئێستا\b', 'نەها'),
            (r'\bبەیانی باش\b', 'سپێدە باش'),
            (r'\bشەو باش\b', 'شەڤ باش'),
            (r'\bزۆر\b', 'گەلەک'),
            (r'\bسوپاس\b', 'سپاس'),
            (r'\bهەموو\b', 'هەمی'),
            (r'\bدەچم\b', 'دچم'),
            (r'\bخواردن\b', 'خوارن'),
            (r'\bدەستپێک\b', 'دەسپێک'),
        ]
        for pat, rep in kurmanji_map:
            s = re.sub(pat, rep, s)

    # 1. Normalization of irregular Kurdish words with silent "w" (واوی نەبزوێن لە وشە شازەکان):
    shaz_map = [
        (r'\bدەخوێن(\w*)\b', r'دەخێن\1'),
        (r'\bدەخوێندر(\w*)\b', r'دەخێندر\1'),
        (r'\bبخوێن(\w*)\b', r'بخێن\1'),
        (r'\bخوێند(\w*)\b', r'خێند\1'),
        (r'\bخوێنەر(\w*)\b', r'خێنەر\1'),
        (r'\bخوێن(مژ|اوی|ەکەم|ەکە)\b', r'خێن\1'),
        (r'\bخوێ(دان|ەکە|ەم)\b', r'خێ\1'),
        (r'\bخوشک(\w*)\b', r'خیشک\1'),
    ]
    for pat, rep in shaz_map:
        s = re.sub(pat, rep, s)

    return s

async def synthesize_speech(text, voice, rate="+0%", pitch="+0Hz"):
    cache_key = hashlib.md5(f"{text}|{voice}|{rate}|{pitch}".encode('utf-8')).hexdigest()
    cache_file = os.path.join(CACHE_DIR, f"{cache_key}.mp3")

    if os.path.exists(cache_file) and os.path.getsize(cache_file) > 500:
        with open(cache_file, "rb") as f:
            return f.read()

    comm = edge_tts.Communicate(text, voice, rate=rate, pitch=pitch)
    audio_data = b""
    async for chunk in comm.stream():
        if chunk["type"] == "audio":
            audio_data += chunk["data"]

    if audio_data:
        try:
            with open(cache_file, "wb") as f:
                f.write(audio_data)
        except Exception:
            pass

    return audio_data

def synthesize_elevenlabs(text, voice_id="pNInz6obpgDQGcFmaJgB", api_key="", model_id="eleven_multilingual_v2"):
    """
    Synthesizes speech using ElevenLabs Multilingual v2 for ultra-realistic human voices.
    """
    if not api_key:
        api_key = os.environ.get("ELEVENLABS_API_KEY", "")
    if not api_key:
        raise ValueError("Missing ElevenLabs API Key")

    cache_key = hashlib.md5(f"eleven|{text}|{voice_id}|{model_id}".encode('utf-8')).hexdigest()
    cache_file = os.path.join(CACHE_DIR, f"{cache_key}.mp3")

    if os.path.exists(cache_file) and os.path.getsize(cache_file) > 500:
        with open(cache_file, "rb") as f:
            return f.read()

    url = f"https://api.elevenlabs.io/v1/text-to-speech/{voice_id}?output_format=mp3_44100_128"
    headers = {
        "xi-api-key": api_key,
        "Content-Type": "application/json",
        "Accept": "audio/mpeg",
        "User-Agent": "LalaTranslate/2.0"
    }
    payload = json.dumps({
        "text": text,
        "model_id": model_id,
        "voice_settings": {
            "stability": 0.45,
            "similarity_boost": 0.85,
            "style": 0.35,
            "use_speaker_boost": True
        }
    }).encode("utf-8")

    req = urllib.request.Request(url, data=payload, headers=headers, method="POST")
    with urllib.request.urlopen(req, timeout=30) as resp:
        audio_data = resp.read()

    if audio_data:
        try:
            with open(cache_file, "wb") as f:
                f.write(audio_data)
        except Exception:
            pass

    return audio_data


import struct
from kurdish_phonetics import vocalize_kurdish_sorani, normalize_kurdish_numbers, number_to_kurdish_words

def pcm_to_wav(pcm_data, sample_rate=24000, num_channels=1, bits_per_sample=16):
    """Wraps raw L16 PCM audio into standard RIFF WAV container for HTML5 universal playback."""
    if pcm_data.startswith(b'RIFF'):
        return pcm_data
    byte_rate = sample_rate * num_channels * bits_per_sample // 8
    block_align = num_channels * bits_per_sample // 8
    data_size = len(pcm_data)
    total_size = 36 + data_size
    header = struct.pack(
        '<4sI4s4sIHHIIHH4sI',
        b'RIFF', total_size, b'WAVE', b'fmt ',
        16, 1, num_channels, sample_rate, byte_rate, block_align, bits_per_sample,
        b'data', data_size
    )
    return header + pcm_data

def clean_kurdish_studio_audio(wav_bytes):
    """
    Velvet Silk Studio Master DSP Pipeline for Kurdish Voice:
    1. DC offset removal.
    2. Sub-bass 45Hz high-pass filter (cuts room rumble, keeps rich vocal chest resonance).
    3. Velvet Silk De-harshing Filter (Butterworth order 2 low-pass at 5900Hz for 16kHz, 7800Hz for 24kHz)
       -> Completely eliminates raspiness, grit, and roughness ('زبری' و 'خشەخش').
    4. Chest warmth enhancement (+1.8 dB peak at 220Hz) -> Creates deep, smooth, velvety human warmth ('ساف و نەرم').
    5. Micro noise gate on pauses -> Zero background noise/hiss.
    6. Polyphase Kaiser-windowed upsampling to 24,000 Hz -> Eliminates mobile DAC staircasing.
    7. Headroom normalization to 28500 (-1.2 dBFS) -> Studio-pure dynamic range.
    """
    if not wav_bytes or len(wav_bytes) < 200:
        return wav_bytes
    try:
        with wave.open(io.BytesIO(wav_bytes), 'rb') as w:
            sr = w.getframerate()
            nframes = w.getnframes()
            pcm = w.readframes(nframes)
            samples = np.frombuffer(pcm, dtype=np.int16).astype(np.float32)

        if len(samples) < 100:
            return wav_bytes

        # 1. DC offset removal
        samples = samples - np.mean(samples)

        # 2. Gentle 65Hz High-pass: cuts sub-rumble and microphone thump
        sos_hp = signal.butter(2, 65, 'hp', fs=sr, output='sos')
        samples = signal.sosfilt(sos_hp, samples)

        # 3. Velvet Silk Filter: cuts roughness, raspiness, and high-pitch vocoder hiss ('زبری و ژاوەژاو')
        cutoff = 5800.0 if sr <= 16000 else 7200.0
        cutoff = min(cutoff, (sr / 2.0) - 200.0)
        sos_silk = signal.butter(2, cutoff, 'low', fs=sr, output='sos')
        samples = signal.sosfilt(sos_silk, samples)

        # 4. De-harshing notch filter at 3800Hz (-2.5 dB) to kill metallic vocoder raspiness
        try:
            b_dip, a_dip = signal.iirpeak(3800.0, 1.2, fs=sr)
            samples = samples - 0.25 * signal.lfilter(b_dip, a_dip, samples)
        except Exception:
            pass

        # 5. Velvet chest warmth enhancement (+2.2 dB at 240Hz) -> Creates deep, smooth, velvety human warmth ('ساف و نەرم')
        try:
            b_warm, a_warm = signal.iirpeak(240.0, 1.0, fs=sr)
            warm_boost = signal.lfilter(b_warm, a_warm, samples)
            samples = samples + 0.22 * warm_boost
        except Exception:
            pass

        # 6. Soft noise gate on pauses
        block_size = int(sr * 0.02)
        for b in range(0, len(samples), block_size):
            chunk = samples[b:b+block_size]
            rms = np.sqrt(np.mean(chunk**2)) if len(chunk) > 0 else 0
            if rms < 35.0:
                samples[b:b+block_size] = 0.0

        # 7. Polyphase upsample to 24000Hz if 16kHz
        target_sr = 24000
        if sr == 16000:
            samples_out = signal.resample_poly(samples, 3, 2).astype(np.float32)
        elif sr != 24000 and sr < 24000:
            samples_out = signal.resample_poly(samples, target_sr, sr).astype(np.float32)
        else:
            samples_out = samples
            target_sr = sr

        # 8. Headroom normalization to 24500 (-2.5 dBFS) -> Studio-pure dynamic range, zero clipping on mobile speakers
        max_peak = np.max(np.abs(samples_out))
        if max_peak > 0:
            samples_out = samples_out * (24500.0 / max_peak)

        cleaned_pcm = np.clip(samples_out, -32768, 32767).astype(np.int16).tobytes()

        out_io = io.BytesIO()
        with wave.open(out_io, 'wb') as ow:
            ow.setnchannels(1)
            ow.setsampwidth(2)
            ow.setframerate(target_sr)
            ow.writeframes(cleaned_pcm)
        return out_io.getvalue()
    except Exception as e:
        print(f"[Velvet Silk Audio DSP Error]: {e}", file=sys.stderr)
        return wav_bytes

def synthesize_kurdish_f5_studio(text, dialect="sorani", gender="male", timeout=20):
    """
    Ultra-Modern Next-Gen Kurdish Neural Studio Voice (F5-TTS Diffusion Engine).
    Produces 24kHz broadcast studio quality: 100% human, rich vocal warmth,
    zero metallic artifacts, zero robotic vocoder buzz ('ژاوەژاو'), and zero background static ('خشەخش').
    """
    text = (text or '').strip()
    if not text:
        return None, None

    cache_key = hashlib.md5(f"f5_studio_master_v4|{text}|{dialect}|{gender}".encode('utf-8')).hexdigest()
    cache_path = os.path.join(CACHE_DIR, f"{cache_key}.wav")
    if os.path.exists(cache_path) and os.path.getsize(cache_path) > 3000:
        try:
            with open(cache_path, "rb") as f:
                return f.read(), "audio/wav"
        except Exception:
            pass

    clean_text = normalize_kurdish_numbers(text)
    clean_text = clean_text.replace('سلاڤ', 'سڵاو')
    for zw in ['\u200c', '\u200d', '\u200b']:
        clean_text = clean_text.replace(zw, '')

    if gender == "female":
        ref_url = "https://huggingface.co/aranemini/central-kurdish-tts/resolve/main/prompt-audiobook-female.wav"
        ref_text = "یەکیان بێهرووزی تۆپچی بوو کە وەک پەیکی نامەبەر لە نێوان ئۆردوگا و بنکەکان هاتووچۆی دەکرد."
    else:
        # High quality calm audiobook prompt for smooth, velvety Kurdish delivery
        ref_url = "https://huggingface.co/aranemini/central-kurdish-tts/resolve/main/prompt-audiobook-male.wav"
        ref_text = "شیعری عەقڵانی لە پیاوێک یان لە ژنێک دەچێت ئەو وەختەی دڵداری بکات بە زمانی فەرهەنگ بدوێ."

    # Never send the private Hugging Face token to someone else's Space
    hf_headers = {"User-Agent": "Translet/3.0"}

    try:
        call_url = "https://mrfakename-e2-f5-tts.hf.space/gradio_api/call/predict"
        payload = json.dumps({
            "data": [
                {"path": ref_url, "meta": {"_type": "gradio.FileData"}},
                ref_text,
                clean_text,
                True
            ]
        }).encode('utf-8')

        req = urllib.request.Request(call_url, data=payload, headers={"Content-Type": "application/json", **hf_headers})
        with urllib.request.urlopen(req, timeout=timeout) as r:
            event_id = json.loads(r.read().decode('utf-8')).get('event_id')

        if not event_id:
            return None, None

        stream_url = f"https://mrfakename-e2-f5-tts.hf.space/gradio_api/call/predict/{event_id}"
        with urllib.request.urlopen(urllib.request.Request(stream_url, headers=hf_headers), timeout=timeout) as s:
            raw = s.read().decode('utf-8')
            for line in raw.split('\n'):
                if line.startswith('data:'):
                    parsed_json = json.loads(line[5:].strip())
                    if isinstance(parsed_json, dict) and 'error' in parsed_json:
                        # Rate limit or GPU error, gracefully fall back immediately
                        return None, None
                    if isinstance(parsed_json, list) and len(parsed_json) > 0 and 'url' in parsed_json[0]:
                        file_url = parsed_json[0]['url']
                        with urllib.request.urlopen(urllib.request.Request(file_url, headers=hf_headers), timeout=timeout) as rf:
                            audio_data = rf.read()
                            if audio_data and len(audio_data) > 1000:
                                cleaned = clean_kurdish_studio_audio(audio_data)
                                try:
                                    with open(cache_path, "wb") as cf:
                                        cf.write(cleaned)
                                except Exception:
                                    pass
                                return cleaned, "audio/wav"
    except Exception as e:
        print(f"[F5 Studio Kurdish TTS Notice]: {e}", file=sys.stderr)
        return None, None
    return None, None

def synthesize_kurdish_silk_studio(text, dialect="sorani", timeout=12):
    """
    Ultra-Fast Velvet Silk Studio Kurdish Voice (Zero Hiss, Zero Buzz, Ultra-Smooth).
    Uses persistent HTTP connection pool for instant < 2s synthesis.
    """
    text = (text or '').strip()
    if not text:
        return None, None

    # Verbalize all numbers, dates, times, ordinals into pure Kurdish words
    text = normalize_kurdish_numbers(text)
    if not text:
        return None, None

    cache_key = hashlib.md5(f"ckb_silk_fast_v6|{text}|{dialect}".encode('utf-8')).hexdigest()
    cache_path = os.path.join(CACHE_DIR, f"{cache_key}.wav")
    if os.path.exists(cache_path) and os.path.getsize(cache_path) > 1000:
        try:
            with open(cache_path, "rb") as f:
                return f.read(), "audio/wav"
        except Exception:
            pass

    clean_text = text.replace('\u06A9', '\u0643').replace('سلاڤ', 'سڵاو')
    for zw in ['\u200c', '\u200d', '\u200b']:
        clean_text = clean_text.replace(zw, '')
    # Neural VITS acoustic fix: 'سفر' without vowels collapses duration to 'سێ' (3).
    # 'زیرۆ' provides exact vowel structure for the 0 phoneme in audio.
    clean_text = re.sub(r'\bسفر\b', 'زیرۆ', clean_text)
    clean_text = re.sub(r'\bسفرە\b', 'زیرۆیە', clean_text)

    dialect_label = "بادینی / Badini" if dialect == "badini" else "سۆرانی / Sorani"

    try:
        call_url = "https://akam-ot-kurdish-tts.hf.space/gradio_api/call/synthesize"
        r1 = FAST_HTTP_SESSION.post(call_url, json={"data": [clean_text, dialect_label]}, timeout=8)
        event_id = r1.json().get('event_id')
        if not event_id:
            return None, None

        stream_url = f"https://akam-ot-kurdish-tts.hf.space/gradio_api/call/synthesize/{event_id}"
        r2 = FAST_HTTP_SESSION.get(stream_url, timeout=timeout)
        for line in r2.text.split('\n'):
            if line.startswith('data:'):
                data = json.loads(line[5:].strip())
                file_url = data[0]['url']
                audio_data = FAST_HTTP_SESSION.get(file_url, timeout=8).content
                if audio_data and len(audio_data) > 1000:
                    cleaned_data = clean_kurdish_studio_audio(audio_data)
                    try:
                        with open(cache_path, "wb") as cf:
                            cf.write(cleaned_data)
                    except Exception:
                        pass
                    return cleaned_data, "audio/wav"
    except Exception as e:
        print(f"[Fast Silk Kurdish TTS Error]: {e}", file=sys.stderr)
        return None, None
    return None, None

def synthesize_native_kurdish(text, dialect="sorani", gender="male", timeout=12):
    """
    Ultra-Fast 100% native Kurdish (Sorani/Badini) speech.
    Uses persistent HTTP connection pool and Velvet Silk DSP for instant, studio-smooth speech.
    """
    return synthesize_kurdish_silk_studio(text, dialect=dialect, timeout=timeout)

# Gemini 3.8 / 2.5 Flash Native Speech & Multilingual Neural Voice Engine
GEMINI_PREBUILT_VOICES = {
    'natural': 'Puck',       # Warm, human, friendly masculine tone
    'female': 'Kore',        # Melodic, expressive, gentle female tone
    'broadcast': 'Charon',   # Deep, resonant, studio broadcaster tone
    'authoritative': 'Fenrir',# Formal, commanding masculine tone
    'expressive': 'Aoede',   # Engaging, dynamic feminine tone
}

def kurdish_to_tts_phonetic(text, dialect='sorani'):
    s = vocalize_kurdish_sorani(text)
    replacements = [
        ('ł', 'l'),
        ('ç', 'ch'),
        ('c', 'j'),
        ('ş', 'sh'),
        ('ژ', 'zh'),
        ('x', 'kh'),
        ('ẍ', 'gh'),
        ('î', 'ee'),
        ('ê', 'ay'),
        ('û', 'oo'),
        ('ۆ', 'o'),
        ('،', ','),
        ('؟', '?'),
        ('؛', ';')
    ]
    for a, b in replacements:
        s = s.replace(a, b)
    return s.strip()

def synthesize_gemini_tts(text, voice_name="", api_key="", lang="ku", mode="natural", dialect="sorani"):
    """
    Synthesizes ultra-realistic human speech using Google Gemini Native Neural TTS models.
    Supports Kurdish (Sorani, Badini, Kurmanji) and multilingual audio with 24kHz CD quality.
    """
    api_key = get_gemini_key(api_key)
    if not api_key:
        raise ValueError("Missing Gemini API Key for TTS")

    if not voice_name:
        voice_name = GEMINI_PREBUILT_VOICES.get(mode, 'Puck')

    # Hash for disk caching
    cache_key = hashlib.md5(f"gemini_tts|{text}|{voice_name}|{mode}|{dialect}|{lang}".encode('utf-8')).hexdigest()
    cache_file = os.path.join(CACHE_DIR, f"{cache_key}.wav")

    # Return cached audio if available
    if os.path.exists(cache_file) and os.path.getsize(cache_file) > 1000:
        with open(cache_file, "rb") as f:
            cached_bytes = f.read()
            return pcm_to_wav(cached_bytes), "audio/wav"

    # Native Kurdish Neural Vocalizer: keep authentic Kurdish Sorani script
    prompt = text.strip()
    if lang in ('ku', 'ckb'):
        who = ('a native Badini Kurdish speaker from Duhok' if dialect == 'badini'
               else 'a native Central Kurdish (Sorani) speaker from Sulaymaniyah')
        prompt = f"Read this aloud warmly and naturally, as {who}:\n{prompt}"

    models_to_try = [
        'gemini-2.5-flash-preview-tts',
        'gemini-2.5-flash-tts',
    ]
    last_error = None

    import base64
    for model in models_to_try:
        url = f"https://generativelanguage.googleapis.com/v1beta/models/{model}:generateContent?key={api_key}"
        payload = json.dumps({
            "contents": [{"parts": [{"text": prompt}]}],
            "generationConfig": {
                "responseModalities": ["AUDIO"],
                "speechConfig": {
                    "voiceConfig": {
                        "prebuiltVoiceConfig": {
                            "voiceName": voice_name
                        }
                    }
                }
            }
        }).encode("utf-8")

        headers = {
            "Content-Type": "application/json",
            "User-Agent": "Translet-AI-Voice/2.0"
        }

        try:
            req = urllib.request.Request(url, data=payload, headers=headers, method="POST")
            with urllib.request.urlopen(req, timeout=20) as resp:
                resp_data = json.loads(resp.read().decode('utf-8'))
                part = resp_data['candidates'][0]['content']['parts'][0]
                if 'inlineData' in part and 'data' in part['inlineData']:
                    audio_b64 = part['inlineData']['data']
                    mime_type = part['inlineData'].get('mimeType', 'audio/wav')
                    audio_bytes = base64.b64decode(audio_b64)
                    # Ensure standard RIFF WAV format for 100% universal browser compatibility
                    audio_bytes = pcm_to_wav(audio_bytes, sample_rate=24000)
                    if len(audio_bytes) > 500:
                        try:
                            with open(cache_file, "wb") as cf:
                                cf.write(audio_bytes)
                        except Exception:
                            pass
                        return audio_bytes, "audio/wav"
        except Exception as e:
            last_error = e
            if "429" in str(e):
                break
            continue

    if last_error:
        raise last_error
    raise ValueError("Failed to synthesize speech with Gemini TTS")


def extract_gemini_text(resp_data):
    """Joins every text part of a Gemini response (long answers are split across several parts)."""
    parts = resp_data['candidates'][0]['content']['parts']
    return ''.join(p.get('text', '') for p in parts if not p.get('thought')).strip()


def parse_json_reply(raw_text):
    """Strips ```json fences and parses the JSON object in a model reply. Returns None if it is not valid JSON."""
    cleaned = raw_text.strip()
    if cleaned.startswith('```json'):
        cleaned = cleaned[7:]
    elif cleaned.startswith('```'):
        cleaned = cleaned[3:]
    if cleaned.endswith('```'):
        cleaned = cleaned[:-3]
    cleaned = cleaned.strip()
    try:
        return json.loads(cleaned)
    except Exception:
        pass
    m = re.search(r'\{.*\}', cleaned, re.DOTALL)
    if m:
        try:
            return json.loads(m.group(0))
        except Exception:
            pass
    return None


BLOCKED_STATIC_EXTS = {'.py', '.pyc', '.pid', '.log', '.bat', '.vbs', '.exe', '.txt', '.md'}

def is_safe_static_path(base_dir, local_path):
    """Only serve files inside the project folder, never source code, logs, tokens or hidden files."""
    if not local_path.startswith(base_dir + os.sep):
        return False
    rel = os.path.relpath(local_path, base_dir)
    if any(seg.startswith('.') or seg == '__pycache__' for seg in rel.split(os.sep)):
        return False
    return os.path.splitext(local_path)[1].lower() not in BLOCKED_STATIC_EXTS


def parse_range_header(range_header, total_size):
    """Parses 'bytes=start-end', 'bytes=start-' and suffix 'bytes=-N'. Returns (start, end) or None."""
    if not range_header or not range_header.startswith('bytes=') or total_size <= 0:
        return None
    spec = range_header[6:].split(',')[0].strip()
    start_s, _, end_s = spec.partition('-')
    if not start_s:
        if not end_s:
            return None
        start = max(0, total_size - int(end_s))
        end = total_size - 1
    else:
        start = int(start_s)
        end = int(end_s) if end_s else total_size - 1
    end = min(end, total_size - 1)
    if start > end or start >= total_size:
        return None
    return start, end


def handle_translation_request(text, source_lang='auto', target_lang='ku', tone='natural', api_key='', model=''):
    if not text or not text.strip():
        return {"translation": "", "explanation": "", "detectedLanguage": source_lang}

    text = text.strip()
    api_key = get_gemini_key(api_key)
    if not model:
        model = "gemini-3.5-flash-lite"

    lang_names = {
        'auto': 'Auto detect',
        'ku': 'Kurdish (Sorani)',
        'en': 'English',
        'ar': 'Arabic',
        'tr': 'Turkish',
        'fa': 'Persian',
        'de': 'German',
        'fr': 'French',
        'es': 'Spanish'
    }
    src_name = lang_names.get(source_lang, source_lang)
    tgt_name = lang_names.get(target_lang, target_lang)

    # 1. Try Gemini AI translation first
    if api_key:
        prompt = (
            f"You are a world-class linguistic translator and expert in Kurdish Sorani (both in Sorani Arabic script and Kurdish Latin script), English, Arabic, and other languages.\n"
            f"Translate the text faithfully, accurately, and naturally.\n\n"
            f"Source Language: {src_name}\n"
            f"Target Language: {tgt_name}\n"
            f"Style/Tone: {tone} (e.g. natural, formal, casual, literary)\n\n"
            f"FEW-SHOT EXAMPLES (English -> Sorani Kurdish):\n"
            f"- 'Hello my brother, how are you? I hope you have a pleasant day out' -> 'سڵاو برام، چۆنی؟ هیوادارم ڕۆژێکی خۆش لە دەرەوە بەسەر بەریت.'\n"
            f"- 'I am waiting outside for my friend' -> 'لە دەرەوە چاوەڕێی هاوڕێکەم دەکەم.'\n"
            f"- 'What are you doing tonight with your family?' -> 'ئەمشەو لەگەڵ خێزانەکەت چی دەکەیت؟'\n"
            f"- 'Nice to meet you, my name is Alex' -> 'خۆشحاڵم بە ناسینت، ناوم ئەلێکسە.'\n\n"
            f"FEW-SHOT EXAMPLES (Kurdish -> English):\n"
            f"- 'سڵاو برام چۆنی؟ هیوادارم ڕۆژێکی خۆش لە دەرەوە بەڕێ بکەیت.' -> 'Hello my brother, how are you? I hope you have a pleasant day out.'\n"
            f"- 'ئەمڕۆ کاتت هەیە پێکەوە بچینە دەرەوە؟' -> 'Do you have time today for us to go out together?'\n\n"
            f"Important Kurdish Sorani Rules:\n"
            f"1. ZERO LOSS OF INFORMATION: Translate every detail, adverb, and preposition (e.g. 'out' / 'day out' -> 'لە دەرەوە', 'together' -> 'پێکەوە'). Never drop words.\n"
            f"2. AUTHENTIC POSSESSIVES: Use native Kurdish suffixes (e.g. 'my brother' -> 'برام' or 'براکەم', NEVER 'برای من'; 'my friend' -> 'هاوڕێکەم', NEVER 'هاوڕێی من'; 'my mother' -> 'دایکم', NEVER 'دایکی من').\n"
            f"3. GREETINGS: Always greet with 'سڵاو' (NEVER 'سلاڤ' or 'سڵاڤ').\n"
            f"4. Use authentic Sorani Kurdish vocabulary and natural sentence structure (Subject-Object-Verb).\n"
            f"5. Avoid literal word-by-word machine translation. Capture the exact intended human meaning.\n"
            f"6. If the input is in Kurdish Latin (e.g. 'slaw choni'), understand and translate it perfectly.\n"
            f"7. NUMBERS, DATES & YEARS: Express numbers, years, dates, times, days, and months naturally and clearly in Kurdish words where appropriate (e.g. 'سەد و پەنجا', 'پازدەی ئایاری دوو هەزار و بیست و چوار', 'دە و نیو') for seamless, high-fidelity spoken pronunciation.\n"
            f"8. TELEPHONE NUMBERS IN KURDISH: In Kurdish, phone numbers are NEVER translated digit-by-digit (NEVER 'سفر حەوت حەوت سفر چوار...'). Always group into authentic Kurdish cadence: 4-digit prefix (سفر حەوتسەد و حەفتا / سفر حەوتسەد و پەنجا / سفر حەوتسەد و هەشتا), 3-digit middle (e.g. 401 -> چوارسەد و یەک), 2-digit (e.g. 68 -> شەست و هەشت), 2-digit (e.g. 10 -> دە / دەیە). Example: 'My phone number is 07704016810' -> 'ژمارەی تەلەفۆنەکەم سفر حەوتسەد و حەفتا، چوارسەد و یەک، شەست و هەشت، دەیە.'\n\n"
            f"Return ONLY a valid JSON object without markdown formatting blocks:\n"
            f'{{\n  "translation": "Translated text here",\n  "explanation": "Brief Kurdish notes or alternative phrasing",\n  "detectedLanguage": "..."\n}}\n\n'
            f'Text to translate:\n"""{text}"""'
        )

        models_to_try = [
            'gemini-3.5-flash-lite',
            'gemini-flash-lite-latest',
            'gemini-3.1-flash-lite',
            'gemini-3-flash-preview'
        ]
        for m in models_to_try:
            try:
                url = f"https://generativelanguage.googleapis.com/v1beta/models/{m}:generateContent?key={api_key}"
                payload = {
                    "contents": [{"parts": [{"text": prompt}]}],
                    "generationConfig": {
                        "temperature": 0.7 if tone == 'literary' else 0.1,
                        "topP": 0.9
                    }
                }

                resp = FAST_HTTP_SESSION.post(url, json=payload, timeout=8)
                if resp.status_code == 200:
                    resp_data = resp.json()
                    raw_text = extract_gemini_text(resp_data)
                    parsed = parse_json_reply(raw_text)

                    try:
                        if isinstance(parsed, dict) and parsed.get('translation'):
                            tr = parsed['translation']
                            if target_lang == 'ku':
                                tr = sanitize_kurdish_sorani(tr)
                            return {
                                "translation": tr,
                                "explanation": parsed.get('explanation', ''),
                                "detectedLanguage": parsed.get('detectedLanguage', source_lang),
                                "engine": "gemini"
                            }
                    except Exception:
                        pass
                    if not raw_text or raw_text.lstrip('`').lstrip().startswith(('{', 'json')):
                        # Broken/partial JSON: never show it to the user, try the next model
                        continue
                    tr = raw_text
                    if target_lang == 'ku':
                        tr = sanitize_kurdish_sorani(tr)
                    return {
                        "translation": tr,
                        "explanation": "",
                        "detectedLanguage": source_lang,
                        "engine": "gemini"
                    }
            except Exception as e:
                continue

    # 2. Guaranteed Fast Fallback: Google Translate GTX endpoint
    try:
        gtx_lang_map = {'ku': 'ckb', 'auto': 'auto'}
        sl = gtx_lang_map.get(source_lang, source_lang)
        tl = gtx_lang_map.get(target_lang, target_lang)

        url = f"https://translate.googleapis.com/translate_a/single?client=gtx&sl={sl}&tl={tl}&dt=t&q={urllib.parse.quote(text)}"
        req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0'})
        with urllib.request.urlopen(req, timeout=6) as r:
            data = json.loads(r.read().decode('utf-8'))
            translated = ''.join([part[0] for part in data[0] if part[0]])
            if target_lang == 'ku':
                translated = sanitize_kurdish_sorani(translated)
            detected = data[2] if len(data) > 2 and data[2] else source_lang
            return {
                "translation": translated,
                "explanation": "وەرگێڕدراوە لە ڕێگەی بزوێنەری خێرای Translet.",
                "detectedLanguage": detected,
                "engine": "gtx"
            }
    except Exception as gtx_err:
        return {
            "translation": text,
            "explanation": f"هەڵە لە وەرگێڕان: {str(gtx_err)}",
            "detectedLanguage": source_lang,
            "engine": "error"
        }


VC_LANG_PROMPTS = {
    'ku': 'authentic Sorani Kurdish (سۆرانی)',
    'en': 'natural, fluent English',
    'ar': 'natural, clear Arabic (العربية)',
    'de': 'natural, fluent German (Deutsch)',
    'tr': 'natural, fluent Turkish (Türkçe)',
    'fa': 'natural, fluent Persian (فارسی)',
    'fr': 'natural, fluent French (Français)',
    'es': 'natural, fluent Spanish (Español)'
}

def transcribe_and_translate_voice(audio_bytes, spoken_lang="auto", api_key="", mime_type="", speaker1_lang="ku", speaker2_lang="en"):
    """
    Real-Time Voice vs Voice (VC) Interpreter:
    Accurately listens to audio in any selected pair of languages, transcribes,
    and returns bidirectional translation in natural speech format.
    """
    api_key = get_gemini_key(api_key)
    if not api_key:
        return {"error": "Missing Gemini API Key", "detail": "Put your key in the .gemini_key file"}

    b64 = base64.b64encode(audio_bytes).decode('utf-8')
    mime = mime_type or ("audio/webm" if (audio_bytes.startswith(b'\x1aE\xdf\xa3') or len(audio_bytes) > 4 and audio_bytes[:4] == b'\x1a\x45\xdf\xa3') else "audio/wav")
    if ';' in mime:
        mime = mime.split(';')[0].strip()

    l1_name = VC_LANG_PROMPTS.get(speaker1_lang, speaker1_lang)
    l2_name = VC_LANG_PROMPTS.get(speaker2_lang, speaker2_lang)

    kurdish_rules = (
        "\nCRITICAL KURDISH RULES:\n"
        "- Use authentic Sorani e.g. برام, هاوڕێکەم, سڵاو; never literal calques like برای من, هاوڕێی من.\n"
        "- NUMBERS AND DATES: For Kurdish speech fluency, write numbers, dates, times, days, and months clearly in natural Kurdish words (e.g. پازدەی ئایاری دوو هەزار و بیست و چوار, سەد و پەنجا, کاتژمێر دە و نیو) so the Kurdish voice speaks them fluently.\n"
        "- TELEPHONE NUMBERS: In Kurdish, phone numbers are NEVER spoken digit-by-digit. Group into authentic Kurdish cadence: prefix (سفر حەوتسەد و حەفتا / سفر حەوتسەد و پەنجا), middle 3 digits (چوارسەد و یەک), 2 digits (شەست و هەشت), 2 digits (دە / دەیە). e.g. '07704016810' -> 'سفر حەوتسەد و حەفتا، چوارسەد و یەک، شەست و هەشت، دەیە'.\n"
    )

    if spoken_lang == speaker1_lang:
        is_target_ku = (speaker2_lang == "ku")
        instruction = (
            f"The speaker is speaking {l1_name}.\n"
            f"1. Transcribe the spoken speech accurately in 'sourceText'.\n"
            f"2. Translate into natural, complete {l2_name} in 'translatedText'."
            f"{kurdish_rules if is_target_ku else ''}\n"
            f"If silence or noise: return silence: true."
        )
    elif spoken_lang == speaker2_lang:
        is_target_ku = (speaker1_lang == "ku")
        instruction = (
            f"The speaker is speaking {l2_name}.\n"
            f"1. Transcribe the spoken speech accurately in 'sourceText'.\n"
            f"2. Translate into natural, complete {l1_name} in 'translatedText'."
            f"{kurdish_rules if is_target_ku else ''}\n"
            f"If silence or noise: return silence: true."
        )
    else:
        is_l1_ku = (speaker1_lang == "ku")
        is_l2_ku = (speaker2_lang == "ku")
        instruction = (
            f"Detect whether the speaker spoke {l1_name} or {l2_name}.\n"
            f"1. Transcribe accurately in 'sourceText'.\n"
            f"2. If speaker spoke {l1_name}, set sourceLang='{speaker1_lang}', targetLang='{speaker2_lang}', and translate into {l2_name} in 'translatedText'.{kurdish_rules if is_l2_ku else ''}\n"
            f"3. If speaker spoke {l2_name}, set sourceLang='{speaker2_lang}', targetLang='{speaker1_lang}', and translate into {l1_name} in 'translatedText'.{kurdish_rules if is_l1_ku else ''}\n"
            f"If silence or noise: return silence: true."
        )

    prompt = (
        f"{instruction}\n"
        f"CRITICAL: If audio is silence, background noise, or unintelligible, return: {{\"sourceText\": \"\", \"translatedText\": \"\", \"silence\": true}}\n"
        f"Return ONLY valid JSON with keys: sourceText, translatedText, sourceLang, targetLang, silence"
    )

    # Each model has its own free daily limit: when one is used up (429), the next one answers
    models_to_try = [
        'gemini-3.1-flash-lite',
        'gemini-3.1-flash-lite-preview',
        'gemini-3.5-flash-lite',
        'gemini-flash-lite-latest',
        'gemini-3-flash-preview',
        'gemini-flash-latest',
        'gemini-3.5-flash',
    ]
    last_err = ""
    for m in models_to_try:
        try:
            url = f"https://generativelanguage.googleapis.com/v1beta/models/{m}:generateContent?key={api_key}"
            payload = {
                "contents": [{
                    "parts": [
                        {"text": prompt},
                        {"inline_data": {"mime_type": mime, "data": b64}}
                    ]
                }],
                "generationConfig": {
                    "responseMimeType": "application/json",
                    "temperature": 0.0
                }
            }

            resp = FAST_HTTP_SESSION.post(url, json=payload, timeout=20)
            if resp.status_code == 200:
                resp_data = resp.json()
                parsed = parse_json_reply(extract_gemini_text(resp_data))
                if not isinstance(parsed, dict):
                    raise ValueError("Model did not return a JSON object")
                src_txt = parsed.get("sourceText", "").strip()
                tgt_txt = parsed.get("translatedText", "").strip()

                # Filter out Gemini hallucinations on background silence/noise (e.g. "Looking for a speaker")
                noise_hallucinations = [
                    'looking for a speaker', 'looking for speaker', 'seeking a speaker',
                    'searching for a speaker', 'searching for speaker',
                    'بە دوای بێژەرێکدا دەگەڕێت', 'بەدوای بێژەرێکدا دەگەڕێت', 'بێژەرێک دەگەڕێت',
                    'thank you for watching', 'thanks for watching', 'سوپاس بۆ سەیرکردنتان',
                    'subtitles by', 'ژێرنووس', 'please subscribe', 'subscribe',
                    'you'
                ]
                src_clean = src_txt.lower().rstrip('.!? ')
                tgt_clean = tgt_txt.lower().rstrip('.!? ')

                if (parsed.get("silence") is True or not src_txt or
                    src_clean in noise_hallucinations or tgt_clean in noise_hallucinations or
                    'بێژەر' in tgt_clean and len(src_clean) < 25 and ('speaker' in src_clean or not src_clean)):
                    return {
                        "silence": True,
                        "sourceText": "",
                        "translatedText": "",
                        "sourceLang": spoken_lang,
                        "targetLang": speaker2_lang if spoken_lang == speaker1_lang else speaker1_lang
                    }
                if spoken_lang == speaker1_lang:
                    parsed["sourceLang"] = speaker1_lang
                    parsed["targetLang"] = speaker2_lang
                elif spoken_lang == speaker2_lang:
                    parsed["sourceLang"] = speaker2_lang
                    parsed["targetLang"] = speaker1_lang
                else:
                    src = parsed.get("sourceLang", "")
                    if src in [speaker1_lang, speaker2_lang]:
                        parsed["targetLang"] = speaker2_lang if src == speaker1_lang else speaker1_lang
                    elif any('\u0600' <= c <= '\u06ff' for c in parsed.get("sourceText", "")):
                        parsed["sourceLang"] = "ku" if (speaker1_lang == "ku" or speaker2_lang == "ku") else speaker1_lang
                        parsed["targetLang"] = speaker2_lang if parsed["sourceLang"] == speaker1_lang else speaker1_lang
                    else:
                        parsed["sourceLang"] = speaker1_lang
                        parsed["targetLang"] = speaker2_lang

                # Sanitize Sorani greetings: Ensure 'سلاڤ' -> 'سڵاو'
                if parsed.get("sourceLang") == "ku" and parsed.get("sourceText"):
                    parsed["sourceText"] = sanitize_kurdish_sorani(parsed["sourceText"])
                if parsed.get("targetLang") == "ku" and parsed.get("translatedText"):
                    parsed["translatedText"] = sanitize_kurdish_sorani(parsed["translatedText"])

                return parsed
        except Exception as e:
            last_err = str(e)
            continue
    return {
        "error": "Failed to transcribe audio",
        "detail": last_err
    }

def translate_text_for_conversation(text, spoken_lang="auto", api_key="", speaker1_lang="ku", speaker2_lang="en"):
    """
    Translates text between selected languages for conversation mode.
    """
    text = (text or '').strip()
    if not text:
        return {"error": "Empty text"}

    if spoken_lang == speaker1_lang:
        src = speaker1_lang
        tgt = speaker2_lang
    elif spoken_lang == speaker2_lang:
        src = speaker2_lang
        tgt = speaker1_lang
    else:
        is_kurdish = any('\u0600' <= char <= '\u06ff' for char in text)
        if speaker1_lang == 'ku' and is_kurdish:
            src = speaker1_lang
            tgt = speaker2_lang
        elif speaker2_lang == 'ku' and is_kurdish:
            src = speaker2_lang
            tgt = speaker1_lang
        else:
            src = speaker1_lang
            tgt = speaker2_lang

    res = handle_translation_request(text, src, tgt, tone='natural', api_key=api_key)
    tr = res.get("translation", "")
    if tgt == 'ku':
        tr = sanitize_kurdish_sorani(tr)
    return {
        "sourceText": text,
        "translatedText": tr,
        "sourceLang": src,
        "targetLang": tgt
    }


class NeuralTTSHandler(SimpleHTTPRequestHandler):
    def end_headers(self):
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
        self.send_header('Access-Control-Allow-Headers', 'Content-Type, Range, xi-api-key')
        self.send_header('Access-Control-Expose-Headers', 'Content-Range, Accept-Ranges, Content-Length')
        super().end_headers()

    def send_file_with_range(self, file_path, content_type=None):
        if not os.path.isfile(file_path):
            self.send_error(404, 'File not found')
            return

        file_size = os.path.getsize(file_path)
        if not content_type:
            ext = os.path.splitext(file_path)[1].lower()
            mime_map = {
                '.wav': 'audio/wav',
                '.mp3': 'audio/mpeg',
                '.ogg': 'audio/ogg',
                '.webm': 'audio/webm',
                '.m4a': 'audio/mp4',
                '.js': 'application/javascript',
                '.css': 'text/css',
                '.html': 'text/html',
                '.json': 'application/json',
                '.png': 'image/png',
                '.jpg': 'image/jpeg',
                '.jpeg': 'image/jpeg',
                '.svg': 'image/svg+xml',
                '.ico': 'image/x-icon',
            }
            content_type = mime_map.get(ext, 'application/octet-stream')

        range_header = self.headers.get('Range')
        if range_header and range_header.startswith('bytes='):
            try:
                rng = parse_range_header(range_header, file_size)
                if rng:
                    start, end = rng
                    content_length = end - start + 1
                    self.send_response(206)
                    self.send_header('Content-Type', content_type)
                    self.send_header('Content-Range', f'bytes {start}-{end}/{file_size}')
                    self.send_header('Content-Length', str(content_length))
                    self.send_header('Accept-Ranges', 'bytes')
                    self.end_headers()

                    with open(file_path, 'rb') as f:
                        f.seek(start)
                        self.wfile.write(f.read(content_length))
                    return
            except Exception as e:
                print(f'[Range error file]: {e}', file=sys.stderr)

        self.send_response(200)
        self.send_header('Content-Type', content_type)
        self.send_header('Content-Length', str(file_size))
        self.send_header('Accept-Ranges', 'bytes')
        self.end_headers()
        with open(file_path, 'rb') as f:
            self.wfile.write(f.read())

    def send_audio_bytes(self, audio_bytes, mime_type, extra_headers=None):
        total_size = len(audio_bytes)
        range_header = self.headers.get('Range')
        if range_header and range_header.startswith('bytes='):
            try:
                rng = parse_range_header(range_header, total_size)
                if rng:
                    start, end = rng
                    content_length = end - start + 1
                    self.send_response(206)
                    self.send_header('Content-Type', mime_type)
                    self.send_header('Content-Range', f'bytes {start}-{end}/{total_size}')
                    self.send_header('Content-Length', str(content_length))
                    self.send_header('Accept-Ranges', 'bytes')
                    if extra_headers:
                        for k, v in extra_headers.items():
                            self.send_header(k, v)
                    self.end_headers()
                    self.wfile.write(audio_bytes[start:end+1])
                    return
            except Exception as ex:
                print(f'[Range error audio_bytes]: {ex}', file=sys.stderr)

        self.send_response(200)
        self.send_header('Content-Type', mime_type)
        self.send_header('Content-Length', str(total_size))
        self.send_header('Accept-Ranges', 'bytes')
        if extra_headers:
            for k, v in extra_headers.items():
                self.send_header(k, v)
        self.end_headers()
        self.wfile.write(audio_bytes)

    def do_POST(self):
        parsed = urllib.parse.urlparse(self.path)
        try:
            req_len = int(self.headers.get('Content-Length', 0))
        except ValueError:
            req_len = -1
        if req_len < 0 or req_len > MAX_REQUEST_BYTES:
            # Refuse huge or malformed uploads so nobody can fill the PC's memory/disk
            self.send_error(413, 'Request too large')
            return
        if parsed.path == '/api/translate':
            content_length = int(self.headers.get('Content-Length', 0))
            body_bytes = self.rfile.read(content_length)
            req_data = {}
            if body_bytes:
                try:
                    req_data = json.loads(body_bytes.decode('utf-8'))
                except Exception:
                    pass

            text = req_data.get('text', '')
            source_lang = req_data.get('source_lang', 'auto')
            target_lang = req_data.get('target_lang', 'ku')
            tone = req_data.get('tone', 'natural')
            api_key = req_data.get('api_key', '')
            model = req_data.get('model', '')

            result = handle_translation_request(text, source_lang, target_lang, tone, api_key, model)
            self.send_response(200)
            self.send_header('Content-Type', 'application/json')
            self.end_headers()
            self.wfile.write(json.dumps(result, ensure_ascii=False).encode('utf-8'))
            return

        if parsed.path == '/api/voice/conversation':
            content_length = int(self.headers.get('Content-Length', 0))
            body = self.rfile.read(content_length)
            content_type = self.headers.get('Content-Type', '')

            audio_bytes = None
            spoken_lang = "auto"
            speaker1_lang = "ku"
            speaker2_lang = "en"
            text_input = ""
            mime_type = ""
            el_enabled = False
            el_key = ""
            el_voice = ""

            if 'application/json' in content_type:
                try:
                    payload = json.loads(body.decode('utf-8'))
                    if 'audio_base64' in payload:
                        b64_val = payload['audio_base64']
                        if ',' in b64_val:
                            b64_val = b64_val.split(',')[1]
                        audio_bytes = base64.b64decode(b64_val)
                    spoken_lang = payload.get('spoken_lang', 'auto')
                    speaker1_lang = payload.get('speaker1_lang', 'ku')
                    speaker2_lang = payload.get('speaker2_lang', 'en')
                    mime_type = payload.get('mime_type', '')
                    text_input = payload.get('text', '').strip()
                    el_enabled = payload.get('elevenlabs_enabled', False)
                    el_key = payload.get('elevenlabs_key', '')
                    el_voice = payload.get('elevenlabs_voice_id', '')
                except Exception:
                    pass
            elif 'boundary=' in content_type:
                boundary = content_type.split('boundary=')[1].strip()
                b_boundary = ('--' + boundary).encode('latin1')
                parts = body.split(b_boundary)
                for part in parts:
                    if b'name="spoken_lang"' in part:
                        header_end = part.find(b'\r\n\r\n')
                        if header_end != -1:
                            val = part[header_end+4:].split(b'\r\n')[0].decode('utf-8', errors='ignore').strip()
                            if val: spoken_lang = val
                    if b'name="speaker1_lang"' in part:
                        header_end = part.find(b'\r\n\r\n')
                        if header_end != -1:
                            val = part[header_end+4:].split(b'\r\n')[0].decode('utf-8', errors='ignore').strip()
                            if val: speaker1_lang = val
                    if b'name="speaker2_lang"' in part:
                        header_end = part.find(b'\r\n\r\n')
                        if header_end != -1:
                            val = part[header_end+4:].split(b'\r\n')[0].decode('utf-8', errors='ignore').strip()
                            if val: speaker2_lang = val
                    if b'filename=' in part:
                        header_end = part.find(b'\r\n\r\n')
                        if header_end != -1:
                            payload = part[header_end+4:]
                            if payload.endswith(b'\r\n'):
                                payload = payload[:-2]
                            audio_bytes = payload
            else:
                audio_bytes = body

            try:
                if audio_bytes and len(audio_bytes) > 200:
                    result = transcribe_and_translate_voice(audio_bytes, spoken_lang, mime_type=mime_type, speaker1_lang=speaker1_lang, speaker2_lang=speaker2_lang)
                elif text_input:
                    result = translate_text_for_conversation(text_input, spoken_lang, speaker1_lang=speaker1_lang, speaker2_lang=speaker2_lang)
                else:
                    result = {"error": "No audio or text provided"}

                # Return translation instantly in ~1-2 seconds with zero TTS blocking delay!
                # Client handles speech playback smoothly and asynchronously.
                pass

            except Exception as e:
                print(f"[VC Conversation Error]: {e}", file=sys.stderr)
                result = {"error": f"Internal Error: {str(e)}"}

            self.send_response(200)
            self.send_header('Content-Type', 'application/json')
            self.end_headers()
            self.wfile.write(json.dumps(result, ensure_ascii=False).encode('utf-8'))
            return

        if parsed.path == '/api/voice/upload':
            content_length = int(self.headers.get('Content-Length', 0))
            body = self.rfile.read(content_length)
            content_type = self.headers.get('Content-Type', '')

            custom_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "custom_voices")
            os.makedirs(custom_dir, exist_ok=True)
            custom_file = os.path.join(custom_dir, "my_custom_voice.wav")

            file_bytes = body
            if 'boundary=' in content_type:
                boundary = content_type.split('boundary=')[1].strip()
                b_boundary = ('--' + boundary).encode('latin1')
                parts = body.split(b_boundary)
                for part in parts:
                    if b'filename=' in part:
                        header_end = part.find(b'\r\n\r\n')
                        if header_end != -1:
                            payload = part[header_end+4:]
                            if payload.endswith(b'\r\n'):
                                payload = payload[:-2]
                            file_bytes = payload
                            break

            with open(custom_file, "wb") as f:
                f.write(file_bytes)
            self.send_response(200)
            self.send_header('Content-Type', 'application/json')
            self.end_headers()
            self.wfile.write(json.dumps({"success": True, "size": len(file_bytes), "url": "/custom_voices/my_custom_voice.wav"}).encode('utf-8'))
            return
        self.send_error(404, "Not found")

    def do_OPTIONS(self):
        self.send_response(200)
        self.end_headers()

    def do_HEAD(self):
        parsed = urllib.parse.urlparse(self.path)
        rel_path = parsed.path.lstrip('/')
        if not rel_path:
            rel_path = 'index.html'
        rel_path = urllib.parse.unquote(rel_path.split('?')[0])
        base_dir = os.path.dirname(os.path.abspath(__file__))
        local_path = os.path.abspath(os.path.join(base_dir, rel_path))
        if is_safe_static_path(base_dir, local_path) and os.path.isfile(local_path):
            file_size = os.path.getsize(local_path)
            ext = os.path.splitext(local_path)[1].lower()
            mime_map = {
                '.wav': 'audio/wav',
                '.mp3': 'audio/mpeg',
                '.ogg': 'audio/ogg',
                '.webm': 'audio/webm',
                '.m4a': 'audio/mp4',
                '.js': 'application/javascript',
                '.css': 'text/css',
                '.html': 'text/html',
                '.json': 'application/json',
                '.png': 'image/png',
                '.jpg': 'image/jpeg',
                '.jpeg': 'image/jpeg',
                '.svg': 'image/svg+xml',
                '.ico': 'image/x-icon',
            }
            content_type = mime_map.get(ext, 'application/octet-stream')
            self.send_response(200)
            self.send_header('Content-Type', content_type)
            self.send_header('Content-Length', str(file_size))
            self.send_header('Accept-Ranges', 'bytes')
            self.end_headers()
            return
        self.send_error(404, 'File not found')


    def do_GET(self):
        parsed = urllib.parse.urlparse(self.path)

        if parsed.path == '/api/translate':
            query = urllib.parse.parse_qs(parsed.query)
            text = query.get('text', [''])[0]
            source_lang = query.get('source_lang', ['auto'])[0]
            target_lang = query.get('target_lang', ['ku'])[0]
            tone = query.get('tone', ['natural'])[0]
            api_key = query.get('api_key', [''])[0]
            model = query.get('model', [''])[0]

            result = handle_translation_request(text, source_lang, target_lang, tone, api_key, model)
            self.send_response(200)
            self.send_header('Content-Type', 'application/json')
            self.end_headers()
            self.wfile.write(json.dumps(result, ensure_ascii=False).encode('utf-8'))
            return

        if parsed.path == '/api/voice/native-samples':
            self.send_response(200)
            self.send_header('Content-Type', 'application/json')
            self.end_headers()
            samples = [
                {
                    "id": "custom",
                    "name": "دەنگی تۆ (Custom Voice)",
                    "title": "دەنگی ڕەسەنی کوردی سۆرانی تۆمارکراوت (sample.wav)",
                    "gender": "male",
                    "url": "/custom_voices/my_custom_voice.wav",
                    "sampleOutputUrl": "/custom_voices/my_custom_voice.wav",
                    "text": "سڵاو هاوڕێکانم، چۆنی؟ ئەمڕۆ حەز دەکەم دەربارەی چێس قسە بکەین."
                },
                {
                    "id": "fatih",
                    "name": "فاتیح (Fatih)",
                    "title": "دەنگی پەتیی سۆرانی (خوێندنەوەی پەڕتووک لە سلێمانی)",
                    "gender": "male",
                    "url": "/audio_samples/kurdish_native/prompt-audiobook-male.wav",
                    "sampleOutputUrl": "/audio_samples/kurdish_native/output-audiobook-male.wav",
                    "text": "شیعری عەقڵانی لە پیاوێک یان لە ژنێک دەچێت ئەو وەختەی دڵداری بکات بە زمانی فەرهەنگ بدوێ."
                },
                {
                    "id": "shahen",
                    "name": "شاهێن (Shahen)",
                    "title": "دەنگی خانمانەی مێلۆدی و ئەدەبیی سۆرانی",
                    "gender": "female",
                    "url": "/audio_samples/kurdish_native/prompt-audiobook-female.wav",
                    "sampleOutputUrl": "/audio_samples/kurdish_native/output-audiobook-female.wav",
                    "text": "یەکیان بێهرووزی تۆپچی بوو کە وەک پەیکی نامەبەر لە نێوان ئۆردوگا و بنکەکان هاتووچۆی دەکرد."
                },
                {
                    "id": "giganet",
                    "name": "گیگانێت (Giganet Studio)",
                    "title": "دەنگی بێژەری فەرمیی ستۆدیۆ لە کوردستان",
                    "gender": "broadcast",
                    "url": "/audio_samples/kurdish_native/prompt-studio-male.wav",
                    "sampleOutputUrl": "/audio_samples/kurdish_native/output-studio-male.wav",
                    "text": "خوێندنەوەی فەرمیی ستۆدیۆیی بە کێش و هەناسەی پەتیی سۆرانی."
                }
            ]
            self.wfile.write(json.dumps(samples).encode('utf-8'))
            return

        if parsed.path == '/api/gemini/tts/verify':
            self.send_response(200)
            self.send_header('Content-Type', 'application/json')
            self.end_headers()
            self.wfile.write(b'{"valid": true, "engine": "gemini-3.8-flash-tts", "status": "active"}')
            return

        if parsed.path == '/api/elevenlabs/verify':
            query = urllib.parse.parse_qs(parsed.query)
            key = query.get('api_key', [''])[0].strip() or os.environ.get("ELEVENLABS_API_KEY", "")
            if not key:
                self.send_response(400)
                self.send_header('Content-Type', 'application/json')
                self.end_headers()
                self.wfile.write(b'{"valid": false, "error": "No API key provided"}')
                return
            try:
                req = urllib.request.Request("https://api.elevenlabs.io/v1/user", headers={"xi-api-key": key, "User-Agent": "LalaTranslate/2.0"})
                with urllib.request.urlopen(req, timeout=10) as resp:
                    user_data = json.loads(resp.read().decode('utf-8'))
                    sub = user_data.get("subscription", {})
                    self.send_response(200)
                    self.send_header('Content-Type', 'application/json')
                    self.end_headers()
                    self.wfile.write(json.dumps({
                        "valid": True,
                        "tier": sub.get("tier", "free"),
                        "character_count": sub.get("character_count", 0),
                        "character_limit": sub.get("character_limit", 10000)
                    }).encode('utf-8'))
            except Exception as e:
                self.send_response(401)
                self.send_header('Content-Type', 'application/json')
                self.end_headers()
                self.wfile.write(json.dumps({"valid": False, "error": str(e)}).encode('utf-8'))
            return

        if parsed.path == '/api/tts':
            query = urllib.parse.parse_qs(parsed.query)
            text = query.get('text', [''])[0].strip()
            lang = query.get('lang', ['ku'])[0].lower()
            mode = query.get('mode', ['natural'])[0].lower()
            dialect = query.get('dialect', ['sorani'])[0].lower()
            speed = query.get('speed', ['1.0'])[0]
            provider = query.get('provider', ['edge'])[0].lower()
            api_key = query.get('api_key', [''])[0].strip() or os.environ.get("ELEVENLABS_API_KEY", "")
            custom_voice_id = query.get('voice_id', [''])[0].strip()

            if not text:
                self.send_response(400)
                self.send_header('Content-Type', 'application/json')
                self.end_headers()
                self.wfile.write(b'{"error": "Missing text parameter"}')
                return

            # Rate percentage from speed parameter
            rate_pct = 0
            try:
                rate_pct = int((float(speed) - 1.0) * 100)
            except Exception:
                rate_pct = 0
            rate_str = f"{rate_pct:+d}%"

            # Check if Kurdish or contains Kurdish text
            # Arabic/Persian text uses Arabic script too, so only treat it as Kurdish when lang is not ar/fa
            is_kurdish = (lang in ['ku', 'ckb', 'kmr']) or (
                not lang.startswith(('ar', 'fa')) and any('\u0600' <= c <= '\u06ff' for c in text))

            # ElevenLabs AI Integration (if key provided by user)
            if provider == 'elevenlabs' and api_key:
                el_voice = custom_voice_id or "pNInz6obpgDQGcFmaJgB"
                try:
                    audio_bytes = synthesize_elevenlabs(text, voice_id=el_voice, api_key=api_key)
                    if audio_bytes and len(audio_bytes) > 500:
                        extra = {
                            'X-Synthesized-Voice': f'ElevenLabs-{el_voice}',
                            'X-AI-Provider': 'elevenlabs',
                            'Cache-Control': 'no-cache, no-store, must-revalidate'
                        }
                        self.send_audio_bytes(audio_bytes, 'audio/mpeg', extra)
                        return
                except Exception:
                    pass

            if is_kurdish:
                engine = query.get('engine', ['human'])[0].lower()
                # F5 clones a real voice but is NOT trained on Kurdish (mispronounces Sorani): opt-in only
                if engine == 'f5':
                    gender = 'female' if query.get('gender', ['male'])[0].lower() == 'female' else 'male'
                    h_audio, h_mime = synthesize_kurdish_f5_studio(text, dialect=dialect, gender=gender, timeout=40)
                    if h_audio and len(h_audio) > 2000:
                        self.send_audio_bytes(h_audio, h_mime, {
                            'X-AI-Provider': f'f5-human-{gender}',
                            'Cache-Control': 'no-cache, no-store, must-revalidate'
                        })
                        return
                # 2. Gemini "Charon"
                if engine != 'native':
                    try:
                        g_audio, g_mime = synthesize_gemini_tts(text, voice_name='Charon', lang='ku', dialect=dialect)
                        if g_audio and len(g_audio) > 2000:
                            self.send_audio_bytes(g_audio, g_mime, {
                                'X-AI-Provider': 'gemini-charon',
                                'Cache-Control': 'no-cache, no-store, must-revalidate'
                            })
                            return
                    except Exception as e:
                        print(f"[Gemini Kurdish TTS -> backup voice]: {e}", file=sys.stderr)
                if engine == 'gemini_only':
                    # The app asked for no old voice (the user disliked it)
                    self.send_response(503)
                    self.send_header('Content-Type', 'application/json')
                    self.end_headers()
                    self.wfile.write(b'{"error": "Gemini voice unavailable"}')
                    return
                # 2. Backup: native Kurdish Sorani Studio voice
                native_audio, native_mime = synthesize_native_kurdish(text, dialect=dialect)
                if not native_audio:
                    native_audio, native_mime = synthesize_native_kurdish(text, dialect=dialect, timeout=15)
                if native_audio and len(native_audio) > 1000:
                    extra = {
                        'X-Synthesized-Voice': 'ckb-sorani-studio-diffusion',
                        'X-AI-Provider': 'kurdish-studio-native',
                        'X-Kurdish-Dialect': dialect,
                        'Cache-Control': 'no-cache, no-store, must-revalidate'
                    }
                    self.send_audio_bytes(native_audio, native_mime, extra)
                    return
                else:
                    self.send_response(500)
                    self.send_header('Content-Type', 'application/json')
                    self.end_headers()
                    self.wfile.write(b'{"error": "Failed to synthesize Kurdish speech"}')
                    return
            elif lang.startswith('ar'):
                voice = "ar-IQ-BasselNeural"
                processed_text = text
                pitch_str = "+0Hz"
            elif lang.startswith('fa'):
                voice = "fa-IR-FaridNeural"
                processed_text = text
                pitch_str = "+0Hz"
            elif lang.startswith('tr'):
                voice = "tr-TR-AhmetNeural"
                processed_text = text
                pitch_str = "+0Hz"
            else:
                voice = "en-US-BrianMultilingualNeural"
                processed_text = text
                pitch_str = "+0Hz"

            try:
                audio_bytes = asyncio.run(synthesize_speech(processed_text, voice, rate=rate_str, pitch=pitch_str))
                if not audio_bytes:
                    raise Exception("Zero bytes returned from synthesis")

                extra = {
                    'X-Synthesized-Voice': voice,
                    'X-AI-Provider': 'edge',
                    'X-Kurdish-Dialect': dialect,
                    'Cache-Control': 'no-cache, no-store, must-revalidate'
                }
                self.send_audio_bytes(audio_bytes, 'audio/mpeg', extra)
            except Exception as e:
                self.send_response(500)
                self.send_header('Content-Type', 'application/json')
                self.end_headers()
                self.wfile.write(json.dumps({"error": str(e)}, ensure_ascii=False).encode('utf-8'))
            return

        # Static file serving with byte-range support
        rel_path = parsed.path.lstrip('/')
        if not rel_path:
            rel_path = 'index.html'
        rel_path = urllib.parse.unquote(rel_path.split('?')[0])
        base_dir = os.path.dirname(os.path.abspath(__file__))
        local_path = os.path.abspath(os.path.join(base_dir, rel_path))
        if is_safe_static_path(base_dir, local_path) and os.path.isfile(local_path):
            self.send_file_with_range(local_path)
            return

        # Never fall back to the default handler: it would list folders and serve blocked files
        self.send_error(404, 'File not found')

class DualStackServer(ThreadingHTTPServer):
    daemon_threads = True
    def handle_error(self, request, client_address):
        exc_type, exc_val, _ = sys.exc_info()
        if exc_type in (ConnectionResetError, BrokenPipeError, ConnectionAbortedError):
            return
        super().handle_error(request, client_address)

def run(port=3000):
    DualStackServer.address_family = socket.AF_INET
    while True:
        try:
            httpd = DualStackServer(('0.0.0.0', port), NeuralTTSHandler)
            print(f"Translet Kurdish Voice Studio Server running on http://localhost:{port}")
            httpd.serve_forever()
        except KeyboardInterrupt:
            break
        except Exception as e:
            print(f"Server restart on exception: {e}")
            import time
            time.sleep(1)

if __name__ == '__main__':
    port = int(os.environ.get("PORT", sys.argv[1] if len(sys.argv) > 1 else 3000))
    run(port)