File size: 60,571 Bytes
97d0511
 
 
 
 
b086208
 
 
 
 
 
 
2dc3606
 
 
 
 
 
 
 
 
 
 
97d0511
 
2dc3606
97d0511
 
2dc3606
 
 
 
 
 
 
 
 
 
 
 
 
b086208
97d0511
 
 
b086208
97d0511
 
 
b086208
 
97d0511
 
 
 
 
b086208
 
97d0511
 
 
 
 
2dc3606
 
 
 
 
 
 
 
 
 
 
97d0511
2dc3606
97d0511
 
 
 
 
 
b086208
 
 
 
97d0511
 
b086208
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2dc3606
97d0511
2dc3606
97d0511
2dc3606
 
 
 
 
97d0511
 
 
2dc3606
 
97d0511
 
2dc3606
 
 
 
97d0511
 
 
 
 
2dc3606
 
 
 
97d0511
 
 
 
2dc3606
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97d0511
2dc3606
 
 
 
 
97d0511
 
2dc3606
 
 
 
 
 
97d0511
2dc3606
 
 
97d0511
 
2dc3606
 
 
97d0511
2dc3606
97d0511
 
 
 
 
 
b086208
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2dc3606
 
b086208
2dc3606
 
b086208
2dc3606
 
 
b086208
 
 
9aebeda
 
2dc3606
 
b086208
 
 
 
2dc3606
 
b086208
 
 
2dc3606
b086208
97d0511
 
2dc3606
97d0511
2dc3606
 
 
 
 
 
 
97d0511
 
2dc3606
 
97d0511
2dc3606
97d0511
2dc3606
 
 
 
 
 
 
97d0511
2dc3606
97d0511
2dc3606
b086208
97d0511
2dc3606
 
 
 
 
97d0511
2dc3606
 
97d0511
 
2dc3606
 
 
 
 
 
b086208
97d0511
 
b086208
 
 
 
 
 
 
97d0511
 
2dc3606
b086208
 
2dc3606
97d0511
 
 
 
 
2dc3606
97d0511
2dc3606
b086208
 
 
2dc3606
97d0511
b086208
2dc3606
97d0511
b086208
2dc3606
b086208
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97d0511
b086208
 
 
 
 
 
97d0511
b086208
 
 
 
97d0511
 
 
2dc3606
 
97d0511
 
2dc3606
97d0511
 
 
2dc3606
 
 
 
 
b086208
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2dc3606
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b086208
 
2dc3606
 
 
b086208
 
2dc3606
 
97d0511
2dc3606
97d0511
 
 
 
 
 
 
 
 
 
 
b086208
97d0511
 
2dc3606
b086208
2dc3606
97d0511
 
b086208
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2dc3606
 
 
b086208
2dc3606
97d0511
b086208
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97d0511
 
b086208
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97d0511
 
 
b086208
 
 
 
 
 
 
97d0511
 
b086208
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97d0511
 
b086208
 
 
 
97d0511
b086208
 
 
 
 
 
 
97d0511
b086208
 
 
 
 
97d0511
b086208
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2dc3606
b086208
 
 
 
 
 
 
 
 
 
 
 
 
 
97d0511
 
b086208
97d0511
 
 
 
 
 
 
 
7a407b5
 
97d0511
 
 
b086208
 
97d0511
 
 
 
9aebeda
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
"""
LTX-2.3 Turbo — ZeroGPU Edition
Generates synchronized audio-video content using Lightricks/LTX-2.3 on
free ZeroGPU hardware via Hugging Face Spaces.

UI inspired by alexnasa/ltx-2-TURBO with full feature parity for LTX-2.3:
  - Image-to-Video mode (first frame conditioning)
  - Interpolate mode (first + last frame)
  - Audio input (user provides audio for lip-sync/soundtrack)
  - Custom UI components (RadioAnimated, PromptBox, CameraDropdown, AudioDropUpload)
  - Duration presets (2s, 3s, 5s) and resolution selector with SVG icons

Architecture (following alexnasa/ltx-2-TURBO's proven ZeroGPU pattern):
  1. Vendored ltx-core and ltx-pipelines added to sys.path before any imports.
  2. Model files downloaded at module startup (CPU, no GPU lease).
  3. ModelLedger constructed at module level (CPU-only dataclass, no CUDA init).
  4. Text encoder loaded at module level (kept in memory for reuse).
  5. DistilledPipeline constructed with gemma_root=None (no text encoder in pipeline).
  6. Video encoder and transformer pre-loaded at module level via pipeline cache.
  7. @spaces.GPU() on encode_prompt — encodes text, returns .detach().cpu() tensors.
  8. @spaces.GPU(duration=callable) on generate_video — runs pipeline with pre-encoded
     contexts passed as video_context/audio_context kwargs.
  9. FP8 quantization fits the 22B transformer on ZeroGPU's A10G (40GB VRAM).

Based on the official LTX-2 codebase: https://github.com/Lightricks/LTX-2
Architecture inspired by alexnasa/ltx-2-TURBO.
"""

# ───────────────────────────────────────────────────────────────────────────
# 0) Add vendored packages to sys.path BEFORE any ltx imports
# ───────────────────────────────────────────────────────────────────────────
import sys
from pathlib import Path

_here = Path(__file__).parent
sys.path.insert(0, str(_here / "packages" / "ltx-pipelines" / "src"))
sys.path.insert(0, str(_here / "packages" / "ltx-core" / "src"))

# ───────────────────────────────────────────────────────────────────────────
# Standard library & third-party imports
# ───────────────────────────────────────────────────────────────────────────
import json
import logging
import os
import random
import subprocess
import tempfile
import time
import traceback
import uuid
from typing import Any

import gradio as gr
import numpy as np
import spaces
import torch
import torch.nn.functional as F
import torchaudio
from huggingface_hub import hf_hub_download, snapshot_download

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

# ───────────────────────────────────────────────────────────────────────────
# LTX imports (from vendored packages)
# ───────────────────────────────────────────────────────────────────────────
from ltx_core.model.video_vae import TilingConfig
from ltx_core.quantization import QuantizationPolicy
from ltx_pipelines.distilled import DistilledPipeline
from ltx_pipelines.utils import ModelLedger
from ltx_pipelines.utils.args import ImageConditioningInput
from ltx_pipelines.utils.helpers import generate_enhanced_prompt

# ───────────────────────────────────────────────────────────────────────────
# Constants
# ───────────────────────────────────────────────────────────────────────────
MAX_SEED = np.iinfo(np.int32).max
LTX_REPO = "Lightricks/LTX-2.3"
GEMMA_REPO = "google/gemma-3-12b-it-qat-q4_0-unquantized"
CKPT_DISTILLED = "ltx-2.3-22b-distilled.safetensors"
CKPT_UPSCALER = "ltx-2.3-spatial-upscaler-x2-1.0.safetensors"

RESOLUTION_MAP = {
    "16:9": (768, 512),
    "1:1": (512, 512),
    "9:16": (512, 768),
}


# ───────────────────────────────────────────────────────────────────────────
# Audio helper functions (ported from alexnasa/ltx-2-TURBO)
# ───────────────────────────────────────────────────────────────────────────
def _coerce_audio_path(audio_path: Any) -> str:
    """Handle Gradio's various audio path formats (tuple, dict, string)."""
    if isinstance(audio_path, tuple) and len(audio_path) > 0:
        audio_path = audio_path[0]
    if isinstance(audio_path, dict):
        audio_path = audio_path.get("name") or audio_path.get("path")
    if not isinstance(audio_path, (str, bytes, os.PathLike)):
        raise TypeError(
            f"audio_path must be a path-like, got {type(audio_path)}: {audio_path}"
        )
    return os.fspath(audio_path)


def match_audio_to_duration(
    audio_path: str,
    target_seconds: float,
    target_sr: int = 48000,
    to_mono: bool = True,
    pad_mode: str = "silence",
    device: str = "cuda",
):
    """
    Load audio, resample, (optionally) mono, then trim/pad to exactly target_seconds.
    Returns: (waveform tensor, sample_rate)
    """
    audio_path = _coerce_audio_path(audio_path)
    wav, sr = torchaudio.load(audio_path)  # [C, T] float32 CPU

    if sr != target_sr:
        wav = torchaudio.functional.resample(wav, sr, target_sr)
        sr = target_sr

    if to_mono and wav.shape[0] > 1:
        wav = wav.mean(dim=0, keepdim=True)

    target_len = int(round(target_seconds * sr))
    cur_len = wav.shape[-1]

    if cur_len > target_len:
        wav = wav[..., :target_len]
    elif cur_len < target_len:
        pad_len = target_len - cur_len
        if pad_mode == "repeat" and cur_len > 0:
            reps = (target_len + cur_len - 1) // cur_len
            wav = wav.repeat(1, reps)[..., :target_len]
        else:
            wav = F.pad(wav, (0, pad_len))

    wav = wav.to(device, non_blocking=True)
    return wav, sr


# ───────────────────────────────────────────────────────────────────────────
# 1) Download model files at module startup (CPU, no GPU lease)
# ───────────────────────────────────────────────────────────────────────────
logger.info("Downloading LTX model files...")
checkpoint_path = hf_hub_download(repo_id=LTX_REPO, filename=CKPT_DISTILLED)
logger.info(f"  Distilled checkpoint: {checkpoint_path}")

spatial_upsampler_path = hf_hub_download(repo_id=LTX_REPO, filename=CKPT_UPSCALER)
logger.info(f"  Upscaler: {spatial_upsampler_path}")

logger.info("Downloading Gemma text encoder...")
HF_TOKEN = os.environ.get("HF_TOKEN")
gemma_root = snapshot_download(repo_id=GEMMA_REPO, token=HF_TOKEN)
logger.info(f"  Gemma root: {gemma_root}")
logger.info("All model files ready on disk.")

# ───────────────────────────────────────────────────────────────────────────
# 2) Construct ModelLedger (CPU — no model weights loaded to GPU)
# ───────────────────────────────────────────────────────────────────────────
logger.info("Constructing ModelLedger (with Gemma for text encoding)...")

fp8_quantization = QuantizationPolicy.fp8_cast()

model_ledger = ModelLedger(
    dtype=torch.bfloat16,
    device="cuda",
    checkpoint_path=checkpoint_path,
    gemma_root_path=gemma_root,
    spatial_upsampler_path=spatial_upsampler_path,
    loras=(),
    quantization=fp8_quantization,
)

logger.info("ModelLedger constructed.")

# ───────────────────────────────────────────────────────────────────────────
# 3) Load text encoder at module level (kept in memory for reuse)
# ───────────────────────────────────────────────────────────────────────────
logger.info("Loading Gemma text encoder...")
text_encoder = model_ledger.text_encoder()
logger.info("Text encoder loaded and ready!")

# ───────────────────────────────────────────────────────────────────────────
# 4) Construct DistilledPipeline WITHOUT text encoder (gemma_root=None)
# ───────────────────────────────────────────────────────────────────────────
logger.info("Constructing DistilledPipeline (gemma_root=None)...")

pipeline = DistilledPipeline(
    device=torch.device("cuda"),
    checkpoint_path=checkpoint_path,
    spatial_upsampler_path=spatial_upsampler_path,
    gemma_root=None,
    loras=[],
    quantization=fp8_quantization,
)

# ───────────────────────────────────────────────────────────────────────────
# 5) Pre-load video encoder and transformer at module level
# ───────────────────────────────────────────────────────────────────────────
logger.info("Pre-loading video encoder and transformer...")
pipeline._video_encoder = pipeline.model_ledger.video_encoder()
pipeline._transformer = pipeline.model_ledger.transformer()

logger.info("=" * 60)
logger.info("Pipeline fully loaded and ready!")
logger.info("=" * 60)


# ───────────────────────────────────────────────────────────────────────────
# Helpers
# ───────────────────────────────────────────────────────────────────────────
def calc_frames(duration: float, fps: float) -> int:
    """Compute num_frames = 8k + 1, frames >= 9."""
    raw = int(duration * fps) + 1
    raw = max(raw, 9)
    k = (raw - 1 + 7) // 8
    return k * 8 + 1


def encode_text_simple(te, prompt: str):
    """Simple text encoding without using pipeline_utils."""
    hidden_states, attention_mask = te.encode(prompt)
    embeddings_processor = model_ledger.gemma_embeddings_processor()
    result = embeddings_processor.process_hidden_states(hidden_states, attention_mask)
    del embeddings_processor
    return result.video_encoding, result.audio_encoding


def apply_resolution(resolution: str):
    w, h = RESOLUTION_MAP.get(resolution, (768, 512))
    return int(w), int(h)


def apply_duration(duration_str: str):
    return int(duration_str[:-1])


def on_mode_change(selected: str):
    is_interpolate = selected == "Interpolate"
    return gr.update(visible=is_interpolate)


def get_duration(
    first_frame,
    end_frame,
    prompt,
    duration,
    generation_mode,
    enhance_prompt,
    seed,
    randomize_seed,
    height,
    width,
    audio_path,
    *args,
    **kwargs,
):
    """Estimate GPU lease duration for @spaces.GPU(duration=...)."""
    extra_time = 0
    if audio_path is not None:
        extra_time += 10

    dur = float(duration)
    if dur <= 2:
        return 120 + extra_time
    elif dur <= 3:
        return 150 + extra_time
    else:
        return 200 + extra_time


# ───────────────────────────────────────────────────────────────────────────
# Phase 1: Text Encoding (separate GPU lease)
# ───────────────────────────────────────────────────────────────────────────
@spaces.GPU()
def encode_prompt(
    prompt: str,
    enhance_prompt: bool = True,
    input_image=None,
    seed: int = 42,
):
    """
    Encode prompt using the module-level text_encoder + embeddings_processor.
    Returns a dict with video_context and audio_context tensors on CPU.
    """
    logger.info(f"[encode_prompt] prompt='{prompt[:80]}...', enhance={enhance_prompt}")

    final_prompt = prompt
    if enhance_prompt:
        final_prompt = generate_enhanced_prompt(
            text_encoder=text_encoder,
            prompt=prompt,
            image_path=input_image if input_image is not None else None,
            seed=seed,
        )
        logger.info(f"[encode_prompt] Enhanced prompt: '{final_prompt[:120]}...'")

    with torch.inference_mode():
        video_context, audio_context = encode_text_simple(text_encoder, final_prompt)

    embedding_data = {
        "video_context": video_context.detach().cpu(),
        "audio_context": audio_context.detach().cpu(),
        "prompt": final_prompt,
    }

    logger.info("[encode_prompt] Done.")
    return embedding_data, final_prompt


# ───────────────────────────────────────────────────────────────────────────
# Phase 2: Video Generation (separate GPU lease, dynamic duration)
# ───────────────────────────────────────────────────────────────────────────
@spaces.GPU(duration=get_duration)
def generate_video(
    first_frame,
    end_frame,
    prompt: str,
    duration: float,
    generation_mode: str = "Image-to-Video",
    enhance_prompt: bool = True,
    seed: int = 42,
    randomize_seed: bool = True,
    height: int = 512,
    width: int = 768,
    audio_path=None,
    progress=gr.Progress(track_tqdm=True),
):
    """
    Full generation: encode prompt then run pipeline with pre-encoded contexts.
    Supports Image-to-Video, Interpolate, and audio input modes.
    """
    if not prompt or not prompt.strip():
        raise gr.Error("Please enter a prompt.")

    current_seed = random.randint(0, MAX_SEED) if randomize_seed else int(seed)
    num_frames = calc_frames(duration, 24.0)
    frame_rate = 24.0

    logger.info(
        f"[generate_video] mode={generation_mode}, seed={current_seed}, {width}x{height}, "
        f"frames={num_frames}, duration={duration}s, enhance={enhance_prompt}, "
        f"audio={'yes' if audio_path else 'no'}"
    )

    # --- Handle input images ---
    images = []
    image_path_for_enhance = None

    if first_frame is not None:
        # first_frame is filepath from gr.Image(type="filepath")
        if isinstance(first_frame, str):
            img_path = first_frame
        else:
            tmp_dir = tempfile.mkdtemp()
            img_path = os.path.join(tmp_dir, f"input_{int(time.time())}.png")
            if hasattr(first_frame, "save"):
                first_frame.save(img_path)
            else:
                from PIL import Image as PILImage

                PILImage.open(first_frame).save(img_path)

        images.append((img_path, 0, 1.0))
        image_path_for_enhance = img_path

    # Interpolation: add end frame as guiding latent
    if generation_mode == "Interpolate" and end_frame is not None:
        if isinstance(end_frame, str):
            end_path = end_frame
        else:
            tmp_dir = tempfile.mkdtemp()
            end_path = os.path.join(tmp_dir, f"end_{int(time.time())}.png")
            if hasattr(end_frame, "save"):
                end_frame.save(end_path)
            else:
                from PIL import Image as PILImage

                PILImage.open(end_frame).save(end_path)

        end_idx = max(0, num_frames - 1)
        images.append((end_path, end_idx, 0.5))

    t0 = time.time()
    try:
        # Phase 1: Encode prompt
        embeddings, final_prompt = encode_prompt(
            prompt=prompt,
            enhance_prompt=enhance_prompt,
            input_image=image_path_for_enhance,
            seed=current_seed,
        )

        video_context = embeddings["video_context"].to("cuda", non_blocking=True)
        audio_context = embeddings["audio_context"].to("cuda", non_blocking=True)
        del embeddings
        torch.cuda.empty_cache()

        # If user provided audio, use a neutral audio_context (encode empty prompt)
        if audio_path is not None:
            with torch.inference_mode():
                _, neutral_audio_context = encode_text_simple(text_encoder, "")
            del audio_context
            audio_context = neutral_audio_context

        # Prepare audio waveform if provided
        input_waveform = None
        input_waveform_sample_rate = None
        if audio_path is not None:
            video_seconds = (num_frames - 1) / frame_rate
            input_waveform, input_waveform_sample_rate = match_audio_to_duration(
                audio_path=audio_path,
                target_seconds=video_seconds,
                target_sr=48000,
                to_mono=True,
                pad_mode="silence",
                device="cuda",
            )

        torch.cuda.empty_cache()

        # Phase 2: Run pipeline with pre-encoded contexts
        with tempfile.NamedTemporaryFile(suffix=".mp4", delete=False) as tmpfile:
            output_path = tmpfile.name

        with torch.inference_mode():
            pipeline(
                prompt=prompt,
                output_path=output_path,
                seed=current_seed,
                height=height,
                width=width,
                num_frames=num_frames,
                frame_rate=frame_rate,
                images=images,
                tiling_config=TilingConfig.default(),
                video_context=video_context,
                audio_context=audio_context,
                input_waveform=input_waveform,
                input_waveform_sample_rate=input_waveform_sample_rate,
            )

        del video_context, audio_context
        if input_waveform is not None:
            del input_waveform
        torch.cuda.empty_cache()

        elapsed = time.time() - t0
        logger.info(f"[generate_video] Done in {elapsed:.1f}s")

    except torch.cuda.OutOfMemoryError:
        elapsed = time.time() - t0
        logger.error(f"OOM after {elapsed:.1f}s")
        raise gr.Error("Out of GPU memory. Try a shorter duration or lower resolution.")
    except Exception as e:
        elapsed = time.time() - t0
        tb = traceback.format_exc()
        logger.error(f"Generation failed after {elapsed:.1f}s:\n{tb}")
        raise gr.Error(f"Generation failed: {type(e).__name__}: {e}")

    return str(output_path)


# ───────────────────────────────────────────────────────────────────────────
# Custom UI Components (ported from alexnasa/ltx-2-TURBO)
# ───────────────────────────────────────────────────────────────────────────


class RadioAnimated(gr.HTML):
    """Animated segmented radio (like iOS pill selector)."""

    def __init__(self, choices, value=None, **kwargs):
        if not choices or len(choices) < 2:
            raise ValueError("RadioAnimated requires at least 2 choices.")
        if value is None:
            value = choices[0]

        uid = uuid.uuid4().hex[:8]
        group_name = f"ra-{uid}"

        inputs_html = "\n".join(
            f'<input class="ra-input" type="radio" name="{group_name}" '
            f'id="{group_name}-{i}" value="{c}">'
            f'<label class="ra-label" for="{group_name}-{i}">{c}</label>'
            for i, c in enumerate(choices)
        )

        html_template = f"""
        <div class="ra-wrap" data-ra="{uid}">
          <div class="ra-inner">
            <div class="ra-highlight"></div>
            {inputs_html}
          </div>
        </div>
        """

        js_on_load = r"""
        (() => {
            const wrap = element.querySelector('.ra-wrap');
            const inner = element.querySelector('.ra-inner');
            const highlight = element.querySelector('.ra-highlight');
            const inputs = Array.from(element.querySelectorAll('.ra-input'));
            const labels = Array.from(element.querySelectorAll('.ra-label'));
            if (!inputs.length || !labels.length) return;
            const choices = inputs.map(i => i.value);
            const PAD = 6;
            let currentIdx = 0;
            function setHighlightByIndex(idx) {
                currentIdx = idx;
                const lbl = labels[idx];
                if (!lbl) return;
                const innerRect = inner.getBoundingClientRect();
                const lblRect = lbl.getBoundingClientRect();
                highlight.style.width = `${lblRect.width}px`;
                const x = (lblRect.left - innerRect.left - PAD);
                highlight.style.transform = `translateX(${x}px)`;
            }
            function setCheckedByValue(val, shouldTrigger=false) {
                const idx = Math.max(0, choices.indexOf(val));
                inputs.forEach((inp, i) => { inp.checked = (i === idx); });
                requestAnimationFrame(() => setHighlightByIndex(idx));
                props.value = choices[idx];
                if (shouldTrigger) trigger('change', props.value);
            }
            setCheckedByValue(props.value ?? choices[0], false);
            inputs.forEach((inp) => {
                inp.addEventListener('change', () => setCheckedByValue(inp.value, true));
            });
            window.addEventListener('resize', () => setHighlightByIndex(currentIdx));
            let last = props.value;
            const syncFromProps = () => {
              if (props.value !== last) {
                last = props.value;
                setCheckedByValue(last, false);
              }
              requestAnimationFrame(syncFromProps);
            };
            requestAnimationFrame(syncFromProps);
        })();
        """

        super().__init__(
            value=value,
            html_template=html_template,
            js_on_load=js_on_load,
            **kwargs,
        )


class PromptBox(gr.HTML):
    """Prompt textarea with an internal footer slot for embedding dropdowns."""

    def __init__(self, value="", placeholder="Describe what you want...", **kwargs):
        uid = uuid.uuid4().hex[:8]

        html_template = f"""
        <div class="ds-card" data-ds="{uid}">
          <div class="ds-top">
            <textarea class="ds-textarea" rows="3" placeholder="{placeholder}"></textarea>
            <div class="ds-footer" aria-label="prompt-footer"></div>
          </div>
        </div>
        """

        js_on_load = r"""
        (() => {
          const textarea = element.querySelector(".ds-textarea");
          if (!textarea) return;
          const autosize = () => {
            textarea.style.height = "0px";
            textarea.style.height = Math.min(textarea.scrollHeight, 240) + "px";
          };
          const setValue = (v, triggerChange=false) => {
            const val = (v ?? "");
            if (textarea.value !== val) textarea.value = val;
            autosize();
            props.value = textarea.value;
            if (triggerChange) trigger("change", props.value);
          };
          setValue(props.value, false);
          textarea.addEventListener("input", () => {
            autosize();
            props.value = textarea.value;
            trigger("change", props.value);
          });
          const shouldAutoFocus = () => {
            const ae = document.activeElement;
            if (ae && ae !== document.body && ae !== document.documentElement) return false;
            if (window.matchMedia && window.matchMedia("(max-width: 768px)").matches) return false;
            return true;
          };
          const focusWithRetry = (tries = 30) => {
            if (!shouldAutoFocus()) return;
            if (document.activeElement !== textarea) textarea.focus({ preventScroll: true });
            if (document.activeElement === textarea) return;
            if (tries > 0) requestAnimationFrame(() => focusWithRetry(tries - 1));
          };
          requestAnimationFrame(() => focusWithRetry());
          let last = props.value;
          const syncFromProps = () => {
            if (props.value !== last) {
              last = props.value;
              setValue(last, false);
            }
            requestAnimationFrame(syncFromProps);
          };
          requestAnimationFrame(syncFromProps);
        })();
        """

        super().__init__(
            value=value,
            html_template=html_template,
            js_on_load=js_on_load,
            **kwargs,
        )


class CameraDropdown(gr.HTML):
    """Custom dropdown with optional icons per item."""

    def __init__(self, choices, value="None", title="Dropdown", **kwargs):
        if not choices:
            raise ValueError("CameraDropdown requires choices.")

        norm = []
        for c in choices:
            if isinstance(c, dict):
                label = str(c.get("label", c.get("value", "")))
                val = str(c.get("value", label))
                icon = c.get("icon", None)
                norm.append({"label": label, "value": val, "icon": icon})
            else:
                s = str(c)
                norm.append({"label": s, "value": s, "icon": None})

        uid = uuid.uuid4().hex[:8]

        def render_item(item):
            icon_html = ""
            if item["icon"]:
                icon_html = f'<span class="cd-icn">{item["icon"]}</span>'
            return (
                f'<button type="button" class="cd-item" '
                f'data-value="{item["value"]}">'
                f'{icon_html}<span class="cd-label">{item["label"]}</span>'
                f"</button>"
            )

        items_html = "\n".join(render_item(item) for item in norm)

        html_template = f"""
        <div class="cd-wrap" data-cd="{uid}">
            <button type="button" class="cd-trigger" aria-haspopup="menu" aria-expanded="false">
              <span class="cd-trigger-icon"></span>
              <span class="cd-trigger-text"></span>
              <span class="cd-caret">&#x25BE;</span>
            </button>
          <div class="cd-menu" role="menu" aria-hidden="true">
            <div class="cd-title">{title}</div>
            <div class="cd-items">
              {items_html}
            </div>
          </div>
        </div>
        """

        value_to_label = {it["value"]: it["label"] for it in norm}
        value_to_icon = {it["value"]: (it["icon"] or "") for it in norm}

        js_on_load = r"""
        (() => {
          const wrap = element.querySelector(".cd-wrap");
          const trigger = element.querySelector(".cd-trigger");
          const triggerIcon = element.querySelector(".cd-trigger-icon");
          const triggerText = element.querySelector(".cd-trigger-text");
          const menu = element.querySelector(".cd-menu");
          const items = Array.from(element.querySelectorAll(".cd-item"));
          if (!wrap || !trigger || !menu || !items.length) return;
          const valueToLabel = __VALUE_TO_LABEL__;
          const valueToIcon  = __VALUE_TO_ICON__;
          const safeLabel = (v) => (valueToLabel && valueToLabel[v]) ? valueToLabel[v] : (v ?? "None");
          const safeIcon  = (v) => (valueToIcon  && valueToIcon[v])  ? valueToIcon[v]  : "";
          function closeMenu() {
            menu.classList.remove("open");
            trigger.setAttribute("aria-expanded", "false");
            menu.setAttribute("aria-hidden", "true");
          }
          function openMenu() {
            menu.classList.add("open");
            trigger.setAttribute("aria-expanded", "true");
            menu.setAttribute("aria-hidden", "false");
          }
          function setValue(val, shouldTrigger = false) {
            const v = (val ?? "None");
            props.value = v;
            triggerText.textContent = safeLabel(v);
            if (triggerIcon) {
              triggerIcon.innerHTML = safeIcon(v);
              triggerIcon.style.display = safeIcon(v) ? "inline-flex" : "none";
            }
            items.forEach(btn => {
              btn.dataset.selected = (btn.dataset.value === v) ? "true" : "false";
            });
            if (shouldTrigger) trigger("change", props.value);
          }
          trigger.addEventListener("pointerdown", (e) => {
            e.preventDefault();
            e.stopPropagation();
            if (menu.classList.contains("open")) closeMenu();
            else openMenu();
          });
          document.addEventListener("pointerdown", (e) => {
            if (!wrap.contains(e.target)) closeMenu();
          }, true);
          document.addEventListener("keydown", (e) => {
            if (e.key === "Escape") closeMenu();
          });
          wrap.addEventListener("focusout", (e) => {
            if (!wrap.contains(e.relatedTarget)) closeMenu();
          });
          items.forEach((btn) => {
            btn.addEventListener("pointerdown", (e) => {
              e.preventDefault();
              e.stopPropagation();
              closeMenu();
              setValue(btn.dataset.value, true);
            });
          });
          setValue((props.value ?? "None"), false);
          let last = props.value;
          const syncFromProps = () => {
            if (props.value !== last) {
              last = props.value;
              setValue(last, false);
            }
            requestAnimationFrame(syncFromProps);
          };
          requestAnimationFrame(syncFromProps);
        })();
        """

        js_on_load = js_on_load.replace(
            "__VALUE_TO_LABEL__", json.dumps(value_to_label)
        )
        js_on_load = js_on_load.replace("__VALUE_TO_ICON__", json.dumps(value_to_icon))

        super().__init__(
            value=value,
            html_template=html_template,
            js_on_load=js_on_load,
            **kwargs,
        )


class AudioDropUpload(gr.HTML):
    """Custom audio drop/click UI that proxies file into a hidden gr.File component."""

    def __init__(self, target_audio_elem_id: str, value=None, **kwargs):
        uid = uuid.uuid4().hex[:8]

        html_template = f"""
        <div class="aud-wrap" data-aud="{uid}">
          <div class="aud-drop" role="button" tabindex="0" aria-label="Upload audio">
            <div><strong>(Optional) Drag &amp; drop an audio file here</strong></div>
            <div class="aud-hint">...or click to browse</div>
          </div>
          <div class="aud-row" aria-live="polite">
            <audio class="aud-player" controls></audio>
            <button class="aud-remove" type="button" aria-label="Remove audio">
              <svg width="16" height="16" viewBox="0 0 24 24" aria-hidden="true" focusable="false">
                <path d="M18 6L6 18M6 6l12 12"
                      stroke="currentColor" stroke-width="2.25" stroke-linecap="round"/>
              </svg>
            </button>
          </div>
          <div class="aud-filelabel"></div>
        </div>
        """

        js_on_load = """
        (() => {{
          function grRoot() {{
            const ga = document.querySelector("gradio-app");
            return (ga && ga.shadowRoot) ? ga.shadowRoot : document;
          }}
          const root = grRoot();
          const wrap = element.querySelector(".aud-wrap");
          const drop = element.querySelector(".aud-drop");
          const row  = element.querySelector(".aud-row");
          const player = element.querySelector(".aud-player");
          const removeBtn = element.querySelector(".aud-remove");
          const label = element.querySelector(".aud-filelabel");
          const TARGET_ID = "__TARGET_ID__";
          let currentUrl = null;
          function findHiddenAudioFileInput() {{
            const host = root.querySelector("#" + CSS.escape(TARGET_ID));
            if (!host) return null;
            const inp = host.querySelector('input[type="file"]');
            return inp;
          }}
          function showDrop() {{
            drop.style.display = "";
            row.style.display = "none";
            label.style.display = "none";
            label.textContent = "";
          }}
          function showPlayer(filename) {{
            drop.style.display = "none";
            row.style.display = "flex";
            if (filename) {{
              label.textContent = "Loaded: " + filename;
              label.style.display = "block";
            }}
          }}
          function clearPreview() {{
            player.pause();
            player.removeAttribute("src");
            player.load();
            if (currentUrl) {{
              URL.revokeObjectURL(currentUrl);
              currentUrl = null;
            }}
          }}
          function clearHiddenGradioAudio() {{
            const fileInput = findHiddenAudioFileInput();
            if (!fileInput) return;
            fileInput.value = "";
            const dt = new DataTransfer();
            fileInput.files = dt.files;
            fileInput.dispatchEvent(new Event("input",  {{ bubbles: true }}));
            fileInput.dispatchEvent(new Event("change", {{ bubbles: true }}));
          }}
          function clearAll() {{
            clearPreview();
            clearHiddenGradioAudio();
            props.value = "__CLEAR__";
            trigger("change", props.value);
            showDrop();
          }}
          function loadFileToPreview(file) {{
            if (!file) return;
            if (!file.type || !file.type.startsWith("audio/")) {{
              alert("Please choose an audio file.");
              return;
            }}
            clearPreview();
            currentUrl = URL.createObjectURL(file);
            player.src = currentUrl;
            showPlayer(file.name);
          }}
          function pushFileIntoHiddenGradioAudio(file) {{
            const fileInput = findHiddenAudioFileInput();
            if (!fileInput) {{
              console.warn("Could not find hidden gr.File input. Check elem_id:", TARGET_ID);
              return;
            }}
            fileInput.value = "";
            const dt = new DataTransfer();
            dt.items.add(file);
            fileInput.files = dt.files;
            fileInput.dispatchEvent(new Event("input",  {{ bubbles: true }}));
            fileInput.dispatchEvent(new Event("change", {{ bubbles: true }}));
          }}
          function handleFile(file) {{
            loadFileToPreview(file);
            pushFileIntoHiddenGradioAudio(file);
          }}
          const localPicker = document.createElement("input");
          localPicker.type = "file";
          localPicker.accept = "audio/*";
          localPicker.style.display = "none";
          wrap.appendChild(localPicker);
          localPicker.addEventListener("change", () => {{
            const f = localPicker.files && localPicker.files[0];
            if (f) handleFile(f);
            localPicker.value = "";
          }});
          drop.addEventListener("click", () => localPicker.click());
          drop.addEventListener("keydown", (e) => {{
            if (e.key === "Enter" || e.key === " ") {{
              e.preventDefault();
              localPicker.click();
            }}
          }});
          removeBtn.addEventListener("click", clearAll);
          ["dragenter","dragover","dragleave","drop"].forEach(evt => {{
            drop.addEventListener(evt, (e) => {{
              e.preventDefault();
              e.stopPropagation();
            }});
          }});
          drop.addEventListener("dragover", () => drop.classList.add("dragover"));
          drop.addEventListener("dragleave", () => drop.classList.remove("dragover"));
          drop.addEventListener("drop", (e) => {{
            drop.classList.remove("dragover");
            const f = e.dataTransfer.files && e.dataTransfer.files[0];
            if (f) handleFile(f);
          }});
          showDrop();
          function setPreviewFromPath(path) {{
            if (path === "__CLEAR__") path = null;
            if (!path) {{
              clearPreview();
              showDrop();
              return;
            }}
            let url = path;
            if (!/^https?:\\/\\//.test(path) && !path.startsWith("gradio_api/file=") && !path.startsWith("/file=")) {{
              url = "gradio_api/file=" + path;
            }}
            clearPreview();
            player.src = url;
            showPlayer(path.split("/").pop());
          }}
          let last = props.value;
          const syncFromProps = () => {{
            const v = props.value;
            if (v !== last) {{
              last = v;
              if (!v || v === "__CLEAR__") setPreviewFromPath(null);
              else setPreviewFromPath(String(v));
            }}
            requestAnimationFrame(syncFromProps);
          }};
          requestAnimationFrame(syncFromProps);
        }})();
        """
        js_on_load = js_on_load.replace("__TARGET_ID__", target_audio_elem_id)

        super().__init__(
            value=value,
            html_template=html_template,
            js_on_load=js_on_load,
            **kwargs,
        )


# ───────────────────────────────────────────────────────────────────────────
# CSS (dark theme, ported from alexnasa/ltx-2-TURBO)
# ───────────────────────────────────────────────────────────────────────────
CSS = """
/* ---- layout ---- */
#controls-row {
  display: none !important;
  align-items: center;
  gap: 12px;
  flex-wrap: nowrap;
}
#controls-row > * {
  flex: 0 0 auto !important;
  width: auto !important;
  min-width: 0 !important;
}
#col-container {
  margin: 0 auto;
  max-width: 1600px;
}
#step-column {
  padding: 10px;
  border-radius: 8px;
  box-shadow: var(--card-shadow);
  margin: 10px;
}

/* ---- generate button ---- */
.button-gradient {
  background: linear-gradient(45deg, rgb(255, 65, 108), rgb(255, 75, 43), rgb(255, 155, 0), rgb(255, 65, 108)) 0% 0% / 400% 400%;
  border: none;
  padding: 14px 28px;
  font-size: 16px;
  font-weight: bold;
  color: white;
  border-radius: 10px;
  cursor: pointer;
  transition: 0.3s ease-in-out;
  animation: 2s linear 0s infinite normal none running gradientAnimation;
  box-shadow: rgba(255, 65, 108, 0.6) 0px 4px 10px;
}
@keyframes gradientAnimation {
  0% { background-position: 0% 50%; }
  50% { background-position: 100% 50%; }
  100% { background-position: 0% 50%; }
}

/* ---- mode row ---- */
#mode-row {
  display: flex !important;
  justify-content: center !important;
  align-items: center !important;
  width: 100% !important;
}
#mode-row > * {
  flex: 0 0 auto !important;
  width: auto !important;
  min-width: 0 !important;
}
#mode-row .gr-html,
#mode-row .gradio-html,
#mode-row .prose,
#mode-row .block {
  width: auto !important;
  flex: 0 0 auto !important;
  display: inline-block !important;
}
#radioanimated_mode {
  display: inline-flex !important;
  justify-content: center !important;
  width: auto !important;
}

/* ---- radioanimated ---- */
.ra-wrap { width: fit-content; }
.ra-inner {
  position: relative;
  display: inline-flex;
  align-items: center;
  gap: 0;
  padding: 6px;
  background: #0b0b0b;
  border-radius: 9999px;
  overflow: hidden;
  user-select: none;
}
.ra-input { display: none; }
.ra-label {
  position: relative;
  z-index: 2;
  padding: 10px 18px;
  font-family: ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, Arial;
  font-size: 14px;
  font-weight: 600;
  color: rgba(255,255,255,0.7);
  cursor: pointer;
  transition: color 180ms ease;
  white-space: nowrap;
}
.ra-highlight {
  position: absolute;
  z-index: 1;
  top: 6px;
  left: 6px;
  height: calc(100% - 12px);
  border-radius: 9999px;
  background: #8bff97;
  transition: transform 200ms ease, width 200ms ease;
}
.ra-input:checked + .ra-label { color: rgba(0,0,0,0.75); }

/* ---- prompt box ---- */
.ds-card {
  width: 100%;
  max-width: 720px;
  margin: 0 auto;
  position: relative;
  z-index: 50;
}
.ds-top {
  position: relative;
  background: #2b2b2b;
  border: 1px solid rgba(255,255,255,0.12);
  border-radius: 14px;
  overflow: visible !important;
}
.ds-textarea {
  width: 100%;
  box-sizing: border-box;
  background: transparent !important;
  border: none !important;
  border-radius: 0 !important;
  color: rgba(255,255,255,0.9);
  padding: 14px 16px;
  padding-bottom: 72px;
  outline: none;
  font-family: ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, Arial;
  font-size: 15px;
  line-height: 1.35;
  resize: none;
  min-height: 210px;
  max-height: 210px;
  overflow-y: auto;
  scrollbar-width: none;
  position: relative;
  z-index: 1;
}
.ds-textarea::-webkit-scrollbar { width: 0; height: 0; }
.ds-textarea:focus,
.ds-textarea:focus-visible { outline: none !important; box-shadow: none !important; }
.ds-textarea { outline: none !important; }
.ds-top:focus-within {
  border-color: rgba(255,255,255,0.22) !important;
  box-shadow: 0 0 0 3px rgba(255,255,255,0.06) !important;
  border-radius: 14px !important;
}
.ds-top { border-radius: 14px !important; }
.ds-top::after {
  content: "";
  position: absolute;
  left: 0; right: 0; bottom: 0;
  height: 56px;
  background: #2b2b2b;
  border-bottom-left-radius: 14px !important;
  border-bottom-right-radius: 14px !important;
  pointer-events: none;
  z-index: 2;
}
.ds-footer {
  position: absolute;
  right: 12px;
  bottom: 10px;
  display: flex;
  gap: 8px;
  align-items: center;
  justify-content: flex-end;
  z-index: 20 !important;
}
.ds-footer .cd-trigger {
  min-height: 32px;
  padding: 6px 10px;
  font-size: 12px;
  gap: 6px;
  border-radius: 9999px;
}
.ds-footer .cd-trigger-icon,
.ds-footer .cd-icn { width: 14px; height: 14px; }
.ds-footer .cd-trigger-icon svg,
.ds-footer .cd-icn svg { width: 14px; height: 14px; }
.ds-footer .cd-caret { font-size: 11px; }
.ds-footer .cd-menu { z-index: 999999 !important; }

/* ---- camera dropdown ---- */
.cd-wrap { position: relative; display: inline-block; }
.cd-trigger {
  margin-top: 2px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
  border: none;
  box-sizing: border-box;
  padding: 10px 18px;
  min-height: 52px;
  line-height: 1.2;
  border-radius: 9999px;
  background: #0b0b0b;
  font-family: ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, Arial;
  font-size: 14px;
  color: rgba(255,255,255,0.7) !important;
  font-weight: 600 !important;
  cursor: pointer;
  user-select: none;
  white-space: nowrap;
}
.cd-trigger .cd-trigger-text,
.cd-trigger .cd-caret { color: rgba(255,255,255,0.7) !important; }
.cd-caret { opacity: 0.8; font-weight: 900; }
.cd-trigger-icon {
  color: rgba(255,255,255,0.9);
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 18px; height: 18px;
}
.cd-trigger-icon svg { width: 18px; height: 18px; display: block; }
.cd-menu {
  position: absolute;
  top: calc(100% + 4px);
  left: 0;
  min-width: 240px;
  background: #2b2b2b !important;
  border: 1px solid rgba(255,255,255,0.14) !important;
  border-radius: 14px;
  box-shadow: 0 18px 40px rgba(0,0,0,0.35);
  padding: 10px;
  opacity: 0;
  transform: translateY(-6px);
  pointer-events: none;
  transition: opacity 160ms ease, transform 160ms ease;
  z-index: 9999;
}
.cd-menu.open {
  opacity: 1;
  transform: translateY(0);
  pointer-events: auto;
}
.cd-title {
  font-size: 12px;
  font-weight: 600;
  text-transform: uppercase;
  letter-spacing: 0.04em;
  color: rgba(255,255,255,0.55) !important;
  margin-bottom: 6px;
  padding: 0 6px;
  pointer-events: none;
}
.cd-items { display: flex; flex-direction: column; gap: 0px; }
.cd-item {
  width: 100%;
  text-align: left;
  border: none;
  background: transparent;
  color: rgba(255,255,255,0.92) !important;
  padding: 8px 34px 8px 12px;
  border-radius: 10px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 700;
  position: relative;
  transition: background 120ms ease;
  display: flex;
  align-items: center;
  gap: 10px;
}
.cd-item * { color: rgba(255,255,255,0.92) !important; }
.cd-item:hover { background: rgba(255,255,255,0.10) !important; }
.cd-item::after {
  content: "\\2713";
  position: absolute;
  right: 12px;
  top: 50%;
  transform: translateY(-50%);
  opacity: 0;
  transition: opacity 120ms ease;
  color: rgba(255,255,255,0.92) !important;
  font-weight: 900;
}
.cd-item[data-selected="true"]::after { opacity: 1; }
.cd-item.selected {
  background: transparent !important;
  border: none !important;
}
.cd-icn {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 18px; height: 18px;
  flex: 0 0 18px;
}
.cd-icn svg { width: 18px; height: 18px; display: block; }
.cd-icn svg * { stroke: rgba(255,255,255,0.9); }
.cd-label { flex: 1; }
.cd-trigger, .cd-trigger * { color: rgba(255,255,255,0.75) !important; }

/* ---- AudioDropUpload ---- */
.aud-wrap { width: 100%; max-width: 720px; }
.aud-drop {
  border: 2px dashed var(--body-text-color-subdued);
  border-radius: 16px;
  padding: 18px;
  text-align: center;
  cursor: pointer;
  user-select: none;
  color: var(--body-text-color);
  background: var(--block-background-fill);
}
.aud-drop.dragover {
  border-color: rgba(255,255,255,0.35);
  background: rgba(255,255,255,0.06);
}
.aud-hint {
  color: var(--body-text-color-subdued);
  font-size: 0.95rem;
  margin-top: 6px;
}
.aud-row {
  display: none;
  align-items: center;
  gap: 10px;
  background: #0b0b0b;
  border-radius: 9999px;
  padding: 8px 10px;
}
.aud-player {
  flex: 1;
  width: 100%;
  height: 34px;
  border-radius: 9999px;
}
.aud-remove {
  appearance: none;
  border: none;
  background: transparent;
  color: rgba(255,255,255);
  cursor: pointer;
  width: 36px; height: 36px;
  border-radius: 9999px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  padding: 0;
  transition: background 120ms ease, color 120ms ease, opacity 120ms ease;
  opacity: 0.9;
  flex: 0 0 auto;
}
.aud-remove:hover {
  background: rgba(255,255,255,0.08);
  color: rgb(255,255,255);
  opacity: 1;
}
.aud-filelabel {
  margin: 10px 6px 0;
  color: var(--body-text-color-subdued);
  font-size: 0.95rem;
  display: none;
}
#audio_input_hidden { display: none !important; }
"""


# ───────────────────────────────────────────────────────────────────────────
# SVG icons for resolution dropdown
# ───────────────────────────────────────────────────────────────────────────
ICON_16_9 = """<svg viewBox="0 0 24 24" fill="none" aria-hidden="true">
  <rect x="3" y="7" width="18" height="10" rx="2" stroke="currentColor" stroke-width="2"/>
</svg>"""

ICON_1_1 = """<svg viewBox="0 0 24 24" fill="none" aria-hidden="true">
  <rect x="6" y="6" width="12" height="12" rx="2" stroke="currentColor" stroke-width="2"/>
</svg>"""

ICON_9_16 = """<svg viewBox="0 0 24 24" fill="none" aria-hidden="true">
  <rect x="7" y="3" width="10" height="18" rx="2" stroke="currentColor" stroke-width="2"/>
</svg>"""


# ───────────────────────────────────────────────────────────────────────────
# Gradio UI
# ───────────────────────────────────────────────────────────────────────────
with gr.Blocks(title="LTX-2.3 Turbo", css=CSS) as demo:
    gr.HTML(
        """
        <div style="text-align: center;">
            <p style="font-size:16px; display: inline; margin: 0;">
                <strong>LTX-2.3 Turbo</strong> &mdash; 22B DiT audio-video model on free ZeroGPU
            </p>
            <a href="https://huggingface.co/Lightricks/LTX-2.3"
               target="_blank" rel="noopener noreferrer"
               style="display: inline-block; vertical-align: middle; margin-left: 0.5em;">
                [model]
            </a>
            <a href="https://github.com/Lightricks/LTX-2"
               target="_blank" rel="noopener noreferrer"
               style="display: inline-block; vertical-align: middle; margin-left: 0.5em;">
                [github]
            </a>
        </div>
        <div style="text-align: center; margin-top: 4px;">
            <strong>HF Space by:</strong>
            <a href="https://huggingface.co/ZeroCollabs" target="_blank" rel="noopener noreferrer"
               style="display: inline-block; vertical-align: middle; margin-left: 0.5em;">
                <img src="https://img.shields.io/badge/%F0%9F%A4%97-Follow%20on%20HF-green.svg" alt="Follow on HF">
            </a>
            <a href="https://github.com/ZeroHackz" target="_blank" rel="noopener noreferrer"
               style="display: inline-block; vertical-align: middle; margin-left: 0.5em;">
                <img src="https://img.shields.io/badge/GitHub-Follow-181717?logo=github" alt="Follow on GitHub">
            </a>
        </div>
        """
    )

    with gr.Column(elem_id="col-container"):
        # ---- Mode selector ----
        with gr.Row(elem_id="mode-row"):
            radioanimated_mode = RadioAnimated(
                choices=["Image-to-Video", "Interpolate"],
                value="Image-to-Video",
                elem_id="radioanimated_mode",
            )

        with gr.Row():
            # ---- Left column: controls ----
            with gr.Column(elem_id="step-column"):
                with gr.Row():
                    first_frame = gr.Image(
                        label="First Frame (Optional)",
                        type="filepath",
                        height=256,
                    )
                    end_frame = gr.Image(
                        label="Last Frame (Optional)",
                        type="filepath",
                        height=256,
                        visible=False,
                    )

                # JS relocator: moves duration & resolution dropdowns into prompt footer
                relocate = gr.HTML(
                    value="",
                    html_template="<div></div>",
                    js_on_load=r"""
                    (() => {
                      function moveIntoFooter() {
                        const promptRoot = document.querySelector("#prompt_ui");
                        if (!promptRoot) return false;
                        const footer = promptRoot.querySelector(".ds-footer");
                        if (!footer) return false;
                        const dur = document.querySelector("#duration_ui .cd-wrap");
                        const res = document.querySelector("#resolution_ui .cd-wrap");
                        if (!dur || !res) return false;
                        footer.appendChild(dur);
                        footer.appendChild(res);
                        return true;
                      }
                      const tick = () => {
                        if (!moveIntoFooter()) requestAnimationFrame(tick);
                      };
                      requestAnimationFrame(tick);
                    })();
                    """,
                )

                prompt_ui = PromptBox(
                    value="A golden retriever puppy plays in fresh snow, tossing it up with its paws, soft winter sunlight, gentle wind sounds and playful barking",
                    elem_id="prompt_ui",
                )

                # Hidden real audio input (backend value)
                audio_input = gr.File(
                    label="Audio (Optional)",
                    file_types=["audio"],
                    type="filepath",
                    elem_id="audio_input_hidden",
                )

                # Custom audio UI that feeds the hidden gr.File
                audio_ui = AudioDropUpload(
                    target_audio_elem_id="audio_input_hidden",
                    elem_id="audio_ui",
                )

                # Hidden prompt textbox (synced from PromptBox)
                prompt = gr.Textbox(
                    label="Prompt",
                    value="A golden retriever puppy plays in fresh snow, tossing it up with its paws, soft winter sunlight, gentle wind sounds and playful barking",
                    lines=3,
                    max_lines=3,
                    visible=False,
                )

                enhance_prompt = gr.Checkbox(
                    label="Enhance Prompt",
                    value=True,
                    visible=False,
                )

                with gr.Accordion("Advanced Settings", open=False, visible=False):
                    seed = gr.Slider(
                        label="Seed",
                        minimum=0,
                        maximum=MAX_SEED,
                        value=42,
                        step=1,
                    )
                    randomize_seed = gr.Checkbox(label="Randomize Seed", value=True)

            # ---- Right column: output + hidden controls ----
            with gr.Column(elem_id="step-column"):
                output_video = gr.Video(
                    label="Generated Video", autoplay=True, height=512
                )

                with gr.Row(elem_id="controls-row"):
                    duration_ui = CameraDropdown(
                        choices=["2s", "3s", "5s"],
                        value="2s",
                        title="Clip Duration",
                        elem_id="duration_ui",
                    )
                    duration = gr.Slider(
                        label="Duration (seconds)",
                        minimum=1.0,
                        maximum=5.0,
                        value=2.0,
                        step=0.1,
                        visible=False,
                    )

                    resolution_ui = CameraDropdown(
                        choices=[
                            {"label": "16:9", "value": "16:9", "icon": ICON_16_9},
                            {"label": "1:1", "value": "1:1", "icon": ICON_1_1},
                            {"label": "9:16", "value": "9:16", "icon": ICON_9_16},
                        ],
                        value="16:9",
                        title="Resolution",
                        elem_id="resolution_ui",
                    )

                    width = gr.Number(
                        label="Width", value=768, precision=0, visible=False
                    )
                    height = gr.Number(
                        label="Height", value=512, precision=0, visible=False
                    )

                generate_btn = gr.Button(
                    "Generate Video",
                    variant="primary",
                    elem_classes="button-gradient",
                )

    # ────────────────────────────────────────────────────────────────────
    # Event wiring
    # ────────────────────────────────────────────────────────────────────

    # Mode selector -> show/hide end_frame
    radioanimated_mode.change(
        fn=on_mode_change,
        inputs=radioanimated_mode,
        outputs=[end_frame],
        api_visibility="private",
    )

    # Duration dropdown -> hidden slider
    duration_ui.change(
        fn=apply_duration,
        inputs=duration_ui,
        outputs=[duration],
        api_visibility="private",
    )

    # Resolution dropdown -> hidden width/height
    resolution_ui.change(
        fn=apply_resolution,
        inputs=resolution_ui,
        outputs=[width, height],
        api_visibility="private",
    )

    # PromptBox -> hidden textbox
    prompt_ui.change(
        fn=lambda x: x,
        inputs=prompt_ui,
        outputs=prompt,
        api_visibility="private",
    )

    # Audio UI clear handler
    def on_audio_ui_change(v):
        if v == "__CLEAR__" or v is None or v == "":
            return None
        return gr.update()

    audio_ui.change(
        fn=on_audio_ui_change,
        inputs=audio_ui,
        outputs=audio_input,
        api_visibility="private",
    )

    # Generate button
    generate_btn.click(
        fn=generate_video,
        inputs=[
            first_frame,
            end_frame,
            prompt,
            duration,
            radioanimated_mode,
            enhance_prompt,
            seed,
            randomize_seed,
            height,
            width,
            audio_input,
        ],
        outputs=[output_video],
    )

    # ---- Footer ----
    gr.Markdown(
        """
        ---
        **Notes:**
        - ZeroGPU provides limited GPU time per request. Shorter durations are more reliable.
        - Max duration is capped at 5 seconds to stay within GPU time limits.
        - FP8 quantization reduces VRAM usage by ~50% with minimal quality impact.
        - The 2x spatial upscaler doubles the initial generation resolution.
        - This Space uses [google/gemma-3-12b-it-qat-q4_0-unquantized](https://huggingface.co/google/gemma-3-12b-it-qat-q4_0-unquantized) as the text encoder.
          If you duplicate this Space, you must first accept the [Gemma license](https://huggingface.co/google/gemma-3-12b-it-qat-q4_0-unquantized) on your HuggingFace account.

        Built with [Lightricks/LTX-2.3](https://huggingface.co/Lightricks/LTX-2.3)
        | [GitHub](https://github.com/Lightricks/LTX-2)
        | Space by [ZeroCollabs](https://huggingface.co/ZeroCollabs)
        | [GitHub](https://github.com/ZeroHackz)
        """
    )

if __name__ == "__main__":
    demo.launch(show_error=True)