File size: 54,397 Bytes
f0e0729
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f14c5d
 
 
f0e0729
 
 
 
3f14c5d
f0e0729
3f14c5d
 
 
f0e0729
3f14c5d
 
 
 
 
 
 
 
 
 
 
 
 
 
f0e0729
 
 
 
3f14c5d
f0e0729
 
 
3f14c5d
 
 
 
 
f0e0729
 
 
 
 
 
 
 
 
 
 
3f14c5d
f0e0729
 
3f14c5d
 
 
 
 
 
 
 
f0e0729
 
3f14c5d
 
 
 
 
 
 
 
f0e0729
 
3f14c5d
 
 
 
 
 
 
 
f0e0729
 
3f14c5d
 
 
 
 
 
f0e0729
 
 
 
 
 
3f14c5d
f0e0729
 
cf4feb8
3f14c5d
 
 
 
 
 
 
f0e0729
 
cf4feb8
3f14c5d
463ea41
 
3f14c5d
463ea41
 
3f14c5d
f0e0729
 
cf4feb8
3f14c5d
 
 
 
 
 
 
f0e0729
 
cf4feb8
3f14c5d
 
 
 
 
 
 
f0e0729
 
cf4feb8
3f14c5d
 
 
 
 
 
 
f0e0729
 
cf4feb8
3f14c5d
 
 
 
 
 
 
f0e0729
 
cf4feb8
3f14c5d
 
 
 
 
 
 
f0e0729
 
cf4feb8
3f14c5d
 
 
 
 
 
 
f0e0729
 
cf4feb8
3f14c5d
 
f0e0729
 
3f14c5d
 
f0e0729
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1604d11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f0e0729
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1604d11
 
 
 
 
 
f0e0729
 
 
 
 
 
 
 
 
 
1604d11
 
 
 
 
 
 
f0e0729
 
 
 
 
 
 
 
 
 
 
 
 
 
1604d11
f0e0729
1604d11
 
 
 
 
 
f0e0729
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1604d11
f0e0729
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1604d11
 
 
 
f0e0729
 
 
 
 
 
 
 
62b6601
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1604d11
 
 
 
62b6601
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f0e0729
 
 
 
1604d11
 
 
 
 
f0e0729
3f14c5d
62b6601
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f0e0729
 
 
 
 
 
 
 
 
 
 
62b6601
 
f0e0729
62b6601
 
 
 
f0e0729
 
3f14c5d
 
 
f0e0729
3f14c5d
 
 
 
 
 
f0e0729
3f14c5d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1604d11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2bb908a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cfe71af
 
 
 
 
2bb908a
 
cfe71af
 
 
 
2bb908a
cfe71af
 
 
2bb908a
cfe71af
32d0c74
 
 
 
 
 
cfe71af
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2bb908a
 
 
3f14c5d
 
 
 
cfe71af
 
 
 
 
 
 
 
3f14c5d
 
32d0c74
cfe71af
 
3f14c5d
 
32d0c74
 
 
 
 
 
3f14c5d
2bb908a
 
 
 
ab93adf
 
 
 
 
 
 
3f14c5d
2bb908a
7de40a5
 
 
 
 
 
 
1604d11
2bb908a
 
 
 
 
 
 
3f14c5d
 
f0e0729
 
 
 
12b5e99
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f0e0729
 
 
 
 
 
 
12b5e99
f0e0729
 
 
 
 
 
12b5e99
 
 
 
 
 
 
 
f0e0729
 
12b5e99
 
f0e0729
12b5e99
f0e0729
12b5e99
f0e0729
12b5e99
 
 
f0e0729
 
 
 
 
12b5e99
 
f0e0729
 
 
12b5e99
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f0e0729
 
12b5e99
f0e0729
 
 
 
 
 
12b5e99
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f0e0729
12b5e99
 
f0e0729
12b5e99
 
 
f0e0729
12b5e99
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f0e0729
 
12b5e99
 
f0e0729
 
 
 
 
12b5e99
 
f0e0729
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f14c5d
 
 
 
f0e0729
 
 
 
 
 
3f14c5d
 
 
f0e0729
 
 
 
 
 
 
 
 
62b6601
 
 
 
 
 
 
 
 
f0e0729
 
62b6601
 
 
 
 
 
 
f0e0729
62b6601
 
 
 
 
 
 
 
 
 
 
3f14c5d
62b6601
 
3f14c5d
 
f0e0729
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f14c5d
 
 
 
 
f0e0729
3f14c5d
 
f0e0729
3f14c5d
 
 
f0e0729
 
1604d11
 
 
f0e0729
 
3f14c5d
 
 
f0e0729
 
 
 
 
 
 
 
 
 
 
3f14c5d
f0e0729
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1604d11
 
 
 
f0e0729
 
 
 
 
 
 
 
 
 
 
 
 
 
7fa3bad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f0e0729
 
 
 
 
 
1604d11
 
7fa3bad
f0e0729
 
 
 
 
7fa3bad
f0e0729
 
7fa3bad
 
f0e0729
 
7fa3bad
f0e0729
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1604d11
 
 
 
f0e0729
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1604d11
 
 
 
 
 
f0e0729
 
 
 
 
 
 
 
 
 
1604d11
 
 
f0e0729
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1604d11
 
 
 
f0e0729
 
 
 
 
 
 
7fa3bad
 
 
 
 
 
f0e0729
1604d11
f0e0729
1604d11
7fa3bad
f0e0729
 
 
 
 
 
 
1604d11
f0e0729
1604d11
f0e0729
 
 
 
 
 
1604d11
f0e0729
1604d11
f0e0729
 
 
 
1604d11
 
f0e0729
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
"""LoRA catalog + per-session custom LoRA loader (JSON-first).

Single shared catalog lives in an external JSON file
(``PERSISTENT_LORA_CATALOG_PATH``, default
``/loras-flux/config/lorasplayground.json``).

Layers:
* EXTERNAL_LORA_STYLES β€” full catalog from JSON (including archived).
  UI listing only shows entries with ``active: true``.
* dynamic_loras (gr.State) β€” session-private try-outs.
* LOADED_ADAPTERS β€” names already attached to the shared pipe.

JSON entry fields:
  title, adapter_name, repo, weights, default_prompt, default_weight,
  admin_approved (bool), active (bool; false = archived/hidden from UI),
  sha256 (optional hex digest of the weight file), image (optional).
"""
from __future__ import annotations

import hashlib
import json
import os
import threading
import uuid
from pathlib import Path

import gradio as gr

from config import MAX_LORA_SLOTS, PERSISTENT_LORA_CATALOG_PATH


FACE_SWAP_PROMPT = """head_swap: start with Picture 1 as the base image, keeping its lighting, environment, and background. Remove the head from Picture 1 completely and replace it with the head from Picture 2.
FROM PICTURE 1 (strictly preserve):
- Scene: lighting conditions, shadows, highlights, color temperature, environment, background
- Head positioning: exact rotation angle, tilt, direction the head is facing
- Expression: facial expression, micro-expressions, eye gaze direction, mouth position, emotion
FROM PICTURE 2 (strictly preserve identity):
- Facial structure: face shape, bone structure, jawline, chin
- All facial features: eye color, eye shape, nose structure, lip shape and fullness, eyebrows
- Hair: color, style, texture, hairline
- Skin: texture, tone, complexion
The replaced head must seamlessly match Picture 1's lighting and expression while maintaining the complete identity from Picture 2. High quality, photorealistic, sharp details, 4k."""

_DEFAULT_LORA_IMAGE = (
    "https://huggingface.co/spaces/prithivMLmods/FLUX.2-Klein-LoRA-Studio/"
    "resolve/main/examples/image.webp"
)

# Seed used only when the external JSON is missing/empty. After first write,
# the JSON is the single source of truth β€” nothing here is merged at runtime.
_SEED_LORA_STYLES = [
    {
        "title": "Klein-Delight-Style",
        "adapter_name": "klein-delight",
        "repo": "linoyts/Flux2-Klein-Delight-LoRA",
        "weights": "pytorch_lora_weights.safetensors",
        "default_prompt": (
            "Relight the image to remove all existing lighting conditions and replace them "
            "with neutral, uniform illumination. Apply soft, evenly distributed lighting with "
            "no directional shadows, no harsh highlights, and no dramatic contrast. Maintain "
            "the original identity of all subjects exactlyβ€”preserve facial structure, skin tone, "
            "proportions, expressions, hair, clothing, and textures. Do not alter pose, camera "
            "angle, background geometry, or image composition. Lighting should appear balanced, "
            "and studio-neutral, similar to diffuse overcast or a soft lightbox setup. Ensure "
            "consistent exposure across the entire image with realistic depth and subtle shading "
            "only where necessary for form."
        ),
        "default_weight": 1.0,
        "admin_approved": True,
        "active": True,
    },
    {
        "title": "Klein-Consistency",
        "adapter_name": "klein-consistency",
        "repo": "dx8152/Flux2-Klein-9B-Consistency",
        "weights": "Klein-consistency.safetensors",
        "default_prompt": None,
        "default_weight": 0.3,
        "admin_approved": True,
        "active": True,
    },
    {
        "title": "Best-Face-Swap",
        "adapter_name": "face-swap",
        "repo": "Alissonerdx/BFS-Best-Face-Swap",
        "weights": "bfs_head_v1_flux-klein_9b_step3750_rank64.safetensors",
        "default_prompt": FACE_SWAP_PROMPT,
        "default_weight": 1.0,
        "admin_approved": True,
        "active": True,
    },
    {
        "title": "NSFW v2",
        "adapter_name": "nsfw-v2",
        "repo": "diroverflo/FLux_Klein_9B_NSFW",
        "weights": "Flux Klein - NSFW v2.safetensors",
        "default_prompt": None,
        "default_weight": 1.0,
        "admin_approved": True,
        "active": True,
    },
    {
        "title": "Ultimate Upscaler Klein-9b",
        "adapter_name": "Ultimate Upscaler",
        "repo": "loras",
        "weights": "Flux2-Klein-Image-RestoreV1.safetensors",
        "default_prompt": (
            "restore the image quality, remove any compression artefacts, remove any haze "
            "and soft edges, enrich the original with new intricate detail in all textures "
            "and surfaces creating a professional photorealistic photograph with natural "
            "lighting and skin texture."
        ),
        "default_weight": 1.0,
        "admin_approved": True,
        "active": True,
    },
    {
        "title": "High Resolution",
        "adapter_name": "High Resolution",
        "repo": "loras",
        "weights": "HighResolution9B.safetensors",
        "default_prompt": "High Resolution",
        "default_weight": 1.0,
        "admin_approved": True,
        "active": True,
    },
    {
        "title": "InstaPic",
        "adapter_name": "InstaPic V3",
        "repo": "loras",
        "weights": "InstaPic V3.safetensors",
        "default_prompt": "instapic",
        "default_weight": 1.0,
        "admin_approved": True,
        "active": True,
    },
    {
        "title": "Realistic Nudes",
        "adapter_name": "Realistic Nudes",
        "repo": "loras",
        "weights": "realistic_nudes_klein_v3.safetensors",
        "default_prompt": None,
        "default_weight": 1.0,
        "admin_approved": True,
        "active": True,
    },
    {
        "title": "Perky Pointy Puffy Breasts",
        "adapter_name": "Perky Pointy Puffy Breasts",
        "repo": "loras",
        "weights": "PerkyPointyPuffy_v1.1_small_pointy_breasts_large_puffy_nipples.safetensors",
        "default_prompt": "Small pointy breasts with large puffy nipples",
        "default_weight": 1.0,
        "admin_approved": True,
        "active": True,
    },
    {
        "title": "Flat Chested",
        "adapter_name": "Flat Chested",
        "repo": "loras",
        "weights": "Flux2-Klein-9b-FlatChested-v1.safetensors",
        "default_prompt": "flat chested",
        "default_weight": 1.5,
        "admin_approved": True,
        "active": True,
    },
    {
        "title": "Controllight",
        "adapter_name": "Controllight",
        "repo": "ControlLight/ControlLight",
        "weights": "controllight.safetensors",
        "default_prompt": None,
        "default_weight": 1.0,
        "admin_approved": True,
        "active": True,
    },
    {
        "title": "RefControl - Depth",
        "adapter_name": "RefConDep",
        "repo": "thedeoxen/refcontrol-FLUX.2-klein-9B-reference-depth-lora",
        "weights": "flux2_klein_9b_refcontrol_depth.safetensors",
        "default_prompt": "refcontrol",
        "default_weight": 1.0,
        "admin_approved": True,
        "active": True,
    },
    {
        "title": "RefControl - Pose",
        "adapter_name": "RefConPos",
        "repo": "thedeoxen/refcontrol-FLUX.2-klein-9B-reference-pose-lora",
        "weights": "refcontrol_v2_poses.safetensors",
        "default_prompt": "apply pose from image 1 with reference from image 2",
        "default_weight": 1.0,
        "admin_approved": True,
        "active": True,
    },
]

# Back-compat alias β€” older imports still work; runtime catalog is JSON-only.
LORA_STYLES: list[dict] = []

LOADED_ADAPTERS: set[str] = set()
_CATALOG_LOCK = threading.Lock()
EXTERNAL_LORA_STYLES: list[dict] = []  # full JSON list (active + archived)

_WEIGHT_EXTS = (".safetensors", ".bin")
_DEFAULT_WEIGHT_CANDIDATES = (
    "pytorch_lora_weights.safetensors",
    "lora.safetensors",
    "adapter_model.safetensors",
)
_HASH_CHUNK = 1024 * 1024


def _sanitize_name(value: str, fallback: str = "custom") -> str:
    cleaned = "".join(c if c.isalnum() or c in "-_" else "_" for c in (value or ""))
    return cleaned.strip("_") or fallback


def _as_bool(value, default: bool = False) -> bool:
    if value is None:
        return default
    if isinstance(value, bool):
        return value
    if isinstance(value, (int, float)):
        return bool(value)
    if isinstance(value, str):
        return value.strip().lower() in {"1", "true", "yes", "y", "on"}
    return default


def _file_sha256(path: str | Path) -> str | None:
    p = Path(path)
    if not p.is_file():
        return None
    h = hashlib.sha256()
    try:
        with open(p, "rb") as f:
            while True:
                chunk = f.read(_HASH_CHUNK)
                if not chunk:
                    break
                h.update(chunk)
        return h.hexdigest()
    except OSError as e:
        print(f"[lora_registry] sha256 failed for {p}: {e}")
        return None


def _weight_path(repo: str, weights: str) -> Path | None:
    if not repo or not weights:
        return None
    if str(repo).startswith("/"):
        candidate = Path(repo) / weights
        if candidate.is_file():
            return candidate
    candidate = Path(repo) / weights
    if candidate.is_file():
        return candidate
    if str(repo).endswith(_WEIGHT_EXTS) and Path(repo).is_file():
        return Path(repo)
    return None


def _compute_entry_sha256(entry: dict) -> str | None:
    if entry.get("sha256"):
        return str(entry["sha256"]).lower()
    path = _weight_path(entry.get("repo", ""), entry.get("weights", ""))
    if path is None:
        return None
    return _file_sha256(path)


def _parse_trigger_list(value) -> list[str]:
    """Normalize known_triggers from JSON list or free text (commas/newlines)."""
    if value is None:
        return []
    if isinstance(value, list):
        out = []
        for item in value:
            s = str(item).strip()
            if s:
                out.append(s)
        return out
    text = str(value).replace(",", "\n")
    return [line.strip() for line in text.splitlines() if line.strip()]


def _normalize_catalog_entry(raw) -> dict | None:
    if not isinstance(raw, dict):
        return None
    title = (raw.get("title") or "").strip()
    repo = raw.get("repo")
    weights = raw.get("weights")
    if not title or not repo or not weights:
        return None
    adapter = (raw.get("adapter_name") or "").strip() or _sanitize_name(title)
    try:
        default_weight = float(raw.get("default_weight", 1.0))
    except (TypeError, ValueError):
        default_weight = 1.0
    prompt = raw.get("default_prompt")
    if isinstance(prompt, str):
        prompt = prompt.strip() or None
    else:
        prompt = None

    if "active" in raw:
        active = _as_bool(raw.get("active"), True)
    else:
        active = not _as_bool(raw.get("archived"), False)

    sha = raw.get("sha256") or raw.get("hash") or raw.get("sha256_hex")
    if isinstance(sha, str):
        sha = sha.strip().lower() or None
    else:
        sha = None

    notes = raw.get("notes")
    if isinstance(notes, str):
        notes = notes.strip() or None
    else:
        notes = None

    return {
        "image": raw.get("image") or _DEFAULT_LORA_IMAGE,
        "title": title,
        "adapter_name": adapter,
        "repo": str(repo),
        "weights": str(weights),
        "default_prompt": prompt,
        "default_weight": default_weight,
        "admin_approved": _as_bool(raw.get("admin_approved"), False),
        "active": active,
        "compatible_with_playground": _as_bool(
            raw.get("compatible_with_playground"), True
        ),
        "notes": notes,
        "known_triggers": _parse_trigger_list(
            raw.get("known_triggers") or raw.get("triggers")
        ),
        "sha256": sha,
    }


def _serialize_entry(e: dict) -> dict:
    out = {
        "title": e["title"],
        "adapter_name": e["adapter_name"],
        "repo": e["repo"],
        "weights": e["weights"],
        "default_prompt": e.get("default_prompt"),
        "default_weight": float(e.get("default_weight", 1.0)),
        "admin_approved": bool(e.get("admin_approved", False)),
        "active": bool(e.get("active", True)),
        "compatible_with_playground": bool(e.get("compatible_with_playground", True)),
    }
    notes = (e.get("notes") or "").strip() if isinstance(e.get("notes"), str) else e.get("notes")
    if notes:
        out["notes"] = notes
    triggers = _parse_trigger_list(e.get("known_triggers"))
    if triggers:
        out["known_triggers"] = triggers
    if e.get("sha256"):
        out["sha256"] = e["sha256"]
    if e.get("image") and e["image"] != _DEFAULT_LORA_IMAGE:
        out["image"] = e["image"]
    return out


def _read_catalog_file(path: str | None = None) -> list[dict]:
    catalog_path = Path(path or PERSISTENT_LORA_CATALOG_PATH)
    if not catalog_path.is_file():
        return []
    try:
        with open(catalog_path, "r", encoding="utf-8") as f:
            data = json.load(f)
    except Exception as e:
        print(f"[lora_registry] Could not read catalog {catalog_path}: {e}")
        return []

    if isinstance(data, dict):
        items = data.get("loras") or data.get("styles") or data.get("items") or []
    elif isinstance(data, list):
        items = data
    else:
        return []

    out, seen_titles = [], set()
    for raw in items:
        entry = _normalize_catalog_entry(raw)
        if not entry or entry["title"] in seen_titles:
            continue
        seen_titles.add(entry["title"])
        out.append(entry)
    return out


def _write_catalog_file(entries: list[dict], path: str | None = None) -> str:
    catalog_path = Path(path or PERSISTENT_LORA_CATALOG_PATH)
    catalog_path.parent.mkdir(parents=True, exist_ok=True)
    payload = {
        "version": 3,
        "loras": [_serialize_entry(e) for e in entries],
    }
    tmp_path = catalog_path.with_suffix(catalog_path.suffix + ".tmp")
    with open(tmp_path, "w", encoding="utf-8") as f:
        json.dump(payload, f, indent=2, ensure_ascii=False)
        f.write("\n")
    os.replace(tmp_path, catalog_path)
    return str(catalog_path)


def _seed_catalog_if_needed(path: str | None = None) -> list[dict]:
    catalog_path = Path(path or PERSISTENT_LORA_CATALOG_PATH)
    entries = _read_catalog_file(str(catalog_path))
    if entries:
        dirty = False
        for e in entries:
            if not e.get("sha256"):
                digest = _compute_entry_sha256(e)
                if digest:
                    e["sha256"] = digest
                    dirty = True
        if dirty:
            try:
                _write_catalog_file(entries, str(catalog_path))
            except Exception as ex:
                print(f"[lora_registry] Could not backfill sha256: {ex}")
        return entries

    seeded = []
    for raw in _SEED_LORA_STYLES:
        entry = _normalize_catalog_entry(raw)
        if not entry:
            continue
        digest = _compute_entry_sha256(entry)
        if digest:
            entry["sha256"] = digest
        seeded.append(entry)
    try:
        written = _write_catalog_file(seeded, str(catalog_path))
        print(f"[lora_registry] Seeded catalog with {len(seeded)} LoRA(s) β†’ {written}")
    except Exception as e:
        print(f"[lora_registry] Could not seed catalog at {catalog_path}: {e}")
    return seeded


def load_external_catalog(path: str | None = None) -> list[dict]:
    global EXTERNAL_LORA_STYLES, LORA_STYLES
    with _CATALOG_LOCK:
        EXTERNAL_LORA_STYLES = _seed_catalog_if_needed(path)
        LORA_STYLES = [
            e for e in EXTERNAL_LORA_STYLES
            if e.get("active", True) and e.get("compatible_with_playground", True)
        ]
        print(
            f"[lora_registry] Catalog: {len(LORA_STYLES)} active / "
            f"{len(EXTERNAL_LORA_STYLES)} total from "
            f"{path or PERSISTENT_LORA_CATALOG_PATH}"
        )
        return list(EXTERNAL_LORA_STYLES)


def reload_catalog_from_disk(path: str | None = None) -> list[dict]:
    """Re-read JSON from disk into memory without re-seeding over an existing file.

    Used on every browser page load so newly saved catalog entries (and
    active/inactive edits) appear without restarting the Space.
    """
    global EXTERNAL_LORA_STYLES, LORA_STYLES
    catalog_path = Path(path or PERSISTENT_LORA_CATALOG_PATH)
    with _CATALOG_LOCK:
        if catalog_path.is_file():
            entries = _read_catalog_file(str(catalog_path))
            # Only fall back to seed when the file is missing, not when it is
            # a deliberate empty list β€” empty list means "show nothing extra".
            EXTERNAL_LORA_STYLES = entries
        else:
            EXTERNAL_LORA_STYLES = _seed_catalog_if_needed(str(catalog_path))
        LORA_STYLES = [
            e for e in EXTERNAL_LORA_STYLES
            if e.get("active", True) and e.get("compatible_with_playground", True)
        ]
        print(
            f"[lora_registry] Reloaded catalog: {len(LORA_STYLES)} active / "
            f"{len(EXTERNAL_LORA_STYLES)} total from {catalog_path}"
        )
        return list(EXTERNAL_LORA_STYLES)


def refresh_catalog_ui(dynamic_loras_state, currently_selected=None):
    """Reload disk catalog and return Gradio updates for selector + remove list.

    Drops session-only entries whose title now exists in the active catalog
    (they were saved). Preserves still-valid checkbox selections.
    """
    reload_catalog_from_disk()
    dynamic_loras = dict(dynamic_loras_state or {})
    active_titles = {s["title"] for s in _active_catalog()}

    # Session copies that were persisted no longer need to live in gr.State.
    stale_keys = [
        k for k, v in dynamic_loras.items()
        if v.get("title") in active_titles
    ]
    for k in stale_keys:
        dynamic_loras.pop(k, None)

    choices = [s["title"] for s in get_selectable_styles(dynamic_loras)]
    choice_set = set(choices)
    new_sel = [t for t in (currently_selected or []) if t in choice_set]
    save_choices = session_custom_lora_titles(dynamic_loras)
    remove_choices = save_choices + removable_catalog_titles()
    return (
        gr.update(choices=choices, value=new_sel),
        gr.update(choices=save_choices),
        gr.update(choices=remove_choices),
        dynamic_loras,
    )


load_external_catalog()


def _active_catalog() -> list[dict]:
    """Entries shown in the main selector: active and playground-compatible."""
    return [
        e for e in EXTERNAL_LORA_STYLES
        if e.get("active", True) and e.get("compatible_with_playground", True)
    ]


def _norm_repo_key(repo: str | None) -> str:
    """Normalize repo/path keys for duplicate comparison.

    Local absolute paths are resolved so macOS /var vs /private/var (and
    trailing slashes) still match. HF ids are lower-cased lightly only for
    exact string compare after strip.
    """
    if not repo:
        return ""
    repo = str(repo).strip()
    if repo.startswith("/"):
        try:
            return str(Path(repo).resolve())
        except OSError:
            return repo.rstrip("/")
    return repo


def _find_duplicate(entries: list[dict], *, title=None, sha256=None, repo=None, weights=None):
    if sha256:
        sha = str(sha256).lower()
        for e in entries:
            if e.get("sha256") and e["sha256"].lower() == sha:
                return e
    if title:
        for e in entries:
            if e.get("title") == title:
                return e
    if repo and weights:
        repo_key = _norm_repo_key(repo)
        weight_key = str(weights).strip()
        for e in entries:
            if (
                _norm_repo_key(e.get("repo")) == repo_key
                and str(e.get("weights") or "").strip() == weight_key
            ):
                return e
    return None


def get_all_styles(dynamic_loras):
    all_styles = list(_active_catalog())
    for dynamic_lora in (dynamic_loras or {}).values():
        all_styles.append(dynamic_lora)
    return all_styles


def get_selectable_styles(dynamic_loras):
    return [s for s in get_all_styles(dynamic_loras) if s.get("adapter_name") is not None]


def get_style_by_title(title, dynamic_loras):
    for style in get_all_styles(dynamic_loras):
        if style["title"] == title:
            return style
    return None


def get_style_by_adapter_name(adapter_name, dynamic_loras):
    for style in get_all_styles(dynamic_loras):
        if style["adapter_name"] == adapter_name:
            return style
    return None


def format_selected_lora_details(selected_titles, dynamic_loras) -> str:
    """Plain-text detail block for currently ticked LoRAs (repo/triggers/notes)."""
    styles = [
        get_style_by_title(t, dynamic_loras)
        for t in (selected_titles or [])
        if get_style_by_title(t, dynamic_loras)
    ]
    if not styles:
        return ""
    blocks = []
    for s in styles:
        lines = [
            f"**{s['title']}**",
            f"- repo: `{s.get('repo')}`",
            f"- weights: `{s.get('weights')}`",
            f"- default weight: {s.get('default_weight', 1.0)}",
        ]
        if s.get("default_prompt"):
            lines.append(f"- default prompt: {s['default_prompt']}")
        triggers = _parse_trigger_list(s.get("known_triggers"))
        if triggers:
            lines.append("- known triggers: " + ", ".join(f"`{t}`" for t in triggers))
        if s.get("notes"):
            lines.append(f"- notes: {s['notes']}")
        blocks.append("\n".join(lines))
    return "\n\n".join(blocks)


_PROMPT_SEP = "\n\n"
_PROMPT_SET_PREFIX = "__set__:"


def _style_default_prompt(style) -> str:
    return (str(style.get("default_prompt") or "")).strip()


def _prompt_set_key(titles) -> str:
    return _PROMPT_SET_PREFIX + "\x1f".join(titles or [])


def _capture_lora_prompts(prev_titles, current_text, prompt_memory):
    """Persist the on-screen LoRA prompt box into session memory."""
    mem = dict(prompt_memory or {})
    prev = list(prev_titles or [])
    if not prev:
        return mem
    text = "" if current_text is None else str(current_text)
    # Always remember the exact previous selection's combined text.
    mem[_prompt_set_key(prev)] = text
    parts = text.split(_PROMPT_SEP)
    if len(parts) == len(prev):
        for title, part in zip(prev, parts):
            mem[str(title)] = part
    elif len(prev) == 1:
        mem[str(prev[0])] = text
    return mem


def _build_lora_prompt(new_titles, prompt_memory, dynamic_loras, prev_titles=None):
    """Rebuild the combined LoRA prompt, preserving edits when possible."""
    mem = dict(prompt_memory or {})
    titles = list(new_titles or [])
    if not titles:
        return "", mem

    set_key = _prompt_set_key(titles)
    if set_key in mem:
        return mem[set_key], mem

    prev = list(prev_titles or [])
    prev_key = _prompt_set_key(prev) if prev else None
    prev_set = set(prev)
    new_set = set(titles)

    # Pure add onto a previous (possibly freely-edited) combined prompt.
    if prev_key and prev_key in mem and prev_set and prev_set.issubset(new_set) and new_set != prev_set:
        base = mem[prev_key]
        extras = []
        for title in titles:
            if title in prev_set:
                continue
            if title in mem:
                frag = mem[title]
            else:
                style = get_style_by_title(title, dynamic_loras) or {}
                frag = _style_default_prompt(style)
                mem[title] = frag
            frag = (frag or "").strip()
            if frag:
                extras.append(frag)
        parts = []
        if (base or "").strip():
            parts.append(base.rstrip())
        parts.extend(extras)
        combined = _PROMPT_SEP.join(parts)
        mem[set_key] = combined
        return combined, mem

    # Pure remove: if the previous combined text still splits cleanly into one
    # fragment per previous title, drop the removed titles' fragments.
    # Otherwise the user free-edited the box β€” keep that text rather than
    # guessing from stale per-title defaults.
    if prev_key and prev_key in mem and new_set and new_set.issubset(prev_set) and new_set != prev_set:
        prev_text = mem[prev_key]
        prev_parts = prev_text.split(_PROMPT_SEP)
        if len(prev_parts) == len(prev):
            title_to_part = dict(zip(prev, prev_parts))
            parts = []
            for title in titles:
                frag = (title_to_part.get(title) or mem.get(title) or "").strip()
                if frag:
                    parts.append(frag)
            combined = _PROMPT_SEP.join(parts)
        else:
            combined = prev_text
        mem[set_key] = combined
        return combined, mem

    # Default path: per-title memory, else catalog default.
    parts = []
    for title in titles:
        if title in mem and not str(title).startswith(_PROMPT_SET_PREFIX):
            frag = mem[title]
        else:
            style = get_style_by_title(title, dynamic_loras) or {}
            frag = _style_default_prompt(style)
            mem[title] = frag
        frag = (frag or "").strip()
        if frag:
            parts.append(frag)
    combined = _PROMPT_SEP.join(parts)
    mem[set_key] = combined
    return combined, mem


def update_weight_sliders(
    selected_titles,
    dynamic_loras,
    weight_memory=None,
    prev_selected=None,
    prompt_memory=None,
    current_lora_prompt=None,
    *current_slider_values,
):
    """Show/hide weight sliders for the current LoRA selection.

    Preserves user-adjusted weights and LoRA prompt text:
    - Reads live slider values for the previous selection into `weight_memory`
    - Reuses remembered weights for still-selected (or re-selected) titles
    - Only new titles fall back to catalog `default_weight`
    - Same idea for the editable LoRA prompt box (per-title + set memory)
    """
    selected_styles = []
    for t in (selected_titles or []):
        style = get_style_by_title(t, dynamic_loras)
        if style is not None:
            selected_styles.append(style)

    memory = dict(weight_memory or {})
    prev = list(prev_selected or [])

    # Capture current on-screen slider values before rebuilding slots.
    for i, title in enumerate(prev):
        if i >= len(current_slider_values):
            break
        val = current_slider_values[i]
        if val is None or title is None:
            continue
        try:
            memory[str(title)] = float(val)
        except (TypeError, ValueError):
            pass

    # Capture current LoRA prompt box before selection rebuild.
    p_memory = _capture_lora_prompts(prev, current_lora_prompt, prompt_memory)

    slider_updates = []
    for i in range(MAX_LORA_SLOTS):
        if i < len(selected_styles):
            style = selected_styles[i]
            title = style["title"]
            default_w = float(style.get("default_weight", 1.0))
            weight = memory.get(title, default_w)
            try:
                weight = float(weight)
            except (TypeError, ValueError):
                weight = default_w
            memory[title] = weight
            slider_updates.append(gr.update(
                visible=True,
                interactive=True,
                label=f"{title} β€” weight",
                value=weight,
            ))
        else:
            # Keep label stable when hiding β€” fewer DOM thrash / stuck-progress cases.
            slider_updates.append(gr.update(
                visible=False,
                interactive=False,
                value=1.0,
            ))

    new_selected = [s["title"] for s in selected_styles]
    combined, p_memory = _build_lora_prompt(
        new_selected, p_memory, dynamic_loras, prev_titles=prev,
    )
    # Keep the box always visible so selection races can't hide it while the
    # prompt is still applied at generate time. Empty when nothing selected.
    lora_prompt_update = gr.update(
        value=combined or "",
        visible=True,
        interactive=True,
    )

    details = format_selected_lora_details(new_selected, dynamic_loras)
    if not details:
        details = (
            "*Tick one or more LoRAs above to see full repo paths, "
            "known triggers, and notes.*"
        )
    # Always keep the Advanced accordion body populated (no visibility toggle).
    details_update = gr.update(value=details)

    return slider_updates + [
        lora_prompt_update,
        details_update,
        memory,
        new_selected,
        p_memory,
    ]


def _looks_like_local_path(value: str) -> bool:
    return bool(value) and value.startswith("/")


def _is_weight_filename(name: str | None) -> bool:
    if not name:
        return False
    lower = str(name).strip().lower()
    return any(lower.endswith(ext) for ext in _WEIGHT_EXTS)


def _split_hf_repo_and_weight(repo_id: str, weight_name: str | None) -> tuple[str, str | None]:
    """Split owner/repo[/nested/weight.safetensors] into hub repo id + weight path.

    Supports nested weights inside the repo, e.g.:
      user/repo/sub/dir/model.safetensors  -> repo=user/repo, weight=sub/dir/model.safetensors
      user/repo + weight=sub/dir/model.safetensors (unchanged)
    """
    repo = (repo_id or "").strip().strip("/")
    weight = weight_name.strip() if weight_name and str(weight_name).strip() else None

    # If weight already given: hub repo is owner/name; optional extra path
    # segments are a subfolder prefix (user/repo/sub + file.safetensors).
    if weight:
        weight = weight.lstrip("/")
        parts = [p for p in repo.split("/") if p]
        if len(parts) >= 2:
            hub = f"{parts[0]}/{parts[1]}"
            extra = parts[2:]
            # user/repo/subfolder + model.safetensors -> subfolder/model.safetensors
            if extra and not _is_weight_filename(extra[-1]):
                prefix = "/".join(extra)
                if not (weight == prefix or weight.startswith(prefix + "/")):
                    weight = f"{prefix}/{weight}"
            return hub, weight
        return repo, weight

    parts = [p for p in repo.split("/") if p]
    if len(parts) <= 2:
        return repo, None

    # owner/repo/<rest...>
    owner, name, *rest = parts
    hub_repo = f"{owner}/{name}"
    rest_path = "/".join(rest)

    # user/repo/file.safetensors  OR  user/repo/sub/file.safetensors
    if _is_weight_filename(rest[-1]):
        return hub_repo, rest_path

    # user/repo/subfolder  (prefix inside repo; weight still unknown)
    # Keep as repo + None so auto-detect can filter siblings under this prefix.
    return hub_repo, None if not rest_path else f"{rest_path}/"  # trailing slash = prefix marker


def _resolve_local_lora(path_str: str, weight_name: str | None):
    path = Path(os.path.expanduser(path_str)).resolve()
    requested = weight_name.strip() if weight_name and weight_name.strip() else None

    if path.is_file():
        if path.suffix.lower() not in _WEIGHT_EXTS:
            raise ValueError(f"Not a LoRA weight file: {path.name}")
        # Keep nested filename only for local load_lora_weights(dir, weight_name=file)
        return str(path.parent), path.name, path.stem

    if not path.is_dir():
        raise FileNotFoundError(f"Local path not found: {path}")

    if requested:
        # Allow nested relative weight paths: sub/dir/model.safetensors
        candidate = (path / requested).resolve()
        try:
            candidate.relative_to(path)
        except ValueError as e:
            raise FileNotFoundError(
                f"Weight path escapes directory {path}: {requested}"
            ) from e
        if not candidate.is_file():
            available = sorted(
                str(p.relative_to(path))
                for p in path.rglob("*")
                if p.is_file() and p.suffix.lower() in _WEIGHT_EXTS
            )[:20]
            raise FileNotFoundError(
                f"'{requested}' not under {path}. Available: {', '.join(available) or 'None'}"
            )
        # diffusers local: repo=dir containing file tree root we pass, weights=relpath
        rel = str(candidate.relative_to(path)).replace("\\", "/")
        return str(path), rel, Path(rel).stem

    for name in _DEFAULT_WEIGHT_CANDIDATES:
        if (path / name).is_file():
            return str(path), name, path.name

    # Prefer top-level weights; fall back to a single nested weight if unique.
    top = sorted(
        p.name for p in path.iterdir()
        if p.is_file() and p.suffix.lower() in _WEIGHT_EXTS
    )
    if len(top) == 1:
        return str(path), top[0], Path(top[0]).stem
    if top:
        raise FileNotFoundError(
            f"Multiple weights in {path}; set Weight filename. Available: {', '.join(top)}"
        )

    nested = sorted(
        str(p.relative_to(path)).replace("\\", "/")
        for p in path.rglob("*")
        if p.is_file() and p.suffix.lower() in _WEIGHT_EXTS
    )
    if len(nested) == 1:
        return str(path), nested[0], Path(nested[0]).stem
    if not nested:
        raise FileNotFoundError(f"No .safetensors/.bin weights found in {path}")
    raise FileNotFoundError(
        f"Multiple nested weights in {path}; set Weight path. Available: {', '.join(nested[:20])}"
    )


def _resolve_hf_lora(repo_id: str, weight_name: str | None):
    from huggingface_hub import model_info

    hub_repo, weight_or_prefix = _split_hf_repo_and_weight(repo_id, weight_name)
    # Trailing slash marks "directory prefix inside repo" from user/repo/subfolder
    prefix = None
    actual_weight = weight_or_prefix
    if actual_weight and actual_weight.endswith("/") and not _is_weight_filename(actual_weight):
        prefix = actual_weight.lstrip("/")
        actual_weight = None
    elif actual_weight:
        actual_weight = actual_weight.lstrip("/")

    info = model_info(hub_repo)
    siblings = list(info.siblings or [])

    def _weight_siblings(pref: str | None = None):
        out = []
        for f in siblings:
            name = getattr(f, "filename", None) or ""
            if not name.endswith(_WEIGHT_EXTS):
                continue
            if pref and not name.startswith(pref):
                continue
            out.append(name)
        return out

    if not actual_weight:
        # Auto-pick under optional subfolder prefix.
        search_prefix = prefix or ""
        for name in _DEFAULT_WEIGHT_CANDIDATES:
            candidate = f"{search_prefix}{name}" if search_prefix else name
            if any(getattr(f, "filename", None) == candidate for f in siblings):
                actual_weight = candidate
                break
        if not actual_weight:
            available = _weight_siblings(search_prefix or None)
            # If prefix was a folder and defaults missing, unique weight under prefix
            if len(available) == 1:
                actual_weight = available[0]
            elif not available and not search_prefix:
                available = _weight_siblings(None)
                if len(available) == 1:
                    actual_weight = available[0]
            if not actual_weight:
                shown = available[:30] if available else _weight_siblings(None)[:30]
                where = f" under '{search_prefix.rstrip('/')}'" if search_prefix else ""
                raise FileNotFoundError(
                    f"No weight found in {hub_repo}{where}. "
                    f"Available: {', '.join(shown) or 'None'}"
                )

    # Validate nested path exists in repo file list when possible
    sibling_names = {getattr(f, "filename", None) for f in siblings}
    if actual_weight not in sibling_names:
        # allow if list incomplete; still try exact match after strip
        alt = actual_weight.lstrip("./")
        if alt in sibling_names:
            actual_weight = alt
        else:
            available = _weight_siblings(None)
            # helpful: show nested matches by basename
            base = Path(actual_weight).name
            nested_hits = [a for a in available if a == actual_weight or a.endswith("/" + base)]
            hint = nested_hits[:10] if nested_hits else available[:20]
            raise FileNotFoundError(
                f"Weight '{actual_weight}' not in {hub_repo}. "
                f"Try nested path like 'subfolder/{base}'. Available: {', '.join(hint) or 'None'}"
            )

    sha = None
    for sib in siblings:
        if getattr(sib, "filename", None) == actual_weight:
            lfs = getattr(sib, "lfs", None) or {}
            if isinstance(lfs, dict):
                sha = lfs.get("sha256") or lfs.get("oid")
            break

    display = Path(actual_weight).stem if actual_weight else hub_repo.split("/")[-1]
    return hub_repo, actual_weight, display, (str(sha).lower() if sha else None)


def session_custom_lora_titles(dynamic_loras) -> list[str]:
    return [s["title"] for s in (dynamic_loras or {}).values() if s.get("title")]


def removable_catalog_titles() -> list[str]:
    return [
        e["title"] for e in EXTERNAL_LORA_STYLES
        if not e.get("admin_approved", False)
    ]


def _unique_adapter_name(base: str) -> str:
    existing = {
        s["adapter_name"]
        for s in EXTERNAL_LORA_STYLES
        if s.get("adapter_name")
    } | set(LOADED_ADAPTERS)
    if base not in existing:
        return base
    for i in range(2, 1000):
        candidate = f"{base}_{i}"
        if candidate not in existing:
            return candidate
    return f"{base}_{uuid.uuid4().hex[:6]}"


def _empty_add_result(msg, dynamic_loras):
    save_choices = session_custom_lora_titles(dynamic_loras)
    remove_choices = save_choices + removable_catalog_titles()
    return (
        msg,
        gr.update(),
        dynamic_loras,
        gr.update(choices=save_choices),
        gr.update(choices=remove_choices),
    )


def add_custom_lora(repo_id, weight_name, adapter_name, dynamic_loras_state):
    dynamic_loras = dict(dynamic_loras_state or {})
    if not repo_id or not repo_id.strip():
        return _empty_add_result(
            "Please enter a HuggingFace repo ID or a local path "
            "(e.g. /loras-flux/my.safetensors).",
            dynamic_loras,
        )

    repo_id = repo_id.strip()
    requested_name = adapter_name.strip() if adapter_name and adapter_name.strip() else None
    try:
        sha = None
        if _looks_like_local_path(repo_id):
            resolved_repo, actual_weight, auto_name = _resolve_local_lora(repo_id, weight_name)
            source_label = resolved_repo
            sha = _file_sha256(Path(resolved_repo) / actual_weight)
        else:
            resolved_repo, actual_weight, auto_name, sha = _resolve_hf_lora(repo_id, weight_name)
            source_label = resolved_repo

        # Re-read disk first so "already in catalog" matches what new browsers should see.
        reload_catalog_from_disk()
        dup = _find_duplicate(
            EXTERNAL_LORA_STYLES,
            sha256=sha,
            repo=resolved_repo,
            weights=actual_weight,
            title=None,
        )
        if dup:
            where = "active catalog" if dup.get("active", True) else "archived catalog"
            # Always refresh selector choices so the existing entry becomes visible
            # (fixes "saved but stuck / not listed in a new session").
            choices = [s["title"] for s in get_selectable_styles(dynamic_loras)]
            save_choices = session_custom_lora_titles(dynamic_loras)
            remove_choices = save_choices + removable_catalog_titles()
            is_active = bool(dup.get("active", True))
            msg = (
                f"⚠️ Already in {where} as '{dup['title']}'"
                + (f" (sha256 {dup['sha256'][:12]}…)" if dup.get("sha256") else "")
            )
            if is_active:
                msg += ". Catalog list refreshed β€” you can select it above."
                sel_upd = gr.update(choices=choices, value=[dup["title"]])
            else:
                msg += ". It is archived (active=false); set active=true in JSON to show it."
                sel_upd = gr.update(choices=choices)
            return (
                msg,
                sel_upd,
                dynamic_loras,
                gr.update(choices=save_choices),
                gr.update(choices=remove_choices),
            )

        for s in dynamic_loras.values():
            if sha and s.get("sha256") and s["sha256"] == sha:
                return (
                    f"⚠️ Already added this session as '{s['title']}' (same sha256).",
                    gr.update(),
                    dynamic_loras,
                    gr.update(choices=session_custom_lora_titles(dynamic_loras)),
                    gr.update(choices=session_custom_lora_titles(dynamic_loras) + removable_catalog_titles()),
                )
            if s.get("repo") == resolved_repo and s.get("weights") == actual_weight:
                return (
                    f"⚠️ Already added this session as '{s['title']}'.",
                    gr.update(),
                    dynamic_loras,
                    gr.update(choices=session_custom_lora_titles(dynamic_loras)),
                    gr.update(choices=session_custom_lora_titles(dynamic_loras) + removable_catalog_titles()),
                )

        base_name = _sanitize_name(requested_name or auto_name, fallback="custom")
        static_names = {
            s["adapter_name"] for s in EXTERNAL_LORA_STYLES if s.get("adapter_name")
        }
        final_adapter_name = f"{base_name}_{uuid.uuid4().hex[:6]}"
        while final_adapter_name in static_names or final_adapter_name in LOADED_ADAPTERS:
            final_adapter_name = f"{base_name}_{uuid.uuid4().hex[:6]}"

        custom_style = {
            "image": _DEFAULT_LORA_IMAGE,
            "title": f"Custom: {base_name}",
            "adapter_name": final_adapter_name,
            "repo": resolved_repo,
            "weights": actual_weight,
            "default_prompt": None,
            "default_weight": 1.0,
            "admin_approved": False,
            "active": True,
            "compatible_with_playground": True,
            "notes": None,
            "known_triggers": [],
            "sha256": sha,
            "session_only": True,
        }
        dynamic_loras[final_adapter_name] = custom_style
        new_choices = [s["title"] for s in get_selectable_styles(dynamic_loras)]
        save_choices = session_custom_lora_titles(dynamic_loras)
        remove_choices = save_choices + removable_catalog_titles()
        hash_note = f", sha256={sha[:12]}…" if sha else ""
        return (
            f"βœ… Added (session only): {base_name} from {source_label} "
            f"({actual_weight}{hash_note}). Try it, then save or remove below.",
            gr.update(choices=new_choices),
            dynamic_loras,
            gr.update(choices=save_choices, value=custom_style["title"]),
            gr.update(choices=remove_choices, value=custom_style["title"]),
        )
    except Exception as e:
        return _empty_add_result(f"❌ Failed: {e}", dynamic_loras)


def remove_lora(selected_title, dynamic_loras_state, currently_selected):
    dynamic_loras = dict(dynamic_loras_state or {})
    if not selected_title:
        choices = [s["title"] for s in get_selectable_styles(dynamic_loras)]
        remove_choices = session_custom_lora_titles(dynamic_loras) + removable_catalog_titles()
        return (
            "Pick a LoRA to remove.",
            gr.update(choices=choices, value=currently_selected or []),
            gr.update(choices=session_custom_lora_titles(dynamic_loras)),
            gr.update(choices=remove_choices),
            dynamic_loras,
        )

    session_key = None
    for k, v in dynamic_loras.items():
        if v.get("title") == selected_title:
            session_key = k
            break
    if session_key is not None:
        dynamic_loras.pop(session_key, None)
        new_sel = [t for t in (currently_selected or []) if t != selected_title]
        choices = [s["title"] for s in get_selectable_styles(dynamic_loras)]
        save_choices = session_custom_lora_titles(dynamic_loras)
        remove_choices = save_choices + removable_catalog_titles()
        return (
            f"πŸ—‘οΈ Removed session LoRA '{selected_title}'.",
            gr.update(choices=choices, value=new_sel),
            gr.update(choices=save_choices, value=None),
            gr.update(choices=remove_choices, value=None),
            dynamic_loras,
        )

    with _CATALOG_LOCK:
        entries = _read_catalog_file()
        global EXTERNAL_LORA_STYLES
        EXTERNAL_LORA_STYLES = list(entries)
        idx = next((i for i, e in enumerate(entries) if e["title"] == selected_title), None)
        if idx is None:
            choices = [s["title"] for s in get_selectable_styles(dynamic_loras)]
            remove_choices = session_custom_lora_titles(dynamic_loras) + removable_catalog_titles()
            return (
                f"❌ '{selected_title}' not found in session or catalog.",
                gr.update(choices=choices),
                gr.update(choices=session_custom_lora_titles(dynamic_loras)),
                gr.update(choices=remove_choices),
                dynamic_loras,
            )
        if entries[idx].get("admin_approved", False):
            choices = [s["title"] for s in get_selectable_styles(dynamic_loras)]
            remove_choices = session_custom_lora_titles(dynamic_loras) + removable_catalog_titles()
            return (
                f"❌ '{selected_title}' is admin-approved and cannot be removed from the UI. "
                f"Set active=false in the JSON to archive it.",
                gr.update(choices=choices),
                gr.update(choices=session_custom_lora_titles(dynamic_loras)),
                gr.update(choices=remove_choices),
                dynamic_loras,
            )
        entries.pop(idx)
        try:
            path = _write_catalog_file(entries)
        except Exception as e:
            return (
                f"❌ Failed to write catalog: {e}",
                gr.update(),
                gr.update(),
                gr.update(),
                dynamic_loras,
            )
        EXTERNAL_LORA_STYLES = list(entries)
        LORA_STYLES[:] = [
            e for e in EXTERNAL_LORA_STYLES
            if e.get("active", True) and e.get("compatible_with_playground", True)
        ]

    new_sel = [t for t in (currently_selected or []) if t != selected_title]
    choices = [s["title"] for s in get_selectable_styles(dynamic_loras)]
    save_choices = session_custom_lora_titles(dynamic_loras)
    remove_choices = save_choices + removable_catalog_titles()
    return (
        f"πŸ—‘οΈ Removed catalog LoRA '{selected_title}' β†’ {path}",
        gr.update(choices=choices, value=new_sel),
        gr.update(choices=save_choices, value=None),
        gr.update(choices=remove_choices, value=None),
        dynamic_loras,
    )


def _filter_selector_value(currently_selected, choices, *, rename_from=None, rename_to=None):
    """Keep CheckboxGroup value valid after choices change.

    Optionally rename one selected title (session "Custom: x" β†’ catalog "x").
    """
    choice_set = set(choices or [])
    out = []
    seen = set()
    for t in currently_selected or []:
        mapped = rename_to if (rename_from is not None and t == rename_from) else t
        if mapped in choice_set and mapped not in seen:
            out.append(mapped)
            seen.add(mapped)
    return out


def save_session_lora_to_catalog(
    selected_title,
    catalog_title,
    default_weight,
    default_prompt,
    dynamic_loras_state,
    known_triggers=None,
    notes=None,
    currently_selected=None,
):
    dynamic_loras = dict(dynamic_loras_state or {})
    save_choices = session_custom_lora_titles(dynamic_loras)
    remove_choices = save_choices + removable_catalog_titles()
    selector_choices = [s["title"] for s in get_selectable_styles(dynamic_loras)]
    cur_sel = list(currently_selected or [])

    def _fail(msg):
        # Always re-assert a valid value so a stale Custom: title can't brick the UI.
        safe_sel = _filter_selector_value(cur_sel, selector_choices)
        return (
            msg,
            gr.update(choices=selector_choices, value=safe_sel),
            gr.update(choices=save_choices),
            gr.update(choices=remove_choices),
            dynamic_loras,
        )

    if not selected_title:
        return _fail("Pick a session LoRA to save (add one above first).")

    source = None
    source_key = None
    for k, style in dynamic_loras.items():
        if style.get("title") == selected_title:
            source = style
            source_key = k
            break
    if source is None:
        return _fail(f"❌ '{selected_title}' is not a session custom LoRA.")

    title = (catalog_title or "").strip() or selected_title.removeprefix("Custom: ").strip()
    if not title:
        title = source.get("adapter_name") or "Custom LoRA"

    try:
        weight = float(default_weight) if default_weight is not None else float(
            source.get("default_weight", 1.0)
        )
    except (TypeError, ValueError):
        weight = 1.0

    prompt = (default_prompt or "").strip() or source.get("default_prompt") or None
    triggers = _parse_trigger_list(known_triggers)
    if not triggers:
        triggers = _parse_trigger_list(source.get("known_triggers"))
    note_text = (notes or "").strip() or source.get("notes") or None
    adapter_base = _sanitize_name(
        title, fallback=_sanitize_name(source.get("adapter_name", "custom"))
    )
    sha = source.get("sha256") or _compute_entry_sha256(source)

    with _CATALOG_LOCK:
        entries = _read_catalog_file()
        global EXTERNAL_LORA_STYLES
        EXTERNAL_LORA_STYLES = list(entries)

        dup = _find_duplicate(
            entries, sha256=sha, title=title,
            repo=source["repo"], weights=source["weights"],
        )
        if dup and dup["title"] != title:
            return _fail(
                f"❌ Duplicate of existing catalog entry '{dup['title']}'"
                + (" (sha256 match)" if sha and dup.get("sha256") == sha else "")
            )
        if dup and dup.get("admin_approved", False) and dup["title"] == title:
            return _fail(
                f"❌ '{title}' is admin-approved β€” edit the JSON directly to change it."
            )

        existing_idx = next((i for i, e in enumerate(entries) if e["title"] == title), None)
        if existing_idx is None:
            adapter_name = _unique_adapter_name(adapter_base)
            prev_approved = False
            prev_active = True
        else:
            adapter_name = entries[existing_idx].get("adapter_name") or _unique_adapter_name(adapter_base)
            prev_approved = bool(entries[existing_idx].get("admin_approved", False))
            prev_active = bool(entries[existing_idx].get("active", True))

        prev_compatible = True
        if existing_idx is not None:
            prev_compatible = bool(
                entries[existing_idx].get("compatible_with_playground", True)
            )

        entry = {
            "image": source.get("image") or _DEFAULT_LORA_IMAGE,
            "title": title,
            "adapter_name": adapter_name,
            "repo": source["repo"],
            "weights": source["weights"],
            "default_prompt": prompt,
            "default_weight": weight,
            "admin_approved": prev_approved,
            "active": prev_active,
            "compatible_with_playground": prev_compatible,
            "notes": note_text,
            "known_triggers": triggers,
            "sha256": sha,
        }

        if existing_idx is None:
            entries.append(entry)
            action = "Saved"
        else:
            entries[existing_idx] = entry
            action = "Updated"

        try:
            path = _write_catalog_file(entries)
        except Exception as e:
            return _fail(f"❌ Failed to write catalog: {e}")

        EXTERNAL_LORA_STYLES = list(entries)
        LORA_STYLES[:] = [
            e for e in EXTERNAL_LORA_STYLES
            if e.get("active", True) and e.get("compatible_with_playground", True)
        ]

    if source_key is not None:
        dynamic_loras.pop(source_key, None)

    selector_choices = [s["title"] for s in get_selectable_styles(dynamic_loras)]
    save_choices = session_custom_lora_titles(dynamic_loras)
    remove_choices = save_choices + removable_catalog_titles()
    # Session title disappears; remap selection to the new catalog title so the
    # CheckboxGroup never keeps "Custom: …" against choices that only have "…".
    new_sel = _filter_selector_value(
        cur_sel, selector_choices,
        rename_from=selected_title, rename_to=title,
    )
    hash_note = f", sha256={sha[:12]}…" if sha else ""
    trig_note = f", {len(triggers)} trigger(s)" if triggers else ""
    return (
        f"βœ… {action} '{title}' β†’ {path} (weight={weight}{hash_note}{trig_note})",
        gr.update(choices=selector_choices, value=new_sel),
        gr.update(choices=save_choices, value=None),
        gr.update(choices=remove_choices, value=None),
        dynamic_loras,
    )


def fill_catalog_save_form(selected_title, dynamic_loras_state):
    empty = gr.update(), gr.update(), gr.update(), gr.update(), gr.update()
    if not selected_title:
        return empty
    style = None
    for s in (dynamic_loras_state or {}).values():
        if s.get("title") == selected_title:
            style = s
            break
    if not style:
        return empty
    suggested = selected_title.removeprefix("Custom: ").strip() or selected_title
    triggers = _parse_trigger_list(style.get("known_triggers"))
    return (
        gr.update(value=suggested),
        gr.update(value=float(style.get("default_weight", 1.0))),
        gr.update(value=style.get("default_prompt") or ""),
        gr.update(value="\n".join(triggers)),
        gr.update(value=style.get("notes") or ""),
    )