File size: 97,462 Bytes
dfc1b18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import uuid
import time
import asyncio
import gc
import re
import requests
import base64
import wave
import edge_tts
import shutil
import textwrap
import math
import traceback
import subprocess
from contextlib import asynccontextmanager
from fastapi import FastAPI, UploadFile, File, Form, BackgroundTasks, Header
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse, JSONResponse
import google.generativeai as genai
from pydantic import BaseModel
from typing import List
import rabbit
import logging
import hashlib

# =========================================================================
# 💡 [TECH MONSTAR FIX] Bot များ၏ 404 Error များကို Log တွင် ဖျောက်ထားရန်
# =========================================================================
class HideBotLogsFilter(logging.Filter):
    def filter(self, record):
        msg = record.getMessage()
        if " 404 " in msg:
            return False 
        return True

logging.getLogger("uvicorn.access").addFilter(HideBotLogsFilter())

TMP_DIR = "/tmp/app_io"
os.makedirs(TMP_DIR, exist_ok=True)

USER_FONT_DIR = os.path.expanduser("~/.fonts")
os.makedirs(USER_FONT_DIR, exist_ok=True)

LOCAL_FONTS = [
    "Zawgyi-One.ttf", 
    "Kanit-Regular.ttf", 
    "NotoSansSC-Regular.ttf",
    "NotoSansMyanmar-Regular.ttf"
]

for f_name in LOCAL_FONTS:
    local_path = os.path.join(os.getcwd(), f_name) 
    dest_path = os.path.join(USER_FONT_DIR, f_name)
    if os.path.exists(local_path):
        if not os.path.exists(dest_path):
            try: shutil.copy(local_path, dest_path)
            except: pass

os.system("fc-cache -f -v")

jobs = {}
upload_tokens = {}
running_tasks = {}
active_user_jobs = {}

MAX_CONCURRENT_JOBS = 3
queue_semaphore = asyncio.Semaphore(MAX_CONCURRENT_JOBS)
tts_semaphore = asyncio.Semaphore(5)  
api_key_counter = 0

BACKEND_SECRET = os.getenv("BACKEND_SECRET", "MY_SUPER_SECRET_TOKEN_123").strip()

VOICE_MAP = {
    "thiha": "my-MM-ThihaNeural", "nilar": "my-MM-NilarNeural",
    "thai_male": "th-TH-NiwatNeural", "thai_female": "th-TH-PremwadeeNeural",
    "english_male": "en-US-BrianNeural", "english_female": "en-US-EmmaNeural",
    "chinese_male": "zh-CN-YunxiNeural", "chinese_female": "zh-CN-XiaoxiaoNeural",
    "gemini_aoede": "Aoede", "gemini_charon": "Charon", "gemini_kore": "Kore",
    "gemini_fenrir": "Fenrir", "gemini_puck": "Puck", "gemini_zephyr": "Zephyr",
    "gemini_leda": "Leda", "gemini_orus": "Orus", "gemini_autonoe": "Autonoe",
    "gemini_callirrhoe": "Callirrhoe", "gemini_enceladus": "Enceladus", "gemini_iapetus": "Iapetus",
    "gemini_umbriel": "Umbriel", "gemini_algieba": "Algieba", "gemini_despina": "Despina",
    "gemini_erinome": "Erinome", "gemini_algenib": "Algenib", "gemini_rasalgethi": "Rasalgethi",
    "gemini_laomedeia": "Laomedeia", "gemini_achernar": "Achernar", "gemini_alnilam": "Alnilam",
    "gemini_schedar": "Schedar", "gemini_gacrux": "Gacrux", "gemini_pulcherrima": "Pulcherrima",
    "gemini_achird": "Achird", "gemini_zubenelgenubi": "Zubenelgenubi", "gemini_vindemiatrix": "Vindemiatrix",
    "gemini_sadachbia": "Sadachbia", "gemini_sadaltager": "Sadaltager", "gemini_sulafat": "Sulafat"
}

DUAL_VOICE_MAP = {
    "thiha": {"edge": "my-MM-ThihaNeural", "gemini": "Charon"},        
    "nilar": {"edge": "my-MM-NilarNeural", "gemini": "Aoede"},        
    "thai_male": {"edge": "th-TH-NiwatNeural", "gemini": "Charon"},   
    "thai_female": {"edge": "th-TH-PremwadeeNeural", "gemini": "Aoede"}, 
    "english_male": {"edge": "en-US-BrianNeural", "gemini": "Charon"}, 
    "english_female": {"edge": "en-US-EmmaNeural", "gemini": "Aoede"}, 
    "chinese_male": {"edge": "zh-CN-YunxiNeural", "gemini": "Charon"}, 
    "chinese_female": {"edge": "zh-CN-XiaoxiaoNeural", "gemini": "Aoede"} 
}

def emergency_disk_cleanup():
    try:
        total_size = sum(os.path.getsize(os.path.join(TMP_DIR, f)) for f in os.listdir(TMP_DIR) if os.path.isfile(os.path.join(TMP_DIR, f)))
        if total_size < 50000 * 1024 * 1024: return 
        current_time = time.time()
        for f in os.listdir(TMP_DIR):
            f_path = os.path.join(TMP_DIR, f)
            if os.path.isfile(f_path) and (current_time - os.path.getmtime(f_path) > 10800):
                os.remove(f_path)
        gc.collect()
    except: pass

# 💡 [THE FIX] Command များ ပိတ်မိမနေစေရန် Timeout ထည့်သွင်းထားပါသည်
async def run_cmd_async(cmd_list, retries=3, timeout=300):
    for attempt in range(retries):
        try:
            process = await asyncio.create_subprocess_exec(*cmd_list, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
            stdout, stderr = await asyncio.wait_for(process.communicate(), timeout=timeout)
            if process.returncode == 0: return stdout.decode()
            await asyncio.sleep(2) 
        except asyncio.TimeoutError:
            try: process.kill()
            except: pass
        except asyncio.CancelledError:
            try: process.kill()
            except: pass
            raise
        except Exception:
            try: process.kill()
            except: pass
    raise Exception(f"FFmpeg Task Failed/Timeout after {retries} attempts.")

async def get_media_duration(file_path):
    cmd = ["ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "default=noprint_wrappers=1:nokey=1", file_path]
    try: out = await run_cmd_async(cmd); return float(out.strip())
    except: return 0.0

def get_api_keys_pool():
    keys = []
    main_key = os.getenv("GEMINI_API_KEY", "").strip()
    if main_key and main_key.startswith("AIza"): keys.append(main_key.replace('"', '').replace("'", "").strip())
    for i in range(2, 101):
        backup_key = os.getenv(f"GEMINI_API_KEY_{i}", "").strip()
        if backup_key and backup_key.startswith("AIza"): keys.append(backup_key.replace('"', '').replace("'", "").strip())
    return keys

def get_working_api_key(user_key: str):
    global api_key_counter
    keys = []
    if user_key and user_key.strip(): keys.extend([k.strip() for k in user_key.split(",") if k.strip().startswith("AIza")])
    keys.extend(get_api_keys_pool())
    if not keys: return None
    selected_key = keys[api_key_counter % len(keys)]
    api_key_counter += 1
    return selected_key

@asynccontextmanager
async def lifespan(app: FastAPI):
    async def periodic_cleanup():
        while True:
            await asyncio.sleep(1800) 
            current_time = time.time()
            for j_id in list(jobs.keys()):
                if current_time - jobs[j_id].get("created_at", 0) > 10800: 
                    try:
                        for prefix in ["temp_", "out_", "ext_", "tts_", "wm_", "bgm_", "list_", "trim_", "sub_", "sil_", "concat_", "ov_", "bp_", "ai_vid_"]:
                            for f in os.listdir(TMP_DIR):
                                if f.startswith(prefix) and j_id in f: os.remove(os.path.join(TMP_DIR, f))
                    except: pass
                    del jobs[j_id]
            for cache_f in os.listdir(TMP_DIR):
                c_p = os.path.join(TMP_DIR, cache_f)
                if cache_f.startswith("cache_") and current_time - os.path.getmtime(c_p) > 10800:
                    try: os.remove(c_p)
                    except: pass
            for t in list(upload_tokens.keys()):
                if current_time > upload_tokens[t]: del upload_tokens[t]
            gc.collect() 
    asyncio.create_task(periodic_cleanup())
    yield

app = FastAPI(lifespan=lifespan)
app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"])

class TokenRequest(BaseModel): secret: str

@app.post("/generate-upload-token")
async def generate_upload_token(req: TokenRequest):
    if req.secret != BACKEND_SECRET: return JSONResponse(status_code=403, content={"error": "Unauthorized Server"})
    new_otp_token = str(uuid.uuid4())
    upload_tokens[new_otp_token] = time.time() + 3600 
    return JSONResponse(content={"token": new_otp_token})

async def generate_tts_audio(text, voice, rate_str, pitch_str, output_path):
    communicate = edge_tts.Communicate(text.strip(), voice, rate=rate_str, pitch=pitch_str)
    await communicate.save(output_path)

def generate_gemini_tts_audio_single(text, voice_name, user_api_key, output_path):
    for attempt in range(3):
        time.sleep(1) 
        api_key = get_working_api_key(user_api_key)
        if not api_key: raise Exception("API Key Missing!")
        url = f"https://generativelanguage.googleapis.com/v1alpha/models/gemini-3.1-flash-tts-preview:generateContent?key={api_key}"
        payload = {"contents": [{"parts": [{"text": text}]}], "generationConfig": {"responseModalities": ["AUDIO"], "speechConfig": {"voiceConfig": {"prebuiltVoiceConfig": {"voiceName": voice_name}}}}}
        response = requests.post(url, json=payload, timeout=60)
        if response.status_code == 200:
            try:
                audio_base64 = response.json()['candidates'][0]['content']['parts'][0]['inlineData']['data']
                audio_base64 += "=" * ((4 - len(audio_base64) % 4) % 4)
                with wave.open(output_path, "wb") as wf:
                    wf.setnchannels(1); wf.setsampwidth(2); wf.setframerate(24000)
                    wf.writeframes(base64.b64decode(audio_base64))
                return
            except: raise Exception("Gemini Data Error")
        elif attempt == 2: raise Exception(f"Gemini API Error: {response.status_code}")

async def process_single_line_tts(idx, text, time_ms, orig_end_ms, unique_job_id, v_name_check, edge_voice, gemini_voice, user_api_key, pitch, lang_key, tts_speed, cache_job_id=None):
    clean_text = re.sub(r'\[\d{1,2}:\d{2}(?::\d{2})?(?:\.\d+)?\s*-\s*\d{1,2}:\d{2}(?::\d{2})?(?:\.\d+)?\]', '', text).strip()
    clean_text = re.sub(r'\[.*?\]|\(.*?\)|<.*?>', '', clean_text).strip()
    clean_text = re.sub(r'["\'“”‘’`\-—_]', ' ', clean_text).strip()
    clean_text = re.sub(r'\.+', ' ', clean_text).strip()
    clean_text = re.sub(r'[?!,;]', ' ', clean_text).strip()
    if not clean_text: return None
    
    sub_wav = os.path.join(TMP_DIR, f"tts_{unique_job_id}_{idx}.wav")
    try: f_speed = float(tts_speed); f_speed = f_speed if f_speed > 0 else 1.15
    except: f_speed = 1.15
    ffmpeg_speed = str(f_speed)
    
    tts_text = clean_text
    if not v_name_check.startswith("gemini_"): tts_text = re.sub(r'\s+', ' ', tts_text).strip()
    is_success = False
    
    async with tts_semaphore:
        for attempt in range(20):
            try:
                if v_name_check.startswith("gemini_"):
                    raw_gemini = os.path.join(TMP_DIR, f"tts_{unique_job_id}_{idx}_raw_gemini.wav")
                    if cache_job_id: 
                        c_raw = os.path.join(TMP_DIR, f"tts_{cache_job_id}_{idx}_raw_gemini.wav")
                        if os.path.exists(c_raw): raw_gemini = c_raw 
                        
                    if not os.path.exists(raw_gemini): 
                        await asyncio.to_thread(generate_gemini_tts_audio_single, clean_text, gemini_voice, user_api_key, raw_gemini)
                    if os.path.exists(raw_gemini): 
                        silence_filter = f"silenceremove=start_periods=1:start_threshold=-60dB,areverse,silenceremove=start_periods=1:start_threshold=-60dB,areverse,atempo={ffmpeg_speed}"
                        await run_cmd_async(["ffmpeg", "-y", "-i", raw_gemini, "-filter:a", silence_filter, sub_wav])
                else:
                    raw_edge = os.path.join(TMP_DIR, f"tts_{unique_job_id}_{idx}_raw_edge.wav")
                    if cache_job_id: 
                        c_raw = os.path.join(TMP_DIR, f"tts_{cache_job_id}_{idx}_raw_edge.wav")
                        if os.path.exists(c_raw): raw_edge = c_raw 
                        
                    if not os.path.exists(raw_edge): 
                        await generate_tts_audio(tts_text, edge_voice, "+0%", f"{int(pitch):+d}Hz", raw_edge)
                    if os.path.exists(raw_edge): 
                        silence_filter = f"silenceremove=start_periods=1:start_threshold=-55dB,areverse,silenceremove=start_periods=1:start_threshold=-55dB,areverse,atempo={ffmpeg_speed}"
                        await run_cmd_async(["ffmpeg", "-y", "-i", raw_edge, "-filter:a", silence_filter, sub_wav])
                
                if os.path.exists(sub_wav) and os.path.getsize(sub_wav) > 0: 
                    is_success = True; break
                else: await asyncio.sleep(2)
            except Exception: await asyncio.sleep(2)
            
    if not is_success: raise Exception(f"❌ အသံဖန်တီးမှု မအောင်မြင်ပါ။ စာသား: '{clean_text[:20]}...'")
    dur = int((await get_media_duration(sub_wav)) * 1000)
    return {"idx": idx, "path": sub_wav, "actual_dur": dur, "time_ms": time_ms, "orig_end_ms": orig_end_ms, "clean_text": clean_text}

async def wrapper_process_task(*args, **kwargs):
    async with queue_semaphore: await process_video_task(*args, **kwargs)

async def process_video_task(job_id: str, user_id: str, file_path: str, wm_path: str, bgm_path: str, ov_path: str, voice_name: str, user_api_key: str, ratio: str, resolution: str, voice_toggle: str, hide_subtitle: str, volume: str, pitch: str, bypass_mode: str, logo_pos: str, logo_size: str, logo_opacity: str, custom_prompt: str, genre: str, bgm_volume: str, target_chunk: str, chunk_minutes: str, mask_toggle: str, mask_y: str, mask_h: str, mask_w: str, sub_toggle: str, sub_y: str, sub_size: str, sub_color: str, tts_speed: str, bgm_toggle: str, logo_toggle: str, logo_shape: str, logo_custom_x: str, logo_custom_y: str, special_effect: str, marquee_toggle: str, marquee_text: str, marquee_y: str, pip_shape: str, pip_pos: str, overlay_size: str, pip_custom_x: str, pip_custom_y: str, bouncing_pip_toggle: str, bp_path: str, bouncing_pip_shape: str, bouncing_pip_size: str, bouncing_pip_opacity: str, jumpcut_mode: str = "off", is_remerge: bool = False, original_job_id: str = None, force_recreate: str = "false", tab_mode: str = "translate"):
    output_video_path = os.path.join(TMP_DIR, f"out_{job_id}.mp4")
    working_video_path = file_path 
    v_check = voice_name.lower()
    is_thai_mode = "thai" in v_check or "th-" in v_check or "ထိုင်း" in v_check
    is_chinese_mode = "chinese" in v_check or "zh-" in v_check or "တရုတ်" in v_check
    is_eng_mode = "english" in v_check or "en-" in v_check or "အင်္ဂလိပ်" in v_check
    lang_key = "thai" if is_thai_mode else "chinese" if is_chinese_mode else "english" if is_eng_mode else "myanmar"
    
    try:
        chunks_info = []
        is_full_auto = False
        
        if is_remerge and original_job_id in jobs:
            print(f"🚀 [{job_id}] ပြန်လည်ပေါင်းစပ်ခြင်း စတင်ပါပြီ...", flush=True)
            orig_job = jobs[original_job_id]
            working_video_path = orig_job.get("working_video_path", file_path)
            chunks_info = orig_job.get("chunks_info", [])
            is_full_auto = len(chunks_info) > 1
            v_dur_full = orig_job.get("v_dur_full", 1.0)
        else:
            if jobs.get(job_id, {}).get("status") == "cancelled": raise Exception("လုပ်ငန်းစဉ်ကို ရပ်ဆိုင်းလိုက်ပါသည်။")
            v_dur_full = await get_media_duration(working_video_path)
            if v_dur_full <= 0: v_dur_full = 1.0
            
            try: 
                c_mins = int(chunk_minutes)
            except: 
                c_mins = 2
            
            if target_chunk.startswith("auto_"):
                try:
                    parts = target_chunk.split("_")
                    if len(parts) > 1:
                        c_mins = int(parts[1])
                except:
                    pass
            
            chunk_duration_sec = c_mins * 60

            if target_chunk.startswith("auto"):
                is_full_auto = True
                total_chunks = math.ceil(v_dur_full / chunk_duration_sec)
                for i in range(total_chunks):
                    chunks_info.append({"start_time": i * chunk_duration_sec, "duration": chunk_duration_sec, "real_idx": i})
            elif target_chunk.isdigit():
                is_full_auto = False
                chunk_num = int(target_chunk)
                start_time = (chunk_num - 1) * chunk_duration_sec
                chunks_info.append({"start_time": start_time, "duration": chunk_duration_sec, "real_idx": chunk_num - 1})
            else:
                is_full_auto = True
                total_chunks = math.ceil(v_dur_full / chunk_duration_sec)
                for i in range(total_chunks):
                    chunks_info.append({"start_time": i * chunk_duration_sec, "duration": chunk_duration_sec, "real_idx": i})

        jobs[job_id]["chunks_info"] = chunks_info
        jobs[job_id]["v_dur_full"] = v_dur_full
        
        completed_chunk_videos = []
        full_transcript_list = []
        total_cost_accum = 0
        total_chunks_count = len(chunks_info)
        video_file_ai = None
        
        jobs[job_id]["total_chunks"] = total_chunks_count

        previous_chunk_memory = ""
        character_sheet_memory = ""

        base_res = 720 if resolution == "720p" else 1080
        if ratio == "9:16":
            target_w = base_res; target_h = int(target_w * 16 / 9)
        elif ratio == "1:1":
            target_w = base_res; target_h = base_res
        elif ratio == "4:5":
            target_w = base_res; target_h = int(target_w * 5 / 4)
        elif ratio == "4:3":
            target_h = base_res; target_w = int(target_h * 4 / 3)
        else: # 16:9
            target_h = base_res; target_w = int(target_h * 16 / 9)

        target_w = (target_w // 2) * 2
        target_h = (target_h // 2) * 2

        for c_idx, chunk_data in enumerate(chunks_info):
            jobs[job_id]["current_chunk"] = c_idx + 1 
            
            # 💡 [THE FIX] UI တန်းတက်သွားစေရန် status ကို အရင်ဆုံး သတ်မှတ်မည်
            jobs[job_id]["status"] = "generating_audio" if is_remerge else "transcribing"
            jobs[job_id]["progress_msg"] = f" [အပိုင်း {c_idx+1}/{total_chunks_count}] ဗီဒီယို ဖြတ်တောက်နေပါသည်..."
            
            if jobs.get(job_id, {}).get("status") == "cancelled": raise Exception("လုပ်ငန်းစဉ်ကို ရပ်ဆိုင်းလိုက်ပါသည်။")
            start_time = chunk_data["start_time"]
            chunk_duration_sec = chunk_data["duration"]
            if start_time >= v_dur_full: break
            
            actual_chunk_dur = min(chunk_duration_sec, v_dur_full - start_time)
            msg_prefix = f" [အပိုင်း {c_idx+1}/{total_chunks_count}] " if is_full_auto else " "
            
            real_idx = chunk_data.get("real_idx", c_idx)
            cache_str = f"{working_video_path}_{wm_path}_{ov_path}_{bp_path}_{real_idx}_{actual_chunk_dur}_{voice_name}_{tts_speed}_{genre}_{custom_prompt}_{sub_toggle}_{sub_y}_{sub_size}_{sub_color}_{bypass_mode}_{voice_toggle}_{bgm_toggle}_{bgm_volume}_{logo_toggle}_{logo_pos}_{logo_size}_{logo_opacity}_{logo_shape}_{logo_custom_x}_{logo_custom_y}_{mask_toggle}_{mask_y}_{mask_h}_{mask_w}_{special_effect}_{marquee_toggle}_{marquee_text}_{marquee_y}_{bouncing_pip_toggle}_{bouncing_pip_shape}_{bouncing_pip_size}_{bouncing_pip_opacity}_{pip_shape}_{pip_pos}_{overlay_size}_{pip_custom_x}_{pip_custom_y}_{jumpcut_mode}_{ratio}_{resolution}_{volume}_{pitch}_{tab_mode}"
            chunk_cache_id = hashlib.md5(cache_str.encode()).hexdigest()
            
            trim_vid = os.path.join(TMP_DIR, f"trim_{job_id}_{c_idx}.mp4")
            tts_audio = os.path.join(TMP_DIR, f"tts_{job_id}_{c_idx}_final.wav")
            sub_file = os.path.join(TMP_DIR, f"sub_{job_id}_{c_idx}.ass")
            
            chunk_out_vid = os.path.join(TMP_DIR, f"chunk_out_{chunk_cache_id}.mp4")
            chunk_txt_file = os.path.join(TMP_DIR, f"chunk_txt_{chunk_cache_id}.txt")
            
            if not is_remerge and force_recreate == "true":
                try:
                    if os.path.exists(chunk_out_vid): os.remove(chunk_out_vid)
                    if os.path.exists(chunk_txt_file): os.remove(chunk_txt_file)
                except: pass

            if not is_remerge and os.path.exists(chunk_out_vid) and os.path.getsize(chunk_out_vid) > 0 and os.path.exists(chunk_txt_file):
                print(f"⏩ [RESUME] Skipping Chunk {c_idx+1}, loading from memory.")
                completed_chunk_videos.append(chunk_out_vid)
                with open(chunk_txt_file, "r", encoding="utf-8") as f:
                    memory_text = f.read()
                    full_transcript_list.append(memory_text)
                    matches = list(re.finditer(r'\[(\d{1,2}:\d{2}(?::\d{2})?(?:\.\d+)?)\s*-\s*(\d{1,2}:\d{2}(?::\d{2})?(?:\.\d+)?)\]\s*([^\[]+)', memory_text))
                    if matches:
                        last_few_lines = [re.sub(r'\[.*?\]', '', m.group(3)).strip() for m in matches[-4:]]
                        previous_chunk_memory = " ".join(last_few_lines).strip()
                continue
            
            if is_remerge:
                old_trim = os.path.join(TMP_DIR, f"trim_{original_job_id}_{c_idx}.mp4")
                if os.path.exists(old_trim):
                    trim_vid = old_trim
                else:
                    await run_cmd_async(['ffmpeg', '-y', '-ss', str(start_time), '-i', working_video_path, '-t', str(actual_chunk_dur), '-c', 'copy', trim_vid])
            else:
                await run_cmd_async(['ffmpeg', '-y', '-ss', str(start_time), '-i', working_video_path, '-t', str(actual_chunk_dur), '-c', 'copy', trim_vid])
            
            c_v_dur = await get_media_duration(trim_vid)
            if c_v_dur <= 0: c_v_dur = 1.0

            parsed_lines = []

            if is_remerge:
                parsed_lines = chunk_data.get("parsed_lines", [])
            else:
                # 💡 [THE FIX] 10% တွင် ရပ်မနေစေရန် AI သို့ပို့မည့် ဗီဒီယိုအား (480p, 10fps) သို့ အမြန်ဆုံး ချုံ့ပစ်ပါမည်
                ai_vid = os.path.join(TMP_DIR, f"ai_vid_{job_id}_{c_idx}.mp4")
                jobs[job_id]["progress_msg"] = f"{msg_prefix}AI အတွက် ဗီဒီယိုအကြမ်း ပြင်ဆင်နေပါသည်..."
                await run_cmd_async(['ffmpeg', '-y', '-i', trim_vid, '-vf', 'scale=-2:480', '-r', '10', '-c:v', 'libx264', '-preset', 'ultrafast', '-crf', '35', '-c:a', 'libmp3lame', '-b:a', '64k', ai_vid])

                genre_instructions = {
                    "original": "မူရင်းအတိုင်း သဘာဝကျသော အသုံးအနှုန်းများဖြင့် ပြောပါ။",
                    "comedy": "⚠️ ဤကားသည် 'ချိုင့်ကေကို (ဟာသ)' စတိုင်ဖြစ်သည်။ အလွန်ရယ်စရာကောင်းသော၊ ဟာသမြောက်သော ဗန်းစကားများ နှင့် ရယ်သံများကို သုံးပါ။",
                    "action": "⚠️ 'အက်ရှင်' စတိုင်ဖြစ်သည်။ မြန်ဆန်သွက်လက်ပြီး စိတ်လှုပ်ရှားဖွယ်ကောင်းအောင် အသက်ဝင်ဝင် ပြောပါ။",
                    "horror": "⚠️ 'မဖဲဝါ (သင်္ချိုင်းစောင့်သူရဲမ)' စတိုင်ဖြစ်သည်။ ခြောက်ခြားဖွယ်ကောင်းသော၊ ထစ်ငေါ့နေသော လေသံဖြင့် ကျောချမ်းအောင် ရေးပါ။",
                    "motivational": "⚠️ 'တက်ကြွတဲ့ကြက်ဖ' စတိုင်ဖြစ်သည်။ မလျှော့သော ဇွဲလုံ့လနှင့် ရင်ထဲကို ထိမှန်စေမည့် အားပေးစကားများ ထည့်သုံးပါ။",
                    "happy": "⚠️ 'ပျော်ရွှင်ဖွယ်လူငယ်' စတိုင်ဖြစ်သည်။ တက်ကြွရွှင်လန်းပြီး ပျော်စရာကောင်းသော လေသံဖြင့် ပြောပါ။",
                    "sad": "⚠️ 'ဝမ်းနည်းဖွယ်လူငယ်' စတိုင်ဖြစ်သည်။ လွမ်းဆွေးဖွယ်ကောင်းသော၊ သနားစရာကောင်းသော လေသံဖြင့် ပြောပါ။",
                    "story": "⚠️ 'ပုံပြင်' စတိုင်ဖြစ်သည်။ အဖိုးအဖွားတစ်ဦးက မြေးလေးများကို ပုံပြင်ပြောပြနေသကဲ့သို့ ချိုသာစွာ ဇာတ်ကြောင်းပြန်ပါ။"
                }
                genre_prompt = genre_instructions.get(genre, genre_instructions["original"])
                
                custom_prompt_text = ""
                if custom_prompt and custom_prompt.strip():
                    custom_prompt_text = f"⚠️ [USER'S SPECIAL INSTRUCTION - OVERRIDE ALL]: {custom_prompt.strip()}"
                
                memory_injection = ""
                if character_sheet_memory:
                    memory_injection += f"⚠️ [CRITICAL MEMORY]: Always remember these key details: '{character_sheet_memory}'. Keep all names consistent.\n"
                if previous_chunk_memory:
                    memory_injection += f"⚠️ [PREVIOUS STORY CONTEXT]: The last part ended with: '{previous_chunk_memory}'. Continue naturally from here."

                current_is_first = (chunk_data.get("real_idx", c_idx) == 0)
                
                if tab_mode == "recap":
                    my_translation_rule = "⚠️ [RECAP MODE - CRITICAL]: ဇာတ်ကောင်များပြောသော စကားများကို တစ်ကြောင်းချင်း တိုက်ရိုက် ဘာသာမပြန်ပါနှင့်။ ဗီဒီယို၏ ဇာတ်လမ်းသွားကို နားလည်အောင်ကြည့်ပြီး၊ မြင်ကွင်းများကို 'ရုပ်ရှင်အကျဉ်းချုပ် (Movie Recap)' စတိုင်ဖြင့် ကိုယ်ပိုင်အသုံးအနှုန်းများ သုံးကာ ဆွဲဆောင်မှုရှိအောင် ဇာတ်ကြောင်းပြန်ပါ။"
                    en_translation_rule = "⚠️ [RECAP MODE - CRITICAL]: Do NOT translate dialogues line-by-line. Write a highly engaging 'Movie Recap' script describing the scenes and plot in your own words."
                    th_translation_rule = "⚠️ [RECAP MODE - CRITICAL]: ห้ามแปลบทสนทนาแบบตรงตัวทุกบรรทัด ให้สรุปและเขียนบท 'สปอยหนัง (Movie Recap)' ที่น่าติดตามโดยใช้คำพูดของคุณเอง"
                    zh_translation_rule = "⚠️ [RECAP MODE - CRITICAL]: 严禁逐句翻译对话。请用你自己的语言撰写引人入胜的“电影解说”脚本。"
                else:
                    my_translation_rule = "မူရင်းက စာရှည်လျှင် ရှည်သလို၊ တိုလျှင် တိုသလို (Line-by-line) ဘာသာပြန်ပါ။ အလွန်အမင်း အကျဉ်းချုံ့ပစ်ခြင်း လုံးဝ မလုပ်ပါနှင့်။ အစအဆုံး အပြည့်အစုံ ဘာသာပြန်ပါ။"
                    en_translation_rule = "Translate the video audio line-by-line completely. Do not over-summarize."
                    th_translation_rule = "แปลเสียงวิดีโอแบบบรรทัดต่อบรรทัดอย่างสมบูรณ์ ห้ามสรุปมากเกินไป"
                    zh_translation_rule = "完整地逐句翻译视频音频。不要过度总结。"

                my_human_narrator_rule = "⚠️ [HUMAN NARRATOR - CRITICAL]: သင်သည် ပုံပြောကောင်းသော၊ လူသားစစ်စစ် ဇာတ်ကြောင်းပြန်သူ (Human Storyteller) ဖြစ်သည်။ စက်ရုပ်ဆန်သော စကားလုံးခြောက်များ၊ တိုပြတ်သော ဝါကျများကို လုံးဝမသုံးရ။ စိတ်ခံစားမှုပါသော စကားလုံးများ၊ ဆွဲဆောင်မှုရှိသော ဝါကျအရှည်အတိုများဖြင့် ပရိသတ်ကို ဇာတ်လမ်းထဲ စီးမျောသွားအောင် ပြောပါ။"
                my_consistency_rule = "⚠️ [MEMORY & CONSISTENCY - CRITICAL]: သင်သည် စုံထောက်တစ်ဦးကဲ့သို့ အသေးစိတ်ကို အာရုံစိုက်ရမည်။ ဇာတ်ကောင်အမည်များ၊ နေရာဒေသများ၊ ခုနှစ်သက္ကရာဇ်များကို ဗီဒီယိုတစ်လျှောက်လုံး လုံးဝမမှားစေရ။ အစမှာ 'ဂျွန်' ဟု ပြောပြီး နောက်ပိုင်းတွင် သူ့နာမည်ကို မေ့ကျန်ခဲ့ခြင်းမျိုး လုံးဝမဖြစ်စေရ။"
                
                en_human_narrator_rule = "⚠️ [HUMAN NARRATOR - CRITICAL]: You are a charismatic, human storyteller. Avoid robotic, dry, or simple sentences. Use vivid verbs, emotional adjectives, and varied sentence structures to immerse the audience in the story."
                en_consistency_rule = "⚠️ [MEMORY & CONSISTENCY - CRITICAL]: You must act like a detective, paying close attention to every detail. Character names, locations, and dates must remain 100% consistent throughout the video. Do not mention a name like 'John' at the start and then forget it later."
                
                th_human_narrator_rule = "⚠️ [HUMAN NARRATOR - CRITICAL]: คุณคือผู้บรรยายที่เป็นมนุษย์และมีเสน่ห์ หลีกเลี่ยงประโยคที่เหมือนหุ่นยนต์ แห้งแล้ง หรือเรียบง่าย ใช้คำกริยาที่ชัดเจน คำคุณศัพท์ที่แสดงอารมณ์ และโครงสร้างประโยคที่หลากหลายเพื่อให้ผู้ชมอินไปกับเรื่องราว"
                th_consistency_rule = "⚠️ [MEMORY & CONSISTENCY - CRITICAL]: คุณต้องทำตัวเหมือนนักสืบ ใส่ใจทุกรายละเอียด ชื่อตัวละคร สถานที่ และวันที่ต้องสอดคล้องกัน 100% ตลอดทั้งวิดีโอ อย่าเอ่ยชื่อ 'จอห์น' ในตอนแรกแล้วลืมในภายหลัง"

                zh_human_narrator_rule = "⚠️ [HUMAN NARRATOR - CRITICAL]: 你是一位富有魅力的人类故事讲述者。避免使用机器人般、枯燥或简单的句子。使用生动的动词、富有情感的形容词和多样的句式结构,让观众沉浸在故事中。"
                zh_consistency_rule = "⚠️ [MEMORY & CONSISTENCY - CRITICAL]: 你必须像侦探一样,密切关注每一个细节。角色名称、地点和日期在整个视频中必须保持100%一致。不要在开头提到像“约翰”这样的名字,然后又忘记了。"
                
                my_pacing = "⚠️ [PACING & CONCISENESS]: ဇာတ်လမ်းပြောရာတွင် ကျစ်လျစ်ပါစေ။ တိုက်ခိုက်ခန်းများ သို့မဟုတ် လှုပ်ရှားမှုများကို တစ်ခုချင်းစီ အသေးစိတ် လိုက်မပြောပါနှင့်။ အဖြစ်အပျက်ကို အကျဉ်းချုပ်ပြီးသာ ပြောပါ။"
                en_pacing = "⚠️ [PACING & CONCISENESS]: Keep narration CONCISE. Do NOT over-describe every single action. Summarize briefly."
                th_pacing = "⚠️ [PACING & CONCISENESS]: เล่าเรื่องให้กระชับ ห้ามอธิบายทุกการกระทำโดยละเอียด สรุปสั้นๆ"
                zh_pacing = "⚠️ [PACING & CONCISENESS]: 保持叙述简明扼要。不要过度描述每一个动作。简要总结事件。"

                if is_eng_mode:
                    intro_rule = "⚠️ [INTRO RULE]: The very first line MUST be exactly [00:00 - 00:02] Hello." if current_is_first else "⚠️ [NO INTRO RULE]: Continuation chunk. NO greetings."
                    prompt = (f"You are a professional movie recap narrator and storyteller. Watch the video carefully and narrate the story in English.\n"
                              f"⚠️ CRITICAL INSTRUCTIONS:\n"
                              f"1. {en_translation_rule}\n"
                              f"2. {en_human_narrator_rule}\n"
                              f"3. {en_consistency_rule}\n"
                              f"4. {en_pacing}\n"
                              f"5. ⚠️ [VIDEO ANALYSIS]: Watch the characters' actions, emotions, and key events. Describe the story seamlessly, even if there is no dialogue.\n"
                              f"6. {intro_rule}\n"
                              f"{memory_injection}{custom_prompt_text} MOVIE GENRE: {genre_prompt}\n"
                              f"FINAL INSTRUCTION: Use only [MM:SS - MM:SS] format for EVERY line. ACT AS A CHARISMATIC HUMAN NARRATOR.")
                elif is_thai_mode:
                    intro_rule = "⚠️ [INTRO RULE]: บรรทัดแรกสุดต้องเป็น [00:00 - 00:02] สวัสดี อย่างเคร่งครัด" if current_is_first else "⚠️ [NO INTRO RULE]: ส่วนต่อขยาย ห้ามทักทาย"
                    prompt = (f"You are a professional movie recap narrator. Watch the video carefully and narrate the story in Thai Language (ภาษาไทย).\n"
                              f"⚠️ CRITICAL INSTRUCTIONS:\n"
                              f"1. {th_translation_rule}\n"
                              f"2. {th_human_narrator_rule}\n"
                              f"3. {th_consistency_rule}\n"
                              f"4. {th_pacing}\n"
                              f"5. ⚠️ [VIDEO ANALYSIS]: ดูการกระทำ อารมณ์ และเหตุการณ์สำคัญในวิดีโออย่างละเอียด เล่าเรื่องอย่างต่อเนื่องแม้จะไม่มีคนพูดก็ตาม\n"
                              f"6. {intro_rule}\n"
                              f"{memory_injection}{custom_prompt_text} MOVIE GENRE: {genre_prompt}\n"
                              f"FINAL INSTRUCTION: ใช้รูปแบบ [MM:SS - MM:SS] สำหรับทุกบรรทัดเท่านั้น ทำตัวเป็นผู้บรรยายที่มีเสน่ห์")
                elif is_chinese_mode:
                    intro_rule = "⚠️ [INTRO RULE]: 第一行必须严格是 [00:00 - 00:02] 你好。" if current_is_first else "⚠️ [NO INTRO RULE]: 后续片段。严禁问候。"
                    prompt = (f"You are a professional movie recap narrator. Watch the video carefully and narrate the story in Simplified Chinese (中文).\n"
                              f"⚠️ CRITICAL INSTRUCTIONS:\n"
                              f"1. {zh_translation_rule}\n"
                              f"2. {zh_human_narrator_rule}\n"
                              f"3. {zh_consistency_rule}\n"
                              f"4. {zh_pacing}\n"
                              f"5. ⚠️ [VIDEO ANALYSIS]: 仔细观察视频中的人物动作、情感和关键事件。即使没有对话,也要连贯地讲述故事。\n"
                              f"6. {intro_rule}\n"
                              f"{memory_injection}{custom_prompt_text} MOVIE GENRE: {genre_prompt}\n"
                              f"FINAL INSTRUCTION: 每一行仅使用 [MM:SS - MM:SS] 格式。扮演一个有魅力的人类叙述者。")
                else: 
                    intro_rule = "⚠️ [INTRO RULE]: ပထမဆုံး စာကြောင်းကို [00:00 - 00:02] မင်္ဂလာပါ ဟု အချိန်အတိအကျဖြင့် နှုတ်ဆက်ပါ။" if current_is_first else "⚠️ [NO INTRO RULE]: နောက်ဆက်တွဲအပိုင်းဖြစ်၍ နှုတ်ဆက်စကားများ လုံးဝ မထည့်ပါနှင့်။"
                    prompt = (f"You are a professional movie recap narrator and storyteller. Watch the video carefully and narrate the story in Burmese Language (မြန်မာဘာသာစကား).\n"
                              f"⚠️ အရေးကြီးဆုံး ညွှန်ကြားချက်များ:\n"
                              f"၁။ {my_translation_rule}\n"
                              f"၂။ {my_human_narrator_rule}\n"
                              f"၃။ {my_consistency_rule}\n"
                              f"၄။ {my_pacing}\n"
                              f"၅။ ⚠️ [VIDEO ANALYSIS - CRITICAL]: ဗီဒီယိုထဲရှိ လူများ၏ လှုပ်ရှားမှုများ၊ ခံစားချက်များ၊ အရေးကြီးသော အဖြစ်အပျက်များကို သေချာကြည့်ရှုပြီး ပရိသတ်ကို ဇာတ်လမ်းပြန်ပြောပြသည့် (Movie Recap) ပုံစံဖြင့် ရေးပါ။ စကားပြောသံမရှိလျှင်လည်း ဇာတ်လမ်း အဆက်မပြတ်သွားစေရန် မြင်ကွင်းကို ဇာတ်ကြောင်းပြန်ပြောပြပါ။\n"
                              f"၆။ {intro_rule}\n"
                              f"{memory_injection}{custom_prompt_text} MOVIE GENRE: {genre_prompt}\n"
                              f"FINAL INSTRUCTION: စာကြောင်းတိုင်းအတွက် [MM:SS - MM:SS] ပုံစံကိုသာ မဖြစ်မနေ သုံးပါ။ လူသားစစ်စစ်ကဲ့သို့ ဆွဲဆောင်မှုရှိစွာ ဇာတ်လမ်းပြောပါ။")

                keys_pool = get_api_keys_pool()
                max_retries = max(5, len(keys_pool) + 2)
                transcript = ""
                
                jobs[job_id]["progress_msg"] = f"{msg_prefix}AI မှ ဗီဒီယိုကို ကြည့်ရှု၍ ဇာတ်လမ်းစဉ်းစားနေပါသည်..."
                
                for attempt in range(max_retries):
                    try:
                        await asyncio.sleep(1)
                        active_key = get_working_api_key(user_api_key)
                        if not active_key: raise Exception("API Key Missing!")
                        genai.configure(api_key=active_key)

                        if video_file_ai:
                            try: await asyncio.to_thread(genai.delete_file, video_file_ai.name)
                            except: pass

                        # 💡 [THE FIX] ai_vid (ချုံ့ထားသော ဗီဒီယို) ကိုသာ AI သို့ ပေးပို့ပါမည်
                        video_file_ai = await asyncio.wait_for(asyncio.to_thread(genai.upload_file, path=ai_vid), timeout=120)
                        await asyncio.sleep(3) 
                        for _ in range(6): 
                            video_file_ai = await asyncio.wait_for(asyncio.to_thread(genai.get_file, video_file_ai.name), timeout=20)
                            if video_file_ai.state.name != "PROCESSING": break
                            await asyncio.sleep(3)

                        try:
                            model = genai.GenerativeModel("models/gemini-3.1-flash")
                            response = await asyncio.wait_for(asyncio.to_thread(model.generate_content, [prompt, video_file_ai]), timeout=120)
                            transcript = response.text.strip()
                        except Exception as e1:
                            print(f"⚠️ Model 3.1 failed: {e1}. Trying Model 2.5...", flush=True)
                            model = genai.GenerativeModel("models/gemini-2.5-flash")
                            response = await asyncio.wait_for(asyncio.to_thread(model.generate_content, [prompt, video_file_ai]), timeout=120)
                            transcript = response.text.strip()
                        
                        if c_idx == 0 and transcript and not is_remerge:
                            try:
                                summary_prompt = f"From the following recap, list main characters, key locations, and primary plot points in a single paragraph. This is for memory.\n\nTranscript:\n{transcript}"
                                summary_response = await asyncio.to_thread(model.generate_content, summary_prompt)
                                character_sheet_memory = summary_response.text.strip()
                            except: pass

                        matches = list(re.finditer(r'\[(\d{1,2}:\d{2}(?::\d{2})?(?:\.\d+)?)\s*-\s*(\d{1,2}:\d{2}(?::\d{2})?(?:\.\d+)?)\]\s*([^\[]+)', transcript))
                        if not matches and transcript.strip(): raise Exception("Timestamp Format Error")
                        break 
                    except Exception as e:
                        if attempt == max_retries - 1: raise e 
                        await asyncio.sleep(2)

                matches = list(re.finditer(r'\[(\d{1,2}:\d{2}(?::\d{2})?(?:\.\d+)?)\s*-\s*(\d{1,2}:\d{2}(?::\d{2})?(?:\.\d+)?)\]\s*([^\[]+)', transcript))
                
                def time_to_ms(time_str):
                    parts = time_str.split(':')
                    if len(parts) == 2: return int((int(parts[0])*60) * 1000 + float(parts[1])*1000)
                    elif len(parts) == 3: return int((int(parts[0])*3600 + int(parts[1])*60) * 1000 + float(parts[2])*1000)
                    return 0

                for m in matches:
                    start_str = m.group(1); end_str = m.group(2); raw_txt = m.group(3).strip()
                    clean_txt = re.sub(r'MOVIE\s*GENRE\s*:?', '', raw_txt, flags=re.IGNORECASE)
                    
                    if is_eng_mode or is_thai_mode: clean_txt = re.sub(r'[\t\n\r]+', ' ', clean_txt)
                    elif is_chinese_mode: clean_txt = re.sub(r'\s+', '', clean_txt) 
                    else: 
                        clean_txt = re.sub(r'[\u0E00-\u0E7F]+', '', clean_txt) 
                        clean_txt = re.sub(r'[\u4E00-\u9FFF]+', '', clean_txt) 
                        clean_txt = re.sub(r'[\t\n\r]+', ' ', clean_txt) 
                    
                    if clean_txt.strip():
                        ms_start = time_to_ms(start_str); ms_end = time_to_ms(end_str)
                        if ms_end <= ms_start: ms_end = ms_start + 1500 
                        parsed_lines.append({"time_ms": int(ms_start), "orig_end_ms": int(ms_end), "text": f"[{start_str} - {end_str}] {clean_txt.strip()}"})

                if not parsed_lines:
                    clean_txt = re.sub(r'MOVIE\s*GENRE\s*:?', '', transcript, flags=re.IGNORECASE)
                    clean_txt = re.sub(r'\[.*?\]|\d{1,2}:\d{2}', '', clean_txt)
                    parsed_lines.append({"time_ms": 0, "orig_end_ms": 2000, "text": clean_txt.strip()})

                chunk_data["parsed_lines"] = parsed_lines
                chunk_data["transcript"] = " ".join([l["text"] for l in parsed_lines])
                
            chunk_text = " ".join([l["text"] for l in parsed_lines])
            full_transcript_list.append(chunk_text)
            
            if parsed_lines:
                last_few_lines = [re.sub(r'\[.*?\]', '', l["text"]).strip() for l in parsed_lines[-4:]]
                previous_chunk_memory = " ".join(last_few_lines).strip()
            
            if not is_remerge:
                with open(chunk_txt_file, "w", encoding="utf-8") as f:
                    f.write(chunk_text)

            # --- 4. Generate TTS & Build Video ---
            if not is_remerge:
                jobs[job_id]["status"] = "generating_audio"
                jobs[job_id]["progress_msg"] = f"{msg_prefix}အသံနှင့် Timestamps ပေါင်းစပ်နေပါသည်..."
            
            dynamic_filter_str = ""
            tts_idx = -1
            
            if voice_toggle == "on":
                if v_check.startswith("gemini_"):
                    g_voice = VOICE_MAP.get(v_check, "Aoede"); edge_voice = g_voice; gemini_voice = g_voice
                else:
                    cfg = DUAL_VOICE_MAP.get(v_check, DUAL_VOICE_MAP["nilar"])
                    edge_voice = cfg["edge"]; gemini_voice = cfg["gemini"]

                tasks = []
                for idx, line in enumerate(parsed_lines):
                    c_id = f"{original_job_id}_{c_idx}" if is_remerge else None
                    tasks.append(process_single_line_tts(idx, line["text"], line["time_ms"], line.get("orig_end_ms", line["time_ms"]+2000), f"{job_id}_{c_idx}", v_check, edge_voice, gemini_voice, user_api_key, pitch, lang_key, tts_speed, c_id))
                
                chunk_results = await asyncio.gather(*tasks)
                chunk_results = sorted([r for r in chunk_results if r is not None], key=lambda x: x["time_ms"])
                
                if chunk_results:
                    dyn_filters = []
                    concat_labels = ""
                    seg_idx = 0
                    current_orig_time = 0.0
                    current_out_time = 0.0
                    safe_v_dur = float(c_v_dur)

                    try:
                        speed_math_map = {"1.0": 1.20, "1.15": 1.25, "1.25": 1.30, "1.30": 1.35}
                        tts_speed_float = speed_math_map.get(tts_speed, 1.20)
                    except:
                        tts_speed_float = 1.20

                    for i, res in enumerate(chunk_results):
                        orig_start = min(res['time_ms'] / 1000.0, safe_v_dur)
                        
                        if orig_start < current_orig_time:
                            orig_start = current_orig_time
                            
                        orig_end = min(res.get('orig_end_ms', res['time_ms'] + 1500) / 1000.0, safe_v_dur)
                        if orig_end <= orig_start: orig_end = min(orig_start + 1.0, safe_v_dur)
                        
                        tts_dur = res['actual_dur'] / 1000.0
                        orig_dur = orig_end - orig_start
                        if orig_dur < 0.1: orig_dur = 0.1

                        # Gap Processing
                        if orig_start > current_orig_time:
                            gap_dur = orig_start - current_orig_time
                            if gap_dur > 0.3:
                                if jumpcut_mode == "on" and gap_dur > 1.5:
                                    keep_gap = 0.5 
                                    gap_start = orig_start - keep_gap
                                    if gap_start < current_orig_time: gap_start = current_orig_time
                                    lbl = f"[vdyn_{seg_idx}]"
                                    dyn_filters.append(f"[0:v]trim=start={gap_start}:end={orig_start},setpts=PTS-STARTPTS,fps=24{lbl}")
                                    current_out_time += keep_gap
                                    concat_labels += lbl
                                    seg_idx += 1
                                else:
                                    lbl = f"[vdyn_{seg_idx}]"
                                    dyn_filters.append(f"[0:v]trim=start={current_orig_time}:end={orig_start},setpts=PTS-STARTPTS,fps=24{lbl}")
                                    current_out_time += gap_dur
                                    concat_labels += lbl
                                    seg_idx += 1
                        
                        # Speech Stretching
                        stretch_factor = tts_dur / orig_dur
                        
                        if stretch_factor < 0.95: 
                            stretch_factor = 1.0 
                        elif stretch_factor > 2.2:
                            stretch_factor = 2.2
                            
                        actual_vid_dur = orig_dur * stretch_factor
                        
                        lbl_sp = f"[vdyn_{seg_idx}]"
                        
                        if stretch_factor > 1.05:
                            dyn_filters.append(f"[0:v]trim=start={orig_start}:end={orig_end},setpts=({stretch_factor})*(PTS-STARTPTS),minterpolate=fps=24:mi_mode=blend{lbl_sp}")
                        else:
                            dyn_filters.append(f"[0:v]trim=start={orig_start}:end={orig_end},setpts=({stretch_factor})*(PTS-STARTPTS),fps=24{lbl_sp}")
                        
                        res['final_start_ms'] = int(current_out_time * 1000)
                        
                        current_out_time += actual_vid_dur
                        concat_labels += lbl_sp
                        seg_idx += 1
                        current_orig_time = orig_end

                    # Tail gap compression
                    if current_orig_time < safe_v_dur:
                        gap_dur = safe_v_dur - current_orig_time
                        if gap_dur > 0.05:
                            if jumpcut_mode == "on" and gap_dur > 1.5:
                                keep_gap = 0.5
                                gap_end = current_orig_time + keep_gap
                                lbl = f"[vdyn_{seg_idx}]"
                                dyn_filters.append(f"[0:v]trim=start={current_orig_time}:end={gap_end},setpts=PTS-STARTPTS,fps=24{lbl}")
                                current_out_time += keep_gap
                            else:
                                lbl = f"[vdyn_{seg_idx}]"
                                dyn_filters.append(f"[0:v]trim=start={current_orig_time}:end={safe_v_dur},setpts=PTS-STARTPTS,fps=24{lbl}")
                                current_out_time += gap_dur
                            concat_labels += lbl
                            seg_idx += 1

                    c_v_dur = current_out_time
                    if seg_idx > 0:
                        dyn_filters.append(f"{concat_labels}concat=n={seg_idx}:v=1:a=0[v_concat]")
                    else:
                        dyn_filters.append(f"[0:v]copy[v_concat]")
                    
                    if resolution == "720p":
                        scale_filter = "scale=-2:720,setsar=1"
                        dyn_filters.append(f"[v_concat]{scale_filter}[v_dyn_stretched]")
                    else:
                        dyn_filters.append(f"[v_concat]copy[v_dyn_stretched]")
                        
                    dynamic_filter_str = ";".join(dyn_filters) + ";"

                    mix_cmd = ["ffmpeg", "-y"]; filter_str = ""; mix_labels = ""; valid_chunks = 0
                    for i, res in enumerate(chunk_results):
                        start_ms = res.get("final_start_ms", 0)
                        mix_cmd.extend(["-i", res['path']])
                        filter_str += f"[{valid_chunks}:a]aformat=sample_rates=24000:channel_layouts=mono,adelay={int(start_ms)}|{int(start_ms)}[d{valid_chunks}];"
                        mix_labels += f"[d{valid_chunks}]"; valid_chunks += 1

                    if valid_chunks > 0:
                        if valid_chunks == 1: filter_str += f"{mix_labels}anull[a_main]"
                        else: filter_str += f"{mix_labels}amix=inputs={valid_chunks}:normalize=0[a_main]"
                        mix_cmd.extend(["-filter_complex", filter_str, "-map", "[a_main]", "-c:a", "pcm_s16le", tts_audio])
                        await run_cmd_async(mix_cmd)
                        tts_idx = 1 
            else:
                dynamic_filter_str = "[0:v]copy[v_dyn_stretched];"

            jobs[job_id]["status"] = "rendering"
            jobs[job_id]["progress_msg"] = f"{msg_prefix}ဗီဒီယို အချောသတ်နေပါသည်..."
            
            s_y_pos = float(sub_y) / 100.0 if sub_y else 0.85
            s_size = int(sub_size) * 3 if sub_size else 48
            s_color = str(sub_color).strip() if sub_color else ""
            if s_color.startswith("&H"): ass_color = s_color
            else:
                s_color = s_color.lstrip('#')
                if len(s_color) == 6: ass_color = f"&H00{s_color[4:6]}{s_color[2:4]}{s_color[0:2]}&"
                else: ass_color = "&H0000FFFF&"

            base_res = 720 if resolution == "720p" else 1080

            if ratio == "9:16":
                target_w = base_res
                target_h = int(target_w * 16 / 9)
            elif ratio == "1:1":
                target_w = base_res
                target_h = base_res
            elif ratio == "4:5":
                target_w = base_res
                target_h = int(target_w * 5 / 4)
            elif ratio == "4:3":
                target_h = base_res
                target_w = int(target_h * 4 / 3)
            else: # 16:9
                target_h = base_res
                target_w = int(target_h * 16 / 9)

            target_w = (target_w // 2) * 2
            target_h = (target_h // 2) * 2
            
            s_size = int(s_size * (target_h / 720.0))

            m_y_val = float(mask_y) / 100.0 if mask_y else 0.80
            m_h_val = float(mask_h) / 100.0 if mask_h else 0.15
            m_w_val = float(mask_w) / 100.0 if mask_w else 0.50
            crop_y = int(target_h * m_y_val); crop_h = int(target_h * m_h_val); crop_w = int(target_w * m_w_val)
            crop_x = int(target_w * (1.0 - m_w_val) / 2)
            crop_w = max(2, (crop_w // 2) * 2); crop_h = max(2, (crop_h // 2) * 2)
            crop_x = (crop_x // 2) * 2; crop_y = (crop_y // 2) * 2
            
            if crop_y + crop_h > target_h: crop_h = ((target_h - crop_y) // 2) * 2
            if crop_x + crop_w > target_w: crop_w = ((target_w - crop_x) // 2) * 2

            font_name = "Zawgyi-One"
            if is_thai_mode: font_name = "Kanit"
            elif is_chinese_mode: font_name = "Noto Sans SC"
            elif is_eng_mode: font_name = "Kanit"

            with open(sub_file, "w", encoding="utf-8") as f:
                f.write(f"[Script Info]\nScriptType: v4.00+\nPlayResX: {target_w}\nPlayResY: {target_h}\nWrapStyle: 2\nScaledBorderAndShadow: yes\n\n[V4+ Styles]\n")
                f.write("Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding\n")
                f.write(f"Style: Default,{font_name},{s_size},{ass_color},&H000000FF,&H00000000,&H99000000,-1,0,0,0,100,100,0,0,3,4,0,5,10,10,0,1\n\n[Events]\n")
                f.write("Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text\n")
                
                pos_x = target_w // 2
                pos_y = int(target_h * s_y_pos) + (int(target_h * m_h_val) // 2)
                
                def fmt_a(ms):
                    h, r = divmod(ms, 3600000); m, r = divmod(r, 60000); s, ml = divmod(r, 1000)
                    return f"{int(h)}:{int(m):02d}:{int(s):02d}.{int(ml/10):02d}"

                if voice_toggle == "on" and 'chunk_results' in locals() and chunk_results:
                    for res in chunk_results:
                        sync_start_ms = res.get("final_start_ms", 0); sync_dur_ms = res.get("actual_dur", 0); clean_text = res.get("clean_text", "")
                        if not clean_text: continue
                        if not is_thai_mode and not is_chinese_mode and not is_eng_mode:
                            try: clean_text = rabbit.Rabbit.uni2zg(clean_text)
                            except: pass
                        
                        if is_chinese_mode:
                            zh_tokens = re.findall(r"[a-zA-Z0-9]+|[^\sa-zA-Z0-9]", clean_text); short_chunks = []; temp_str = ""; count = 0
                            for tk in zh_tokens:
                                temp_str += tk; count += 1
                                if count >= 15: short_chunks.append(temp_str.strip()); temp_str = ""; count = 0
                            if temp_str: short_chunks.append(temp_str.strip())
                        elif is_thai_mode:
                            thai_chars = re.findall(r"[\u0E00-\u0E7F](?:[\u0E31-\u0E3A\u0E47-\u0E4E])*|[^\u0E00-\u0E7F\s]+", clean_text); short_chunks = []; temp_str = ""; count = 0
                            for char in thai_chars:
                                temp_str += char; count += 1
                                if count >= 20: short_chunks.append(temp_str.strip()); temp_str = ""; count = 0
                            if temp_str: short_chunks.append(temp_str.strip())
                        elif is_eng_mode: short_chunks = textwrap.wrap(clean_text, width=35)
                        else:
                            max_syllables = 12 if ratio in ["9:16", "4:5"] else 22
                            base_chars = r'\u1000-\u102A\u103F\u1040-\u1049\u104E-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u1090-\u1099\u109E\u109F'
                            pattern = f"(?:[{base_chars}][^{base_chars}\s]*)|[^\u1000-\u109F\s]+"
                            
                            words = clean_text.split()
                            short_chunks = []
                            temp_str = ""
                            
                            for w in words:
                                if not w: continue
                                syllables = re.findall(pattern, w)
                                if not syllables: syllables = [w]
                                
                                current_syl_count = len(re.findall(pattern, temp_str))
                                
                                if current_syl_count + len(syllables) > max_syllables:
                                    if temp_str: short_chunks.append(temp_str.strip())
                                    
                                    if len(syllables) > max_syllables:
                                        for i in range(0, len(syllables), max_syllables):
                                            short_chunks.append("".join(syllables[i:i+max_syllables]))
                                        temp_str = ""
                                    else:
                                        temp_str = w + " "
                                else:
                                    temp_str += w + " "
                                    
                            if temp_str:
                                short_chunks.append(temp_str.strip())
                            
                        total_chars = sum(len(c) for c in short_chunks)
                        chunk_start_ms = sync_start_ms
                        for s_chunk in short_chunks:
                            c_dur = (len(s_chunk) / max(1, total_chars)) * sync_dur_ms
                            chunk_end_ms = chunk_start_ms + c_dur
                            f.write(f"Dialogue: 0,{fmt_a(chunk_start_ms)},{fmt_a(chunk_end_ms)},Default,,0,0,0,,{{\\pos({pos_x},{pos_y})}}{s_chunk}\n")
                            chunk_start_ms += c_dur
                else:
                    for line_data in parsed_lines:
                        current_start = line_data.get("time_ms", 0); current_end = line_data.get("orig_end_ms", current_start + 2000)
                        clean_text = re.sub(r'\[.*?\]', '', line_data.get("text", "")).strip()
                        if not clean_text: continue
                        if not is_thai_mode and not is_chinese_mode and not is_eng_mode:
                            try: clean_text = rabbit.Rabbit.uni2zg(clean_text)
                            except: pass

                        if is_chinese_mode:
                            zh_tokens = re.findall(r"[a-zA-Z0-9]+|[^\sa-zA-Z0-9]", clean_text); short_chunks = []; temp_str = ""; count = 0
                            for tk in zh_tokens:
                                temp_str += tk; count += 1
                                if count >= 10: short_chunks.append(temp_str.strip()); temp_str = ""; count = 0
                            if temp_str: short_chunks.append(temp_str.strip())
                        elif is_thai_mode:
                            thai_chars = re.findall(r"[\u0E00-\u0E7F](?:[\u0E31-\u0E3A\u0E47-\u0E4E])*|[^\u0E00-\u0E7F\s]+", clean_text); short_chunks = []; temp_str = ""; count = 0
                            for char in thai_chars:
                                temp_str += char; count += 1
                                if count >= 15: short_chunks.append(temp_str.strip()); temp_str = ""; count = 0
                            if temp_str: short_chunks.append(temp_str.strip())
                        elif is_eng_mode: short_chunks = textwrap.wrap(clean_text, width=25) 
                        else:
                            max_syllables = 12 if ratio in ["9:16", "4:5"] else 22
                            base_chars = r'\u1000-\u102A\u103F\u1040-\u1049\u104E-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u1090-\u1099\u109E\u109F'
                            pattern = f"(?:[{base_chars}][^{base_chars}\s]*)|[^\u1000-\u109F\s]+"
                            
                            words = clean_text.split()
                            short_chunks = []
                            temp_str = ""
                            
                            for w in words:
                                if not w: continue
                                syllables = re.findall(pattern, w)
                                if not syllables: syllables = [w]
                                
                                current_syl_count = len(re.findall(pattern, temp_str))
                                
                                if current_syl_count + len(syllables) > max_syllables:
                                    if temp_str: short_chunks.append(temp_str.strip())
                                    
                                    if len(syllables) > max_syllables:
                                        for i in range(0, len(syllables), max_syllables):
                                            short_chunks.append("".join(syllables[i:i+max_syllables]))
                                        temp_str = ""
                                    else:
                                        temp_str = w + " "
                                else:
                                    temp_str += w + " "
                                    
                            if temp_str:
                                short_chunks.append(temp_str.strip())

                            
                        total_chars = sum(len(c) for c in short_chunks)
                        chunk_start_ms = current_start
                        for s_chunk in short_chunks:
                            c_dur = (len(s_chunk) / max(1, total_chars)) * (current_end - current_start)
                            chunk_end_ms = chunk_start_ms + c_dur - 30
                            f.write(f"Dialogue: 0,{fmt_a(chunk_start_ms)},{fmt_a(chunk_end_ms)},Default,,0,0,0,,{{\\pos({pos_x},{pos_y})}}{s_chunk}\n")
                            chunk_start_ms += c_dur

            cmd = ["ffmpeg", "-y", "-i", trim_vid]
            input_idx = 1; wm_idx = bgm_idx = ov_idx = bp_idx = -1

            if voice_toggle == "on" and os.path.exists(tts_audio):
                cmd.extend(["-itsoffset", "0", "-i", tts_audio]); tts_idx = input_idx; input_idx += 1
            if logo_toggle == "on" and wm_path and os.path.exists(wm_path): 
                cmd.extend(["-i", wm_path]); wm_idx = input_idx; input_idx += 1
            if bgm_toggle == "on" and bgm_path and os.path.exists(bgm_path): 
                cmd.extend(["-stream_loop", "-1", "-i", bgm_path]); bgm_idx = input_idx; input_idx += 1
            if ov_path and os.path.exists(ov_path): 
                cmd.extend(["-stream_loop", "-1", "-i", ov_path]); ov_idx = input_idx; input_idx += 1
            if bouncing_pip_toggle == "on" and bp_path and os.path.exists(bp_path):
                cmd.extend(["-stream_loop", "-1", "-i", bp_path]); bp_idx = input_idx; input_idx += 1

            pan_period = min(60.0, c_v_dur); pan_period = max(10.0, pan_period)
            
            pre_filters = []
            if bypass_mode in ["flip", "ultra"]: pre_filters.append("hflip")
            if bypass_mode in ["color", "ultra"]: pre_filters.append("eq=brightness=0.03:saturation=1.1")
            
            # 💡 [NEW ZOOM FIX] ရီဝေဝေဖြစ်သော Circular Pan အစား သဘာဝကျသော Cinematic Zoom-In ကို ပြောင်းလဲအသုံးပြုထားသည်
            if bypass_mode in ["zoom", "ultra"]: 
                zoom_rate = 0.15 / max(1.0, c_v_dur)
                pre_filters.append(f"zoompan=z='min(1.0+({zoom_rate:.5f}*time),1.15)':d=1:x='iw/2-(iw/zoom/2)':y='ih/2-(ih/zoom/2)':fps=24:s={target_w}x{target_h}")

            pre_filter_str = ",".join(pre_filters) if pre_filters else "copy"

            if special_effect == "split_screen" and ov_idx != -1:
                v_complex = dynamic_filter_str + f"[v_dyn_stretched]{pre_filter_str},fps=24[fg_in];"
                sz = float(overlay_size) / 100.0
                split_h = int(target_h * sz); split_h = (split_h // 2) * 2
                top_h = target_h - split_h; top_h = (top_h // 2) * 2
                v_complex += f"[fg_in]scale='max({target_w},iw*({top_h}/ih))':'max({top_h},ih*({target_w}/iw))',crop={target_w}:{top_h}:(in_w-out_w)/2:(in_h-out_h)/2,setsar=1,format=yuv420p[main_scaled];"
                v_complex += f"[{ov_idx}:v]fps=24,setpts=PTS-STARTPTS,scale='max({target_w},iw*({split_h}/ih))':'max({split_h},ih*({target_w}/iw))',crop={target_w}:{split_h}:(in_w-out_w)/2:(in_h-out_h)/2,setsar=1,format=yuv420p[bot_scaled];"
                v_complex += f"[main_scaled][bot_scaled]vstack=shortest=1[v_base];"
                current_v_node = "[v_base]"
            else:
                v_complex = dynamic_filter_str + f"[v_dyn_stretched]{pre_filter_str},fps=24,split[bg_in][fg_in];"
                v_complex += f"[bg_in]scale=160:-1,boxblur=5:1,scale={target_w}:{target_h},setsar=1[bg];"
                v_complex += f"[fg_in]scale='min({target_w},iw*({target_h}/ih))':'min({target_h},ih*({target_w}/iw))',setsar=1[fg_base];"
                v_complex += f"[bg][fg_base]overlay=(W-w)/2:(H-h)/2[v_base];"
                current_v_node = "[v_base]"

            if mask_toggle == "on":
                v_complex += (
                    f"{current_v_node}split=2[main_vid][glass_src];"
                    f"[glass_src]crop={crop_w}:{crop_h}:{crop_x}:{crop_y},boxblur=12:2,drawbox=x=0:y=0:w=iw:h=ih:color=white@0.2:t=fill[glass_eff];"
                    f"[main_vid][glass_eff]overlay=x={crop_x}:y={crop_y}[v_glass];"
                )
                current_v_node = "[v_glass]"

            if marquee_toggle == "on" and marquee_text:
                font_path = os.path.join(USER_FONT_DIR, "Zawgyi-One.ttf").replace('\\', '/')
                safe_text = marquee_text.replace("'", "").replace(":", "\\:")
                if not is_thai_mode and not is_chinese_mode and not is_eng_mode:
                    try: safe_text = rabbit.Rabbit.uni2zg(safe_text) 
                    except: pass
                mq_y = float(marquee_y) / 100.0 * target_h
                v_complex += f"{current_v_node}drawtext=fontfile='{font_path}':text='{safe_text}':fontcolor=gold:fontsize=40:box=1:boxcolor=black@0.5:boxborderw=10:y={mq_y}:x='w-mod(t*150,w+tw)'[v_mq];"
                current_v_node = "[v_mq]"

            if wm_idx != -1:
                opac = float(logo_opacity) / 100.0; sz = float(logo_size) / 100.0
                pos_map = {"top-left": "10:10", "top-right": "W-w-10:10", "bottom-left": "10:H-h-10", "bottom-right": "W-w-10:H-h-10"}
                if special_effect == "bouncing_logo": overlay_pos = "x='abs(sin(t*0.5))*(W-w)':y='abs(cos(t*0.3))*(H-h)'"
                elif logo_pos == "custom":
                    lx = float(logo_custom_x) / 100.0 * target_w; ly = float(logo_custom_y) / 100.0 * target_h
                    overlay_pos = f"x={int(lx)}:y={int(ly)}"
                else: overlay_pos = pos_map.get(logo_pos, "10:10")
                
                w_logo = int(target_w * sz) // 2 * 2
                if logo_shape == "circle": v_complex += f"[{wm_idx}:v]crop='min(in_w,in_h)':'min(in_w,in_h)',scale={w_logo}:{w_logo},setsar=1,format=rgba,geq=r='r(X,Y)':g='g(X,Y)':b='b(X,Y)':a='if(lt(pow(X-(W/2),2)+pow(Y-(H/2),2),pow(W/2,2)),255,0)',colorchannelmixer=aa={opac}[wm];{current_v_node}[wm]overlay={overlay_pos}[v_wm_out];"
                else: v_complex += f"[{wm_idx}:v]crop='min(in_w,in_h)':'min(in_w,in_h)',scale={w_logo}:{w_logo},setsar=1,format=rgba,colorchannelmixer=aa={opac}[wm];{current_v_node}[wm]overlay={overlay_pos}[v_wm_out];"
                current_v_node = "[v_wm_out]"

            if sub_toggle == "on":
                 safe_sub_file = sub_file.replace('\\', '/').replace(':', '\\:')
                 v_complex += f"{current_v_node}subtitles='{safe_sub_file}'[v_sub];"
                 current_v_node = "[v_sub]"

            if bouncing_pip_toggle == "on" and bp_idx != -1:
                bp_sz = float(bouncing_pip_size) / 100.0; bp_opac = float(bouncing_pip_opacity) / 100.0 if bouncing_pip_opacity else 1.0
                w_bp = int(target_w * bp_sz) // 2 * 2
                if bouncing_pip_shape == "circle": v_complex += f"[{bp_idx}:v]fps=24,setpts=PTS-STARTPTS,crop='min(in_w,in_h)':'min(in_w,in_h)',scale={w_bp}:{w_bp},setsar=1,format=rgba,geq=r='r(X,Y)':g='g(X,Y)':b='b(X,Y)':a='if(lt(pow(X-(W/2),2)+pow(Y-(H/2),2),pow(W/2,2)),255,0)',colorchannelmixer=aa={bp_opac}[bp];{current_v_node}[bp]overlay=x='abs(sin(t*0.5))*(W-w)':y='abs(cos(t*0.3))*(H-h)':shortest=1[v_bp_out];"
                else: v_complex += f"[{bp_idx}:v]fps=24,setpts=PTS-STARTPTS,crop='min(in_w,in_h)':'min(in_w,in_h)',scale={w_bp}:{w_bp},setsar=1,format=rgba,colorchannelmixer=aa={bp_opac}[bp];{current_v_node}[bp]overlay=x='abs(sin(t*0.5))*(W-w)':y='abs(cos(t*0.3))*(H-h)':shortest=1[v_bp_out];"
                current_v_node = "[v_bp_out]"

            if special_effect == "pip" and ov_idx != -1:
                sz = float(overlay_size) / 100.0; w_pip = int(target_w * sz) // 2 * 2
                pos_map = {"top-left": "10:10", "top-right": "W-w-10:10", "bottom-left": "10:H-h-10", "bottom-right": "W-w-10:H-h-10"}
                if pip_pos == "custom":
                    px = float(pip_custom_x) / 100.0 * target_w; py = float(pip_custom_y) / 100.0 * target_h
                    overlay_pos = f"x={int(px)}:y={int(py)}"
                else: overlay_pos = pos_map.get(pip_pos, "W-w-10:H-h-10")
                
                if pip_shape == "circle": v_complex += f"[{ov_idx}:v]fps=24,setpts=PTS-STARTPTS,crop='min(in_w,in_h)':'min(in_w,in_h)',scale={w_pip}:{w_pip},setsar=1,format=rgba,geq=r='r(X,Y)':g='g(X,Y)':b='b(X,Y)':a='if(lt(pow(X-(W/2),2)+pow(Y-(H/2),2),pow(W/2,2)),255,0)'[pip];{current_v_node}[pip]overlay={overlay_pos}:shortest=1[v_pip_out];"
                else: v_complex += f"[{ov_idx}:v]fps=24,setpts=PTS-STARTPTS,crop='min(in_w,in_h)':'min(in_w,in_h)',scale={w_pip}:{w_pip},setsar=1,format=yuva420p[pip];{current_v_node}[pip]overlay={overlay_pos}:shortest=1[v_pip_out];"
                current_v_node = "[v_pip_out]"
                
            v_complex += f"{current_v_node}copy[v_out];"

            a_complex = ""
            if tts_idx != -1:
                vol_float = float(volume) / 100.0
                if bgm_idx != -1:
                    bgm_vol_float = float(bgm_volume) / 100.0
                    a_complex = (f"[{tts_idx}:a]volume={vol_float}[a_tts];"
                                 f"[{bgm_idx}:a]aresample=44100,sidechaincompress=threshold=0.02:ratio=30:attack=10:release=200,volume={bgm_vol_float}*5[a_bgm];"
                                 f"[a_tts][a_bgm]amix=inputs=2:duration=first:dropout_transition=2:normalize=0[a_out]")
                else: a_complex = f"[{tts_idx}:a]volume={vol_float}[a_out]"
                audio_map = "[a_out]"
            else:
                if bgm_idx != -1:
                    bgm_vol_float = float(bgm_volume) / 100.0
                    a_complex = f"[0:a]volume=1.0[a_main];[{bgm_idx}:a]volume={bgm_vol_float}[a_bgm];[a_main][a_bgm]amix=inputs=2:duration=first:dropout_transition=2:normalize=0[a_out]"
                    audio_map = "[a_out]"
                else: audio_map = "0:a"

            filter_complex = v_complex + a_complex
            cmd.extend(["-filter_complex", filter_complex, "-map", "[v_out]"])
            
            cmd.extend([
                "-map", f"{audio_map}", "-c:v", "libx264", "-loglevel", "error", "-r", "24", "-crf", "24", 
                "-preset", "ultrafast", "-profile:v", "baseline", "-level", "3.0", "-pix_fmt", "yuv420p", 
                "-movflags", "+faststart", "-c:a", "aac", "-b:a", "128k", "-ar", "44100",
                "-t", str(c_v_dur), chunk_out_vid
            ])
            
            await run_cmd_async(cmd)
            completed_chunk_videos.append(chunk_out_vid)
            
        if jobs.get(job_id, {}).get("status") == "cancelled": raise Exception("လုပ်ငန်းစဉ်ကို ရပ်ဆိုင်းလိုက်ပါသည်။")
        
        jobs[job_id]["status"] = "merging"
        jobs[job_id]["progress_msg"] = "အပိုင်းများ အားလုံးကို ပြန်လည်ပေါင်းစပ်နေပါသည်..."
        
        temp_output_path = os.path.join(TMP_DIR, f"temp_final_{job_id}.mp4")
        
        if len(completed_chunk_videos) > 1:
            list_file = os.path.join(TMP_DIR, f"list_{job_id}.txt")
            with open(list_file, "w", encoding="utf-8") as f:
                for cv in completed_chunk_videos: f.write(f"file '{os.path.abspath(cv)}'\n")
            await run_cmd_async(["ffmpeg", "-y", "-f", "concat", "-safe", "0", "-i", list_file, "-c", "copy", temp_output_path])
        elif len(completed_chunk_videos) == 1:
            shutil.copy(completed_chunk_videos[0], temp_output_path)
        else:
            raise Exception("ဗီဒီယိုဖန်တီးမှု မအောင်မြင်ပါ။")

        if os.path.exists(temp_output_path):
            shutil.move(temp_output_path, output_video_path)

        total_processed_seconds = sum([min(c["duration"], v_dur_full - c["start_time"]) for c in chunks_info])
        actual_mins = int(math.ceil(total_processed_seconds / 60.0))
        if actual_mins < 1: actual_mins = 1
        
        rate = 10 if "gemini" in voice_name.lower() else 5
        
        if is_remerge:
            final_cost = 0
        else:
            final_cost = actual_mins * rate

        jobs[job_id]["status"] = "completed"
        jobs[job_id]["video_url"] = f"/download/{job_id}"
        jobs[job_id]["transcript"] = "\n\n".join(full_transcript_list)
        jobs[job_id]["final_cost"] = final_cost
        jobs[job_id]["v_dur_mins"] = actual_mins 
        jobs[job_id]["tts_type"] = "Gemini TTS" if "gemini" in voice_name.lower() else "Microsoft Edge TTS"

    except Exception as e:
        jobs[job_id]["status"] = "failed"
        if is_remerge:
            jobs[job_id]["error"] = f"အမြန်နှုန်းပြောင်းခြင်း မအောင်မြင်ပါ။ ({str(e)})"
        else:
            jobs[job_id]["error"] = str(e)
    finally:
        if video_file_ai:
            try: await asyncio.to_thread(genai.delete_file, video_file_ai.name)
            except: pass
        gc.collect()

@app.post("/adjust-speed")
async def adjust_speed(
    background_tasks: BackgroundTasks,
    job_id: str = Form(...),
    tts_speed: str = Form(...),
    x_secure_token: str = Header(None)
):
    try:
        is_valid_token = False
        if x_secure_token == BACKEND_SECRET: is_valid_token = True
        elif x_secure_token in upload_tokens:
            if time.time() <= upload_tokens[x_secure_token]:
                is_valid_token = True
                del upload_tokens[x_secure_token] 
                
        if not is_valid_token: return JSONResponse(status_code=403, content={"error": "Token မမှန်ကန်ပါ။"})
        if job_id not in jobs: return JSONResponse(status_code=404, content={"error": "မူရင်းဗီဒီယို မှတ်ဉာဏ် မရှိတော့ပါ။"})

        old_job = jobs[job_id]
        
        real_original_id = old_job.get("original_job_id") or job_id
        
        source_video = os.path.join(TMP_DIR, f"out_{real_original_id}.mp4")
        
        if not os.path.exists(source_video):
            return JSONResponse(status_code=404, content={"error": "ဆာဗာပေါ်တွင် ဗီဒီယိုအဟောင်း မရှိတော့ပါ။ (အချိန်ကျော်လွန်သွားပါသည်)"})

        new_job_id = str(uuid.uuid4())
        
        jobs[new_job_id] = {
            "status": "pending",
            "created_at": time.time(),
            "user_id": old_job.get("user_id", "default_user"),
            "transcript": old_job.get("transcript", ""),
            "original_job_id": real_original_id,
            "final_cost": 0, 
            "tts_type": "Fast Re-edit Mode",
            "v_dur_mins": 0
        }

        async def fast_ffmpeg_speed_task(n_id, src_vid, speed_str):
            jobs[n_id]["status"] = "rendering"
            jobs[n_id]["progress_msg"] = "ဗီဒီယို တစ်ခုလုံး၏ အမြန်နှုန်းကို ပြောင်းလဲနေပါသည်... (စက္ကန့်ပိုင်းသာ ကြာပါမည်)"
            
            out_vid = os.path.join(TMP_DIR, f"out_{n_id}.mp4")
            
            try:
                s_val = float(speed_str)
                if s_val <= 0: s_val = 1.15
                v_pts = 1.0 / s_val 
                
                cmd = [
                    "ffmpeg", "-y", "-i", src_vid,
                    "-filter_complex", f"[0:v]setpts={v_pts}*PTS[v];[0:a]atempo={s_val}[a]",
                    "-map", "[v]", "-map", "[a]",
                    "-c:v", "libx264", "-preset", "ultrafast", "-crf", "24",
                    out_vid
                ]
                await run_cmd_async(cmd)
                
                jobs[n_id]["status"] = "completed"
                jobs[n_id]["video_url"] = f"/download/{n_id}"
                
            except Exception as e:
                jobs[n_id]["status"] = "failed"
                jobs[n_id]["error"] = f"အမြန်နှုန်းပြောင်းလဲခြင်း မအောင်မြင်ပါ။ ({str(e)})"

        task = asyncio.create_task(fast_ffmpeg_speed_task(new_job_id, source_video, tts_speed))
        running_tasks[new_job_id] = task
        active_user_jobs[jobs[new_job_id]["user_id"]] = new_job_id
        
        return JSONResponse(content={"success": True, "job_id": new_job_id})

    except Exception as e:
        return JSONResponse(status_code=400, content={"error": f"API Error: {str(e)}"})

class MergePayload(BaseModel): job_ids: List[str]

@app.post("/merge-videos")
async def merge_cart_videos(payload: MergePayload):
    try:
        if not payload.job_ids or len(payload.job_ids) < 2: 
            return JSONResponse(status_code=400, content={"error": "အနည်းဆုံး ဗီဒီယို (၂) ခု လိုအပ်ပါသည်။"})
        
        valid_files = [os.path.join(TMP_DIR, f"out_{j_id}.mp4") for j_id in payload.job_ids if os.path.exists(os.path.join(TMP_DIR, f"out_{j_id}.mp4"))]
        if len(valid_files) < 2: 
            return JSONResponse(status_code=400, content={"error": "ဗီဒီယိုများ ရှာမတွေ့ပါ။ (အချိန်ကျော်လွန်၍ ဖျက်သွားခြင်း ဖြစ်နိုင်ပါသည်)"})
        
        m_id = str(uuid.uuid4())
        o_path = os.path.join(TMP_DIR, f"out_{m_id}.mp4")
        l_path = os.path.join(TMP_DIR, f"list_{m_id}.txt")
        
        merged_transcripts = []
        for j_id in payload.job_ids:
            if j_id in jobs and jobs[j_id].get("transcript"):
                merged_transcripts.append(jobs[j_id]["transcript"])
            else:
                for f in os.listdir(TMP_DIR):
                    if f.startswith("chunk_txt_") and f.endswith(".txt"):
                        try:
                            with open(os.path.join(TMP_DIR, f), "r", encoding="utf-8") as tf:
                                merged_transcripts.append(tf.read())
                                break
                        except: pass

        with open(l_path, "w", encoding="utf-8") as f:
            for vf in valid_files: f.write(f"file '{os.path.abspath(vf)}'\n")
            
        await run_cmd_async(["ffmpeg", "-y", "-f", "concat", "-safe", "0", "-i", l_path, "-c", "copy", o_path])
        
        final_merged_text = "\n\n=== ဇာတ်လမ်းအစအဆုံး စာသားများ ===\n\n" + "\n\n".join(merged_transcripts) if merged_transcripts else "✅ အပိုင်းများ အားလုံး ပေါင်းစပ်ပြီးပါပြီ။"

        jobs[m_id] = {
            "status": "completed", 
            "created_at": time.time(), 
            "transcript": final_merged_text
        }
        
        for vf in valid_files:
            try: os.remove(vf)
            except: pass
            
        return JSONResponse(content={"job_id": m_id, "transcript": final_merged_text})
    except Exception as e: 
        return JSONResponse(status_code=500, content={"error": f"Server Error: {str(e)}"})
        
def write_chunk_sync(chunk_file, path, mode):
    with open(path, mode) as f: shutil.copyfileobj(chunk_file, f)

@app.post("/upload-chunk")
async def upload_chunk(chunk: UploadFile = File(...), file_hash: str = Form(...), chunk_index: int = Form(...)):
    emergency_disk_cleanup()
    chunk_path = os.path.join(TMP_DIR, f"cache_{file_hash}.mp4")
    mode = "ab" if chunk_index > 0 else "wb"
    await asyncio.to_thread(write_chunk_sync, chunk.file, chunk_path, mode)
    return JSONResponse(content={"success": True})

@app.post("/delete-cache")
async def delete_cache(file_hash: str = Form(...)):
    try:
        p = os.path.join(TMP_DIR, f"cache_{file_hash}.mp4")
        if os.path.exists(p): os.remove(p) 
        gc.collect(); return JSONResponse(content={"success": True})
    except: return JSONResponse(content={"success": False})

def save_upload_sync(upload_file, path):
    with open(path, "wb") as f: shutil.copyfileobj(upload_file.file, f)

@app.post("/process-video")
async def process_video(
    background_tasks: BackgroundTasks,
    video: UploadFile = File(None), watermark: UploadFile = File(None), bgm: UploadFile = File(None), overlay_video: UploadFile = File(None),
    voice: str = Form("thiha"), api_key: str = Form(""), ratio: str = Form("16:9"), resolution: str = Form("original"),
    voice_toggle: str = Form("on"), hide_subtitle: str = Form("off"), volume: str = Form("100"), pitch: str = Form("0"),
    bypass_mode: str = Form("none"), logo_pos: str = Form("top-left"), logo_size: str = Form("5"), logo_opacity: str = Form("100"),
    custom_prompt: str = Form(""), genre: str = Form("original"), bgm_volume: str = Form("20"), target_chunk: str = Form("auto"), chunk_minutes: str = Form("2"),
    user_id: str = Form("default_user"), x_secure_token: str = Header(None), mask_toggle: str = Form("off"), mask_y: str = Form("80"),
    mask_h: str = Form("15"), mask_w: str = Form("50"), sub_toggle: str = Form("on"), sub_y: str = Form("85"), sub_size: str = Form("16"), 
    sub_color: str = Form("D4AF37"), file_hash: str = Form(""), tts_speed: str = Form("1.15"), 
    bgm_toggle: str = Form("on"), logo_toggle: str = Form("on"), logo_shape: str = Form("square"), logo_custom_x: str = Form("10"), logo_custom_y: str = Form("10"),
    special_effect: str = Form("none"), marquee_toggle: str = Form("off"), marquee_text: str = Form(""), marquee_y: str = Form("90"), pip_shape: str = Form("square"), pip_pos: str = Form("bottom-right"), overlay_size: str = Form("15"),
    pip_custom_x: str = Form("10"), pip_custom_y: str = Form("10"),
    bouncing_pip_toggle: str = Form("off"), bouncing_pip_video: UploadFile = File(None), bouncing_pip_shape: str = Form("circle"), bouncing_pip_size: str = Form("20"), bouncing_pip_opacity: str = Form("100"),
    jumpcut_mode: str = Form("off"),
    force_recreate: str = Form("false"),
    tab_mode: str = Form("translate")
):
    try:
        is_valid_token = False
        if x_secure_token == BACKEND_SECRET: is_valid_token = True
        elif x_secure_token in upload_tokens:
            if time.time() <= upload_tokens[x_secure_token]:
                is_valid_token = True; del upload_tokens[x_secure_token] 
        if not is_valid_token: return JSONResponse(status_code=403, content={"error": "Token မမှန်ကန်ပါ။"})

        emergency_disk_cleanup()
        job_id = str(uuid.uuid4())
        working_video_path = ""
        
        if user_id in active_user_jobs:
            old_job = active_user_jobs[user_id]
            if old_job in running_tasks:
                running_tasks[old_job].cancel()
                del running_tasks[old_job]
            if old_job in jobs:
                jobs[old_job]["status"] = "cancelled"
                
        if file_hash:
            cache_path = os.path.join(TMP_DIR, f"cache_{file_hash}.mp4")
            if video and video.filename:
                await asyncio.to_thread(save_upload_sync, video, cache_path)
                working_video_path = cache_path
            elif os.path.exists(cache_path): working_video_path = cache_path
            else: return JSONResponse(status_code=400, content={"error": "ဗီဒီယိုဖိုင် ရှာမတွေ့ပါ။"})
        else:
            if not video or not video.filename: return JSONResponse(status_code=400, content={"error": "ဗီဒီယိုဖိုင် လိုအပ်ပါသည်။"})
            working_video_path = os.path.join(TMP_DIR, f"temp_{job_id}_{video.filename}")
            await asyncio.to_thread(save_upload_sync, video, working_video_path)
        
        wm_path = ""; bgm_path = ""; ov_path = ""; bp_path = ""
        if watermark and watermark.filename:
            wm_path = os.path.join(TMP_DIR, f"wm_{job_id}_{watermark.filename}"); await asyncio.to_thread(save_upload_sync, watermark, wm_path)
        if bgm and bgm.filename:
            bgm_path = os.path.join(TMP_DIR, f"bgm_{job_id}_{bgm.filename}"); await asyncio.to_thread(save_upload_sync, bgm, bgm_path)
        if overlay_video and overlay_video.filename:
            ov_path = os.path.join(TMP_DIR, f"ov_{job_id}_{overlay_video.filename}"); await asyncio.to_thread(save_upload_sync, overlay_video, ov_path)
        if bouncing_pip_video and bouncing_pip_video.filename:
            bp_path = os.path.join(TMP_DIR, f"bp_{job_id}_{bouncing_pip_video.filename}"); await asyncio.to_thread(save_upload_sync, bouncing_pip_video, bp_path)

        settings = {
            "voice": voice, "api_key": api_key, "ratio": ratio, "resolution": resolution,
            "voice_toggle": voice_toggle, "hide_subtitle": hide_subtitle, "volume": volume, "pitch": pitch,
            "bypass_mode": bypass_mode, "logo_pos": logo_pos, "logo_size": logo_size, "logo_opacity": logo_opacity,
            "custom_prompt": custom_prompt, "genre": genre, "bgm_volume": bgm_volume, "target_chunk": target_chunk, "chunk_minutes": chunk_minutes,
            "mask_toggle": mask_toggle, "mask_y": mask_y, "mask_h": mask_h, "mask_w": mask_w,
            "sub_toggle": sub_toggle, "sub_y": sub_y, "sub_size": sub_size, "sub_color": sub_color,
            "tts_speed": tts_speed, "bgm_toggle": bgm_toggle, "logo_toggle": logo_toggle, "logo_shape": logo_shape,
            "logo_custom_x": logo_custom_x, "logo_custom_y": logo_custom_y, "special_effect": special_effect,
            "marquee_toggle": marquee_toggle, "marquee_text": marquee_text, "marquee_y": marquee_y,
            "pip_shape": pip_shape, "pip_pos": pip_pos, "overlay_size": overlay_size,
            "pip_custom_x": pip_custom_x, "pip_custom_y": pip_custom_y,
            "bouncing_pip_toggle": bouncing_pip_toggle, "bouncing_pip_shape": bouncing_pip_shape,
            "bouncing_pip_size": bouncing_pip_size, "bouncing_pip_opacity": bouncing_pip_opacity,
            "jumpcut_mode": jumpcut_mode, "force_recreate": force_recreate, "tab_mode": tab_mode
        }
        
        jobs[job_id] = {
            "status": "pending", "created_at": time.time(), "video_path": working_video_path, "transcript": "", 
            "user_id": user_id, "wm_path": wm_path, "bgm_path": bgm_path, "ov_path": ov_path, "bp_path": bp_path, "settings": settings
        }
        
        task = asyncio.create_task(
            wrapper_process_task(
                job_id, user_id, working_video_path, wm_path, bgm_path, ov_path, voice, api_key, ratio, resolution, voice_toggle, hide_subtitle, volume, pitch, bypass_mode, logo_pos, logo_size, logo_opacity, custom_prompt, genre, bgm_volume, target_chunk, chunk_minutes, mask_toggle, mask_y, mask_h, mask_w, sub_toggle, sub_y, sub_size, sub_color, tts_speed, bgm_toggle, logo_toggle, logo_shape, logo_custom_x, logo_custom_y, special_effect, marquee_toggle, marquee_text, marquee_y, pip_shape, pip_pos, overlay_size, pip_custom_x, pip_custom_y, bouncing_pip_toggle, bp_path, bouncing_pip_shape, bouncing_pip_size, bouncing_pip_opacity, jumpcut_mode, False, None, force_recreate, tab_mode
            )
        )
        running_tasks[job_id] = task
        active_user_jobs[user_id] = job_id
        return JSONResponse(content={"success": True, "job_id": job_id})
    except Exception as e: return JSONResponse(status_code=400, content={"error": str(e)})

@app.get("/preview-voice")
async def preview_voice(voice: str = "thiha"):
    v_name = voice.lower().strip()
    preview_path = os.path.join(TMP_DIR, f"preview_{v_name}.wav")
    if os.path.exists(preview_path): return FileResponse(preview_path, media_type="audio/wav")

    female_voices = ["nilar", "thai_female", "english_female", "chinese_female", "gemini_aoede", "gemini_kore", "gemini_leda", "gemini_autonoe", "gemini_callirrhoe", "gemini_despina", "gemini_erinome", "gemini_laomedela", "gemini_pulcherrima", "gemini_vindemiatrix"]
    name_map = {"thiha": "သီဟ", "nilar": "နီလာ"}
    display_name = name_map.get(v_name, v_name.replace("gemini_", "").capitalize())
    
    if "english" in v_name: text = "Hello, I am an English voice. Nice to meet you."
    elif "thai" in v_name: text = "สวัสดีค่ะ ดิฉันคือเสียงภาษาไทย" if v_name in female_voices else "สวัสดีครับ ผมคือเสียงภาษาไทย"
    elif "chinese" in v_name: text = "你好,我是中文语音。 很高兴认识你。"
    else: text = f"{'ကျွန်မ' if v_name in female_voices else 'ကျွန်တော်'}က {display_name} ဖြစ်ပါတယ်။ တွေ့ရတာ ဝမ်းသာပါတယ်။"

    try:
        if v_name.startswith("gemini_"):
            api_key = get_working_api_key("") 
            if not api_key: raise Exception("No API Key")
            await asyncio.to_thread(generate_gemini_tts_audio_single, text, VOICE_MAP.get(v_name, "Aoede"), api_key, preview_path)
        else: await generate_tts_audio(text, DUAL_VOICE_MAP.get(v_name, DUAL_VOICE_MAP["thiha"])["edge"], "+0%", "+0Hz", preview_path)
        if os.path.exists(preview_path): return FileResponse(preview_path, media_type="audio/wav")
    except Exception as e: return JSONResponse(status_code=500, content={"error": str(e)})
    return JSONResponse(status_code=404, content={"error": "Not generated"})

@app.post("/cancel/{job_id}")
async def cancel_job_process(job_id: str):
    if job_id in running_tasks:
        running_tasks[job_id].cancel() 
        del running_tasks[job_id]
    if job_id in jobs:
        jobs[job_id]["status"] = "cancelled"
        gc.collect()
        return JSONResponse(content={"success": True})
    return JSONResponse(status_code=404, content={"error": "Not found"})

@app.post("/delete-old-job")
async def delete_old_job(job_id: str = Form(...)):
    try:
        if job_id in running_tasks:
            running_tasks[job_id].cancel()
            del running_tasks[job_id]
        for f in os.listdir(TMP_DIR):
            if job_id in f: 
                try: os.remove(os.path.join(TMP_DIR, f))
                except: pass
        if job_id in jobs: del jobs[job_id]
        gc.collect(); return JSONResponse(content={"success": True})
    except Exception as e: return JSONResponse(status_code=500, content={"error": str(e)})    

@app.get("/status/{job_id}")
async def get_status(job_id: str):
    job_data = jobs.get(job_id, {"error": "Not found"})
    return JSONResponse(content=job_data)
    
@app.get("/download/{job_id}")
async def download_video(job_id: str):
    v_path = os.path.join(TMP_DIR, f"out_{job_id}.mp4")
    if jobs.get(job_id, {}).get("status") == "completed" and os.path.exists(v_path):
        headers = {"Content-Disposition": f'attachment; filename="Nabule_Recap_Video_{job_id[:6]}.mp4"'}
        return FileResponse(v_path, media_type="video/mp4", headers=headers)
    return JSONResponse(content={"error": "Not ready"})

@app.get("/download-audio/{job_id}")
async def download_audio(job_id: str):
    v_path = os.path.join(TMP_DIR, f"out_{job_id}.mp4")
    a_path = os.path.join(TMP_DIR, f"audio_{job_id}.mp3")
    
    if jobs.get(job_id, {}).get("status") == "completed" and os.path.exists(v_path):
        if not os.path.exists(a_path):
            await run_cmd_async(["ffmpeg", "-y", "-i", v_path, "-q:a", "0", "-map", "a", a_path])
        
        if os.path.exists(a_path):
            headers = {"Content-Disposition": f'attachment; filename="Nabule_Recap_Audio_{job_id[:6]}.mp3"'}
            return FileResponse(a_path, media_type="audio/mpeg", headers=headers)
            
    return JSONResponse(content={"error": "Audio Not ready"})

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=7860)