File size: 61,963 Bytes
1c97e64
 
 
 
 
 
 
 
 
 
 
 
ff9fe10
 
 
 
 
 
 
 
e159346
ff9fe10
 
1c97e64
 
ff9fe10
 
 
 
 
 
 
 
e159346
1c97e64
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ff9fe10
1c97e64
 
 
 
 
 
 
 
 
ff9fe10
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e159346
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ff9fe10
 
 
 
 
 
 
 
 
 
 
e159346
 
 
 
 
 
 
 
 
 
 
 
ff9fe10
 
 
 
 
e159346
ff9fe10
 
e159346
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ff9fe10
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1c97e64
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ff9fe10
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1c97e64
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""

LoRA Loader for WAN 2.2 I2V - multi-repo.

Baseline: lkzd7/WAN2.2_LoraSet_NSFW. Plus curated I2V act/helper LoRAs from

Lythiga/WAN2.2_I2V_Lora, rolechar/rc_wan2.2_i2v_loraset_nsfw_private,

lopi999/Wan2.2-I2V_General-NSFW-LoRA. T2V / lightning / furry / dance / male-char filtered out.



Auto-activation: scored inverse-concept-frequency (ICF) matching against the

normalized prompt. Each LoRA's score sums the distinctiveness weights of every

trigger phrase present in the prompt; concept categories dedupe output to at

most one LoRA per category. See LORA_AUTO_PHRASES / LORA_AUTO_CATEGORIES /

auto_activation_details below.

"""
import os
import urllib.parse
import re
import math
import json
import hashlib
import tempfile
import urllib.request
import requests
import safetensors.torch
from huggingface_hub import hf_hub_download

LORA_REPO = "lkzd7/WAN2.2_LoraSet_NSFW"
HF_TOKEN = os.environ.get("HF_TOKEN")  # authenticated downloads (covers private repos)

# The Space mounts its persistent HF Bucket at /data.  User-added LoRAs live
# here rather than in the ephemeral Hugging Face cache, so a LoRA fetched once
# remains available after the Space sleeps or restarts.
LORA_LIBRARY_DIR = os.environ.get("LORA_LIBRARY_DIR", "/data/loras")
LORA_LIBRARY_MANIFEST = os.path.join(LORA_LIBRARY_DIR, "library.json")
MAX_CUSTOM_LORA_BYTES = int(os.environ.get("MAX_CUSTOM_LORA_BYTES", 8 * 1024**3))
CIVITAI_HOSTS = ("civitai.com", "civitai.red", "civitai.green", "civitai.work")

# Pinned commit hashes (2026-07-19) β€” protection from breaking upstream changes
PINNED_REVISIONS = {
    "lkzd7/WAN2.2_LoraSet_NSFW": "ccfa867ce4b1",
    "Lythiga/WAN2.2_I2V_Lora": "67ef542e6faa",
    "rolechar/rc_wan2.2_i2v_loraset_nsfw_private": "4855a2f216ac",
    "lopi999/Wan2.2-I2V_General-NSFW-LoRA": "aeef17d7fa51",
}

LORA_FILES = [
    "Blink_Squatting_Cowgirl_Position_I2V_HIGH.safetensors",
    "Blink_Squatting_Cowgirl_Position_I2V_LOW.safetensors",
    "PENISLORA_22_i2v_HIGH_e320.safetensors",
    "PENISLORA_22_i2v_LOW_e496.safetensors",
    "Pornmaster_wan 2.2_14b_I2V_bukkake_v1.4_high_noise.safetensors",
    "Pornmaster_wan 2.2_14b_I2V_bukkake_v1.4_low_noise.safetensors",
    "W22_Multiscene_Photoshoot_Softcore_i2v_HN.safetensors",
    "W22_Multiscene_Photoshoot_Softcore_i2v_LN.safetensors",
    "WAN-2.2-I2V-Double-Blowjob-HIGH-v1.safetensors",
    "WAN-2.2-I2V-Double-Blowjob-LOW-v1.safetensors",
    "WAN-2.2-I2V-HandjobBlowjobCombo-HIGH-v1.safetensors",
    "WAN-2.2-I2V-HandjobBlowjobCombo-LOW-v1.safetensors",
    "WAN-2.2-I2V-SensualTeasingBlowjob-HIGH-v1.safetensors",
    "WAN-2.2-I2V-SensualTeasingBlowjob-LOW-v1.safetensors",
    "iGOON_Blink_Blowjob_I2V_HIGH.safetensors",
    "iGOON_Blink_Blowjob_I2V_LOW.safetensors",
    "iGoon - Blink_Front_Doggystyle_I2V_HIGH.safetensors",
    "iGoon - Blink_Front_Doggystyle_I2V_LOW.safetensors",
    "iGoon - Blink_Missionary_I2V_HIGH.safetensors",
    "iGoon - Blink_Missionary_I2V_LOW v2.safetensors",
    "iGoon - Blink_Missionary_I2V_LOW.safetensors",
    "iGoon%20-%20Blink_Back_Doggystyle_HIGH.safetensors",
    "iGoon%20-%20Blink_Back_Doggystyle_LOW.safetensors",
    "iGoon%20-%20Blink_Facial_I2V_HIGH.safetensors",
    "iGoon%20-%20Blink_Facial_I2V_LOW.safetensors",
    "iGoon_Blink_Missionary_I2V_HIGH v2.safetensors",
    "iGoon_Blink_Titjob_I2V_HIGH.safetensors",
    "iGoon_Blink_Titjob_I2V_LOW.safetensors",
    "lips-bj_high_noise.safetensors",
    "lips-bj_low_noise.safetensors",
    "mql_casting_sex_doggy_kneel_diagonally_behind_vagina_wan22_i2v_v1_high_noise.safetensors",
    "mql_casting_sex_doggy_kneel_diagonally_behind_vagina_wan22_i2v_v1_low_noise.safetensors",
    "mql_casting_sex_reverse_cowgirl_lie_front_vagina_wan22_i2v_v1_high_noise.safetensors",
    "mql_casting_sex_reverse_cowgirl_lie_front_vagina_wan22_i2v_v1_low_noise.safetensors",
    "mql_casting_sex_spoon_wan22_i2v_v1_high_noise.safetensors",
    "mql_casting_sex_spoon_wan22_i2v_v1_low_noise.safetensors",
    "mql_massage_tits_wan22_i2v_v1_high_noise.safetensors",
    "mql_massage_tits_wan22_i2v_v1_low_noise.safetensors",
    "mql_panties_aside_wan22_i2v_v1_high_noise.safetensors",
    "mql_panties_aside_wan22_i2v_v1_low_noise.safetensors",
    "sfbehind_v2.1_high_noise.safetensors",
    "sfbehind_v2.1_low_noise.safetensors",
    "sid3l3g_transition_v2.0_H.safetensors",
    "sid3l3g_transition_v2.0_L.safetensors",
    "wan2.2_i2v_high_ulitmate_pussy_asshole.safetensors",
    "wan2.2_i2v_low_ulitmate_pussy_asshole.safetensors",
    "wan22-mouthfull-140epoc-high-k3nk.safetensors",
    "wan22-mouthfull-152epoc-low-k3nk.safetensors",
]

# group -> {"HIGH": (repo, file) | None, "LOW": (repo, file) | None}
LORA_PAIRS = {}
for f in LORA_FILES:
    name = urllib.parse.unquote(f).replace(".safetensors", "")
    is_high = bool(re.search(r'(high|HN|_H\b)', name, re.IGNORECASE))
    is_low = bool(re.search(r'(low|LN|_L\b)', name, re.IGNORECASE))
    group = re.sub(r'[\s_-]*(high|low|noise|HN|LN)([\s_-]*noise)?[\s_-]*(v?\d+(\.\d+)?)?\s*$', '', name, flags=re.IGNORECASE).strip()
    group = re.sub(r'[\s_]+$', '', group)
    LORA_PAIRS.setdefault(group, {"HIGH": None, "LOW": None})
    if is_high:
        LORA_PAIRS[group]["HIGH"] = (LORA_REPO, f)
    elif is_low:
        LORA_PAIRS[group]["LOW"] = (LORA_REPO, f)

L = "Lythiga/WAN2.2_I2V_Lora"
R = "rolechar/rc_wan2.2_i2v_loraset_nsfw_private"
P = "lopi999/Wan2.2-I2V_General-NSFW-LoRA"

# curated extra act/helper LoRAs (label -> (repo, high_file, low_file|None))
EXTRA = {
    # --- deepthroat ---
    "Ultimate Deepthroat": (L, "wan22-ultimatedeepthroat-i2v-102epoc-high-k3nk.safetensors", "wan22-ultimatedeepthroat-I2V-101epoc-low-k3nk.safetensors"),
    "BBC Deepthroat": (L, "wan22-bbcdeepthroat-115epoc-high-k3nk.safetensors", "wan22-bbcdeepthroat-155epoc-low-720-k3nk.safetensors"),
    "Throat V2": (L, "Wan22_ThroatV2_High.safetensors", "Wan22_ThroatV2_Low.safetensors"),
    "JFJ Deepthroat": (L, "jfj-deepthroat-W22-I2V-HN.safetensors", None),
    # --- blowjob extra ---
    "BBC Blowjob Extreme": (L, "BBC Blowjobs Extreme_high_noise.safetensors", "BBC Blowjobs Extreme_low_noise.safetensors"),
    "POV Blowjob": (L, "Pov_Blowjob_Wan2.2_high_I2V_v1.0.safetensors", None),
    # --- cunnilingus ---
    "Cunnilingus": (L, "wan22-cunilingus-I2V-106epoc-high.safetensors", "wan22-cunilingus-I2V-72epoc-low.safetensors"),
    # --- cowgirl ---
    "Reverse Cowgirl v2": (L, "wan22.r3v3rs3_c0wg1rl-14b-High-i2v_e70.safetensors", "wan22.r3v3rs3_c0wg1rl-14b-Low-i2v_e70.safetensors"),
    # --- doggy / from behind ---
    "Doggy Front View v2": (L, "doggy_style_sex_front_view_Wan2.2_I2V_high_v1.0.safetensors", "doggy_style_sex_front_view_Wan2.2_I2V_Low_v1.0.safetensors"),
    "Fucked From Behind": (L, "derpfuckedfrombehind_000002125_high_noise.safetensors", "derpfuckedfrombehind_000002125_low_noise.safetensors"),
    "Prone Bone": (L, "Pronebone_high_noise.safetensors", "Pronebone_low_noise.safetensors"),
    "Reverse Suspended Congress": (L, "reverse_suspended_congress_I2V_high.safetensors", "reverse_suspended_congress_I2V_low.safetensors"),
    # --- missionary ---
    "POV Missionary": (L, "wan2.2_i2v_highnoise_pov_missionary_v1.0.safetensors", "wan2.2_i2v_lownoise_pov_missionary_v1.0.safetensors"),
    "Mating Press": (L, "mating_press_high.safetensors", "mating_press_low.safetensors"),
    # --- standing ---
    "Standing Upright Sex": (L, "Upright_sex_Wan2.2_14B_TI2V_HIGH_v1.0.safetensors", "Upright_sex_Wan2.2_14B_TI2V_LOW_v1.0.safetensors"),
    # --- anal / ass ---
    "Oral Insertion": (L, "wan2.2-i2v-high-oral-insertion-v1.0.safetensors", "wan2.2-i2v-low-oral-insertion-v1.0.safetensors"),
    # --- handjob / balls ---
    "Handjob": (L, "WAN-2.2-I2V-Handjob-HIGH-v1.safetensors", "WAN-2.2-I2V-Handjob-LOW-v1.safetensors"),
    "Balls Sucking": (L, "WAN-2.2-I2V_Balls_sucking_High_noise.safetensors", "WAN-2.2-I2V_Balls_sucking_Low_noise.safetensors"),
    # --- fingering ---
    "Fingering": (R, "Sensual_fingering_v1_high_noise.safetensors", "Sensual_fingering_v1_low_noise.safetensors"),
    # --- cumshot / creampie ---
    "Facesplash Cumshot": (L, "wan22-f4c3spl4sh-100epoc-high-k3nk.safetensors", "wan22-f4c3spl4sh-154epoc-low-k3nk.safetensors"),
    "Creampie CRM": (L, "Creampie CRM-FULL-EPOCH-80-HIGH.safetensors", "Creampie CRM-FULL-EPOCH-80-LOW.safetensors"),
    "Pornmaster Creampie": (L, "Pornmaster_wan 2.2_14b_I2V_Creampie_v1_high_noise.safetensors", "Pornmaster_wan 2.2_14b_I2V_Creampie_v1_low_noise.safetensors"),
    "Cum (generic)": (L, "Wan22_Cum_high_noise_1.V1.safetensors", "Wan22_Cum_low_noise_1.V1.safetensors"),
    # --- fetish / expression ---
    "French Kiss": (L, "WAN2.2-FrenchKiss_HighNoise.safetensors", "WAN2.2-FrenchKiss_LowNoise.safetensors"),
    "Twerking": (L, "Twerking_I2V_high_noise.safetensors", "Twerking_I2V_low_noise.safetensors"),
    "Ahegao Drooling": (R, "middlefinger_drooling_ahegao_high.safetensors", "middlefinger_drooling_ahegao_low.safetensors"),
    # --- helpers: size / penetration / anatomy / camera / booster ---
    "General NSFW Booster": (P, "NSFW-22-H-e8.safetensors", "NSFW-22-L-e8.safetensors"),
    "Penetration Insert": (L, "PenInsert_high_noise.safetensors", "PenInsert_low_noise.safetensors"),
    "Biggest Cock (size)": (L, "WAN-2.2-I2V_BiggestCock_high_noise_V1.safetensors", "WAN-2.2-I2V_BiggestCock_low_noise_V1.safetensors"),
    "Doggy Slider": (L, "I2V_doggyslider_high.safetensors", "I2V_doggyslider_low.safetensors"),
    "Pussy Helper": (R, "wan2.2_i2v_ulitmate_pussy_helper_high.safetensors", "wan2.2_i2v_ulitmate_pussy_helper_low.safetensors"),
    "FOV Slider (camera)": (L, "wan2.2-i2v-high-sex-fov-slider-v1.0.safetensors", "wan2.2-i2v-low-sex-fov-slider-v1.0.safetensors"),
    "Smashcut (camera)": (R, "wan2.2-i2v-sex-smashcut-v1.0-high.safetensors", "wan2.2-i2v-sex-smashcut-v1.0-low.safetensors"),
}
for label, (repo, hi, lo) in EXTRA.items():
    LORA_PAIRS.setdefault(label, {"HIGH": None, "LOW": None})
    if hi:
        LORA_PAIRS[label]["HIGH"] = (repo, hi)
    if lo:
        LORA_PAIRS[label]["LOW"] = (repo, lo)


def get_lora_choices():
    choices = []
    for group in sorted(LORA_PAIRS.keys()):
        p = LORA_PAIRS[group]
        if p["HIGH"] and p["LOW"]:
            choices.append(group)
        elif p["HIGH"]:
            choices.append(f"{group} (HIGH only)")
        elif p["LOW"]:
            choices.append(f"{group} (LOW only)")
    return choices


def _custom_key(label):
    return f"User: {label}"


def _read_custom_library():
    """Return the persisted custom LoRA manifest, tolerating a first run."""
    try:
        with open(LORA_LIBRARY_MANIFEST, "r", encoding="utf-8") as handle:
            data = json.load(handle)
        return data if isinstance(data, dict) else {}
    except (OSError, ValueError, TypeError):
        return {}


def _write_custom_library(entries):
    os.makedirs(LORA_LIBRARY_DIR, exist_ok=True)
    fd, temporary_path = tempfile.mkstemp(prefix="library-", suffix=".json", dir=LORA_LIBRARY_DIR)
    try:
        with os.fdopen(fd, "w", encoding="utf-8") as handle:
            json.dump(entries, handle, indent=2, sort_keys=True)
        os.replace(temporary_path, LORA_LIBRARY_MANIFEST)
    finally:
        if os.path.exists(temporary_path):
            os.unlink(temporary_path)


def get_custom_lora_choices():
    return [_custom_key(label) for label in sorted(_read_custom_library(), key=str.casefold)]


def get_all_lora_choices():
    return get_lora_choices() + get_custom_lora_choices()


def _stage_for_custom_lora(filename, requested_stage):
    if requested_stage in {"high", "low"}:
        return requested_stage.upper()
    return "LOW" if re.search(r"(?:low|[_-]ln\\b|[_-]l\\b)", filename, re.IGNORECASE) else "HIGH"


def _civitai_token():
    return (os.environ.get("CIVITAI_TOKEN") or os.environ.get("CIVITAI_API_KEY") or "").strip()


def _slug(value, fallback):
    value = re.sub(r"[^A-Za-z0-9._-]+", "-", value or "").strip(".-_")
    return (value or fallback)[:120]


def _resolve_civitai_lora(source):
    """Resolve a CivitAI model page or download link to one safetensors file."""
    parsed = urllib.parse.urlparse(source)
    host = (parsed.hostname or "").lower()
    if host not in CIVITAI_HOSTS:
        raise ValueError("This is not a CivitAI URL.")
    if parsed.scheme != "https":
        raise ValueError("Use an HTTPS CivitAI page or download link.")

    page_match = re.search(r"/models/(\d+)", parsed.path, flags=re.IGNORECASE)
    download_match = re.search(r"/api/download/models/(\d+)", parsed.path, flags=re.IGNORECASE)
    query = dict(urllib.parse.parse_qsl(parsed.query, keep_blank_values=True))
    if download_match:
        version_id = download_match.group(1)
        file_id = query.get("fileId") or "file"
        return source, f"CivitAI LoRA {version_id}", f"civitai-lora--{version_id}--{file_id}.safetensors"

    version_id = query.get("modelVersionId") or ""
    api_base = f"https://{host}/api/v1"
    if not version_id and page_match:
        model = requests.get(f"{api_base}/models/{page_match.group(1)}", timeout=30).json()
        versions = model.get("modelVersions") or []
        if not versions:
            raise ValueError("CivitAI returned no versions for that model page.")
        version_id = str(versions[0].get("id") or "")
    if not version_id:
        raise ValueError("Could not identify a CivitAI model version from that link.")

    version = requests.get(f"{api_base}/model-versions/{version_id}", timeout=30).json()
    files = [item for item in (version.get("files") or []) if str(item.get("name") or "").lower().endswith(".safetensors")]
    if not files:
        raise ValueError("That CivitAI version has no safetensors file.")
    chosen = next((item for item in files if item.get("primary")), files[0])
    file_id = chosen.get("id")
    if not file_id:
        raise ValueError("CivitAI did not provide a safetensors file id.")
    model_name = str((version.get("model") or {}).get("name") or "").strip()
    version_name = str(version.get("name") or "").strip()
    display_name = " - ".join(part for part in (model_name, version_name) if part) or str(chosen.get("name") or "CivitAI LoRA")
    filename = f"{_slug(model_name, 'civitai-lora')}--{_slug(version_name, str(version_id))}.safetensors"
    return f"https://{host}/api/download/models/{version_id}?fileId={file_id}", display_name[:160], filename


def add_custom_lora(label, url, stage="auto"):
    """Fetch one public safetensors URL into the persistent LoRA library.

    Reusing the same label lets the user add its HIGH and LOW stage files as a
    pair.  The download lands atomically, so an interrupted request never
    leaves a selectable partial weight file in the Bucket.
    """
    label = (label or "").strip()
    url = (url or "").strip()
    parsed = urllib.parse.urlparse(url)
    if parsed.scheme not in {"http", "https"} or not parsed.netloc:
        raise ValueError("Use an http(s) safetensors endpoint or a CivitAI model page.")

    host = (parsed.hostname or "").lower()
    if host in CIVITAI_HOSTS:
        download_url, detected_label, source_name = _resolve_civitai_lora(url)
        label = label or detected_label
    else:
        download_url = url
        source_name = os.path.basename(urllib.parse.unquote(parsed.path))
        if not source_name.lower().endswith(".safetensors"):
            raise ValueError("Direct endpoints must end in .safetensors.")
        label = label or os.path.splitext(source_name)[0]
    os.makedirs(LORA_LIBRARY_DIR, exist_ok=True)
    digest = hashlib.sha256(url.encode("utf-8")).hexdigest()[:12]
    safe_label = re.sub(r"[^A-Za-z0-9._-]+", "-", label).strip(".-") or "lora"
    destination = os.path.join(LORA_LIBRARY_DIR, f"{safe_label}-{digest}.safetensors")
    fd, temporary_path = tempfile.mkstemp(prefix="download-", suffix=".part", dir=LORA_LIBRARY_DIR)
    os.close(fd)
    size = 0
    try:
        download_parsed = urllib.parse.urlparse(download_url)
        token = _civitai_token()
        if token and host in CIVITAI_HOSTS and "token=" not in download_parsed.query:
            query = urllib.parse.parse_qsl(download_parsed.query, keep_blank_values=True) + [("token", token)]
            download_url = urllib.parse.urlunparse(download_parsed._replace(query=urllib.parse.urlencode(query)))
            download_parsed = urllib.parse.urlparse(download_url)
        candidates = [download_url]
        if host in CIVITAI_HOSTS and (download_parsed.hostname or "").lower() != "civitai.red":
            for alternate in CIVITAI_HOSTS:
                if download_parsed.hostname and alternate != download_parsed.hostname.lower():
                    candidates.append(download_url.replace(download_parsed.hostname, alternate, 1))

        last_error = "download failed"
        for candidate in candidates:
            size = 0
            try:
                with requests.get(candidate, stream=True, allow_redirects=True, timeout=(30, 600), headers={"User-Agent": "wan2.2-lora-library/1.0"}) as response:
                    response.raise_for_status()
                    if "text/html" in response.headers.get("Content-Type", "").lower():
                        raise ValueError("The endpoint returned a web page instead of LoRA weights.")
                    length = response.headers.get("Content-Length")
                    if length and int(length) > MAX_CUSTOM_LORA_BYTES:
                        raise ValueError("That LoRA is larger than this Space's 8 GB library limit.")
                    with open(temporary_path, "wb") as output:
                        for chunk in response.iter_content(chunk_size=4 * 1024 * 1024):
                            if not chunk:
                                continue
                            size += len(chunk)
                            if size > MAX_CUSTOM_LORA_BYTES:
                                raise ValueError("That LoRA is larger than this Space's 8 GB library limit.")
                            output.write(chunk)
                break
            except (OSError, ValueError, requests.RequestException) as exc:
                last_error = str(exc)
                if os.path.exists(temporary_path):
                    os.unlink(temporary_path)
        else:
            raise ValueError(last_error)
        if size == 0:
            raise ValueError("The LoRA endpoint returned an empty file.")
        # Validate the safetensors header without materializing the weights.
        with safetensors.safe_open(temporary_path, framework="pt") as weights:
            if not list(weights.keys()):
                raise ValueError("The downloaded safetensors file has no tensors.")
        os.replace(temporary_path, destination)
        entries = _read_custom_library()
        entry = entries.setdefault(label, {"HIGH": None, "LOW": None})
        entry[_stage_for_custom_lora(source_name, stage)] = {"path": destination, "url": url, "bytes": size}
        _write_custom_library(entries)
    except Exception:
        if os.path.exists(temporary_path):
            os.unlink(temporary_path)
        raise
    return f"Saved {label} ({size / 1024**2:.1f} MB) in the persistent LoRA library."


# ── Auto-activation: scored inverse-concept-frequency (ICF) ───────────────
# New architecture. Instead of the old "longest matched keyword wins" tie-break
# per category, every trigger phrase carries an ICF weight: log(N / (1 + k))
# where N is the number of LoRAs that have trigger phrases and k is how many of
# those LoRAs contain this phrase. Phrases unique to one LoRA (e.g.
# "deepthroat") get a high weight; phrases shared by many LoRAs (generic) get a
# low weight. A LoRA's score is the sum of the ICF weights of every phrase
# present in the NORMALIZED prompt. Concept categories still dedupe the output
# to at most one LoRA per category, but the winner is the highest score, not
# the longest keyword.
#
# All matching happens against _normalize()d text, so "face-fucking" matches
# "face fucking", "deepthroat" matches "deepthroats", etc. Only DISTINCTIVE
# phrases are listed so a plain prompt ("a woman walking in a garden") does not
# activate anything. Near-duplicate variants of the same concept are left
# manual-only to keep auto firing on one representative LoRA per concept.

_TYPO_FIXES = {
    "naaked": "naked", "nuude": "nude", "nuudity": "nudity",
    "niipples": "nipples", "tiits": "tits", "tiitty": "titty",
    "arreola": "areola", "vaagina": "vagina", "vuulva": "vulva",
    "coompletely": "completely", "sqquirting": "squirting",
}


def _normalize(text):
    """Normalize text for phrase matching.



    Lowercases, strips everything except letters/digits (so hyphens, slashes,

    newlines, tabs and punctuation all become spaces), collapses whitespace

    runs to single spaces, and pads the result with surrounding spaces so

    substring matches respect token boundaries. "face-fucking" and

    "face fucking" both normalize to "face fucking". Curated misspellings are

    corrected first, on intact words, before punctuation stripping.

    """
    if not text or not isinstance(text, str):
        return ""
    t = text.lower()
    # Typo/misspelling fixes β€” applied AFTER lowercase but BEFORE the character
    # filter, so they run on intact words ("naaked" -> "naked", etc.).
    for _wrong, _right in _TYPO_FIXES.items():
        t = t.replace(_wrong, _right)
    t = re.sub(r"[^a-z0-9]+", " ", t)
    t = re.sub(r"\s+", " ", t)
    return " " + t.strip() + " "


LORA_AUTO_PHRASES = {
    # ── blowjob / deepthroat family ──
    "Ultimate Deepthroat": [
        "deepthroat", "deep throat", "facefuck", "face-fuck", "facefucking",
        "face-fucking", "face fucking", "piston", "piston-like", "in and out of her throat",
        "into her throat", "down her throat", "deep in her throat", "nose against his pelvis",
        "nose pressed against his pelvis", "nose is pressed", "cock down her throat",
        "gagging on his cock", "gags on his cock", "throatpie", "throat pie",
        "all the way down his cock", "fucks her face", "fucks her mouth", "fucking her face",
        "fucking her mouth", "cock fully into her mouth", "fully into her mouth",
        "deep in her mouth",
    ],
    "BBC Deepthroat": [
        "deepthroat", "deep throat", "facefuck", "face-fuck", "facefucking",
        "face-fucking", "face fucking", "piston", "piston-like", "in and out of her throat",
        "into her throat", "down her throat", "deep in her throat", "nose against his pelvis",
        "nose pressed against his pelvis", "nose is pressed", "cock down her throat",
        "gagging on his cock", "gags on his cock", "throatpie", "throat pie",
        "all the way down his cock", "fucks her face", "fucks her mouth", "fucking her face",
        "fucking her mouth", "cock fully into her mouth", "fully into her mouth",
        "deep in her mouth",
        "bbc deep throat", "bbc deepthroat", "black deep throat", "bbc facefuck",
        "bbc face-fuck", "bbc face fucking", "interracial deepthroat", "bbc down her throat",
        "black cock down her throat", "bbc throatpie",
    ],
    "Throat V2": [
        "throat fuck", "throatfuck", "throat deep penetration", "throatpie", "throat pie",
        "throat depth", "pushed into her throat", "deep in her throat", "throat gagging",
        "choking on his cock",
    ],
    "wan22-mouthfull-140epoc-high-k3nk": [
        "mouthfull", "mouth full", "m0u7hfu11", "mouth full of his cock", "mouth full of cock",
        "cock fills her mouth", "stuffed mouth", "mouth stretched around",
    ],
    "POV Blowjob": [
        "pov blowjob", "point of view blowjob", "pov bj", "pov blow job", "point of view bj",
        "pov sucking",
    ],
    "iGOON_Blink_Blowjob_I2V": [
        "blowjob", "blow job", "sucking his cock", "sucking cock", "sucking him off",
        "sucking his dick", "cock in her mouth", "cock into her mouth", "into her open mouth",
        "cock between her lips", "her lips around his cock", "mouth around his cock",
        "bobbing her head", "taking him in her mouth", "sucks his cock", "open mouth",
        "cock in her open mouth", "mouth on his cock",
    ],
    "BBC Blowjob Extreme": [
        "blowjob", "blow job", "sucking his cock", "sucking cock", "sucking him off",
        "sucking his dick", "cock in her mouth", "cock into her mouth", "into her open mouth",
        "cock between her lips", "her lips around his cock", "mouth around his cock",
        "bobbing her head", "taking him in her mouth", "sucks his cock", "open mouth",
        "cock in her open mouth", "mouth on his cock",
        "bbc blowjob", "black blowjob", "bbc extreme blowjob", "bbc sucking",
        "interracial blowjob", "black cock in her mouth", "bbc facefuck", "bbc bj",
    ],
    "lips-bj": [
        "lips bj", "lipjob", "lips-bj", "cock between her lips", "lips around his cock",
        "lip blowjob", "cock against her lips",
    ],
    "WAN-2.2-I2V-SensualTeasingBlowjob": [
        "sensual blowjob", "sensual bj", "teasing blowjob", "sensualbj", "teasing his cock",
        "licking the tip", "licking his shaft", "slow teasing", "kissing the tip",
        "licking his cock",
    ],
    "WAN-2.2-I2V-HandjobBlowjobCombo": [
        "handjob blowjob", "handjob and blowjob", "hand and mouth", "stroking and sucking",
        "handjob and bj", "hand on his cock while sucking", "combination handjob",
    ],
    "WAN-2.2-I2V-Double-Blowjob": [
        "double blowjob", "double bj", "two men blowjob", "two cocks in her mouth",
        "both cocks", "double facefuck", "two men facefuck", "double blow job",
    ],
    # ── cowgirl / riding ──
    "Blink_Squatting_Cowgirl_Position_I2V": [
        "squatting cowgirl", "squat cowgirl", "squatting on his cock", "squat position",
        "squatting ride", "squat riding",
    ],
    "Reverse Cowgirl v2": [
        "reverse cowgirl", "reverse cowgirl position", "cowgirl facing away",
        "riding backwards", "facing away riding", "cowgirl facing the feet",
        "cowgirl", "cowgirl position", "woman on top", "girl on top",
    ],
    # ── doggystyle family ──
    "iGoon - Blink_Back_Doggystyle": [
        "back doggystyle", "doggystyle from behind", "rear doggy", "doggy from the back",
        "doggystyle from the back", "rear entry doggy", "doggy from behind",
    ],
    "iGoon - Blink_Front_Doggystyle_I2V": [
        "front doggystyle", "front doggy", "doggystyle facing the camera",
        "front facing doggy", "doggy facing camera", "doggy facing her",
        "doggystyle position", "doggystyle rhythm", "facing toward the camera",
        "facing towards the camera",
    ],
    "Fucked From Behind": [
        "sex from behind", "fucked from behind", "bent over gripping", "taking it from behind",
        "pounding from behind", "grabbing her hips from behind", "from behind while standing",
        "from behind", "fucking from behind", "fucks from behind", "fucking her from behind",
        "thrusting from behind", "taking her from behind", "doggy style", "doggystyle",
    ],
    "Prone Bone": [
        "prone bone", "pronebone", "prone position", "lying flat on her stomach",
        "flat on the bed face down", "lying under him face down",
    ],
    "sfbehind_v2.1": [
        "sfbehind", "sfb3hind", "bent over at the waist", "bent forward",
        "leaning over the bed", "bent over the edge", "bent over", "bends over",
        "bending over",
    ],
    "mql_casting_sex_doggy_kneel_diagonally_behind_vagina_wan22_i2v_v1": [
        "mqldgy", "diagonal doggy", "doggy diagonally", "kneeling doggy", "doggy kneel",
        "diagonal behind", "diagonal doggystyle",
    ],
    "mql_casting_sex_spoon_wan22_i2v_v1": [
        "spooning", "spoon position", "mqlspn", "spooning position", "spooning sex",
        "side by side sex", "laying on their sides",
    ],
    "sid3l3g_transition_v2.0_H": [
        "side leg", "sid3l3g", "leg transition", "side leg position", "one leg over",
        "leg over his shoulder",
    ],
    "Doggy Slider": [
        "doggy slider", "sliding in and out", "slow in and out", "in and out sliding",
        "doggystyle slider", "sliding his cock in and out",
    ],
    # ── missionary family ──
    "POV Missionary": [
        "pov missionary", "pov missionary position", "missionary pov", "point of view missionary",
    ],
    "iGoon - Blink_Missionary_I2V": [
        "missionary", "missionary position", "face to face sex", "man on top",
        "lying on top of her",
    ],
    "iGoon_Blink_Missionary_I2V": [
        "deep missionary", "missionary deep", "ankles over shoulders", "legs over his shoulders",
        "legs on his shoulders", "deep penetration missionary", "pinned her legs back",
    ],
    "Mating Press": [
        "mating press", "matingpress", "folded in half", "legs pushed to her chest",
        "pressed against his chest", "legs folded up",
    ],
    "Reverse Suspended Congress": [
        "reverse suspended congress", "suspended congress", "reverse suspended",
        "suspended congress position", "suspended in the air",
    ],
    "Standing Upright Sex": [
        "standing sex", "upright sex", "standing against the wall",
        "standing pressed against the wall", "upright against wall", "standing doggy",
        "sex while standing",
    ],
    # ── oral on her / fingering ──
    "Cunnilingus": [
        "cunnilingus", "eating her out", "eating pussy", "licking her pussy",
        "licking her clit", "tongue on her pussy", "eating her cunt", "licking her slit",
        "muff diving", "going down on her",
    ],
    "Fingering": [
        "fingering", "fingers her", "finger her pussy", "fingers inside her",
        "playing with her pussy", "finger her", "rub her clit", "fingering her pussy",
        "rubbing her vagina", "rubs her vagina", "rubbing her pussy", "rubs her pussy",
        "rubbing her clit", "masturbating", "masturbation", "touching herself",
        "finger herself", "fingering herself", "spread pussy lips", "spreads her pussy lips",
        "circling clit",
    ],
    "Oral Insertion": [
        "oral insertion", "oral insert", "tip of his cock", "just the tip",
        "cock at her entrance", "penis head at", "inserting the tip",
    ],
    "Handjob": [
        "handjob", "hand job", "jerking him off", "jerking", "stroking his cock",
        "stroking his dick", "pumping his cock", "hand around his cock",
        "jerking him", "stroke him off", "handjob with her hand",
    ],
    "Balls Sucking": [
        "balls sucking", "sucking his balls", "ball sucking", "licking his balls",
        "balls in her mouth", "sucking his testicles", "sucking his sack",
    ],
    "iGoon_Blink_Titjob_I2V": [
        "titjob", "tit job", "titty fuck", "tittyfuck", "between her breasts",
        "cock between her tits", "tits around his cock", "boobjob", "breast job",
        "squeezing his cock between her breasts", "cock between her boobs",
    ],
    # ── cum family ──
    "Cum (generic)": [
        "cumshot", "cum shot", "shooting his load", "ejaculates", "ejaculation",
        "cumming on", "load on her", "shoots his cum", "cum bursting",
        "cum all over", "cum all over her", "sprays cum", "cum loads",
        "massive cum loads", "shoots cum", "covers her with cum",
    ],
    "Facesplash Cumshot": [
        "facesplash", "cum on her face", "cum on face", "facial cumshot",
        "load on her face", "cum across her face", "cum on her face and mouth",
        "cum all over her face", "all over her face", "cum covers her face",
        "cum splattered on her face",
    ],
    "iGoon - Blink_Facial_I2V": [
        "cum across her face", "cum on her face", "facial cumshot",
        "cums on her face", "facial finish",
    ],
    "Pornmaster_wan 2.2_14b_I2V_bukkake_v1.4": [
        "bukkake", "multiple men cum", "group cumshot", "cum bath", "gangbang cumshot",
        "many men cumming",
    ],
    "Creampie CRM": [
        "creampie", "cum inside her", "cum inside", "internal cumshot", "load inside her",
        "cum inside her pussy", "creampie shot", "finishes deep inside her",
        "finish deep inside her", "finishing inside her", "leaking out of her",
        "cum leaking out", "cum visible leaking",
    ],
    "Pornmaster Creampie": [
        "pornmaster creampie", "detailed creampie", "extreme creampie",
    ],
    # ── size / penis focus ──
    "Biggest Cock (size)": [
        "biggest cock", "huge cock", "massive cock", "big cock", "enormous cock",
        "giant cock", "monster cock", "thick cock", "long cock", "massive penis",
    ],
    "PENISLORA_22_i2v_HIGH_e320": [
        "erect penis", "cock close up", "penis close up", "penis focus", "cock detail",
        "penis detail", "cock closeup", "penis closeup", "focus on his cock",
    ],
    # ── pussy / penetration ──
    "Pussy Helper": [
        "pussy spread", "spread her pussy", "pussy helper", "rub her vagina",
        "opens her pussy", "pussy spread open",
    ],
    "wan2.2_i2v_high_ulitmate_pussy_asshole": [
        "pussy and asshole", "asshole focus", "pussy and anus", "asshole spread",
        "anus focus", "pussy and ass", "both holes", "vulva", "vulva close up",
        "labia", "labial folds", "pussy close up", "vagina close up",
        "intimate close up of her pussy",
    ],
    "Penetration Insert": [
        "penetration insert", "moment of entry", "penetrating her", "entering her",
        "sliding inside her", "first penetration", "cock entering", "sliding in",
        "penetration close up", "thrusting into her pussy", "thrusting into and out of her",
        "thrusting in and out of her pussy", "thrusts into her pussy", "into and out of her pussy",
        "penetrating her pussy", "entering her pussy", "deep vaginal penetration",
        "deep penetration", "penetrating deep inside", "penetrates her",
        "slides deep into her", "slides deep inside", "slides deep into her vagina",
        "thrust deeper inside", "penetrating her deeply",
        "into her pussy", "thrusting in and out", "pounding her hard",
        "pounding her pussy", "pounds her pussy",
    ],
    # ── expressions / foreplay ──
    "Ahegao Drooling": [
        "ahegao", "tongue out eyes rolled", "ahegao face", "tongue out", "eyes rolled back",
        "drooling", "tongue hanging out", "brain melt", "pleasure overload face",
    ],
    "French Kiss": [
        "french kiss", "tongues intertwined", "making out", "tongues together",
        "kissing tongues", "deep kiss", "open mouth kiss",
    ],
    "Twerking": [
        "twerking", "twerk", "shaking her ass", "bounce her ass", "booty shake",
        "ass shaking", "twerk on him",
    ],
    "mql_massage_tits_wan22_i2v_v1": [
        "breast massage", "massage her tits", "boob massage", "massaging her breasts",
        "cupping her breasts", "fondling her breasts", "kneading her tits", "groping her tits",
        "squeezes her breasts", "squeezing her breasts", "squeeze her breasts",
        "squeezing them", "squeezes them", "cup her breasts", "cupping them",
        "caressing her breasts", "caress her breasts", "caressing them",
        "pinching her nipples", "pinching nipples",
        "caresses her breasts", "groping her breasts", "groping them", "groping and squeezing",
        "stroking her breasts", "stroking them", "fondling them", "caresses them",
    ],
    "mql_panties_aside_wan22_i2v_v1": [
        "panties aside", "panties to the side", "pulled to one side", "panties pulled aside",
        "pulling her panties aside", "knickers aside", "panties to the side",
    ],
    # ── camera / scene effects ──
    "FOV Slider (camera)": [
        "camera zooms", "push in", "fov slider", "zoom in", "zoom out", "zooms in",
        "zooms out", "push in close", "camera pushes in", "fov change", "close up on",
    ],
    "Smashcut (camera)": [
        "smashcut", "sm4shcut", "jump cut", "quick cut", "hard cut", "instant cut",
        "abrupt cut", "no transition", "no morphing", "no blending", "no fade",
        "hard cut to", "instant cut to",
    ],
    "W22_Multiscene_Photoshoot_Softcore_i2v": [
        "softcore", "photoshoot", "posing provocatively", "glamour photoshoot",
        "posing for the camera", "studio photoshoot",
    ],
    # ── generic sex / scene quality ──
    "General NSFW Booster": [
        "having sex", "have sex", "sexual intercourse", "intercourse", "making love",
        "fucking her", "fucking him", "fucking each other", "hardcore sex", "rough sex",
        "sex scene", "porn scene",
        "naked", "nude", "undressed", "undressing", "stripped", "no underwear",
        "completely bare", "bare body", "shedding her clothes", "removes all clothing",
        "removes her clothes", "discard garments", "completely naked", "fully naked",
        "standing naked", "naked body",
    ],
}


# ── Concept categories for auto-activation dedupe ─────────────────────────
# LoRAs of the same type are grouped so at most ONE fires per category:
# no double blowjob, no double doggystyle, no double sex LoRA, etc.
# When several LoRAs in a category match, the one with the HIGHEST ICF score
# wins (not the longest keyword).
LORA_AUTO_CATEGORIES = {
    "oral": [
        "Ultimate Deepthroat",
        "BBC Deepthroat",
        "Throat V2",
        "wan22-mouthfull-140epoc-high-k3nk",
        "BBC Blowjob Extreme",
        "POV Blowjob",
        "iGOON_Blink_Blowjob_I2V",
        "lips-bj",
        "WAN-2.2-I2V-SensualTeasingBlowjob",
        "WAN-2.2-I2V-HandjobBlowjobCombo",
        "WAN-2.2-I2V-Double-Blowjob",
        "Oral Insertion",
    ],
    "handjob": ["Handjob"],
    "balls": ["Balls Sucking"],
    "titjob": ["iGoon_Blink_Titjob_I2V"],
    "cunnilingus": ["Cunnilingus"],
    "fingering": ["Fingering"],
    "cowgirl": ["Blink_Squatting_Cowgirl_Position_I2V", "Reverse Cowgirl v2"],
    "doggystyle": [
        "iGoon - Blink_Back_Doggystyle",
        "iGoon - Blink_Front_Doggystyle_I2V",
        "Fucked From Behind",
        "Prone Bone",
        "sfbehind_v2.1",
        "mql_casting_sex_doggy_kneel_diagonally_behind_vagina_wan22_i2v_v1",
        "mql_casting_sex_spoon_wan22_i2v_v1",
        "sid3l3g_transition_v2.0_H",
        "Doggy Slider",
    ],
    "missionary": [
        "iGoon - Blink_Missionary_I2V",
        "iGoon_Blink_Missionary_I2V",
        "POV Missionary",
        "Mating Press",
        "Reverse Suspended Congress",
        "Standing Upright Sex",
    ],
    "cumshot": [
        "Cum (generic)",
        "Facesplash Cumshot",
        "iGoon - Blink_Facial_I2V",
        "Pornmaster_wan 2.2_14b_I2V_bukkake_v1.4",
    ],
    "creampie": ["Creampie CRM", "Pornmaster Creampie"],
    "penis": ["Biggest Cock (size)", "PENISLORA_22_i2v_HIGH_e320"],
    "pussy": [
        "Pussy Helper",
        "wan2.2_i2v_high_ulitmate_pussy_asshole",
        "Penetration Insert",
    ],
    "foreplay": [
        "Ahegao Drooling",
        "French Kiss",
        "Twerking",
        "mql_massage_tits_wan22_i2v_v1",
        "mql_panties_aside_wan22_i2v_v1",
    ],
    "camera": [
        "FOV Slider (camera)",
        "Smashcut (camera)",
        "W22_Multiscene_Photoshoot_Softcore_i2v",
    ],
    "generic": ["General NSFW Booster"],
}

# Extra phrases a LoRA must additionally see in the prompt (ANY match).
# Smashcut only fires when the cut leads to a scene of a man thrusting
# into her pussy β€” matching its replacement prompt "SM4SHCUT, the scene
# changes and a man is thrusting his penis into and out of her pussy".
# The BBC variants share the generic action phrases of their category
# (so "fucks her face" etc. reach them) but are gated on black context:
# a deepthroat scene that does not mention a black man / black cock /
# interracial wording must fall through to the generic LoRA, not the BBC
# one. This also keeps "black man" itself out of the scoring phrase lists
# (a kissing scene mentioning a black man must not fire a blowjob LoRA).
LORA_AUTO_REQUIRES = {
    "Smashcut (camera)": [
        "thrusting his penis into and out of her pussy",
        "thrusting his cock into and out of her pussy",
        "thrusting into and out of her pussy",
        "penis into and out of her pussy",
        "cock into and out of her pussy",
        "into and out of her pussy",
        "in and out of her pussy",
        "thrusting into her pussy",
        "pounding her pussy",
        "fucking her pussy",
        "thrusting in and out",
        "pounding her hard",
        "fucking her",
        "fucks her pussy",
        "thrusting hard",
        "thrusting fast",
        "fully in and fully out",
        "driving his hips forward",
        "hips driving forward",
        "hips slamming forward",
    ],
    "BBC Deepthroat": [
        "black man", "black man's", "black guy", "black male", "black lover",
        "black partner", "black cock", "black dick", "black penis",
        "bbc", "interracial", "black man with",
    ],
    "BBC Blowjob Extreme": [
        "black man", "black man's", "black guy", "black male", "black lover",
        "black partner", "black cock", "black dick", "black penis",
        "bbc", "interracial", "black man with",
    ],
}


# ── ICF weights (computed once at import) ─────────────────────────────────
# A phrase's inverse-concept-frequency (ICF) is log(N / (1 + k)) where N is the
# number of LoRAs that carry trigger phrases and k is the number of those LoRAs
# containing the phrase. A phrase unique to one LoRA (e.g. "deepthroat") gets a
# high weight (~3.28); a phrase shared by many LoRAs gets a low weight. This is
# the principled replacement for the old "longest keyword wins" heuristic.
_phrase_to_groups = {}
for _g, _phrases in LORA_AUTO_PHRASES.items():
    for _p in _phrases:
        _np = _normalize(_p)
        _phrase_to_groups.setdefault(_np, set()).add(_g)
_phrase_icf = {}
_total_phrase_groups = len(LORA_AUTO_PHRASES)
for _np, _groups in _phrase_to_groups.items():
    _phrase_icf[_np] = math.log(_total_phrase_groups / (1.0 + len(_groups)))

# Per-group list of unique NORMALIZED phrases (deduped so "facefuck" and
# "face-fuck" β€” which normalize identically β€” are not double-counted). The
# stored entries keep the padded _normalize() form for ICF lookup; matching
# strips the padding so inflected variants still hit (see auto_activation_details).
_NORM_PHRASES_BY_GROUP = {}
for _g in LORA_AUTO_PHRASES:
    _seen = []
    for _p in LORA_AUTO_PHRASES[_g]:
        _np = _normalize(_p)
        if _np not in _seen:
            _seen.append(_np)
    _NORM_PHRASES_BY_GROUP[_g] = _seen

# Minimum score a group needs to auto-activate. A single distinctive phrase
# ("deepthroat") scores ~3.28; even the most shared phrase in the current table
# still scores > 2.5, so 0.35 only guards against stray low-weight/shared
# phrases leaking through.
AUTO_SCORE_THRESHOLD = 0.35


_NEGATION_TOKENS = ("no ", "zero ", "not ", "never ", "without ", "without any ")


def _is_negated(text, phrase):
    """True if a phrase occurrence is preceded by a negation token

    (no/zero/not/never/without) within a few words. Handles 'no zooming',

    'no zooms that crop', 'no panning tilting zooming', but NOT positive

    'quick greedy zooms in'."""
    start = 0
    while True:
        i = text.find(phrase, start)
        if i == -1:
            return False
        before = text[max(0, i - 30):i]
        # \s*$ allows the slice to end with a space right before the phrase
        # ("no zooms that crop" -> before ends "...no ").
        if re.search(r"\b(no|zero|not|never|without)\b(?:\s+\w+){0,3}\s*$", before):
            return True
        start = i + 1


def auto_activation_details(prompt):
    """Score every LoRA group against the prompt and return activation details.



    Returns a list of dicts (one per activated LoRA), sorted by descending

    score:

        {"group": <name>, "score": <rounded float>, "matched": [phrases...]}



    Matching runs on the _normalize()d prompt. Each LoRA's score is the sum of

    the ICF weights of every phrase present in the prompt. Groups with

    LORA_AUTO_REQUIRES entries additionally need at least one require phrase

    (ANY-match) or they are excluded. Results are deduped per concept category

    so at most one LoRA per category fires β€” the highest-scoring group wins.

    LoRAs that have phrases but appear in no category are treated as their own

    category. Empty/None prompts return [].

    """
    if not prompt:
        return []
    text = _normalize(prompt)

    scored = []  # (score, group, matched_phrases)
    for group, phrases in _NORM_PHRASES_BY_GROUP.items():
        matched = []
        score = 0.0
        for np in phrases:
            # Match the normalized phrase (padding stripped) as a substring of
            # the padded normalized prompt. The prompt's surrounding spaces keep
            # matches token-safe, while the unpadded phrase still catches
            # morphological variants: "deepthroat" matches "deepthroats",
            # "piston" matches "pistoning", "face fuck" matches "face fucks".
            inner = np.strip()
            if inner in text and not _is_negated(text, inner):
                matched.append(inner)
                score += _phrase_icf[np]
        if not matched:
            continue
        reqs = LORA_AUTO_REQUIRES.get(group)
        if reqs and not any(_normalize(r).strip() in text for r in reqs):
            continue
        scored.append((score, group, matched))

    # Dedupe by concept category: at most one (highest-scoring) group per
    # category. Groups without a category become their own category.
    cat_groups = {}
    for cat, groups in LORA_AUTO_CATEGORIES.items():
        members = [g for g in groups if g in LORA_AUTO_PHRASES]
        if members:
            cat_groups[cat] = members
    covered = set(g for members in cat_groups.values() for g in members)
    for g in LORA_AUTO_PHRASES:
        if g not in covered:
            cat_groups[g] = [g]

    results = []
    for members in cat_groups.values():
        best = None
        for score, group, matched in scored:
            # On an exact score tie the LAST-scored group wins (>=), so the
            # more specific/later variant (e.g. iGoon Facial over Facesplash
            # when both share "facial cumshot") takes the category slot.
            if group in members and (best is None or score >= best[0]):
                best = (score, group, matched)
        if best and best[0] >= AUTO_SCORE_THRESHOLD:
            results.append({"group": best[1], "score": round(best[0], 3), "matched": best[2]})

    results.sort(key=lambda d: (-d["score"], d["group"]))
    return results


def auto_activate_loras(prompt):
    """Return the LoRA group names to auto-activate for the prompt."""
    return [d["group"] for d in auto_activation_details(prompt)]


# ── Full replacement prompts for each LoRA ────────────────────────────────
# When a LoRA is selected, its trigger words are prepended to the user's
# prompt. Format: [TRIGGER]; [SUBJECT], [MOTION], [CAMERA], [SCENE]
# (80–120 words, Wan 2.2 4-layer formula β€” early tokens weighted most)

LORA_PROMPT_TRIGGERS = {

 "Ahegao Drooling":
  "ahegao face drooling, a woman shows her middle finger flipping off the viewer, sticks out her "
  "tongue and rolls her eyes, she is drooling",

 "BBC Blowjob Extreme":
  "bbc extreme blowjob, a woman with glossy lips stretching her mouth around a large thick black "
  "erect penis",

 "BBC Deepthroat":
  "bbc deepthroat, a woman in front of a large thick black penis, she "
  "swallows the thick penis all the way",

 "Balls Sucking":
  "balls sucking, a woman with her lips wrapped around a man's testicles sucking",

 "Biggest Cock (size)":
  "biggest cock huge penis, an extraordinarily large erect penis with extreme length and girth",

 "Blink_Squatting_Cowgirl_Position_I2V":
  "squatting cowgirl position, a thick woman with thick thighs squatting over a man's erect penis",

 "Creampie CRM":
  "creampie, a woman with legs spread wide after intercourse",

 "Cum (generic)":
  "cumshot, a man ejaculating thick ropes of semen from his erect penis",

 "Cunnilingus":
  "cunnilingus, a woman lying back with her legs spread wide, a man's head between her thighs",

 "Doggy Front View v2":
  "Pl0wView, a woman on hands and knees facing the camera with a "
  "man kneeling behind her",

 "Doggy Slider":
  "doggy slider, a man sliding his cock in and out of a woman from behind in "
  "doggy style",

 "FOV Slider (camera)":
  "the camera zooms out while she is having sex, the camera pushes in very tight on "
  "the action then pulls back",

 "Facesplash Cumshot":
  "f4c3spl4sh, a woman kneeling eyes closed mouth open",

 "Fingering":
  "sensual_fingering, fingering, a woman lying back with her legs spread",

 "French Kiss":
  "french kiss, a man and woman already kissing deeply mouths locked together",

 "Fucked From Behind":
  "fucked from behind, a woman bent over gripping her ankles as a man stands behind her",

 "General NSFW Booster":
  "nsfwsks, highly detailed realistic scene with sharp focus and vivid textures",

 "Handjob":
  "handjob, a woman's hand with manicured nails wrapped around an erect penis",

 "JFJ Deepthroat":
  "blowjob, deepthroat",

 "Mating Press":
  "mating press, a small woman folded in half with her knees pressed to her chest",

 "Oral Insertion":
  "oral insertion, a woman with parted lips taking the tip of an erect penis into her "
  "mouth",

 "PENISLORA_22_i2v_HIGH_e320":
  "erect penis focus, a fully erect penis standing upright with prominent veins and flared glans",

 "PENISLORA_22_i2v_LOW_e496":
  "erect penis focus, a fully erect penis standing upright with prominent veins and flared glans",

 "POV Blowjob":
  "pov blowjob, the view from a man lying back watching a woman descend onto his erect "
  "penis",

 "POV Missionary":
  "pov missionary, missionary position, the view from a man's perspective looking down at a woman beneath "
  "him",

 "Penetration Insert":
  "penetration insertion, the moment of entry as an erect penis drives into a wet vagina",

 "Pornmaster Creampie":
  "pornmaster creampie, a woman's vulva filled with semen already leaking onto her thighs",

 "Pornmaster_wan 2.2_14b_I2V_bukkake_v1.4":
  "pornmaster bukkake, a woman, after a completely black screen, the camera quickly switches and excessive sperm "
  "on her face, excessive sperm on her hair",

 "Prone Bone":
  "prone bone position, a woman lying flat on her stomach with a man lying on top "
  "of her",

 "Pussy Helper":
  "pussy spread open, she rubs her vagina with her hand, she inserts her finger into her "
  "vagina",

 "Reverse Cowgirl v2":
  "reverse cowgirl, a woman with heavy curves straddling a man facing away from him",

 "Reverse Suspended Congress":
  "reverse suspended congress, a woman lying on her back with her hips raised and legs over "
  "a man's shoulders",

 "Smashcut (camera)":
  "SM4SHCUT, the scene changes and a man is thrusting his penis into and out of her "
  "pussy",

 "Standing Upright Sex":
  "standing sex, a woman pressed against a wall with one leg wrapped around a man's hip",

 "Throat V2":
  "throat fuck deep penetration, a woman gripping a man's thighs as he thrusts into her throat",

 "Twerking":
  "twerking, a thick woman with large buttocks bent over shaking her ass rhythmically",

 "Ultimate Deepthroat":
  "deep throat blowjob, a woman in front of a penis, she swallows the penis "
  "all the way",

 "W22_Multiscene_Photoshoot_Softcore_i2v":
  "softcore photoshoot, a beautiful woman posing provocatively on a bed wearing delicate lingerie",

 "WAN-2.2-I2V-Double-Blowjob":
  "double blowjob, a woman kneeling between two men, their erect penises positioned on either side of "
  "her face",

 "WAN-2.2-I2V-HandjobBlowjobCombo":
  "handjob blowjob combination, a woman with manicured nails kneeling in front of a man",

 "WAN-2.2-I2V-SensualTeasingBlowjob":
  "sensualBJ, a woman with glossy lips kneeling before a man, his erect penis inches from her "
  "mouth",

 "iGOON_Blink_Blowjob_I2V":
  "blowjob, a woman kneeling in front of a man, his erect penis in front of her "
  "face",

 "iGoon - Blink_Back_Doggystyle":
  "back doggystyle, back doggystyle position, a thick woman on all fours with her back arched deeply",

 "iGoon - Blink_Facial_I2V":
  "facial, a woman on her knees looking up at the camera with mouth open and tongue "
  "extended",

 "iGoon - Blink_Front_Doggystyle_I2V":
  "front doggystyle, front doggystyle position, a woman on hands and knees facing toward the camera",

 "iGoon - Blink_Missionary_I2V":
  "missionary, missionary position, a woman with a lean body lying on her back with legs spread "
  "wide",

 "iGoon_Blink_Missionary_I2V":
  "missionary position deep, a small woman lying back with her ankles hooked over a man's shoulders",

 "iGoon_Blink_Titjob_I2V":
  "titjob, titjob motion, a woman with heavy tits kneeling in front of a man",

 "lips-bj":
  "lips-bj, a woman with full prominent lips stretched taut around an erect penis",

 "mql_casting_sex_doggy_kneel_diagonally_behind_vagina_wan22_i2v_v1":
  "mqldgy_a, the woman is on all fours, the man is behind her",

 "mql_casting_sex_reverse_cowgirl_lie_front_vagina_wan22_i2v_v1":
  "reverse cowgirl, a full-figured woman straddling a man while facing his feet, leaning forward onto her "
  "hands",

 "mql_casting_sex_spoon_wan22_i2v_v1":
  "mqlspn_a, the woman lies on her side, the man spoons behind her",

 "mql_massage_tits_wan22_i2v_v1":
  "breast massage, a woman with full natural breasts lying back",

 "mql_panties_aside_wan22_i2v_v1":
  "panties aside, a woman with her panties pulled to one side revealing her exposed vulva",

 "sfbehind_v2.1":
  "sfb3hind, sfbehind, a woman bent over at the waist gripping the edge of a surface",

 "sid3l3g_transition_v2.0_H":
  "side leg transition, a toned woman lying on her side with her top leg raised and "
  "hooked",

 "sid3l3g_transition_v2.0_L":
  "side leg transition, a toned woman lying on her side with her top leg raised and "
  "hooked",

 "wan2.2_i2v_high_ulitmate_pussy_asshole":
  "pussy and asshole focus, a woman's vulva and anus fully exposed, labia spread open",

 "wan2.2_i2v_low_ulitmate_pussy_asshole":
  "pussy and asshole focus, a woman's vulva and anus fully exposed, labia spread open",

 "wan22-mouthfull-140epoc-high-k3nk":
  "m0u7hfu11, a woman with her mouth completely full of a penis",

 "wan22-mouthfull-152epoc-low-k3nk":
  "m0u7hfu11, a woman with her mouth completely full of a penis",
}


def _get_trigger_words(prompt_text):
    """Extract the activation trigger phrase from a LoRA prompt.



    The trigger is the leading concept clause (everything before the first

    comma or semicolon). Scene/position details later in the body are dropped

    so they never override the user's own prompt.

    """
    text = prompt_text.strip()
    for sep in (",", ";"):
        idx = text.find(sep)
        if idx != -1:
            return text[:idx].strip()
    return text


# LoRAs whose prompt body IS the effect (camera moves, generic quality
# boost) rather than a scene that conflicts with the user's prompt. These
# keep their full prompt; all other LoRAs contribute trigger words only.
LORA_KEEP_FULL_BODY = {
    "FOV Slider (camera)",
    "Smashcut (camera)",
    "General NSFW Booster",
}


def get_lora_prompt_additions(lora_groups):
    """Return the trigger phrase(s) for the selected LoRA group names.



    Scene LoRAs contribute ONLY their activation trigger words (the leading

    concept clause) so the user's own prompt controls the scene β€” a LoRA that

    describes "lying back" will never override a user prompt that says

    "standing up". Camera/booster LoRAs keep their full prompt because their

    body is the effect itself. A single selection returns its phrase; multiple

    selections join their phrases with '; ' so every selected LoRA activates.

    Far under the 512-token cap.



    Strips '(HIGH only)' / '(LOW only)' suffixes before lookup.

    Returns empty string when no triggers are found.

    """
    if not lora_groups:
        return ""
    cleaned = []
    for name in lora_groups:
        if not name or not isinstance(name, str):
            continue  # skip None / non-string entries from the API/MCP client
        n = re.sub(r'\s*\(HIGH only\)|\s*\(LOW only\)', '', name)
        prompt = LORA_PROMPT_TRIGGERS.get(n)
        if prompt:
            cleaned.append((n, prompt))

    if not cleaned:
        return ""
    if len(cleaned) == 1:
        n, p = cleaned[0]
        return p if n in LORA_KEEP_FULL_BODY else _get_trigger_words(p)

    # Multiple LoRAs: join each LoRA's phrase so every LoRA activates
    triggers = "; ".join(
        p if n in LORA_KEEP_FULL_BODY else _get_trigger_words(p)
        for n, p in cleaned
    )
    return triggers


def download_lora(group_name):
    if not group_name:
        return None, None
    clean_name = re.sub(r'\s*\(HIGH only\)|\s*\(LOW only\)', '', group_name)
    if clean_name.startswith("User: "):
        entry = _read_custom_library().get(clean_name[6:])
        if not entry:
            return None, None
        high = (entry.get("HIGH") or {}).get("path")
        low = (entry.get("LOW") or {}).get("path")
        # A manually removed Bucket file should disappear cleanly rather than
        # becoming a permanent failed selection.
        return (high if high and os.path.isfile(high) else None,
                low if low and os.path.isfile(low) else None)
    if clean_name not in LORA_PAIRS:
        return None, None
    pair = LORA_PAIRS[clean_name]
    high_path, low_path = None, None
    if pair["HIGH"]:
        repo, fn = pair["HIGH"]
        high_path = hf_hub_download(repo, fn, token=HF_TOKEN, revision=PINNED_REVISIONS.get(repo))
    if pair["LOW"]:
        repo, fn = pair["LOW"]
        low_path = hf_hub_download(repo, fn, token=HF_TOKEN, revision=PINNED_REVISIONS.get(repo))
    return high_path, low_path


def _strip_lora_bias(state_dict):
    """Drop keys that would make peft's TorchaoLoraLinear reject the adapter.



    Two sources of a learned bias term:

    1. Already-converted dicts: keys containing "lora_B" ending in ".bias"

       (diffusers' lora_bias auto-detect looks for these in

       src/diffusers/utils/peft_utils.py).

    2. Wan-native dicts: keys ending in ".diff_b". diffusers'

       _convert_non_diffusers_wan_lora_to_diffusers maps every diff_b key to a

       "lora_B.bias" key, tripping the same lora_bias=True path.



    Both are dropped so lora_bias stays False; only the (small) learned bias

    delta is discarded.

    """
    return {
        k: v for k, v in state_dict.items()
        if not (k.endswith(".diff_b") or ("lora_B" in k and k.endswith(".bias")))
    }


def _load_wan_lora(pipe, path, adapter_name, load_into_transformer_2=False):
    """Load a single Wan LoRA .safetensors via the dict path so we can strip

    lora_B bias keys first. HIGH files go to `transformer`, LOW files to

    `transformer_2` (the Wan 2.2 high/low-noise stage split), mirroring the

    validated startup load in app.py."""
    state_dict = safetensors.torch.load_file(path)
    state_dict = _strip_lora_bias(state_dict)
    kwargs = {"load_into_transformer_2": True} if load_into_transformer_2 else {}
    pipe.load_lora_weights(state_dict, adapter_name=adapter_name, **kwargs)


def load_lora_to_pipe(pipe, group_name, adapter_name="lora"):
    """Load a LoRA group into the pipe.



    HIGH -> transformer, LOW -> transformer_2 (Wan 2.2 stage split). Returns

    the list of adapter names registered ([] if nothing was loaded). Callers

    must pipe.set_adapters(names, weights) afterwards to activate them. On any

    failure all adapters are unloaded (names become reusable) and the error

    re-raised.

    """
    high_path, low_path = download_lora(group_name)
    if not (high_path or low_path):
        return []
    names = []
    try:
        if high_path:
            _load_wan_lora(pipe, high_path, f"{adapter_name}_high")
            names.append(f"{adapter_name}_high")
        if low_path:
            _load_wan_lora(pipe, low_path, f"{adapter_name}_low", load_into_transformer_2=True)
            names.append(f"{adapter_name}_low")
        return names
    except Exception:
        pipe.unload_lora_weights()  # drop partial/ghost adapters; names reusable
        raise


def unload_lora(pipe):
    try:
        pipe.unload_lora_weights()
    except:
        pass