File size: 118,458 Bytes
bbbbc0b
 
 
 
731d4fc
c977a06
bbbbc0b
c977a06
 
 
bbbbc0b
c1cbf61
bbbbc0b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f7f09ad
 
bbbbc0b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40ddddb
 
 
bbbbc0b
 
 
 
 
 
 
3cd4c9d
 
bbbbc0b
 
 
3cd4c9d
 
bbbbc0b
 
 
 
 
 
 
 
 
 
 
 
40ddddb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bbbbc0b
 
 
 
 
 
 
 
 
 
 
 
 
 
731d4fc
 
 
bbbbc0b
 
 
 
 
 
 
731d4fc
bbbbc0b
 
c977a06
bbbbc0b
 
 
731d4fc
 
bbbbc0b
 
 
 
731d4fc
 
 
 
 
 
 
 
bbbbc0b
 
1acc2f3
 
c977a06
 
 
 
 
 
 
 
 
c1cbf61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c977a06
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bbbbc0b
 
 
 
 
 
 
 
 
c977a06
 
 
bbbbc0b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c977a06
bbbbc0b
 
f7f09ad
 
 
 
bbbbc0b
f7f09ad
 
c977a06
 
f7f09ad
c977a06
f7f09ad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c977a06
f7f09ad
 
cded1e5
 
 
 
 
 
 
 
 
 
 
 
 
3cd4c9d
 
cded1e5
 
 
 
 
 
3cd4c9d
 
cded1e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f7f09ad
731d4fc
 
f7f09ad
 
c977a06
f7f09ad
731d4fc
f7f09ad
c977a06
bbbbc0b
 
f7f09ad
731d4fc
 
f7f09ad
bbbbc0b
c977a06
731d4fc
 
 
 
 
 
 
 
f7f09ad
1acc2f3
 
c977a06
f7f09ad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bbbbc0b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c1cbf61
bbbbc0b
 
 
 
 
 
 
 
c977a06
bbbbc0b
 
 
c977a06
c1cbf61
bbbbc0b
 
 
 
c977a06
 
 
bbbbc0b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c977a06
bbbbc0b
 
c977a06
 
 
c1cbf61
bbbbc0b
 
 
 
 
 
 
 
 
 
 
 
1acc2f3
 
 
c1cbf61
bbbbc0b
 
 
 
 
 
 
c977a06
c1cbf61
 
 
 
 
 
 
 
 
c977a06
 
 
 
bbbbc0b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
731d4fc
 
 
 
bbbbc0b
 
 
c977a06
 
 
731d4fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bbbbc0b
 
c977a06
 
 
c1cbf61
1acc2f3
 
 
 
 
 
 
bbbbc0b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c977a06
 
 
 
bbbbc0b
 
 
f7f09ad
bbbbc0b
 
 
 
 
 
 
c977a06
 
 
 
c1cbf61
bbbbc0b
c1cbf61
 
 
 
 
 
 
 
bbbbc0b
 
c1cbf61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c977a06
c1cbf61
bbbbc0b
 
 
 
 
 
 
 
 
 
 
c977a06
c1cbf61
1acc2f3
 
 
 
 
c1cbf61
 
 
 
 
bbbbc0b
c1cbf61
731d4fc
f7f09ad
731d4fc
 
 
 
bbbbc0b
731d4fc
 
 
 
bbbbc0b
731d4fc
 
 
 
1acc2f3
 
 
 
 
 
 
 
 
c1cbf61
c977a06
1acc2f3
bbbbc0b
 
c977a06
 
bbbbc0b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f7f09ad
cded1e5
f7f09ad
cded1e5
 
 
 
 
 
f7f09ad
cded1e5
f7f09ad
cded1e5
f7f09ad
cded1e5
 
 
f7f09ad
 
bbbbc0b
 
 
 
 
 
f7f09ad
 
 
bbbbc0b
 
 
 
 
 
 
c1cbf61
bbbbc0b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f7f09ad
bbbbc0b
 
 
 
 
731d4fc
 
 
 
 
 
 
bbbbc0b
 
c1cbf61
1acc2f3
 
 
 
bbbbc0b
 
 
f7f09ad
 
 
 
bbbbc0b
 
 
 
 
 
 
c977a06
3cd4c9d
bbbbc0b
 
c977a06
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c1cbf61
c977a06
c1cbf61
 
 
 
 
 
c977a06
 
 
bbbbc0b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3cd4c9d
bbbbc0b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cded1e5
 
 
f7f09ad
cded1e5
 
 
f7f09ad
cded1e5
 
 
 
 
 
bbbbc0b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cded1e5
 
bbbbc0b
 
 
 
cded1e5
 
 
 
bbbbc0b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
"""MiniMax-H3 `t2va` / `fl2va`, split deployment β€” the denoising half."""

from __future__ import annotations

import glob
import json
import os
import re
import shutil
import struct
import tempfile
import threading
import time
import traceback
from functools import cache

# Before anything that could initialize CUDA: `import spaces` patches `torch.cuda` so the 72 GiB load can happen at
# startup rather than on GPU time.
import spaces
import gradio as gr

MODEL_REPO = os.environ.get("H3_MODEL_REPO", "MiniMaxAI/MiniMax-H3")
CONDITIONER_SPACE = os.environ.get("H3_CONDITIONER", "multimodalart/qwen3vl-conditioner")
# `pack` places the transformer at startup, `lazy` moves everything on the first GPU call, `offload` hands placement to
# `ComponentsManager.enable_auto_cpu_offload`.
PLACEMENT = os.environ.get("H3_PLACEMENT", "pack").lower()
# cuDNN's fused attention is 10-20% faster than the SDPA default on this pool and needs nothing installed.
ATTENTION = os.environ.get("H3_ATTENTION", "_native_cudnn").lower()
GPU_SIZE = os.environ.get("H3_GPU_SIZE", "xlarge")

# larryvrh distillation LoRA (diffusers conversion): A/B factors stored on CPU, merged on-demand inside @spaces.GPU.
TURBO_LORA_REPO = os.environ.get("H3_TURBO_LORA", "InstantX/MiniMax-H3-Turbo-Lora-Diffusers")
TURBO_LORA_FILE = "minimax_h3_turbo_4step_ckpt500_diffusers.safetensors"
TURBO_LORA_SCALE = 1.0  # alpha == rank

# NSFW / anatomy LoRAs (ComfyUI format, converted at load). Lazy: downloaded + converted on CPU in generate(),
# merged on GPU inside @spaces.GPU only when selected. Standard LoRA only β€” LoKR (.lokr_w1/.lokr_w2) is unsupported.
NSFW_LORA_CONFIGS = {
    "nsfw_innie": {
        "repo": "Hearmeman/minimax-h3-loras",
        "file": "HMInnie_v1_e50.safetensors",
        "scale": 1.0,
        "label": "NSFW Innie Pussy (HMInnie V1)",
        "trigger": "inniepussy",
        "desc": "Renders the vulva as a neat 'innie' β€” labia tucked in with no protruding inner lips. Use for close-up genital shots where you want a clean, compact vulva look. Not for scenes needing prominent outer labia or detailed pussy anatomy β€” pair with HMPussy for that.",
    },
    "nsfw_penis": {
        "repo": "observantdistressed/plora-h3",  # CivitAI "Penis Lora - H3" v1.1, mirrored to HF
        "file": "PLORA_H3_V2-step00006300.safetensors",
        "scale": 0.7,
        "label": "NSFW Penis (Penis Lora - H3 v1.1)",
        "trigger": "PENISLORA",
        "format": "kohya",
        "desc": "Adds a detailed, erect penis to male subjects β€” the core anatomy LoRA for any scene with a visible penis. Use whenever a penis is in frame. Not for solo female scenes, and don't stack it with HMPenis v2.0 (same purpose, conflicting weights).",
    },
    "nsfw_dildo": {
        "repo": "EllaPriest45/MinimaxH3_Actions",  # CivitAI "Dildoing" model 2903074, backup repo
        "file": "Dildoing - MinimaxH3 - pumping a dildo insider her vagina.safetensors",
        "scale": 0.7,
        "label": "NSFW Dildoing (Dildo Insertion)",
        "trigger": "pumping a dildo insider her vagina",
        "desc": "Makes dildo insertion read naturally β€” the toy slides into the vagina with proper depth and motion instead of clipping or floating. Use for any dildo penetration scene. Not for scenes without a dildo, and don't combine it with other insertion LoRAs at full strength.",
    },
    # Motion/action adapter β€” auto-loaded (not user-selectable) whenever any anatomy LoRA is on, so the
    # anatomy renders sharply AND the act moves naturally. The Hearmeman README says to stack anatomy
    # adapters underneath this action adapter.
    "nsfw_aio": {
        "repo": "Hearmeman/minimax-h3-loras",
        "file": "HMNSFW-AIO-V2.5.safetensors",
        "scale": 0.7,
        "label": "HMNSFW AIO V2.5 (motion)",
        "trigger": "hmmotion",
        "desc": "Motion/action adapter that makes anatomy LoRAs move naturally during sex acts β€” auto-loaded whenever any NSFW LoRA is selected. Use stacked underneath anatomy LoRAs for sharp rendering plus natural motion. Not for standalone use; it's a motion enhancer, not an anatomy fix.",
    },
    # ── EllaPriest45/MinimaxH3_Actions catalog (t2va-compatible, standard LoRA only) ──
    # 93 LoRAs, classified by header inspection: 80 ComfyUI + 13 kohya. LoKR, I2V, REF2V, R2V, FL2VA excluded.
    # Triggers/scales extracted from the CivitAI filenames (best effort β€” refine per-LoRA as needed).
    'nsfw_ahegao_face': {
        "repo": "EllaPriest45/MinimaxH3_Actions",
        "file": 'Ahegao Face - MinimaxH3 - She is making the ahegao face - eyes rolled back and tongue hanging out.safetensors',
        "scale": 0.7,
        "label": 'Ahegao Face',
        "trigger": 'ahegao face',
        "desc": "Makes the subject's face contort into the ahegao expression β€” eyes rolled back, tongue hanging out β€” for intense reaction shots. Use during orgasm or overstimulation scenes. Not for normal expressions or dialogue scenes; it overrides the face.",
    },
    'nsfw_all_tied_up': {
        "repo": "EllaPriest45/MinimaxH3_Actions",
        "file": 'All Tied Up - MinimaxH3 - 0.8str.safetensors',
        "scale": 0.8,
        "label": 'All Tied Up',
        "trigger": 'all tied up',
        "desc": "Renders the subject bound and restrained, with rope or ties visible and functional. Use for bondage and restraint scenes. Not for scenes where the subject needs to move freely; it locks them into restraint poses.",
    },
    'nsfw_astro_nsfw': {
        "repo": "EllaPriest45/MinimaxH3_Actions",
        "file": 'Astro NSFW - MinimaxH3 - improves human movement and anatomy.safetensors',
        "scale": 0.7,
        "label": 'Astro NSFW',
        "trigger": 'astro nsfw',
        "format": "kohya",
        "desc": "General NSFW quality enhancer that improves human movement and anatomy in explicit scenes. Use as a base layer on top of specific anatomy or act LoRAs. Not a specific act LoRA β€” don't expect it to produce a particular act on its own.",
    },
    'nsfw_auto_cunnilingus': {
        "repo": "EllaPriest45/MinimaxH3_Actions",
        "file": 'Auto-Cunnilingus - MinimaxH3 - She performs oral sex on herself.She licks her vulva.safetensors',
        "scale": 0.7,
        "label": 'Auto-Cunnilingus',
        "trigger": 'She performs oral sex on herself.She licks her vulva',
        "desc": "Makes the subject perform oral sex on herself β€” licking her own vulva. Use for self-cunnilingus scenes. Not for partnered cunnilingus; that's a different act with its own LoRAs.",
    },
    'nsfw_beanflk_masturbation_finger_insertion_au': {
        "repo": "EllaPriest45/MinimaxH3_Actions",
        "file": 'BEANFLK - Masturbation & Finger Insertion + Audio - MinimaxH3 - BEANFLK,0.4str.safetensors',
        "scale": 0.4,
        "label": 'BEANFLK - Masturbation & Finger Insertion + Audio',
        "trigger": 'BEANFLK',
        "desc": "Masturbation with finger insertion, plus audio cues for the act. Use for solo fingering scenes. Not for scenes without finger penetration; the audio may not fit non-masturbation content.",
    },
    'nsfw_bunny_general_motion_continuity_repair': {
        "repo": "EllaPriest45/MinimaxH3_Actions",
        "file": 'BUNNY General Motion Continuity Repair - MinimaxH3 - for dynamic scenes,bunny_crisp_motion,resmultistep+simple,euler+beta,0.9str,stage1,0.6str,stage2,0.25str.safetensors',
        "scale": 0.9,
        "label": 'BUNNY General Motion Continuity Repair',
        "trigger": 'bunny_crisp_motion',
        "desc": "Repairs motion continuity in dynamic scenes β€” reduces warping and keeps movement coherent across frames. Use for fast-action or high-motion shots. Not for slow, static scenes where it adds little.",
    },
    'nsfw_better_motion': {
        "repo": "EllaPriest45/MinimaxH3_Actions",
        "file": 'Better Motion - MinimaxH3 - 720x1280,15-30steps,0.2-0.4str.safetensors',
        "scale": 0.3,
        "label": 'Better Motion',
        "trigger": 'better motion',
        "desc": "General motion-quality LoRA that makes movement smoother and more natural. Use as a base enhancer for any scene. Not for specific acts; it's a motion polish, not an action generator.",
    },
    'nsfw_better_titfuck_v0_95': {
        "repo": "EllaPriest45/MinimaxH3_Actions",
        "file": 'Better Titfuck v0.95 - MinimaxH3 - res_multistep+simple,titjob,titfuck.safetensors',
        "scale": 0.7,
        "label": 'Better Titfuck v0.95',
        "trigger": 'titjob,titfuck',
        "desc": "Makes titfuck scenes read properly β€” breasts wrap around the penis with realistic motion. Use for titjob/titfuck scenes. Not for other sex acts; it specializes in breast-on-penis action.",
    },
    'nsfw_blowjob_v3_0': {
        "repo": "EllaPriest45/MinimaxH3_Actions",
        "file": 'Blowjob v3.0 - MinimaxH3 - bl0w_j0b.safetensors',
        "scale": 0.7,
        "label": 'Blowjob v3.0',
        "trigger": 'bl0w_j0b',
        "desc": "Core blowjob LoRA β€” makes oral sex on a penis read naturally with proper head motion. Use for blowjob scenes. Not for scenes without a visible penis; it won't do anything useful.",
    },
    'nsfw_blowjob_wearing_thong': {
        "repo": "EllaPriest45/MinimaxH3_Actions",
        "file": 'Blowjob wearing Thong - MinimaxH3 - blowjob_wearing_thong.safetensors',
        "scale": 0.7,
        "label": 'Blowjob wearing Thong',
        "trigger": 'blowjob_wearing_thong',
        "desc": "Blowjob variant where the performer keeps a thong on. Use for thong-clad blowjob scenes. Not for nude blowjobs β€” the thong is part of the concept.",
    },
    'nsfw_bluebella_nova_lingerie': {
        "repo": "EllaPriest45/MinimaxH3_Actions",
        "file": 'Bluebella Nova Lingerie - MinimaxH3 - She is wearing COLOR Bluebella Nova Lingerie.safetensors',
        "scale": 0.7,
        "label": 'Bluebella Nova Lingerie',
        "trigger": 'She is wearing COLOR Bluebella Nova Lingerie',
        "format": "kohya",
        "desc": "Renders the subject wearing the Bluebella Nova lingerie set β€” a specific lace-and-straps design. Use for scenes featuring this exact lingerie. Not for other outfits; it's tied to this one garment.",
    },
    'nsfw_boob_physics': {
        "repo": "EllaPriest45/MinimaxH3_Actions",
        "file": 'Boob Physics - MinimaxH3 - jiggle,grab,massage,bounce.safetensors',
        "scale": 0.7,
        "label": 'Boob Physics',
        "trigger": 'jiggle,grab,massage,bounce',
        "desc": "Adds natural breast motion β€” jiggle, bounce, and sway during movement. Use for any scene with breast movement. Not for static shots; it only shows when there's motion.",
    },
    'nsfw_bustywomen': {
        "repo": "EllaPriest45/MinimaxH3_Actions",
        "file": 'BustyWomen - MinimaxH3 - 0.75-1str.safetensors',
        "scale": 0.88,
        "label": 'BustyWomen',
        "trigger": 'busty women',
        "desc": "Makes female subjects busty β€” fuller, larger breasts. Use when you want a well-endowed figure. Not for flat-chested or petite figures; it conflicts with tiny-breast LoRAs.",
    },
    'nsfw_button_pop': {
        "repo": "EllaPriest45/MinimaxH3_Actions",
        "file": 'Button pop - MinimaxH3 - 0.2-0.5str,butt0n_p0p.safetensors',
        "scale": 0.35,
        "label": 'Button pop',
        "trigger": 'butt0n_p0p',
        "desc": "Makes buttons pop off clothing under strain β€” a clothing-failure effect. Use for scenes where a tight top bursts open. Not for general scenes; it's a specific gag/effect.",
    },
    'nsfw_cameltoe_v2_0': {
        "repo": "EllaPriest45/MinimaxH3_Actions",
        "file": 'Cameltoe v2.0 - MinimaxH3 - cameltoe.safetensors',
        "scale": 0.7,
        "label": 'Cameltoe v2.0',
        "trigger": 'cameltoe',
        "desc": "Renders a visible cameltoe through tight clothing. Use for scenes with tight bottoms. Not for nude scenes; it needs clothing to show through.",
    },
    'nsfw_can_t_stop_shaking': {
        "repo": "EllaPriest45/MinimaxH3_Actions",
        "file": "Can't Stop Shaking! - MinimaxH3 - endface1,endbody1.safetensors",
        "scale": 0.7,
        "label": "Can't Stop Shaking!",
        "trigger": 'endface1,endbody1',
        "desc": "Makes the subject shake uncontrollably β€” body and face tremors, often during intense stimulation. Use for overstimulation and orgasm scenes. Not for calm scenes; it adds constant shaking.",
    },
    'nsfw_chasing_blowjob_v1_2': {
        "repo": "EllaPriest45/MinimaxH3_Actions",
        "file": 'Chasing blowjob v1.2 - MinimaxH3 - The girl performs a blowjob.safetensors',
        "scale": 0.7,
        "label": 'Chasing blowjob v1.2',
        "trigger": 'The girl performs a blowjob',
        "desc": "Blowjob where the performer chases the penis β€” active, eager head movement. Use for enthusiastic blowjob scenes. Not for slow or gentle oral; it's an energetic variant.",
    },
    'nsfw_combat_base_v2_0': {
        "repo": "EllaPriest45/MinimaxH3_Actions",
        "file": 'Combat BASE v2.0 - MinimaxH3 - prfight2,prfin1,res_multistep+simple,euler+beta.safetensors',
        "scale": 0.7,
        "label": 'Combat BASE v2.0',
        "trigger": 'prfight2,prfin1',
        "desc": "Base LoRA for fight and combat scenes β€” wrestling, grappling, and physical struggle. Use for combat or struggle scenes. Not for sex acts; it's a fight-motion base.",
    },
    'nsfw_cum_swallow': {
        "repo": "EllaPriest45/MinimaxH3_Actions",
        "file": 'Cum Swallow - MinimaxH3 - TADAA,0.4str.safetensors',
        "scale": 0.4,
        "label": 'Cum Swallow',
        "trigger": 'TADAA',
        "desc": "Makes the subject swallow cum after a facial or oral scene β€” the swallowing action reads clearly. Use for cum-swallow endings. Not for scenes without a cumshot; it needs the setup.",
    },
    'nsfw_cumshot': {
        "repo": "EllaPriest45/MinimaxH3_Actions",
        "file": 'Cumshot - MinimaxH3 - 20steps,euler+beta,0.85str.safetensors',
        "scale": 0.85,
        "label": 'Cumshot',
        "trigger": 'cumshot',
        "desc": "Renders a visible cumshot β€” ejaculation with realistic volume and motion. Use for cumshot scenes. Not for non-ejaculation scenes; it forces the act.",
    },
    'nsfw_deeper_hold_it': {
        "repo": "EllaPriest45/MinimaxH3_Actions",
        "file": 'Deeper... Hold It. - MinimaxH3 - oralmove1,oraldetail1,0.8str.safetensors',
        "scale": 0.8,
        "label": 'Deeper... Hold It.',
        "trigger": 'oralmove1,oraldetail1',
        "desc": "Oral-sex detail LoRA β€” deep-throat motion and oral detail. Use for deep oral scenes. Not for shallow kissing or foreplay; it's oral-specific.",
    },
    'nsfw_dildo_masturbation_v2_0': {
        "repo": "EllaPriest45/MinimaxH3_Actions",
        "file": 'Dildo Masturbation v2.0 - MinimaxH3 - She slide a dildo in and out of her pussy.safetensors',
        "scale": 0.7,
        "label": 'Dildo Masturbation v2.0',
        "trigger": 'She slide a dildo in and out of her pussy',
        "desc": "Makes solo dildo masturbation read naturally β€” the subject slides a dildo in and out of her pussy. Use for solo dildo scenes. Not for partnered penetration; it's solo-focused.",
    },
    'nsfw_disney_style_renaissance_era': {
        "repo": "EllaPriest45/MinimaxH3_Actions",
        "file": 'Disney Style - Renaissance Era - MinimaxH3 - In the style of Disney animation.safetensors',
        "scale": 0.7,
        "label": 'Disney Style - Renaissance Era',
        "trigger": 'In the style of Disney animation',
        "format": "kohya",
        "desc": "Applies a Disney Renaissance-era animation style β€” the classic 90s hand-drawn look. Use for stylized or animated scenes. Not for photorealistic content; it fights realism.",
    },
    'nsfw_drone_shot': {
        "repo": "EllaPriest45/MinimaxH3_Actions",
        "file": 'Drone Shot - MinimaxH3 - dr0nesh0t.safetensors',
        "scale": 0.7,
        "label": 'Drone Shot',
        "trigger": 'dr0nesh0t',
        "desc": "Adds a drone-style aerial camera shot β€” high-angle and sweeping. Use for establishing or overhead shots. Not for close-up intimate scenes; it pulls the camera away.",
    },
    'nsfw_facial_cumshot_v0_1': {
        "repo": "EllaPriest45/MinimaxH3_Actions",
        "file": 'Facial CumShot v0.1 - MinimaxH3 - cmst.safetensors',
        "scale": 0.7,
        "label": 'Facial CumShot v0.1',
        "trigger": 'cmst',
        "desc": "Renders a facial cumshot β€” cum landing on the face. Use for facial scenes. Not for internal or swallow endings; it's face-specific.",
    },
    'nsfw_faster_harder_shake_harder_v0_2': {
        "repo": "EllaPriest45/MinimaxH3_Actions",
        "file": 'Faster! Harder! Shake Harder! v0.2 - MinimaxH3 - dynv2.safetensors',
        "scale": 0.7,
        "label": 'Faster! Harder! Shake Harder! v0.2',
        "trigger": 'dynv2',
        "desc": "Makes the subject move faster and harder β€” intense, vigorous motion. Use for rough or fast scenes. Not for gentle or slow scenes; it escalates intensity.",
    },
    'nsfw_fetish_submission_chain_teddy': {
        "repo": "EllaPriest45/MinimaxH3_Actions",
        "file": 'Fetish Submission Chain Teddy - MinimaxH3 - She is wearing a red latex fetish submission chain teddy.Her hands are bound in front of her.safetensors',
        "scale": 0.7,
        "label": 'Fetish Submission Chain Teddy',
        "trigger": 'She is wearing a red latex fetish submission chain teddy',
        "desc": "Renders the subject in a red latex fetish submission chain teddy, with her hands bound in front. Use for latex or bondage outfit scenes. Not for casual outfits; it's a specific fetish garment.",
    },
    'nsfw_fingering': {
        "repo": "EllaPriest45/MinimaxH3_Actions",
        "file": 'Fingering - MinimaxH3 - 0.8-1str.safetensors',
        "scale": 0.9,
        "label": 'Fingering',
        "trigger": 'fingering',
        "desc": "Makes fingering scenes read naturally β€” fingers inside the vagina with realistic motion. Use for manual stimulation scenes. Not for scenes without hand-on-genital contact.",
    },
    'nsfw_framerush': {
        "repo": "EllaPriest45/MinimaxH3_Actions",
        "file": 'FrameRush - MinimaxH3 - lights.safetensors',
        "scale": 0.7,
        "label": 'FrameRush',
        "trigger": 'lights',
        "desc": "Camera and lighting effect LoRA β€” adds a rushed, dynamic frame feel. Use for energetic camera work. Not for stable, slow shots.",
    },
    'nsfw_furry_enhancer_video_v1_5': {
        "repo": "EllaPriest45/MinimaxH3_Actions",
        "file": 'Furry Enhancer Video v1.5 - MinimaxH3 - 0.6-0.7str.safetensors',
        "scale": 0.65,
        "label": 'Furry Enhancer Video v1.5',
        "trigger": 'furry enhancer',
        "desc": "Enhances furry and anthro characters in video β€” fur texture and anthro anatomy. Use for furry content. Not for human subjects; it will fur-ify them.",
    },
    'nsfw_futanari_transformation_futanarization_v': {
        "repo": "EllaPriest45/MinimaxH3_Actions",
        "file": 'Futanari transformation (Futanarization) v5.1 - MinimaxH3 - futanaei transformation,futanaei transformation.safetensors',
        "scale": 0.7,
        "label": 'Futanari transformation (Futanarization) v5.1',
        "trigger": 'futanaei transformation',
        "desc": "Renders futanari transformation β€” a female subject gaining a penis. Use for futanari or transformation scenes. Not for standard male-female scenes; it changes anatomy.",
    },
    'nsfw_grindtime': {
        "repo": "EllaPriest45/MinimaxH3_Actions",
        "file": 'Grindtime - MinimaxH3 - grindtime,a woman performing continuous rhythmic gyrating hip motion while having sex,front-rear-side view.safetensors',
        "scale": 0.7,
        "label": 'Grindtime',
        "trigger": 'grindtime',
        "desc": "Makes the subject perform continuous rhythmic hip grinding during sex β€” front, rear, and side views. Use for grinding or riding scenes. Not for static poses; it's a motion LoRA.",
    },
    'nsfw_h3_footjob_v0': {
        "repo": "EllaPriest45/MinimaxH3_Actions",
        "file": "H3 Footjob v0 - MinimaxH3 - a photoealistic video depicting a woman sitting in front of the viewer.the camera angle is a male pov.the viewer's penis is exposed.the woman is performing a footjob.h3fj.safetensors",
        "scale": 0.7,
        "label": 'H3 Footjob v0',
        "trigger": 'h3fj',
        "desc": "POV footjob LoRA β€” the subject strokes a penis with her feet from a male POV. Use for footjob scenes. Not for scenes without a visible penis and feet; it's a specific POV setup.",
    },
    'nsfw_hmbreasts_v2_0': {
        "repo": "EllaPriest45/MinimaxH3_Actions",
        "file": 'HMBreasts v2.0 - MinimaxH3 - tits,seeds2+ddim_uniform,8stepsturbolora.safetensors',
        "scale": 0.7,
        "label": 'HMBreasts v2.0',
        "trigger": 'tits',
        "desc": "Hearmeman breast LoRA β€” renders attractive, natural breasts. Use for breast-focused scenes. Not for flat-chested figures; it conflicts with tiny-breast LoRAs.",
    },
    'nsfw_hmmasturbation_squirting_and_female_mast': {
        "repo": "EllaPriest45/MinimaxH3_Actions",
        "file": 'HMMasturbation - Squirting and Female Masturbation - MinimaxH3 - hmmasturbation,euler+simple,12steps,shift6,turbo lora 0.5str,use hmpussy at 0.4-0.8str.safetensors',
        "scale": 0.6,
        "label": 'HMMasturbation - Squirting and Female Masturbation',
        "trigger": 'hmmasturbation',
        "desc": "Hearmeman masturbation LoRA β€” solo masturbation with squirting. Use for solo scenes with squirting. Not for partnered sex; it's solo-focused.",
    },
    'nsfw_hmpenis_v2_0': {
        "repo": "EllaPriest45/MinimaxH3_Actions",
        "file": 'HMPenis v2.0 - MinimaxH3 - penis,0.9str.safetensors',
        "scale": 0.9,
        "label": 'HMPenis v2.0',
        "trigger": 'penis',
        "desc": "Hearmeman penis LoRA β€” detailed erect penis anatomy. Use for any scene with a visible penis. Not for solo female scenes, and don't stack it with the dedicated penis LoRA (same purpose).",
    },
    'nsfw_hmpussy_v1_0': {
        "repo": "EllaPriest45/MinimaxH3_Actions",
        "file": 'HMPussy v1.0 - MinimaxH3 - pussy,0.9str.safetensors',
        "scale": 0.9,
        "label": 'HMPussy v1.0',
        "trigger": 'pussy',
        "desc": "Hearmeman pussy LoRA β€” detailed vulva anatomy. Use for close-up genital shots. Not for scenes where the vulva isn't visible; it only affects what's in frame.",
    },
    'nsfw_hmsquirt_squirting_v0_1': {
        "repo": "EllaPriest45/MinimaxH3_Actions",
        "file": 'HMSquirt - Squirting v0.1 - MinimaxH3 - euler+simple,hmsquirt,12steps,6shift,turbolora 0.5str.safetensors',
        "scale": 0.5,
        "label": 'HMSquirt - Squirting v0.1',
        "trigger": 'hmsquirt',
        "desc": "Hearmeman squirting LoRA β€” makes squirting read clearly during stimulation. Use for squirting scenes. Not for dry scenes; it forces the effect.",
    },
    'nsfw_hand_in_panties_masturbation': {
        "repo": "EllaPriest45/MinimaxH3_Actions",
        "file": 'Hand in Panties Masturbation  - MinimaxH3 - 0.7str,She has her hand in her panties,She slides her hand in her panties.She rubs her vagina.safetensors',
        "scale": 0.7,
        "label": 'Hand in Panties Masturbation',
        "trigger": 'She has her hand in her panties,She slides her hand in her panties.She rubs her vagina',
        "desc": "Makes the subject slide her hand into her panties and rub herself. Use for clothed masturbation scenes. Not for nude masturbation; the panties are part of the concept.",
    },
    'nsfw_hip_gyration': {
        "repo": "EllaPriest45/MinimaxH3_Actions",
        "file": 'Hip Gyration - MinimaxH3 - gyrating her hips,0.8str.safetensors',
        "scale": 0.8,
        "label": 'Hip Gyration',
        "trigger": 'gyrating her hips',
        "desc": "Makes the subject gyrate her hips rhythmically β€” circular hip motion. Use for grinding or dancing scenes. Not for static poses; it's a motion LoRA.",
    },
    'nsfw_hip_sway_dance': {
        "repo": "EllaPriest45/MinimaxH3_Actions",
        "file": 'Hip Sway Dance - MinimaxH3 - dancing with arms in front.safetensors',
        "scale": 0.7,
        "label": 'Hip Sway Dance',
        "trigger": 'dancing with arms in front',
        "desc": "Dance LoRA β€” the subject dances with arms in front, swaying her hips. Use for dance scenes. Not for sex acts; it's a dance-motion LoRA.",
    },
    'nsfw_hitachi_magic_wand_vibrator': {
        "repo": "EllaPriest45/MinimaxH3_Actions",
        "file": 'Hitachi Magic Wand Vibrator - MinimaxH3 - using a Hitachi Magic Wand vibrator.safetensors',
        "scale": 0.7,
        "label": 'Hitachi Magic Wand Vibrator',
        "trigger": 'using a Hitachi Magic Wand vibrator',
        "desc": "Renders the subject using a Hitachi Magic Wand vibrator β€” the toy and its use read clearly. Use for vibrator scenes. Not for scenes without the toy; it won't add anything.",
    },
    'nsfw_holi_festival_of_colors': {
        "repo": "EllaPriest45/MinimaxH3_Actions",
        "file": 'Holi Festival of Colors - MinimaxH3 - Festival_of_Colors,multicolored smoke,multicolored paint,multicolored powder.safetensors',
        "scale": 0.7,
        "label": 'Holi Festival of Colors',
        "trigger": 'Festival_of_Colors',
        "desc": "Holi festival effect β€” multicolored smoke, paint, and powder. Use for colorful festival scenes. Not for NSFW acts; it's a visual-effects LoRA.",
    },
    'nsfw_huge_breasts_large_breasts': {
        "repo": "EllaPriest45/MinimaxH3_Actions",
        "file": 'Huge Breasts - Large Breasts - MinimaxH3 - bigsloppytits,huge-massive-enormous saggy breasts-bust,nip_protruding-flat-soft,areola_large-wide-medium-small.safetensors',
        "scale": 0.7,
        "label": 'Huge Breasts - Large Breasts',
        "trigger": 'bigsloppytits',
        "desc": "Renders huge, saggy breasts β€” massive with large areolas. Use for extreme-breast scenes. Not for natural or petite figures; it goes big.",
    },
    'nsfw_icy_ass_smacking': {
        "repo": "EllaPriest45/MinimaxH3_Actions",
        "file": 'Icy Ass Smacking - MinimaxH3 - icyslap.safetensors',
        "scale": 0.7,
        "label": 'Icy Ass Smacking',
        "trigger": 'icyslap',
        "desc": "Makes ass-smacking read naturally β€” the slap and the resulting jiggle. Use for spanking scenes. Not for non-spanking scenes; it forces the action.",
    },
    'nsfw_icy_twerk_pro_max_v2_0': {
        "repo": "EllaPriest45/MinimaxH3_Actions",
        "file": 'Icy Twerk Pro MAX v2.0 - MinimaxH3 - icytwerk.safetensors',
        "scale": 0.7,
        "label": 'Icy Twerk Pro MAX v2.0',
        "trigger": 'icytwerk',
        "desc": "Twerk LoRA β€” vigorous twerking with strong ass motion. Use for twerk scenes. Not for slow or gentle movement; it's high-energy.",
    },
    'nsfw_innie_pussy': {
        "repo": "EllaPriest45/MinimaxH3_Actions",
        "file": 'Innie Pussy - MinimaxH3.safetensors',
        "scale": 0.7,
        "label": 'Innie Pussy',
        "trigger": 'inniepussy',
        "format": "kohya",
        "desc": "Innie pussy variant (kohya format) β€” a clean, tucked vulva look. Use for close-up genital shots wanting a neat innie. Not for scenes needing prominent labia; same caveat as the dedicated innie LoRA.",
    },
    'nsfw_jav_moans_audio_only': {
        "repo": "EllaPriest45/MinimaxH3_Actions",
        "file": 'JAV moans audio only - MinimaxH3 - jpnMoans.safetensors',
        "scale": 0.7,
        "label": 'JAV moans audio only',
        "trigger": 'jpnMoans',
        "format": "kohya",
        "desc": "Audio LoRA β€” adds JAV-style moans to the soundtrack. Use for scenes where you want Japanese AV-style vocalizations. Not for scenes with dialogue; it's audio-only.",
    },
    'nsfw_jiggle_walk': {
        "repo": "EllaPriest45/MinimaxH3_Actions",
        "file": 'JIGGLE WALK - MinimaxH3 - JGLWLK.safetensors',
        "scale": 0.7,
        "label": 'JIGGLE WALK',
        "trigger": 'JGLWLK',
        "desc": "Makes the subject walk with a pronounced jiggle β€” breast and body bounce while walking. Use for walking scenes. Not for static or lying-down scenes; it needs locomotion.",
    },
    'nsfw_kaku_table_humping': {
        "repo": "EllaPriest45/MinimaxH3_Actions",
        "file": 'KAKU - Table Humping - MinimaxH3 - 0.4-0.5str,KAKU,euler+simple.safetensors',
        "scale": 0.45,
        "label": 'KAKU - Table Humping',
        "trigger": 'KAKU',
        "desc": "Makes the subject hump a table or surface β€” grinding against furniture. Use for table-humping scenes. Not for partnered sex; it's a solo furniture act.",
    },
    'nsfw_lesbian_cunnilingus_v2_0': {
        "repo": "EllaPriest45/MinimaxH3_Actions",
        "file": 'Lesbian Cunnilingus v2.0 - MinimaxH3.safetensors',
        "scale": 0.7,
        "label": 'Lesbian Cunnilingus v2.0',
        "trigger": 'lesbian cunnilingus',
        "desc": "Lesbian cunnilingus β€” one woman performs oral sex on another. Use for lesbian oral scenes. Not for solo or hetero scenes; it's a partnered female act.",
    },
    'nsfw_licking_penis_and_testicles_nsfw_v1_2': {
        "repo": "EllaPriest45/MinimaxH3_Actions",
        "file": 'Licking Penis and Testicles (NSFW) v1.2 - MinimaxH3 - licking penis,licking testicles,licking penis tip,Only works if penis and testicles are in view.safetensors',
        "scale": 0.7,
        "label": 'Licking Penis and Testicles (NSFW) v1.2',
        "trigger": 'licking penis,licking testicles,licking penis tip',
        "desc": "Makes the subject lick a penis and testicles β€” detailed oral attention. Use for oral scenes focused on the penis and testicles. Only works if the penis and testicles are in view.",
    },
    'nsfw_mini_dick_fix_penis_helper': {
        "repo": "EllaPriest45/MinimaxH3_Actions",
        "file": 'Mini Dick Fix - Penis Helper - MinimaxH3 - 3r3kt (but not really needed).safetensors',
        "scale": 0.7,
        "label": 'Mini Dick Fix - Penis Helper',
        "trigger": '3r3kt',
        "desc": "Fixes the 'mini dick' problem β€” makes the penis render at a realistic size instead of shrinking. Use alongside any penis LoRA. Not a standalone anatomy LoRA; it's a helper.",
    },
    'nsfw_missionary_sex_pov': {
        "repo": "EllaPriest45/MinimaxH3_Actions",
        "file": 'Missionary Sex - POV - MinimaxH3 - having missionary sex.safetensors',
        "scale": 0.7,
        "label": 'Missionary Sex - POV',
        "trigger": 'having missionary sex',
        "desc": "Missionary sex from the male POV β€” the act reads naturally from above. Use for missionary scenes. Not for other positions; it's position-specific.",
    },
    'nsfw_moawxx_female_pleasure_moans_body_writhi': {
        "repo": "EllaPriest45/MinimaxH3_Actions",
        "file": 'Moawxx - Female Pleasure Moans + Body Writhing v0.1 2000e - MinimaxH3 - moawxx,0.6-0.85str.safetensors',
        "scale": 0.72,
        "label": 'Moawxx - Female Pleasure Moans + Body Writhing v0.1 2000e',
        "trigger": 'moawxx',
        "desc": "Moawxx pleasure LoRA β€” female moans plus body writhing during stimulation. Use for pleasure and orgasm scenes. Not for calm scenes; it adds audible and visible arousal.",
    },
    'nsfw_moawxx_female_pleasure_moans_body_writhi_2': {
        "repo": "EllaPriest45/MinimaxH3_Actions",
        "file": 'Moawxx - Female Pleasure Moans + Body Writhing v0.1 2500e - MinimaxH3 - moawxx,0.6-0.85str.safetensors',
        "scale": 0.72,
        "label": 'Moawxx - Female Pleasure Moans + Body Writhing v0.1 2500e',
        "trigger": 'moawxx',
        "desc": "Moawxx pleasure LoRA β€” female moans plus body writhing during stimulation (2500e training variant). Use for pleasure and orgasm scenes. Not for calm scenes; it adds audible and visible arousal.",
    },
    'nsfw_moawxx_female_pleasure_moans_body_writhi_3': {
        "repo": "EllaPriest45/MinimaxH3_Actions",
        "file": 'Moawxx - Female Pleasure Moans + Body Writhing v0.1 2750e - MinimaxH3 - moawxx,0.6-0.85str.safetensors',
        "scale": 0.72,
        "label": 'Moawxx - Female Pleasure Moans + Body Writhing v0.1 2750e',
        "trigger": 'moawxx',
        "desc": "Moawxx pleasure LoRA β€” female moans plus body writhing during stimulation (2750e training variant). Use for pleasure and orgasm scenes. Not for calm scenes; it adds audible and visible arousal.",
    },
    'nsfw_mystic_xxx_v2_0': {
        "repo": "EllaPriest45/MinimaxH3_Actions",
        "file": 'Mystic XXX v2.0 - MinimaxH3 - 0.7str.safetensors',
        "scale": 0.7,
        "label": 'Mystic XXX v2.0',
        "trigger": 'mystic xxx',
        "desc": "General NSFW enhancer β€” improves overall explicitness and scene quality. Use as a base on top of specific act LoRAs. Not a specific act; it's a general boost.",
    },
    'nsfw_natural_sagging_breasts': {
        "repo": "EllaPriest45/MinimaxH3_Actions",
        "file": 'Natural Sagging Breasts - MinimaxH3 - She has naturally sagging breasts.safetensors',
        "scale": 0.7,
        "label": 'Natural Sagging Breasts',
        "trigger": 'She has naturally sagging breasts',
        "desc": "Renders naturally sagging breasts β€” realistic gravity and shape. Use for mature or natural figures. Not for perky or enhanced breasts; it adds sag.",
    },
    'nsfw_natural_saggy_boobs': {
        "repo": "EllaPriest45/MinimaxH3_Actions",
        "file": 'Natural Saggy Boobs - MinimaxH3 - hugesaggytits,shirt-lift titty drop,bra unhook from behind,then drop.safetensors',
        "scale": 0.7,
        "label": 'Natural Saggy Boobs',
        "trigger": 'hugesaggytits',
        "desc": "Saggy boobs with specific reveal actions β€” shirt-lift titty drop and bra unhook from behind. Use for breast-reveal scenes. Not for clothed scenes; it's about the reveal.",
    },
    'nsfw_nipple_play': {
        "repo": "EllaPriest45/MinimaxH3_Actions",
        "file": 'Nipple Play - MinimaxH3 - flicks her own nipples,gently pinch and slowly roll her own beautifully formed,fully erect,firm and symmetrical nipples.safetensors',
        "scale": 0.7,
        "label": 'Nipple Play',
        "trigger": 'nipple play',
        "desc": "Makes the subject play with her nipples β€” flicking, pinching, and rolling them. Use for nipple-play scenes. Not for scenes without breast focus; it centers on the nipples.",
    },
    'nsfw_pjslide_pussyjob': {
        "repo": "EllaPriest45/MinimaxH3_Actions",
        "file": 'PJSLIDE - Pussyjob - MinimaxH3 - 0.5str,PJSLIDE,add HMPenis lora at 0.5str.safetensors',
        "scale": 0.5,
        "label": 'PJSLIDE - Pussyjob',
        "trigger": 'PJSLIDE',
        "desc": "Pussyjob LoRA β€” the penis slides along the vulva. Use for pussyjob scenes; the author recommends adding the penis LoRA at 0.5 strength alongside it. Not for penetration scenes; it's a sliding act.",
    },
    'nsfw_pk_parasyte_turbo_clean_up_the_models_vi': {
        "repo": "EllaPriest45/MinimaxH3_Actions",
        "file": 'PK Parasyte Turbo (clean up the models visuals and audio) - MinimaxH3 - 3.5-5str,6-8steps,8-3 shift,euler+simple.safetensors',
        "scale": 4.25,
        "label": 'PK Parasyte Turbo (clean up the models visuals and audio)',
        "trigger": 'PK Parasyte Turbo',
        "desc": "Turbo LoRA that cleans up model visuals and audio β€” improves overall quality at low step counts. Use with turbo mode (6-8 steps, high strength 3.5-5). Not for standard 25-step generation; it's tuned for turbo.",
    },
    'nsfw_pov_missionary_insertion_v0_7': {
        "repo": "EllaPriest45/MinimaxH3_Actions",
        "file": 'POV Missionary Insertion v0.7 - MinimaxH3.safetensors',
        "scale": 0.7,
        "label": 'POV Missionary Insertion v0.7',
        "trigger": 'missionary insertion',
        "format": "kohya",
        "desc": "POV missionary insertion β€” the insertion moment reads clearly from the male POV. Use for missionary insertion scenes. Not for other positions; it's position-specific.",
    },
    'nsfw_passionate_kissing': {
        "repo": "EllaPriest45/MinimaxH3_Actions",
        "file": 'Passionate Kissing - MinimaxH3 - They kiss passionately,1str.safetensors',
        "scale": 1.0,
        "label": 'Passionate Kissing',
        "trigger": 'They kiss passionately',
        "desc": "Makes passionate kissing read naturally β€” lip contact and head motion. Use for kissing scenes. Not for oral or sex acts; it's kissing-specific.",
    },
    'nsfw_photorealistic_image_generator': {
        "repo": "EllaPriest45/MinimaxH3_Actions",
        "file": 'Photorealistic Image Generator - MinimaxH3 - ph0t0r34l.safetensors',
        "scale": 0.7,
        "label": 'Photorealistic Image Generator',
        "trigger": 'ph0t0r34l',
        "format": "kohya",
        "desc": "Pushes output toward photorealism β€” more realistic textures and lighting. Use for photorealistic scenes. Not for stylized or animated content; it fights the style.",
    },
    'nsfw_pillow_humping': {
        "repo": "EllaPriest45/MinimaxH3_Actions",
        "file": 'Pillow Humping - MinimaxH3 - She is straddling a pillow.She is humping the pillow.safetensors',
        "scale": 0.7,
        "label": 'Pillow Humping',
        "trigger": 'She is straddling a pillow.She is humping the pillow',
        "desc": "Makes the subject straddle and hump a pillow β€” solo grinding on a pillow. Use for pillow-humping scenes. Not for partnered sex; it's a solo act.",
    },
    'nsfw_pokies': {
        "repo": "EllaPriest45/MinimaxH3_Actions",
        "file": 'Pokies - MinimaxH3 - covered nipples,pokies.safetensors',
        "scale": 0.7,
        "label": 'Pokies',
        "trigger": 'covered nipples,pokies',
        "format": "kohya",
        "desc": "Renders visible nipple outlines through clothing β€” pokies. Use for clothed scenes with tight tops. Not for nude scenes; it needs clothing.",
    },
    'nsfw_polyhedron_perfect_eyes_perfect_skin_per': {
        "repo": "EllaPriest45/MinimaxH3_Actions",
        "file": 'Polyhedron Perfect Eyes - Perfect Skin - Perfect Hands T2VA - MinimaxH3 - perfe8ct,perfect hands,perfect skin,perfect eyes.safetensors',
        "scale": 0.7,
        "label": 'Polyhedron Perfect Eyes - Perfect Skin - Perfect Hands T2VA',
        "trigger": 'perfe8ct',
        "desc": "Quality enhancer for eyes, skin, and hands β€” fixes common rendering flaws. Use as a general quality boost for any scene. Not for specific acts; it's a detail fixer.",
    },
    'nsfw_realism_people': {
        "repo": "EllaPriest45/MinimaxH3_Actions",
        "file": 'Realism People - MinimaxH3 - r34l1sm,0.6-1str.safetensors',
        "scale": 0.8,
        "label": 'Realism People',
        "trigger": 'r34l1sm',
        "desc": "Makes people look more realistic β€” natural proportions and skin. Use for photorealistic human scenes. Not for stylized content; it fights the style.",
    },
    'nsfw_sexgod_after_midnight_sexytime_r64': {
        "repo": "EllaPriest45/MinimaxH3_Actions",
        "file": 'SexGod After Midnight Sexytime R64 - MinimaxH3 - euler+beta.safetensors',
        "scale": 0.7,
        "label": 'SexGod After Midnight Sexytime R64',
        "trigger": 'sexgod',
        "format": "kohya",
        "desc": "SexGod base LoRA β€” general NSFW scene quality. Use as a base enhancer on top of specific act LoRAs. Not a specific act; it's a general boost.",
    },
    'nsfw_sexgod_s_naughtytimes_v2_0_pruned_rank25': {
        "repo": "EllaPriest45/MinimaxH3_Actions",
        "file": "SexGod's NaughtyTimes v2.0 pruned rank256 - MinimaxH3.safetensors",
        "scale": 0.7,
        "label": "SexGod's NaughtyTimes v2.0 pruned rank256",
        "trigger": 'naughtytimes',
        "format": "kohya",
        "desc": "SexGod's NaughtyTimes β€” general NSFW scene enhancer (rank-256 pruned). Use as a base enhancer. Not act-specific; pair it with act LoRAs.",
    },
    'nsfw_sexgod_s_naughtytimes_v2_0_pruned_rank51': {
        "repo": "EllaPriest45/MinimaxH3_Actions",
        "file": "SexGod's NaughtyTimes v2.0 pruned rank512 - MinimaxH3.safetensors",
        "scale": 0.7,
        "label": "SexGod's NaughtyTimes v2.0 pruned rank512",
        "trigger": 'naughtytimes',
        "format": "kohya",
        "desc": "SexGod's NaughtyTimes β€” general NSFW scene enhancer (rank-512 pruned, slightly higher capacity). Use as a base enhancer. Pick one of the two NaughtyTimes variants; don't stack both.",
    },
    'nsfw_she_struts': {
        "repo": "EllaPriest45/MinimaxH3_Actions",
        "file": 'She Struts - MinimaxH3 - she struts.safetensors',
        "scale": 0.7,
        "label": 'She Struts',
        "trigger": 'she struts',
        "desc": "Makes the subject strut β€” confident walking with attitude. Use for walk or entrance scenes. Not for static scenes; it needs locomotion.",
    },
    'nsfw_sideview_deepthroat_gag_audio': {
        "repo": "EllaPriest45/MinimaxH3_Actions",
        "file": 'SideView Deepthroat Gag Audio - MinimaxH3.safetensors',
        "scale": 0.7,
        "label": 'SideView Deepthroat Gag Audio',
        "trigger": 'deepthroat',
        "format": "kohya",
        "desc": "Side-view deepthroat with gag audio β€” the gag reflex reads and sounds. Use for deepthroat scenes. Not for gentle oral; it's intense.",
    },
    'nsfw_skin_tight_bottoms_cameltoe': {
        "repo": "EllaPriest45/MinimaxH3_Actions",
        "file": 'Skin Tight Bottoms (Cameltoe) - MinimaxH3 - cameltoe,0.9str.safetensors',
        "scale": 0.9,
        "label": 'Skin Tight Bottoms (Cameltoe)',
        "trigger": 'cameltoe',
        "desc": "Skin-tight bottoms with a visible cameltoe. Use for tight-clothing scenes. Not for nude scenes; it needs the clothing.",
    },
    'nsfw_slop_twerk_v0_2_epoch6': {
        "repo": "EllaPriest45/MinimaxH3_Actions",
        "file": "Slop Twerk v0.2 Epoch6 - MinimaxH3 - twerks causing her ass to jiggle and shake,0.5-1str,0.5 STR if you don't want Asians in T2V.safetensors",
        "scale": 0.75,
        "label": 'Slop Twerk v0.2 Epoch6',
        "trigger": 'twerk',
        "desc": "Twerk LoRA with strong ass jiggle and shake. Use for twerk scenes. Note: use 0.5 strength if you don't want Asian subjects in text-to-video.",
    },
    'nsfw_slop_bounce': {
        "repo": "EllaPriest45/MinimaxH3_Actions",
        "file": 'Slop bounce - MinimaxH3 - breasts bounce,shake,jiggle,sway.safetensors',
        "scale": 0.7,
        "label": 'Slop bounce',
        "trigger": 'breasts bounce',
        "desc": "Breast bounce, shake, jiggle, and sway during movement. Use for any scene with breast motion. Not for static shots; it only shows with movement.",
    },
    'nsfw_snow_white_lingerie': {
        "repo": "EllaPriest45/MinimaxH3_Actions",
        "file": 'Snow White Lingerie - MinimaxH3 - She is wearing slutty snow white lingerie.safetensors',
        "scale": 0.7,
        "label": 'Snow White Lingerie',
        "trigger": 'She is wearing slutty snow white lingerie',
        "desc": "Renders the subject in slutty Snow White lingerie. Use for scenes featuring this specific outfit. Not for other outfits; it's tied to this garment.",
    },
    'nsfw_strapon_dildo_v0_1': {
        "repo": "EllaPriest45/MinimaxH3_Actions",
        "file": 'Strapon Dildo v0.1 - MinimaxH3 - She is wearing a strapon dildo.safetensors',
        "scale": 0.7,
        "label": 'Strapon Dildo v0.1',
        "trigger": 'She is wearing a strapon dildo',
        "desc": "Makes the subject wear and use a strapon dildo. Use for strapon scenes. Not for scenes without the toy; it won't add anything.",
    },
    'nsfw_synth_pussy_v0_5': {
        "repo": "EllaPriest45/MinimaxH3_Actions",
        "file": 'Synth Pussy v0.5 - MinimaxH3.safetensors',
        "scale": 0.7,
        "label": 'Synth Pussy v0.5',
        "trigger": 'synth pussy',
        "format": "kohya",
        "desc": "Synth pussy β€” a stylized or synthetic vulva rendering. Use for stylized genital shots. Not for photorealistic anatomy; it's a stylized look.",
    },
    'nsfw_the_orgasm_button': {
        "repo": "EllaPriest45/MinimaxH3_Actions",
        "file": 'The Orgasm button - MinimaxH3 - Remoteorgasm.safetensors',
        "scale": 0.7,
        "label": 'The Orgasm button',
        "trigger": 'Remoteorgasm',
        "desc": "Remote-control orgasm β€” the subject reacts to a remote trigger. Use for orgasm-control scenes. Not for natural orgasms; it's the remote-control concept.",
    },
    'nsfw_thumb_finger_puppets': {
        "repo": "EllaPriest45/MinimaxH3_Actions",
        "file": 'Thumb-Finger puppets - MinimaxH3 - A thumb person.safetensors',
        "scale": 0.7,
        "label": 'Thumb-Finger puppets',
        "trigger": 'A thumb person',
        "desc": "Thumb-finger puppets β€” a 'thumb person' novelty effect. Use for puppet or novelty scenes. Not for realistic content; it's a gag.",
    },
    'nsfw_thumbinbutt': {
        "repo": "EllaPriest45/MinimaxH3_Actions",
        "file": 'ThumbInButt - MinimaxH3 - thum1n8utt,the man inserts his right thumb in her anus causing the woman to moan with pleasure.safetensors',
        "scale": 0.7,
        "label": 'ThumbInButt',
        "trigger": 'thum1n8utt',
        "desc": "Makes the man insert his thumb into the woman's anus, causing a pleasure moan. Use for anal-fingering scenes. Not for non-anal scenes; it forces the action.",
    },
    'nsfw_tiddies_and_realism_slider_vbeta': {
        "repo": "EllaPriest45/MinimaxH3_Actions",
        "file": 'Tiddies and Realism Slider vBeta - MinimaxH3 - 0.4-2str.safetensors',
        "scale": 1.2,
        "label": 'Tiddies and Realism Slider vBeta',
        "trigger": 'tiddies and realism',
        "desc": "Slider LoRA β€” adjust breast size and realism on a scale (0.4-2 strength; 1.2 is a good default). Use to fine-tune breast size. Not a fixed anatomy LoRA; it's a continuous slider.",
    },
    'nsfw_tiny_breasts_flat_chest': {
        "repo": "EllaPriest45/MinimaxH3_Actions",
        "file": 'Tiny Breasts - Flat Chest  - MinimaxH3 - She is flat chested,she has a flat chest.safetensors',
        "scale": 0.7,
        "label": 'Tiny Breasts - Flat Chest',
        "trigger": 'She is flat chested,she has a flat chest',
        "desc": "Renders a flat chest or tiny breasts. Use for petite figures. Not for busty figures; it conflicts with breast-size LoRAs.",
    },
    'nsfw_tiny_panties': {
        "repo": "EllaPriest45/MinimaxH3_Actions",
        "file": 'Tiny Panties - MinimaxH3 - She is wearing tiny panties.safetensors',
        "scale": 0.7,
        "label": 'Tiny Panties',
        "trigger": 'She is wearing tiny panties',
        "desc": "Renders the subject in tiny panties β€” minimal coverage. Use for lingerie scenes. Not for nude scenes; the panties are the point.",
    },
    'nsfw_torpedo_tits_t2v': {
        "repo": "EllaPriest45/MinimaxH3_Actions",
        "file": 'Torpedo Tits T2V - MinimaxH3 - torpedo tits,a 20 year old woman,wearing nothing shows off her medium sized torpedo tit breasts.safetensors',
        "scale": 0.7,
        "label": 'Torpedo Tits T2V',
        "trigger": 'torpedo tits',
        "desc": "Torpedo-shaped breasts β€” a specific conical breast shape. Use for torpedo-tit scenes. Not for natural shapes; it imposes the torpedo look.",
    },
    'nsfw_transition_boomsplitro': {
        "repo": "EllaPriest45/MinimaxH3_Actions",
        "file": 'Transition BoomSplitRo - MinimaxH3 - ysp_spliroa12 a woman. hard cut with no smooth transition, jumps straight into spitroast.safetensors',
        "scale": 0.7,
        "label": 'Transition BoomSplitRo',
        "trigger": 'ysp_spliroa12',
        "format": "kohya",
        "desc": "Hard-cut transition straight into a spitroast scene β€” no smooth transition. Use for abrupt scene changes. Not for continuous scenes; it's a cut effect.",
    },
    'nsfw_transition_f2v_instant_cut_to_things': {
        "repo": "EllaPriest45/MinimaxH3_Actions",
        "file": 'Transition F2V - Instant Cut to Things - MinimaxH3 - ysp_smshcut.safetensors',
        "scale": 0.7,
        "label": 'Transition F2V - Instant Cut to Things',
        "trigger": 'ysp_smshcut',
        "format": "kohya",
        "desc": "Instant cut transition to a new scene. Use for abrupt scene changes. Not for continuous scenes; it's a cut effect.",
    },
    'nsfw_tribtime': {
        "repo": "EllaPriest45/MinimaxH3_Actions",
        "file": 'Tribtime - MinimaxH3 - tribtime.safetensors',
        "scale": 0.7,
        "label": 'Tribtime',
        "trigger": 'tribtime',
        "desc": "Tribbing β€” scissoring or grinding between two women. Use for tribadism scenes. Not for solo scenes; it needs two partners.",
    },
    'nsfw_upskirt_helper_v0_1': {
        "repo": "EllaPriest45/MinimaxH3_Actions",
        "file": 'Upskirt Helper v0.1 - MinimaxH3 - upsk1rt_panties,upsk1rt_no_panties.safetensors',
        "scale": 0.7,
        "label": 'Upskirt Helper v0.1',
        "trigger": 'upsk1rt_panties,upsk1rt_no_panties',
        "format": "kohya",
        "desc": "Upskirt view β€” with or without panties. Use for upskirt shots. Not for nude scenes; it needs a skirt.",
    },
    'nsfw_whispering': {
        "repo": "EllaPriest45/MinimaxH3_Actions",
        "file": 'Whispering - MinimaxH3 - 0.7str,she whisper XYZ.safetensors',
        "scale": 0.7,
        "label": 'Whispering',
        "trigger": 'she whisper XYZ',
        "desc": "Makes the subject whisper β€” replace XYZ in the trigger with what she whispers. Use for whispering scenes. Not for loud or vocal scenes; it's a quiet effect.",
    },
}

# LoRAs that overlap in purpose and fight each other when stacked. The description box warns whenever 2+ from a
# group are selected. Groups may overlap (e.g. a deepthroat LoRA is both a blowjob act and an audio LoRA).
LORA_CONFLICT_GROUPS = {
    "penis anatomy": ["nsfw_penis", "nsfw_hmpenis_v2_0"],
    "innie pussy": ["nsfw_innie", "nsfw_innie_pussy"],
    "breast size/shape": ["nsfw_bustywomen", "nsfw_tiny_breasts_flat_chest", "nsfw_huge_breasts_large_breasts",
                          "nsfw_torpedo_tits_t2v", "nsfw_tiddies_and_realism_slider_vbeta",
                          "nsfw_natural_sagging_breasts", "nsfw_natural_saggy_boobs"],
    "breast motion": ["nsfw_boob_physics", "nsfw_slop_bounce", "nsfw_jiggle_walk"],
    "cameltoe": ["nsfw_cameltoe_v2_0", "nsfw_skin_tight_bottoms_cameltoe"],
    "twerk": ["nsfw_icy_twerk_pro_max_v2_0", "nsfw_slop_twerk_v0_2_epoch6"],
    "squirting": ["nsfw_hmmasturbation_squirting_and_female_mast", "nsfw_hmsquirt_squirting_v0_1"],
    "blowjob act": ["nsfw_blowjob_v3_0", "nsfw_blowjob_wearing_thong", "nsfw_chasing_blowjob_v1_2",
                    "nsfw_sideview_deepthroat_gag_audio", "nsfw_deeper_hold_it",
                    "nsfw_licking_penis_and_testicles_nsfw_v1_2"],
    "cumshot": ["nsfw_cumshot", "nsfw_facial_cumshot_v0_1"],
    "scene transition": ["nsfw_transition_boomsplitro", "nsfw_transition_f2v_instant_cut_to_things"],
    "moans (same LoRA, different training epochs)": ["nsfw_moawxx_female_pleasure_moans_body_writhi",
                                                     "nsfw_moawxx_female_pleasure_moans_body_writhi_2",
                                                     "nsfw_moawxx_female_pleasure_moans_body_writhi_3"],
    "SexGod NaughtyTimes (same LoRA, different ranks)": ["nsfw_sexgod_s_naughtytimes_v2_0_pruned_rank25",
                                                         "nsfw_sexgod_s_naughtytimes_v2_0_pruned_rank51"],
    "general NSFW enhancer": ["nsfw_astro_nsfw", "nsfw_mystic_xxx_v2_0",
                              "nsfw_sexgod_after_midnight_sexytime_r64",
                              "nsfw_sexgod_s_naughtytimes_v2_0_pruned_rank25",
                              "nsfw_sexgod_s_naughtytimes_v2_0_pruned_rank51"],
    "visual style": ["nsfw_disney_style_renaissance_era", "nsfw_photorealistic_image_generator",
                     "nsfw_realism_people"],
    "missionary POV": ["nsfw_missionary_sex_pov", "nsfw_pov_missionary_insertion_v0_7"],
    "dildo": ["nsfw_dildo", "nsfw_dildo_masturbation_v2_0", "nsfw_strapon_dildo_v0_1"],
    "audio": ["nsfw_jav_moans_audio_only", "nsfw_whispering", "nsfw_sideview_deepthroat_gag_audio"],
    "hip motion": ["nsfw_grindtime", "nsfw_hip_gyration"],
}


# Must stay identical to the conditioner's table: the *label* goes over the wire, so a canvas that half does not know
# is rejected there and surfaces as a failure here.
CANVASES = {
    # 16:9
    "960x544 Β· 16:9 fast": (544, 960),
    "1024x576 Β· 16:9 fast": (576, 1024),
    "1152x640 Β· 16:9": (640, 1152),
    "1280x704 Β· 16:9": (704, 1280),
    "1344x768 Β· 16:9 full": (768, 1344),
    # 9:16
    "544x960 Β· 9:16 fast": (960, 544),
    "640x1152 Β· 9:16": (1152, 640),
    "768x1344 Β· 9:16 full": (1344, 768),
    # 1:1
    "544x544 Β· 1:1 fast": (544, 544),
    "768x768 Β· 1:1 full": (768, 768),
    # 4:3 / 3:4
    "768x576 Β· 4:3 fast": (576, 768),
    "1024x768 Β· 4:3 full": (768, 1024),
    "576x768 Β· 3:4 fast": (768, 576),
    "768x1024 Β· 3:4 full": (1024, 768),
    # 21:9
    "1152x512 Β· 21:9 fast": (512, 1152),
    "1536x672 Β· 21:9 full": (672, 1536),
}
DEFAULT_CANVAS = "960x544 Β· 16:9 fast"
FPS, FRAMES_PER_CHUNK, LATENTS_PER_CHUNK = 24, 17, 5
# It is the *snapped* frame count the ceiling has to hold for: 15 s is 360 frames, which rounds up to 362, i.e.
# 15.083 s, and is refused.
MIN_UI_DURATION, MAX_UI_DURATION = 2, 14


def snap_frames(seconds: float) -> int:
    """The frame count MiniMax-H3's video VAE can decode: the next `17 * n + 5` at 24 fps."""
    frames = max(1, round(float(seconds) * FPS))
    while frames % FRAMES_PER_CHUNK != LATENTS_PER_CHUNK:
        frames += 1
    return frames


def lower_duration_floor(seconds: float = MIN_UI_DURATION) -> None:
    """Let the pipeline generate below its 5 s floor. 56 frames (2.33 s) is fine on the released checkpoint."""
    from diffusers.modular_pipelines.minimax_h3.modular_pipeline import MiniMaxH3ModularPipeline

    MiniMaxH3ModularPipeline.min_duration = property(lambda self: float(seconds))


PIPE = None
MANAGER = None
LOAD_ERROR: str | None = None
LOADED_IN: float | None = None
TURBO_AVAILABLE: bool = False
_TURBO_LoRA: list | None = None  # list of (module, A, B) tuples β€” A/B factors on CPU, tiny footprint
_TURBO_merged = False
_NSFW_LoRA: dict[str, list] = {}   # key -> list of (module, A, B) tuples, A/B on CPU
_NSFW_merged: set[str] = set()
_CUSTOM_LoRA: dict[tuple[str, str], list] = {}   # (repo, file) -> list of (module, A, B) tuples, A/B on CPU
_CUSTOM_merged: set[tuple[str, str]] = set()


def _convert_comfyui_h3_lora(sd):
    """Convert ComfyUI-format MiniMax-H3 LoRA keys to the module-tree keys the loader navigates.



    ComfyUI keys look like `diffusion_model.blocks.N.attn.out_proj.lora_A.weight` (and

    `diffusion_model.token_refiner.blocks.N.attn.out_proj.lora_A.weight` for the token refiner). The diffusers module

    tree uses `transformer_blocks.N.attn.to_out.0` / `token_refiner.refiner_blocks.N.attn.to_out.0`, `attn.to_q/to_k/to_v`

    (fused `qkv_proj` split 3-way), and `ff.net.0.proj` / `ff.net.2` (for `mlp.fc1` / `mlp.fc2`).

    """
    out = {}
    for k, v in sd.items():
        k = k.removeprefix("diffusion_model.").removeprefix("transformer.")
        parts = k.split(".")
        # Main blocks:   [blocks, N, attn|mlp, target, lora_A|B, weight]
        # Token refiner: [token_refiner, blocks, N, attn|mlp, target, lora_A|B, weight]
        if parts[0] == "token_refiner":
            prefix = "token_refiner.refiner_blocks."
            block, layer, target = parts[2], parts[3], parts[4]
            suffix = ".".join(parts[5:])  # e.g. "lora_A.weight"
        else:
            prefix = "transformer_blocks."
            block, layer, target = parts[1], parts[2], parts[3]
            suffix = ".".join(parts[4:])  # e.g. "lora_A.weight"
        # Some ComfyUI exports also carry kohya-style `.alpha` scalars (alpha == rank here, so a no-op).
        # Skip any non-lora_A/B key so metadata never reaches the shape-sensitive qkv split below.
        if suffix not in ("lora_A.weight", "lora_B.weight"):
            continue
        if layer == "attn":
            if target == "out_proj":
                out[f"{prefix}{block}.attn.to_out.0.{suffix}"] = v
            elif target == "qkv_proj":
                if suffix == "lora_A.weight":
                    # A is shared across q/k/v
                    for name in ("to_q", "to_k", "to_v"):
                        out[f"{prefix}{block}.attn.{name}.lora_A.weight"] = v
                else:  # lora_B.weight β€” split the rows 3-way into q/k/v
                    head_dim = v.shape[0] // 3
                    for i, name in enumerate(("to_q", "to_k", "to_v")):
                        out[f"{prefix}{block}.attn.{name}.lora_B.weight"] = v[i * head_dim:(i + 1) * head_dim]
        elif layer == "mlp":
            if target == "fc1":
                out[f"{prefix}{block}.ff.net.0.proj.{suffix}"] = v
            elif target == "fc2":
                out[f"{prefix}{block}.ff.net.2.{suffix}"] = v
    return out


def _convert_kohya_h3_lora(sd):
    """Convert kohya/musubi-tuner-format MiniMax-H3 LoRA keys to ComfyUI format, then to module-tree keys.



    kohya keys look like `lora_unet_blocks_N_attn_out_proj.lora_down.weight` / `.lora_up.weight` / `.alpha`

    (also `attn_qkv_proj`, `mlp_fc1`, `mlp_fc2`). Some exports are hybrids: the ComfyUI-style prefix

    (`diffusion_model.blocks.N.attn.out_proj`) with kohya-style suffixes β€” the prefix is already the

    ComfyUI layout, so only the suffix needs renaming. We first rename to the ComfyUI layout the loader

    understands (`diffusion_model.blocks.N.attn.out_proj.lora_A/lora_B.weight`), folding the per-module

    `alpha/rank` factor into the `lora_up` (B) tensor so the loader's `B @ A * scale` stays correct, then

    hand off to `_convert_comfyui_h3_lora`. kohya has no `token_refiner` keys β€” those are simply absent.

    """
    import torch
    comfy = {}
    alphas: dict[str, float] = {}
    # First pass: collect alpha factors (alpha/rank) per module base name. `.alpha` is a 0-dim
    # scalar tensor (ndim == 0), so the rank must come from the lora_down weight's shape[0].
    for k, v in sd.items():
        if k.endswith(".alpha"):
            base = k[: -len(".alpha")]
            _down = sd.get(f"{base}.lora_down.weight")
            rank = _down.shape[0] if _down is not None else float(v)
            alphas[base] = float(v) / float(rank)
    for k, v in sd.items():
        if k.endswith(".alpha"):
            continue
        if k.endswith(".lora_down.weight"):
            base = k[: -len(".lora_down.weight")]
            lora = "lora_A"
        elif k.endswith(".lora_up.weight"):
            base = k[: -len(".lora_up.weight")]
            lora = "lora_B"
        else:
            continue
        if base.startswith("diffusion_model.") or base.startswith("transformer."):
            # Hybrid export: ComfyUI-style prefix with kohya-style suffixes
            # (diffusion_model.blocks.N.attn.out_proj.lora_down.weight). The prefix is already the
            # ComfyUI layout β€” only the suffix needs renaming. token_refiner keys, if any, flow
            # through unchanged too.
            comfy_key = f"{base}.{lora}.weight"
        else:
            # base: lora_unet_blocks_N_attn_out_proj -> diffusion_model.blocks.N.attn.out_proj
            parts = base.split("_")
            # parts: [lora, unet, blocks, N, attn, out, proj]  (mlp_fc1 -> [.., mlp, fc1])
            if len(parts) < 6:
                continue  # unknown key shape β€” skip rather than crash
            block = parts[3]
            layer = parts[4]
            target = "_".join(parts[5:])
            comfy_key = f"diffusion_model.blocks.{block}.{layer}.{target}.{lora}.weight"
        if lora == "lora_B" and base in alphas:
            v = v * alphas[base]
        comfy[comfy_key] = v
    return _convert_comfyui_h3_lora(comfy)


def _apply_turbo():
    """Merge LoRA into transformer weights using A/B factors.



    The precomputed delta (B @ A) is ~57 MB per module Γ— 363 = ~20 GB β€” far more GPU memory

    than is free after the transformer is unpacked (~14 GB on an 80 GB card).  Instead we store

    the LoRA factors A (~2.6 MB) and B (~2.6 MB) per module β€” total ~1.2 GB β€” and compute

    the delta on-the-fly:  mod.weight += B @ A * scale.  Peak extra GPU memory is one temporary

    delta tensor (~57 MB), freed each iteration.



    A/B factors stay CPU-resident in `_TURBO_LoRA`; local CUDA copies are made per merge so the

    store is never mutated and no CUDA memory is held between requests.

    """
    global _TURBO_merged, _TURBO_LoRA
    if _TURBO_merged or _TURBO_LoRA is None:
        return
    _t0 = time.time()
    for mod, A, B in _TURBO_LoRA:
        # delta = B @ A is temporary (~57 MB), freed next iteration β€” never stored simultaneously.
        mod.weight.data += (B.to("cuda", non_blocking=True) @ A.to("cuda", non_blocking=True)) * TURBO_LORA_SCALE
    _elapsed = time.time() - _t0
    _TURBO_merged = True
    _log(f"turbo LoRA merged ({len(_TURBO_LoRA)} modules in {_elapsed:.2f}s)")


def _remove_turbo():
    """Restore base weights by undoing the LoRA merge. Idempotent: only acts when `_TURBO_merged`,

    and rolls back in reverse order so a partial failure leaves the fewest modules touched."""
    global _TURBO_merged
    if not _TURBO_merged or _TURBO_LoRA is None:
        return
    _t0 = time.time()
    _done = 0
    try:
        for mod, A, B in reversed(_TURBO_LoRA):
            mod.weight.data -= (B.to("cuda", non_blocking=True) @ A.to("cuda", non_blocking=True)) * TURBO_LORA_SCALE
            _done += 1
    except Exception as _e:
        _log(f"turbo LoRA partial unmerge ({_done}/{len(_TURBO_LoRA)}): {_e}", "ERROR")
        raise
    _elapsed = time.time() - _t0
    _TURBO_merged = False
    import torch as _torch
    _torch.cuda.empty_cache()
    _log(f"turbo LoRA removed ({len(_TURBO_LoRA)} modules in {_elapsed:.2f}s)")


# ── Debug logging ──────────────────────────────────────────────────────────────
def _log(msg, level="INFO"):
    """Timestamped line to the Space logs (stdout). Levels: DEBUG / INFO / WARN / ERROR."""
    print(f"[gen][{time.strftime('%H:%M:%S')}][{level}] {msg}", flush=True)


# ── Memory / OOM diagnostics ───────────────────────────────────────────────────
# The Space has a history of OOM crashes. A hard kill leaves no traceback, so the phase
# logs + bucket dumps below are the only evidence. `_log_mem` snapshots GPU + CPU at phase
# boundaries; `_debug_dump` persists diagnostics to the bucket under /data/debug;
# `_oom_dump` captures a CUDA OOM (traceback + torch memory summary) before re-raising.
# `H3_MEM_SAMPLE_INTERVAL` (s, 0 = off) drives the in-generation sampler thread.
_DEBUG_DIR = os.environ.get("H3_DEBUG_DIR", "/data/debug")
_MEM_SAMPLE_INTERVAL = float(os.environ.get("H3_MEM_SAMPLE_INTERVAL", "5"))


def _mem_info():
    """Compact GPU + CPU memory snapshot for the logs. Never raises."""
    _parts = []
    try:
        import torch
        if torch.cuda.is_available():
            _free, _total = torch.cuda.mem_get_info()
            _parts.append(
                f"gpu_alloc={torch.cuda.memory_allocated() / 2**30:.2f}G "
                f"gpu_resv={torch.cuda.memory_reserved() / 2**30:.2f}G "
                f"gpu_max={torch.cuda.max_memory_allocated() / 2**30:.2f}G "
                f"gpu_free={_free / 2**30:.2f}G/{_total / 2**30:.2f}G"
            )
    except Exception:
        pass
    try:
        import psutil
        _parts.append(f"rss={psutil.Process().memory_info().rss / 2**30:.2f}G")
    except Exception:
        try:
            with open("/proc/self/status") as _f:
                for _line in _f:
                    if _line.startswith("VmRSS:"):
                        _parts.append(f"rss={int(_line.split()[1]) / 2**20:.2f}G")
                        break
        except Exception:
            pass
    return " ".join(_parts) or "mem=n/a"


def _log_mem(tag):
    """Log a memory snapshot under the greppable `MEM` level."""
    _log(f"{tag}: {_mem_info()}", "MEM")


def _debug_dump(tag, text):
    """Persist a diagnostic to the bucket debug folder (/data/debug). Never raises."""
    try:
        os.makedirs(_DEBUG_DIR, exist_ok=True)
        _path = os.path.join(_DEBUG_DIR, f"{tag}_{time.strftime('%Y%m%d_%H%M%S')}.txt")
        _body = (
            f"=== {tag} @ {time.strftime('%Y-%m-%d %H:%M:%S')} ===\n"
            f"{_mem_info()}\n"
            f"{text}\n"
        )
        _tmp = _path + ".tmp"
        with open(_tmp, "w", encoding="utf-8") as _f:
            _f.write(_body)
        os.replace(_tmp, _path)
        try:
            shutil.copyfile(_path, os.path.join(_DEBUG_DIR, f"{tag}_latest.txt"))
        except OSError:
            pass
        _log(f"debug dump written: {_path}")
    except Exception as _e:
        _log(f"debug dump failed ({_e}); see logs", "WARN")


def _oom_dump(tag, exc, extra=""):
    """Capture a CUDA OOM: exception + context + torch memory summary, saved to the bucket."""
    _text = [f"exception: {type(exc).__name__}: {exc}"]
    if extra:
        _text.append(extra)
    _text.append(traceback.format_exc())
    try:
        import torch
        if torch.cuda.is_available():
            _text.append(torch.cuda.memory_summary())
    except Exception:
        pass
    _debug_dump(f"oom_{tag}", "\n".join(_text))
    _log(f"OOM captured ({tag}): {exc}", "ERROR")


# ── Bucket-backed LoRA cache ───────────────────────────────────────────────────
# Every downloaded LoRA is copied into the mounted bucket (/data) so a Space restart
# loads it from the bucket instead of re-downloading it. Falls back to the HF cache
# whenever the bucket isn't mounted or a write fails. `H3_LORA_CACHE_DIR` overrides
# the mount path (used by tests).
_LORA_CACHE_DIR = os.environ.get("H3_LORA_CACHE_DIR", "/data/loras")


def _lora_cache_path(repo, file):
    """Bucket path for a (repo, file) LoRA, or None if the bucket isn't usable."""
    try:
        os.makedirs(_LORA_CACHE_DIR, exist_ok=True)
        _probe = os.path.join(_LORA_CACHE_DIR, ".probe")
        with open(_probe, "w") as _f:
            _f.write("ok")
        os.remove(_probe)
    except Exception:
        return None
    _key = re.sub(r"[^A-Za-z0-9._-]", "_", f"{repo.replace('/', '__')}__{file}")
    return os.path.join(_LORA_CACHE_DIR, _key)


def _fetch_lora_file(repo, file):
    """Local path to a LoRA .safetensors, preferring the bucket cache over a fresh download."""
    from huggingface_hub import hf_hub_download

    _cached = _lora_cache_path(repo, file)
    if _cached and os.path.exists(_cached):
        try:
            with open(_cached, "rb") as _f:
                _n = struct.unpack("<Q", _f.read(8))[0]
                json.loads(_f.read(_n))
            _log(f"LoRA cache hit: {repo}/{file} ({os.path.getsize(_cached) / 1e6:.0f} MB)")
            return _cached
        except Exception:
            _log(f"LoRA cache corrupt, re-downloading: {repo}/{file}", "WARN")
            try:
                os.remove(_cached)
            except OSError:
                pass
    _t0 = time.time()
    _path = hf_hub_download(repo, file)
    _log(f"LoRA downloaded: {repo}/{file} ({os.path.getsize(_path) / 1e6:.0f} MB in {time.time() - _t0:.0f}s)")
    if _cached:
        try:
            _tmp = _cached + ".tmp"
            with open(_path, "rb") as _src, open(_tmp, "wb") as _dst:
                shutil.copyfileobj(_src, _dst, 1024 * 1024)
            os.replace(_tmp, _cached)
            _log(f"LoRA cached to bucket: {repo}/{file}")
        except Exception as _e:
            _log(f"LoRA bucket cache write failed ({_e}); using HF cache", "WARN")
    return _path


def _ensure_nsfw_lora_loaded(key):
    """Download + convert + store a lazy NSFW LoRA's A/B factors on CPU. No-op if already loaded."""
    if key in _NSFW_LoRA:
        return
    cfg = NSFW_LORA_CONFIGS[key]
    import torch
    from safetensors.torch import load_file as _load_lora
    _t0 = time.time()
    _log(f"loading NSFW LoRA {key} from {cfg['repo']} ...")
    _path = _fetch_lora_file(cfg["repo"], cfg["file"])
    _raw = _load_lora(_path)
    if cfg.get("format") == "kohya":
        _sd = _convert_kohya_h3_lora(_raw)
    else:
        _sd = _convert_comfyui_h3_lora(_raw)
    _pairs: dict[str, dict[str, torch.Tensor]] = {}
    for _k, _v in _sd.items():
        if ".lora_A." in _k:
            _pairs.setdefault(_k.split(".lora_A.")[0], {})["A"] = _v
        elif ".lora_B." in _k:
            _pairs.setdefault(_k.split(".lora_B.")[0], {})["B"] = _v
    _loaded = []
    for _base, _pair in _pairs.items():
        if "A" not in _pair or "B" not in _pair:
            continue
        _parts = _base.split(".")
        _obj = PIPE.transformer
        for _p in _parts:
            _obj = _obj[int(_p)] if _p.isdigit() else getattr(_obj, _p)
        _loaded.append((_obj, _pair["A"].to(_obj.weight.dtype), _pair["B"].to(_obj.weight.dtype)))
    del _sd, _pairs
    import gc as _gc; _gc.collect()
    _NSFW_LoRA[key] = _loaded
    _log(f"NSFW LoRA {key} parsed ({len(_loaded)} modules in {time.time() - _t0:.1f}s)")


def _ensure_custom_lora_loaded(repo, file):
    """Download + convert + store a user-supplied Hugging Face LoRA's A/B factors on CPU. No-op if already loaded."""
    key = (repo, file)
    if key in _CUSTOM_LoRA:
        return
    import torch
    from safetensors.torch import load_file as _load_lora
    _t0 = time.time()
    _log(f"loading custom LoRA {repo}/{file} ...")
    try:
        _path = _fetch_lora_file(repo, file)
        _raw = _load_lora(_path)
    except Exception as _e:
        raise gr.Error(f"Couldn't fetch custom LoRA `{repo}/{file}`: {_e}")
    _has_comfy = any(".lora_A." in _k for _k in _raw)
    _has_kohya = any(".lora_down.weight" in _k or _k.startswith("lora_unet_") for _k in _raw)
    if _has_comfy:
        _sd = _convert_comfyui_h3_lora(_raw)
    elif _has_kohya:
        _sd = _convert_kohya_h3_lora(_raw)
    else:
        raise gr.Error(f"`{repo}/{file}` doesn't look like a MiniMax-H3 LoRA (no lora_A/lora_down keys found).")
    _pairs: dict[str, dict[str, torch.Tensor]] = {}
    for _k, _v in _sd.items():
        if ".lora_A." in _k:
            _pairs.setdefault(_k.split(".lora_A.")[0], {})["A"] = _v
        elif ".lora_B." in _k:
            _pairs.setdefault(_k.split(".lora_B.")[0], {})["B"] = _v
    _loaded = []
    for _base, _pair in _pairs.items():
        if "A" not in _pair or "B" not in _pair:
            continue
        _parts = _base.split(".")
        _obj = PIPE.transformer
        for _p in _parts:
            _obj = _obj[int(_p)] if _p.isdigit() else getattr(_obj, _p)
        _loaded.append((_obj, _pair["A"].to(_obj.weight.dtype), _pair["B"].to(_obj.weight.dtype)))
    if not _loaded:
        raise gr.Error(f"`{repo}/{file}` converted to no usable modules β€” is it a MiniMax-H3 LoRA?")
    del _sd, _pairs, _raw
    import gc as _gc; _gc.collect()
    _CUSTOM_LoRA[key] = _loaded
    _log(f"custom LoRA {repo}/{file} parsed ({len(_loaded)} modules in {time.time() - _t0:.1f}s)")


def _parse_hf_link(url):
    """Parse a Hugging Face repo or file link into (repo, file). `file` is None for a bare repo link."""
    url = (url or "").strip().split("?")[0].split("#")[0]
    if not url:
        raise gr.Error("Paste a Hugging Face link first.")
    if not url.startswith("http"):
        parts = [p for p in url.split("/") if p]
        if len(parts) >= 2:
            return parts[0] + "/" + parts[1], "/".join(parts[2:]) or None
        raise gr.Error(f"Couldn't parse `{url}` as a Hugging Face repo link.")
    if "huggingface.co" not in url:
        raise gr.Error("Only Hugging Face links are supported (huggingface.co).")
    parts = [p for p in url.split("huggingface.co", 1)[1].strip("/").split("/") if p]
    if parts and parts[0] in ("spaces", "models", "datasets"):
        parts = parts[1:]  # https://huggingface.co/spaces/Owner/Repo β†’ Owner/Repo
    if len(parts) < 2:
        raise gr.Error(f"Couldn't parse `{url}` as a Hugging Face repo link.")
    repo = parts[0] + "/" + parts[1]
    if len(parts) == 2:
        return repo, None
    if parts[2] in ("resolve", "tree", "blob"):
        if len(parts) == 4 and parts[2] in ("tree", "blob"):
            return repo, None  # tree/main or blob/main with no subpath β†’ treat as a repo link
        if len(parts) < 5:
            raise gr.Error(f"Couldn't parse a filename from `{url}`.")
        if parts[3] != "main":
            raise gr.Error("Only `main`-branch links are supported β€” use a `resolve/main/...` link.")
        return repo, "/".join(parts[4:])
    return repo, "/".join(parts[2:])


def _resolve_repo_file(repo):
    """Pick the single .safetensors file of a repo link; error if there isn't exactly one."""
    from huggingface_hub import list_repo_files
    try:
        files = [f for f in list_repo_files(repo) if f.endswith(".safetensors")]
    except Exception as _e:
        raise gr.Error(f"Couldn't list files in `{repo}`: {_e}")
    if len(files) == 1:
        return files[0]
    if not files:
        raise gr.Error(f"No .safetensors files found in `{repo}`.")
    raise gr.Error(f"`{repo}` has multiple .safetensors files β€” paste a direct file link instead: "
                   + ", ".join(files[:5]) + ("…" if len(files) > 5 else ""))


def _download_custom_lora(url, scale=1.0, trigger=""):
    """Download + verify a user-supplied Hugging Face LoRA and report status. Loads it for the next Generate."""
    try:
        repo, file = _parse_hf_link(url)
        if file is None:
            file = _resolve_repo_file(repo)
        _ensure_custom_lora_loaded(repo, file)
    except gr.Error as _e:
        return gr.update(value=f"**❌ {_e}**", visible=True)
    except Exception as _e:
        return gr.update(value=f"**❌ Unexpected error loading the LoRA: {_e}**", visible=True)
    n = len(_CUSTOM_LoRA[(repo, file)])
    note = f" (scale {scale:g}" + (f", trigger `{trigger}`)" if trigger else ")")
    return gr.update(
        value=f"**βœ… Loaded `{repo}/{file}`** β€” {n} modules, will apply on Generate{note}.",
        visible=True,
    )


def _apply_lora(key, scale, store, merged):
    """Merge a loaded LoRA into transformer weights on GPU. A/B factors stay CPU-resident in

    `store`; local CUDA copies are made per merge so the store is never mutated."""
    if key in merged or key not in store:
        return
    _t0 = time.time()
    for _mod, _A, _B in store[key]:
        _mod.weight.data += (_B.to("cuda", non_blocking=True) @ _A.to("cuda", non_blocking=True)) * scale
    merged.add(key)
    _log(f"LoRA {key} merged ({len(store[key])} modules in {time.time() - _t0:.2f}s)")


def _remove_lora(key, scale, store, merged):
    """Undo a LoRA merge. Idempotent: only acts when `key` is in `merged`, and rolls back in

    reverse order so a partial failure leaves the fewest modules touched."""
    if key not in merged or key not in store:
        return
    _t0 = time.time()
    _done = 0
    try:
        for _mod, _A, _B in reversed(store[key]):
            _mod.weight.data -= (_B.to("cuda", non_blocking=True) @ _A.to("cuda", non_blocking=True)) * scale
            _done += 1
    except Exception as _e:
        _log(f"LoRA {key} partial unmerge ({_done}/{len(store[key])}): {_e}", "ERROR")
        raise
    merged.discard(key)
    import torch as _torch
    _torch.cuda.empty_cache()
    _log(f"LoRA {key} removed ({len(store[key])} modules in {time.time() - _t0:.2f}s)")


def _apply_nsfw(key):
    _apply_lora(key, NSFW_LORA_CONFIGS[key]["scale"], _NSFW_LoRA, _NSFW_merged)


def _remove_nsfw(key):
    _remove_lora(key, NSFW_LORA_CONFIGS[key]["scale"], _NSFW_LoRA, _NSFW_merged)


def _apply_custom(key, scale):
    _apply_lora(key, scale, _CUSTOM_LoRA, _CUSTOM_merged)


def _remove_custom(key, scale):
    _remove_lora(key, scale, _CUSTOM_LoRA, _CUSTOM_merged)


def status() -> str:
    if LOAD_ERROR:
        return LOAD_ERROR
    if PIPE is None:
        return f"Loading `{MODEL_REPO}` (transformer + VAEs, 77.3 GB). Watch the Space logs."
    import h3_aoti

    return (
        f"Ready Β· transformer + VAEs **bfloat16, unquantized** Β· placement `{PLACEMENT}` Β· attention `{ATTENTION}` Β· "
        f"{h3_aoti.status()} Β· loaded in {LOADED_IN:.0f}s Β· conditioner `{CONDITIONER_SPACE}`"
    )


def load_models() -> str | None:
    """Load the denoising half at startup.



    `MiniMaxH3GeneratorBlocks` declares `transformer`, `vae`, `audio_vae`, the two schedulers and `video_processor`,

    so `load_components` fetches exactly those subfolders β€” `text_encoder/` and `transformer_ref/` are never touched.

    Both autoencoders carry `_keep_in_fp32_modules` over every module and stay float32: a bfloat16 audio VAE decodes

    the soundtrack roughly 20 dB too quiet.

    """
    global PIPE, MANAGER, LOAD_ERROR, LOADED_IN

    if PIPE is not None or LOAD_ERROR is not None:
        return LOAD_ERROR

    started = time.time()
    try:
        _log_mem("startup begin")
        import torch
        from diffusers import ComponentsManager

        from h3_split_blocks import MiniMaxH3GeneratorBlocks

        lower_duration_floor()
        manager = ComponentsManager()
        blocks = MiniMaxH3GeneratorBlocks()
        _log(f"loading {[c.name for c in blocks.expected_components]} from {MODEL_REPO} ...")
        pipe = blocks.init_pipeline(MODEL_REPO, components_manager=manager, collection="h3")
        pipe.load_components(dtype=torch.bfloat16)
        pipe.transformer.set_attention_backend(ATTENTION)
        _log(f"components loaded in {time.time() - started:.0f}s")
        _log_mem("startup components loaded")

        if TURBO_LORA_REPO:
            from safetensors.torch import load_file as _load_lora

            _t0 = time.time()
            _log(f"loading turbo LoRA from {TURBO_LORA_REPO} ...")
            _lora_path = _fetch_lora_file(TURBO_LORA_REPO, TURBO_LORA_FILE)
            _lora_sd = _load_lora(_lora_path)

            # Group LoRA A/B pairs by target module name.
            _lora_pairs: dict[str, dict[str, torch.Tensor]] = {}
            for _k, _v in _lora_sd.items():
                if ".lora_A." in _k:
                    _base = _k.split(".lora_A.")[0]
                    _lora_pairs.setdefault(_base, {})["A"] = _v
                elif ".lora_B." in _k:
                    _base = _k.split(".lora_B.")[0]
                    _lora_pairs.setdefault(_base, {})["B"] = _v

            # Store LoRA A/B factors on CPU (~1.2 GB total).  The full delta (B @ A) would be
            # ~20 GB and overflow GPU memory when moved to CUDA inside @spaces.GPU (~14 GB free).
            # Instead _apply_turbo computes the delta on-the-fly: one temporary ~57 MB tensor
            # per module, freed each iteration.
            global TURBO_AVAILABLE, _TURBO_LoRA
            _TURBO_LoRA = []
            for _base_name, _pair in _lora_pairs.items():
                if "A" not in _pair or "B" not in _pair:
                    continue
                _base_name = _base_name.removeprefix("transformer.")
                _parts = _base_name.split(".")
                _obj = pipe.transformer
                for _p in _parts:
                    _obj = _obj[int(_p)] if _p.isdigit() else getattr(_obj, _p)
                _A = _pair["A"].to(_obj.weight.dtype)  # (rank, in_features)
                _B = _pair["B"].to(_obj.weight.dtype)  # (out_features, rank)
                _TURBO_LoRA.append((_obj, _A, _B))

            del _lora_sd, _lora_pairs
            import gc as _gc; _gc.collect()
            TURBO_AVAILABLE = True
            _log(f"turbo LoRA parsed ({len(_TURBO_LoRA)} modules in {time.time() - _t0:.0f}s, merge pending)")
            if _TURBO_LoRA:
                _m, _A, _B = _TURBO_LoRA[0]
                _log(f"  sample: module={type(_m).__name__}, "
                     f"A.shape={_A.shape}, B.shape={_B.shape}, "
                     f"A.device={_A.device}, dtype={_A.dtype}")
            _log_mem("startup turbo lora parsed")

        # Still startup, still free: an AoTI package carries no weights and opens its archive lazily inside the GPU
        # worker. Off unless `H3_AOTI=1`.
        import h3_aoti

        h3_aoti.maybe_load(pipe.transformer)

        if PLACEMENT == "pack":
            # Scoped to the transformer. `spaces` packs every startup-resident CUDA tensor into a second on-disk copy,
            # and packing all 77.3 GB busts the 150 GB storage quota; the 61.7 GB transformer alone fits. The ~10 GB of
            # fp32 VAEs move on the first GPU call instead.
            pipe.transformer.to("cuda")
            import gc as _gc
            _gc.collect()
            torch.cuda.empty_cache()
            _log_mem("startup transformer packed")

        if PLACEMENT == "offload":
            manager.enable_auto_cpu_offload(device="cuda")
            _arm_decode_hooks(pipe)

        PIPE, MANAGER = pipe, manager
        LOADED_IN = time.time() - started
        _log(f"ready in {LOADED_IN:.0f}s")
        _log_mem("startup ready")
        _dump_text = [f"placement={PLACEMENT}, attention={ATTENTION}, model={MODEL_REPO}"]
        try:
            import torch as _torch
            if _torch.cuda.is_available():
                _dump_text.append(_torch.cuda.memory_summary())
        except Exception:
            pass
        _debug_dump("startup", "\n".join(_dump_text))
        if _lora_cache_path("probe", "probe.safetensors"):
            _log(f"LoRA bucket cache ready: {_LORA_CACHE_DIR}")
        else:
            _log(f"LoRA bucket cache unavailable ({_LORA_CACHE_DIR} not writable); using HF cache only", "WARN")
    except Exception as error:
        traceback.print_exc()
        LOAD_ERROR = f"**Loading `{MODEL_REPO}` failed** after {time.time() - started:.0f}s: `{type(error).__name__}: {error}`"
    return LOAD_ERROR


def _arm_decode_hooks(pipe):
    """Make the offload hooks fire for the two VAEs.



    `enable_auto_cpu_offload` wraps `forward`, and the decode blocks call `vae.decode(...)` directly, so the hook

    never runs and the VAE is still on the host when the latents arrive on the card.

    """
    for name in ("vae", "audio_vae"):
        module = getattr(pipe, name)
        inner = module.decode

        def armed(*args, _module=module, _decode=inner, **kwargs):
            hook = getattr(_module, "_hf_hook", None)
            if hook is not None:
                hook.pre_forward(_module)
            return _decode(*args, **kwargs)

        module.decode = armed


@cache
def conditioner():
    """The other half, over the gradio API. `gradio_client` attaches the caller's own ZeroGPU token per call, so the

    conditioner's booking is billed to whoever asked for the video."""
    from gradio_client import Client

    return Client(CONDITIONER_SPACE)


def encode_remote(prompt, image_path, last_image_path, canvas, num_frames, rewrite_prompt=False):
    """`/encode` on the conditioner Space: a safetensors file holding `prompt_embeds` + `text_token_tags`, with the

    resolved `height` / `width` / `num_frames` in its metadata, plus the plan. `canvas` is the label.



    The cached `Client` is dropped and rebuilt on a failed call (the conditioner may have restarted

    or the connection dropped); one retry before giving up."""
    from gradio_client import handle_file
    from safetensors import safe_open

    _t0 = time.time()
    _log(f"encode_remote: conditioning on {CONDITIONER_SPACE} (canvas={canvas}, {num_frames}f, "
         f"rewrite={rewrite_prompt}, image={bool(image_path)}, last_image={bool(last_image_path)}) ...")
    for _attempt in (1, 2):
        try:
            path, plan = conditioner().predict(
                prompt=prompt,
                image_path=handle_file(image_path) if image_path else None,
                last_image_path=handle_file(last_image_path) if last_image_path else None,
                canvas=canvas,
                num_frames=num_frames,
                rewrite_prompt=bool(rewrite_prompt),
                api_name="/encode",
            )
            break
        except Exception:
            conditioner.cache_clear()
            if _attempt == 2:
                raise
            _log("encode_remote: conditioner call failed; reconnecting ...", "WARN")
            time.sleep(2)
    with safe_open(path, framework="pt") as handle:
        metadata = handle.metadata()
        _log(f"encode_remote: done in {time.time() - _t0:.0f}s "
             f"({plan.get('num_text_tokens')} tokens, {metadata.get('height')}x{metadata.get('width')}, "
             f"{metadata.get('num_frames')}f)")
        _log_mem("encode_remote done")
        _embeds = handle.get_tensor("prompt_embeds")
        _tags = handle.get_tensor("text_token_tags")
    try:
        os.remove(path)
    except OSError:
        pass
    return _embeds, _tags, metadata, plan


# Seconds of GPU one request needs, from the packed video rows it is about to denoise: linear in the rows for the
# matmuls, quadratic for the attention, against the AoTI block package this Space runs.
_DUR_B, _DUR_C = 1.1745e-4, 3.8396e-9
# The two resident decoders and the mux, which scale with the output rather than with the step count.
_DECODE_BASE, _DECODE_PER_DEFAULT_CANVAS, _DEFAULT_CANVAS_PIXELS = 15, 15, 960 * 544 * 124
# `pack` mode: only the ~10 GB of VAEs move on a cold worker.
_PLACEMENT_ALLOWANCE, _PAD = 12, 10


def get_duration(prompt_embeds, text_token_tags, image, last_image, height, width, num_frames, steps, seed, *a, **k):
    height, width, num_frames, steps = int(height), int(width), int(num_frames), int(steps)
    latent_frames = (num_frames - LATENTS_PER_CHUNK) // FRAMES_PER_CHUNK * LATENTS_PER_CHUNK + 2
    patches = (height // 32) * (width // 32)
    rows = latent_frames * patches + (int(image is not None) + int(last_image is not None)) * patches
    denoise = steps * (_DUR_B * rows + _DUR_C * rows**2)
    decode = _DECODE_BASE + _DECODE_PER_DEFAULT_CANVAS * (height * width * num_frames) / _DEFAULT_CANVAS_PIXELS
    _dur = max(60, int(denoise + decode) + _PLACEMENT_ALLOWANCE + _PAD)
    _log(f"get_duration: {width}x{height}, {num_frames}f, {steps} steps, rows={rows} -> {_dur}s "
         f"(denoise {denoise:.0f}s + decode {decode:.0f}s + {_PLACEMENT_ALLOWANCE + _PAD}s allowance)")
    return _dur


@spaces.GPU(duration=get_duration, size=GPU_SIZE)
def _generate(prompt_embeds, text_token_tags, image, last_image, height, width, num_frames, steps, seed, turbo=False, nsfw_keys=(), custom_loras=()):
    """The only thing on GPU time: the packed-sequence denoise loop and the two decoders.



    Only the three generated outputs come back β€” a `@spaces.GPU` return crosses a process boundary by pickling, and

    the full `PipelineState` still holds the packed latents, the rotary grid and the row indices on the card.

    """
    import torch

    _t0 = time.time()
    _log(f"_generate ENTER: turbo={turbo}, TURBO_AVAILABLE={TURBO_AVAILABLE}, "
         f"_TURBO_merged={_TURBO_merged}, steps={steps}, {width}x{height}, {num_frames}f, "
         f"nsfw={tuple(nsfw_keys)}, custom={[(r, f) for r, f, _s in custom_loras]}")
    _log_mem("_generate ENTER")

    # Intra-phase memory sampler: a hard OOM kill leaves no traceback, so the last sampler
    # lines before the crash are the only evidence of where memory grew. Queries only.
    _stop_sampler = threading.Event()
    def _sampler():
        while not _stop_sampler.wait(_MEM_SAMPLE_INTERVAL):
            _log_mem("sampler")
    if _MEM_SAMPLE_INTERVAL > 0:
        threading.Thread(target=_sampler, daemon=True).start()

    try:
        if PLACEMENT == "lazy":
            PIPE.to("cuda")
        elif PLACEMENT == "pack":
            PIPE.vae.to("cuda")
            PIPE.audio_vae.to("cuda")
        _log_mem("_generate VAEs on cuda")

        # Merge LoRA inside @spaces.GPU where the real weights are live on CUDA (in pack mode,
        # ZeroGPU unpacks the real transformer weights before calling this function).
        if turbo and TURBO_AVAILABLE:
            _log("_generate: calling _apply_turbo ...")
            _apply_turbo()
            _log("_generate: _apply_turbo done")
        for _key in nsfw_keys:
            _apply_nsfw(_key)
        for _repo, _file, _scale in custom_loras:
            _apply_custom((_repo, _file), _scale)
        _log_mem("_generate LoRAs merged")

        _log(f"_generate: starting PIPE (steps={steps}) ...")
        _log_mem("_generate before PIPE")
        state = PIPE(
            prompt_embeds=prompt_embeds.to("cuda"),
            text_token_tags=text_token_tags,
            image=image,
            last_image=last_image,
            height=height,
            width=width,
            num_frames=num_frames,
            num_inference_steps=int(steps),
            generator=torch.Generator("cpu").manual_seed(int(seed) if int(seed) >= 0 else torch.randint(0, 2**32, (1,)).item()),
        )
        _log(f"_generate: PIPE done in {time.time() - _t0:.0f}s")
        _log_mem("_generate after PIPE")
        # Pull the outputs out of the state before the finally block drops it: the state still holds
        # the packed latents, rotary grid and row indices on the card.
        _videos = state.get("videos")[0]
        _audio = state.get("audio")[0].cpu()
        _sampling_rate = state.get("sampling_rate")
    except torch.cuda.OutOfMemoryError as _e:
        _oom_dump("generate", _e, f"request: {width}x{height}, {num_frames}f, steps={steps}, "
                                  f"turbo={turbo}, nsfw={tuple(nsfw_keys)}, "
                                  f"custom={[(r, f) for r, f, _s in custom_loras]}")
        raise
    finally:
        _stop_sampler.set()
        # Each unmerge is attempted independently so one failure can't leave the others merged.
        for _repo, _file, _scale in custom_loras:
            try:
                _remove_custom((_repo, _file), _scale)
            except Exception as _e:
                _log(f"custom LoRA unmerge failed for {_repo}/{_file}: {_e}", "ERROR")
        for _key in nsfw_keys:
            try:
                _remove_nsfw(_key)
            except Exception as _e:
                _log(f"NSFW LoRA unmerge failed for {_key}: {_e}", "ERROR")
        if turbo and TURBO_AVAILABLE:
            try:
                _remove_turbo()
            except Exception as _e:
                _log(f"turbo LoRA unmerge failed: {_e}", "ERROR")
        # Aggressive worker-side release: drop the packed state and hand every cached CUDA block back
        # so the worker's GPU + RSS footprint is flat between requests.
        try:
            del state
        except Exception:
            pass
        import gc as _gc
        _gc.collect()
        torch.cuda.empty_cache()
    _log_mem("_generate EXIT")
    _log(f"_generate EXIT: {(time.time() - _t0):.0f}s total (denoise + decode)")
    return _videos, _audio, _sampling_rate


def _generate_impl(prompt, image_path=None, last_image_path=None, canvas=DEFAULT_CANVAS, duration=5, steps=25, seed=-1, upsample=False, turbo=False, nsfw_lora_keys=(), custom_lora_url="", custom_lora_scale=1.0, custom_lora_trigger="", progress=gr.Progress(track_tqdm=True)):
    """The request pipeline: LoRA prep β†’ remote conditioning β†’ @spaces.GPU denoise β†’ mux."""
    if LOAD_ERROR:
        raise gr.Error(LOAD_ERROR)
    if PIPE is None:
        raise gr.Error("The denoiser is still loading.")
    if not prompt or not prompt.strip():
        raise gr.Error("MiniMax-H3 always takes a prompt, keyframes or not.")

    from PIL import Image, ImageOps

    from diffusers.utils import encode_video

    num_frames = snap_frames(duration)

    if turbo and TURBO_AVAILABLE:
        steps = 7  # 7 sigma points β†’ 6 transformer evaluations (sweet spot for larryvrh v4-step600-EMA)

    # LoRAs the user selected via the catalog dropdown; the AIO motion adapter is auto-loaded whenever any is on.
    nsfw_keys = tuple(k for k in (nsfw_lora_keys or ()) if k in NSFW_LORA_CONFIGS)

    # User-supplied LoRA from the custom URL box: parse the link and require it was downloaded & verified.
    custom = []
    if custom_lora_url and str(custom_lora_url).strip():
        _repo, _file = _parse_hf_link(custom_lora_url)
        if _file is None:
            _file = _resolve_repo_file(_repo)
        if (_repo, _file) not in _CUSTOM_LoRA:
            raise gr.Error(f"`{_repo}/{_file}` isn't downloaded yet β€” press 'Download & Verify' first.")
        try:
            _scale = float(custom_lora_scale) if custom_lora_scale not in (None, "") else 1.0
        except (TypeError, ValueError):
            raise gr.Error("Custom LoRA scale must be a number.")
        if not 0.01 <= _scale <= 4.0:
            raise gr.Error("Custom LoRA scale must be between 0.01 and 4.")
        _trigger = str(custom_lora_trigger or "").strip()
        custom = [(_repo, _file, _scale, _trigger)]

    if nsfw_keys or custom:
        nsfw_keys += ("nsfw_aio",)
    for _key in nsfw_keys:
        _ensure_nsfw_lora_loaded(_key)
    for _key in nsfw_keys:
        # The trigger token must be in the prompt text for the conditioner to encode the LoRA's concept.
        prompt = f"{prompt}, {NSFW_LORA_CONFIGS[_key]['trigger']}"
    for _repo, _file, _scale, _trigger in custom:
        if _trigger:
            prompt = f"{prompt}, {_trigger}"

    progress(0.0, desc=f"Upsampling the prompt on {CONDITIONER_SPACE} ..." if upsample else f"Conditioning on {CONDITIONER_SPACE} ...")
    conditioned = time.time()
    prompt_embeds, text_token_tags, metadata, plan = encode_remote(
        prompt, image_path, last_image_path, canvas, num_frames, rewrite_prompt=upsample
    )
    condition_seconds = time.time() - conditioned
    _log_mem("after conditioning")
    height, width, num_frames = (int(metadata[key]) for key in ("height", "width", "num_frames"))
    refined = plan.get("refined_prompt") or ""

    def keyframe(path):
        # The conditioning latents encoded here have to be of the image the conditioner looked at, which it prepares
        # exactly this way.
        return ImageOps.exif_transpose(Image.open(path)).convert("RGB") if path else None

    progress(0.1, desc=f"Denoising {steps} steps at {width}x{height}, {num_frames} frames ...")
    started = time.time()
    frames, audio, sampling_rate = _generate(
        prompt_embeds,
        text_token_tags,
        keyframe(image_path),
        keyframe(last_image_path),
        height,
        width,
        num_frames,
        steps,
        seed,
        turbo,
        nsfw_keys=nsfw_keys,
        custom_loras=[(r, f, s) for r, f, s, _t in custom],
    )
    generate_seconds = time.time() - started

    directory = os.path.join(tempfile.gettempdir(), "h3-outputs")
    os.makedirs(directory, exist_ok=True)
    # Rotate: keep only the newest _MAX_OUTPUTS MP4s so /tmp never fills up.
    _MAX_OUTPUTS = 25
    for _f in sorted(glob.glob(os.path.join(directory, "*.mp4")), key=os.path.getmtime)[:-_MAX_OUTPUTS]:
        try:
            os.remove(_f)
        except OSError:
            pass
    path = os.path.join(directory, f"h3-{int(time.time() * 1000)}.mp4")
    encode_video(frames, fps=FPS, output_path=path, audio=audio, audio_sample_rate=sampling_rate)
    _log_mem("after mux")
    # The frames list and audio tensor are the last big main-process objects; drop them now.
    del frames, audio
    import gc as _gc
    _gc.collect()

    lora_note = " Β· LoRA: " + ", ".join(NSFW_LORA_CONFIGS[k]["trigger"] for k in nsfw_keys) if nsfw_keys else ""
    lora_label_text = "**LoRAs applied:** " + ", ".join(NSFW_LORA_CONFIGS[k]["label"] for k in nsfw_keys) if nsfw_keys else ""
    if custom:
        _custom_note = ", ".join(f"{r}/{f} (Γ—{s:g})" for r, f, s, _t in custom)
        lora_note = (lora_note + " Β· custom: " + _custom_note) if lora_note else " Β· custom: " + _custom_note
        lora_label_text = (lora_label_text + " Β· " + _custom_note) if lora_label_text else "**LoRAs applied:** " + _custom_note
    report = (
        f"`{width}x{height}`, {num_frames} frames ({num_frames / FPS:.3f} s), {int(steps)} steps Β· "
        f"conditioner {condition_seconds:.0f}s ({plan['num_text_tokens']} tokens"
        f"{', upsampled' if refined else ''}) Β· "
        f"denoise + decode {generate_seconds:.0f}s ({generate_seconds / int(steps):.1f} s/step) Β· seed {int(seed)}"
        f"{lora_note}"
    )
    _log(report)
    return path, report, refined, gr.update(visible=bool(refined)), gr.DownloadButton(value=path, visible=True), gr.update(value=lora_label_text, visible=bool(nsfw_keys) or bool(custom))


def generate(prompt, image_path=None, last_image_path=None, canvas=DEFAULT_CANVAS, duration=5, steps=25, seed=-1, upsample=False, turbo=False, nsfw_lora_keys=(), custom_lora_url="", custom_lora_scale=1.0, custom_lora_trigger="", progress=gr.Progress(track_tqdm=True)):
    """One request. `upsample` is last among the pre-existing positional args, so a positional API client that

    predates it is unaffected; the custom-LoRA args come after it.



    Logs the full request to the Space logs, then runs the pipeline. Any failure is logged with a full

    traceback before it reaches the UI.

    """
    _log(f"generate ENTER: prompt={prompt!r:.120}, canvas={canvas}, duration={duration}s -> {snap_frames(duration)}f, "
         f"steps={steps}, seed={seed}, upsample={upsample}, turbo={turbo}, "
         f"nsfw={tuple(nsfw_lora_keys or ())}, custom_url={custom_lora_url!r}, "
         f"custom_scale={custom_lora_scale}, custom_trigger={custom_lora_trigger!r}")
    _t_req = time.time()
    try:
        return _generate_impl(
            prompt, image_path, last_image_path, canvas, duration, steps, seed, upsample, turbo,
            nsfw_lora_keys, custom_lora_url, custom_lora_scale, custom_lora_trigger, progress,
        )
    except gr.Error as _e:
        _log(f"generate rejected: {_e}", "WARN")
        raise
    except Exception as _e:
        _log(f"generate FAILED after {time.time() - _t_req:.0f}s:\n{traceback.format_exc()}", "ERROR")
        try:
            import torch as _torch
            if isinstance(_e, _torch.cuda.OutOfMemoryError):
                _oom_dump("request", _e)
        except Exception:
            pass
        raise


def export_last_frame(video_path):
    """Extract the last frame from a generated video and return it as an image file."""
    if not video_path:
        raise gr.Error("No video to extract from.")
    import subprocess, tempfile
    out = os.path.join(tempfile.gettempdir(), f"h3-lastframe-{int(time.time() * 1000)}.png")
    result = subprocess.run(
        ["ffmpeg", "-sseof", "-0.1", "-i", video_path, "-frames:v", "1", "-y", out],
        capture_output=True, text=True,
    )
    if result.returncode != 0:
        raise gr.Error(f"ffmpeg failed: {result.stderr[-300:]}")
    return out


def _fit_keyframe(image_path, current_canvas):
    """Cover-crop an uploaded keyframe to the closest supported aspect ratio and select that ratio's smallest

    (fastest) canvas, unless the user already picked a matching ratio."""
    if not image_path:
        return gr.update(), gr.update()
    from PIL import Image as _Image

    img = _Image.open(image_path)
    aspect = img.width / img.height
    fastest = {}
    for label, (h, w) in CANVASES.items():
        r = w / h
        if r not in fastest or w * h < fastest[r][1][0] * fastest[r][1][1]:
            fastest[r] = (label, (h, w))
    ratio = min(fastest, key=lambda r: abs(r - aspect))
    label, (h, w) = fastest[ratio]

    cur_h, cur_w = CANVASES[current_canvas]
    if abs(cur_w / cur_h - aspect) <= abs(ratio - aspect):
        label = current_canvas
        h, w = cur_h, cur_w

    target = w / h
    if abs(img.width / img.height - target) <= 1e-3:
        return gr.update(value=image_path), gr.update(value=label)
    if img.width / img.height > target:
        new_w = int(img.height * target)
        left = (img.width - new_w) // 2
        img = img.crop((left, 0, left + new_w, img.height))
    else:
        new_h = int(img.width / target)
        top = (img.height - new_h) // 2
        img = img.crop((0, top, img.width, top + new_h))
    img.save(image_path)
    return gr.update(value=image_path), gr.update(value=label)


load_models()

INTRO = """# minimax h3 turbo + lora's



<div align="center">

  <a href="https://huggingface.co/MiniMaxAI/MiniMax-H3" target="_blank" rel="noopener"><strong>[ model ]</strong></a> &nbsp;

  <a href="https://www.minimax.io/blog/minimax-h3" target="_blank" rel="noopener"><strong>[ blog ]</strong></a> &nbsp;

  <a href="https://huggingface.co/spaces/multimodalart/minimax-h3-reference" target="_blank" rel="noopener"><strong>[ reference to video ]</strong></a>

</div>



**MiniMax-H3** is a 33B parameter state of the art video generation model that produces video and a

fully synchronized soundtrack (ambience, foley, speech).



**Turbo mode** (optional) applies the [larryvrh distillation LoRA](https://huggingface.co/InstantX/MiniMax-H3-Turbo-Lora-Diffusers)

at generation time, reducing inference from 25 steps to 7 for ~4Γ— faster generation with minimal quality loss.

"""

CSS = """

.main.fillable { max-width: 1250px !important; }



/* ── Root gradient background ── */

.dark .gradio-container {

    background: linear-gradient(135deg, #0a1628 0%, #0d2137 25%, #0f2b3a 50%, #0e3330 75%, #0a2a1f 100%) !important;

    color: #e8f0f8 !important;

    min-height: 100vh;



    /* ── Override Gradio's CSS variables for dark theme ── */

    --background-fill-primary: rgba(10, 22, 40, 0.6) !important;

    --background-fill-secondary: rgba(10, 22, 40, 0.4) !important;

    --block-background-fill: rgba(10, 22, 40, 0.5) !important;

    --block-border-color: rgba(79, 195, 247, 0.15) !important;

    --block-label-text-color: #a8c4d8 !important;

    --block-title-text-color: #a8c4d8 !important;

    --background-text-color: #e0edf5 !important;

    --body-text-color: #e0edf5 !important;

    --body-text-color-subdued: #8aa8bc !important;

    --border-color-primary: rgba(79, 195, 247, 0.15) !important;

    --color-accent: #26a69a !important;

    --color-accent-soft: rgba(38, 166, 154, 0.15) !important;

    --button-primary-background-fill: linear-gradient(135deg, #0288d1 0%, #00897b 50%, #2e7d32 100%) !important;

    --button-primary-text-color: #ffffff !important;

    --button-secondary-background-fill: rgba(255, 255, 255, 0.06) !important;

    --button-secondary-border-color: rgba(255, 255, 255, 0.1) !important;

    --button-secondary-text-color: #b0c8dc !important;

    --input-background-fill: rgba(10, 22, 40, 0.6) !important;

    --input-background-fill-focus: rgba(10, 22, 40, 0.7) !important;

    --input-border-color: rgba(79, 195, 247, 0.15) !important;

    --input-border-color-focus: rgba(79, 195, 247, 0.45) !important;

    --slider-color: #26a69a !important;

    --accordion-border-color: rgba(255, 255, 255, 0.06) !important;

}



/* ── Intro markdown ── */

.gradio-container .prose h1,

.gradio-container .prose h2 {

    background: linear-gradient(135deg, #4fc3f7, #26a69a) !important;

    -webkit-background-clip: text !important;

    -webkit-text-fill-color: transparent !important;

    background-clip: text !important;

}

.gradio-container .prose {

    color: #c8dde8 !important;

}

.gradio-container .prose a {

    color: #4dd0e1 !important;

}



/* ── Glass card panels (no backdrop-filter on .block β€” it traps fixed-position dropdown popups) ── */

.gradio-container .block {

    background: rgba(255, 255, 255, 0.04) !important;

    border: 1px solid rgba(255, 255, 255, 0.08) !important;

    border-radius: 14px !important;

    box-shadow: 0 4px 30px rgba(0, 0, 0, 0.25), inset 0 1px 0 rgba(255,255,255,0.05) !important;

}



/* ── Text / Number inputs (Gradio 6: label.container > .input-container > textarea/input) ── */

.gradio-container label.container textarea,

.gradio-container label.container input[type="text"],

.gradio-container input[type="number"] {

    background: rgba(10, 22, 40, 0.6) !important;

    border: 1px solid rgba(79, 195, 247, 0.15) !important;

    color: #e0edf5 !important;

    border-radius: 10px !important;

}

.gradio-container label.container textarea:focus,

.gradio-container label.container input[type="text"]:focus,

.gradio-container input[type="number"]:focus {

    border-color: rgba(79, 195, 247, 0.45) !important;

    box-shadow: 0 0 0 2px rgba(79, 195, 247, 0.12) !important;

}



/* ── Labels (Gradio 6: BlockTitle renders <span data-testid="block-info">) ── */

.gradio-container [data-testid="block-info"],

.gradio-container label {

    color: #a8c4d8 !important;

    font-weight: 500 !important;

}



/* ── Slider track ── */

.gradio-container input[type="range"] {

    accent-color: #26a69a !important;

}



/* ── Checkbox (Gradio 6: <label class="checkbox-container"> β†’ <input> + <span class="label-text">) ── */

.gradio-container .checkbox-container {

    color: #c0d4e4 !important;

}

.gradio-container .checkbox-container .label-text {

    color: #c0d4e4 !important;

}



/* ── Dropdown (Gradio 6: div.container > div.wrap > div.wrap-inner > input[role="combobox"]) ── */

.gradio-container .wrap {

    background: rgba(10, 22, 40, 0.6) !important;

    border: 1px solid rgba(79, 195, 247, 0.15) !important;

    border-radius: 10px !important;

}

.gradio-container .wrap:focus-within {

    border-color: rgba(79, 195, 247, 0.45) !important;

    box-shadow: 0 0 0 2px rgba(79, 195, 247, 0.12) !important;

}

.gradio-container .wrap-inner input[role="combobox"] {

    color: #e0edf5 !important;

    background: transparent !important;

}

/* Dropdown popup options (Gradio 6: <ul class="options"> with position:fixed) */

.gradio-container ul.options {

    background: rgba(10, 22, 40, 0.95) !important;

    border: 1px solid rgba(79, 195, 247, 0.25) !important;

    border-radius: 10px !important;

    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.5) !important;

    z-index: 1000 !important;

}

.gradio-container ul.options li.item {

    color: #e0edf5 !important;

}

.gradio-container ul.options li.item:hover,

.gradio-container ul.options li.item.active {

    background: rgba(79, 195, 247, 0.15) !important;

}



/* ── Image upload area ── */

.gradio-container .image-container,

.gradio-container .upload-container {

    background: rgba(10, 22, 40, 0.35) !important;

    border: 2px dashed rgba(79, 195, 247, 0.2) !important;

    border-radius: 12px !important;

}

.gradio-container .image-container:hover,

.gradio-container .upload-container:hover {

    border-color: rgba(38, 166, 154, 0.5) !important;

}



/* ── Video output ── */

.gradio-container video {

    border-radius: 12px !important;

    border: 1px solid rgba(255,255,255,0.06) !important;

}



/* ── Generate button β€” hero gradient ── */

.gradio-container .lg.primary,

.gradio-container button.primary,

.gradio-container button.lg.primary {

    background: linear-gradient(135deg, #0288d1 0%, #00897b 50%, #2e7d32 100%) !important;

    color: #ffffff !important;

    border: none !important;

    border-radius: 12px !important;

    font-weight: 700 !important;

    letter-spacing: 0.03em !important;

    text-transform: uppercase !important;

    box-shadow: 0 4px 20px rgba(0, 137, 123, 0.35), 0 0 40px rgba(2, 136, 209, 0.15) !important;

    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1) !important;

    position: relative;

    overflow: hidden;

}

.gradio-container .lg.primary::before {

    content: "";

    position: absolute;

    inset: 0;

    background: linear-gradient(135deg, rgba(255,255,255,0.15) 0%, transparent 50%, rgba(255,255,255,0.05) 100%);

    pointer-events: none;

}

.gradio-container .lg.primary:hover,

.gradio-container button.primary:hover {

    box-shadow: 0 6px 28px rgba(0, 137, 123, 0.5), 0 0 60px rgba(2, 136, 209, 0.25) !important;

    transform: translateY(-1px) !important;

}



/* ── Secondary buttons ── */

.gradio-container button.secondary,

.gradio-container button.lg.secondary {

    background: rgba(255, 255, 255, 0.06) !important;

    border: 1px solid rgba(255, 255, 255, 0.1) !important;

    color: #b0c8dc !important;

}

.gradio-container button.secondary:hover {

    background: rgba(255, 255, 255, 0.1) !important;

    border-color: rgba(79, 195, 247, 0.3) !important;

}



/* ── Accordion (Gradio 6: Index.svelte adds "gr-accordion" to elem_classes; header is <button class="label-wrap">) ── */

.gradio-container .gr-accordion {

    background: rgba(255, 255, 255, 0.03) !important;

    border: 1px solid rgba(255, 255, 255, 0.06) !important;

    border-radius: 12px !important;

}

.gradio-container .gr-accordion .label-wrap {

    color: #a8c4d8 !important;

    font-weight: 600 !important;

}

.gradio-container .gr-accordion .label-wrap:hover {

    color: #4fc3f7 !important;

}

.gradio-container .gr-accordion [data-testid="accordion-content"] {

    padding-top: var(--size-2, 8px) !important;

}



/* ── Examples ── */

.gradio-container .examples {

    background: rgba(10, 22, 40, 0.3) !important;

    border: 1px solid rgba(255, 255, 255, 0.06) !important;

    border-radius: 12px !important;

}



/* ── Markdown output ── */

.gradio-container .prose {

    color: #b8ccda !important;

}

.gradio-container .prose code {

    background: rgba(79, 195, 247, 0.1) !important;

    color: #4dd0e1 !important;

    border-radius: 4px !important;

    padding: 2px 6px !important;

}



/* ── Scrollbar ── */

.gradio-container ::-webkit-scrollbar {

    width: 6px !important;

}

.gradio-container ::-webkit-scrollbar-track {

    background: rgba(0,0,0,0.2) !important;

}

.gradio-container ::-webkit-scrollbar-thumb {

    background: rgba(79, 195, 247, 0.3) !important;

    border-radius: 3px !important;

}

"""

def _lora_descriptions(keys):
    """Markdown of each selected LoRA's label + description, plus conflict warnings; hidden when nothing is selected."""
    keys = tuple(k for k in (keys or ()) if k in NSFW_LORA_CONFIGS)
    if not keys:
        return gr.update(visible=False)
    blocks = [f"**{NSFW_LORA_CONFIGS[k]['label']}** β€” {NSFW_LORA_CONFIGS[k]['desc']}" for k in keys]
    conflicts = []
    for group, members in LORA_CONFLICT_GROUPS.items():
        hit = [k for k in keys if k in members]
        if len(hit) > 1:
            conflicts.append(f"**{group}**: " + " + ".join(NSFW_LORA_CONFIGS[k]['label'] for k in hit))
    if conflicts:
        blocks.append("**⚠️ Conflicts:** " + "  ".join(conflicts)
                      + " β€” these overlap in purpose and may fight each other; consider picking one from each group.")
    return gr.update(value="\n\n".join(blocks), visible=True)

with gr.Blocks(title="minimax h3 turbo + lora's") as demo:
    gr.Markdown(INTRO)

    with gr.Row():
        with gr.Column():
            prompt = gr.Textbox(
                label="Prompt",
                lines=3,
                value="A red fox trotting through a snowy pine forest at dawn, snow crunching underfoot",
            )
            with gr.Row():
                upsample = gr.Checkbox(label="Upsample prompt", value=False)
                turbo = gr.Checkbox(label="Turbo (7-step LoRA)", value=False,
                                    visible=TURBO_AVAILABLE,
                                    info="Apply larryvrh distillation LoRA, reduce steps from 25 to 7")
            with gr.Accordion("NSFW LoRAs", open=False):
                nsfw_lora_keys = gr.Dropdown(
                    label="Select LoRAs to apply",
                    choices=[(cfg["label"], key) for key, cfg in NSFW_LORA_CONFIGS.items() if key != "nsfw_aio"],
                    value=[],
                    multiselect=True,
                    filterable=True,
                    info="Searchable β€” type to filter. Selected LoRAs show as removable tags; their trigger tokens are auto-appended to the prompt. The HMNSFW AIO motion adapter auto-loads whenever any LoRA is selected.",
                )
                lora_desc = gr.Markdown(visible=False)
            with gr.Accordion("Custom LoRA (Hugging Face)", open=False):
                gr.Markdown("Paste a Hugging Face link β€” a repo page or a direct `.safetensors` file link β€” then press "
                            "**Download & Verify**. The verified LoRA is applied on Generate. "
                            "ComfyUI and kohya formats are auto-detected.")
                custom_lora_url = gr.Textbox(
                    label="HF repo or .safetensors link",
                    placeholder="https://huggingface.co/Owner/Repo  or  https://huggingface.co/Owner/Repo/resolve/main/file.safetensors",
                )
                with gr.Row():
                    custom_lora_scale = gr.Number(label="Scale", value=1.0, minimum=0.01, maximum=4.0, step=0.1)
                    custom_lora_trigger = gr.Textbox(label="Trigger (optional)",
                                                     placeholder="Auto-appended to the prompt if given")
                custom_lora_btn = gr.Button("Download & Verify", size="sm")
                custom_lora_status = gr.Markdown(visible=False)
            with gr.Row():
                image = gr.Image(label="First frame (optional)", type="filepath")
                last_image = gr.Image(label="Last frame (optional)", type="filepath")
            run = gr.Button("Generate", variant="primary")
            with gr.Accordion("Advanced options", open=False):
                canvas = gr.Dropdown(label="Canvas", choices=list(CANVASES), value=DEFAULT_CANVAS)
                duration = gr.Slider(label="Duration (s)", minimum=MIN_UI_DURATION, maximum=MAX_UI_DURATION, step=1, value=5)
                steps = gr.Slider(label="Steps", minimum=7, maximum=40, step=1, value=25)
                seed = gr.Number(label="Seed (βˆ’1 = random)", value=-1, precision=0)

        with gr.Column():
            video = gr.Video(label="Video + soundtrack")
            with gr.Row():
                last_frame_btn = gr.Button("Export Last Frame", size="sm")
                download_btn = gr.DownloadButton("Download Video", size="sm", visible=False)
            last_frame_output = gr.Image(label="Last frame")
            lora_label = gr.Markdown(visible=False)
            report = gr.Markdown(visible=False)
            # An output, so it can be revealed only for a request that asked for a rewrite.
            with gr.Accordion("Upsampled prompt", open=False, visible=False) as upsampled_panel:
                upsampled = gr.Textbox(show_label=False, lines=8, interactive=False)

    image.upload(_fit_keyframe, [image, canvas], [image, canvas])

    run.click(
        generate,
        [prompt, image, last_image, canvas, duration, steps, seed, upsample, turbo, nsfw_lora_keys,
         custom_lora_url, custom_lora_scale, custom_lora_trigger],
        [video, report, upsampled, upsampled_panel, download_btn, lora_label],
        api_name="generate",
    )

    custom_lora_btn.click(_download_custom_lora,
                          [custom_lora_url, custom_lora_scale, custom_lora_trigger],
                          [custom_lora_status])

    nsfw_lora_keys.change(_lora_descriptions, [nsfw_lora_keys], [lora_desc])

    last_frame_btn.click(
        export_last_frame,
        [video],
        [last_frame_output],
    )

    download_btn.click(
        lambda: gr.Info("Downloading video..."),
        [],
        [],
    )


if __name__ == "__main__":
    demo.launch(show_error=True, theme=gr.themes.Base(), css=CSS)