File size: 106,393 Bytes
20ec431
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
"""Anima ZeroGPU Space.

重建方案:**官方转换仓库的 diffusers 组件 + 我们自己的 DiT / LLM adapter 权重**。

组件(全部来自 CalamitousFelicitousness/Anima-sdnext-diffusers 的 config / VAE / text encoder):
    tokenizer(Qwen) + text_encoder(Qwen3Model) + t5_tokenizer(T5TokenizerFast)
    + scheduler(FlowMatchEulerDiscreteScheduler) + vae(AutoencoderKLWan)
    + transformer/config.json(CosmosTransformer3DModel) + llm_adapter/config.json(AnimaLLMAdapter)

权重(我们自己的 ComfyUI / 原版 Cosmos 命名 ckpt,位于 Storage Bucket 只读挂载点 /data/models):
    net.*            -> CosmosTransformer3DModel(按映射表改名,见 anima_key_to_diffusers)
    net.llm_adapter.* -> AnimaLLMAdapter(仅去掉 net.llm_adapter. 前缀)
    net.pos_embedder.* / first_stage_model.* -> 丢弃

铁律:任何 import 期错误都不 raise。全局依赖栈失败只写 FATAL_ERROR,单个基座失败只写
BASE_ERRORS[<base_key>],两者都打 traceback,容器必须能起来。一个基座坏了只影响它自己。
"""

import gc
import hashlib
import json
import logging
import math
import os
import re
import threading
import time
import traceback
from collections import OrderedDict
from typing import Dict, List, Optional, Tuple

import torch

# -----------------------------------------------------------------------------
# 0. 初始化状态 / 日志(本文件所有 import 期失败都只记录,不 raise)
# -----------------------------------------------------------------------------
FATAL_ERROR = ""                     # 只有全局依赖栈不可用才写这里(写 = 全站拒绝请求)
BASE_ERRORS: Dict[str, str] = {}     # 每个基座各自的构建 / 注入错误(只影响它自己)

_LOG = logging.getLogger("anima-space")
if not _LOG.handlers:
    _handler = logging.StreamHandler()
    _handler.setFormatter(logging.Formatter("%(asctime)s | %(levelname)s | %(message)s"))
    _LOG.addHandler(_handler)
    _LOG.setLevel(logging.INFO)
    _LOG.propagate = False


def log(message: str) -> None:
    """同时写 stdout(HF / ZeroGPU 日志)和 logging。"""
    try:
        print(message, flush=True)
    except Exception:
        pass
    try:
        _LOG.info(message)
    except Exception:
        pass


def _record_fatal_error(stage: str, exc: BaseException) -> str:
    """记录**全局依赖栈**级错误:写入 FATAL_ERROR,打完整 traceback,绝不 raise。

    只有“整个站点都用不了”的情况才走这里(核心依赖 import 失败、官方组件下载失败、
    PIPE 外壳构建失败)。单个基座的失败一律走 _record_base_error。
    """
    global FATAL_ERROR
    text = f"[{stage}] {type(exc).__name__}: {exc}"
    FATAL_ERROR = f"{FATAL_ERROR}\n{text}".strip()
    log(f"[Init Fatal] {text}")
    _log_traceback()
    return text


def _record_base_error(key: str, stage: str, exc: BaseException) -> str:
    """记录**单个基座**的错误:只写 BASE_ERRORS[key],绝不影响其它基座,绝不 raise。"""
    text = f"[{stage}] {type(exc).__name__}: {exc}"
    prev = BASE_ERRORS.get(key, "")
    BASE_ERRORS[key] = f"{prev}\n{text}".strip()
    log(f"[Init Base Error] {key}: {text}")
    _log_traceback()
    return text


def _log_traceback() -> None:
    """把当前异常上下文的 traceback 打进日志;没有异常上下文(NoneType: None)时静默。"""
    try:
        tb = traceback.format_exc()
    except Exception:
        return
    if not tb or tb.strip().endswith("NoneType: None"):
        return
    log(tb)


# -----------------------------------------------------------------------------
# 1. 依赖导入(全部非致命)
# -----------------------------------------------------------------------------
try:
    import requests
except Exception as _exc:  # pragma: no cover
    requests = None
    _record_fatal_error("import requests", _exc)

try:
    from safetensors import safe_open
except Exception as _exc:  # pragma: no cover
    safe_open = None
    _record_fatal_error("import safetensors", _exc)

try:
    from huggingface_hub import HfApi, hf_hub_download, snapshot_download
except Exception as _exc:  # pragma: no cover
    HfApi = hf_hub_download = snapshot_download = None
    _record_fatal_error("import huggingface_hub", _exc)

try:
    import gradio as gr
except Exception as _exc:  # pragma: no cover
    gr = None
    _record_fatal_error("import gradio", _exc)

try:
    import spaces
except Exception as _exc:  # pragma: no cover
    # 本地 / 非 ZeroGPU 环境:用一个透明装饰器顶替
    class _SpacesShim:
        @staticmethod
        def GPU(*args, **kwargs):
            def _decorator(fn):
                return fn

            return _decorator

    spaces = _SpacesShim()
    log(f"[Init] spaces 不可用,使用 passthrough 装饰器: {_exc}")

try:
    from PIL import Image
except Exception as _exc:  # pragma: no cover
    Image = None
    _record_fatal_error("import PIL", _exc)

try:
    import torchvision.transforms.functional as TF
except Exception as _exc:  # pragma: no cover
    TF = None
    log(f"[Init] torchvision 不可用(Remacri 会被跳过): {_exc}")

try:
    from diffusers import AutoencoderKLWan, CosmosTransformer3DModel, FlowMatchEulerDiscreteScheduler
    from transformers import Qwen3Model, AutoTokenizer, T5TokenizerFast
    from pipeline import AnimaTextToImagePipeline
    from modeling_llm_adapter import AnimaLLMAdapter

    _STACK_OK = True
except Exception as _exc:  # pragma: no cover
    AutoencoderKLWan = CosmosTransformer3DModel = FlowMatchEulerDiscreteScheduler = None
    Qwen3Model = AutoTokenizer = T5TokenizerFast = None
    AnimaTextToImagePipeline = AnimaLLMAdapter = None
    _STACK_OK = False
    _record_fatal_error("import diffusers/transformers/pipeline", _exc)

# -----------------------------------------------------------------------------
# 2. 基础配置
# -----------------------------------------------------------------------------
if torch.cuda.is_available():
    try:
        torch.backends.cuda.matmul.allow_tf32 = True
        torch.backends.cudnn.allow_tf32 = True
    except Exception:
        pass

DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
# 权重存 bf16(CPU 上也用 bf16 存,省一半内存;只有在 GPU 上才会真正做前向)
DTYPE = torch.bfloat16
# ZeroGPU 下 import 期禁止碰 CUDA 显存
ZERO_GPU = bool(os.environ.get("SPACES_ZERO_GPU"))


def _auth_secret() -> str:
    """只从环境变量读;缺失时打警告并返回空串(等价于校验恒失败)。没有硬编码明文。"""
    secret = os.environ.get("SPACE_AUTH_SECRET")
    if not secret:
        log(
            "[Init Warning] 环境变量 SPACE_AUTH_SECRET 未设置:空 secret 绝不放行,"
            "所有生成请求一律拒绝(UI 会显示明确提示,不再出现 空串==空串 通过校验)。"
            "请在 Space Settings -> Variables and secrets 里配置。"
        )
        return ""
    return str(secret)


SPACE_AUTH_SECRET = _auth_secret()

HF_TOKEN = os.environ.get("HF_TOKEN") or os.environ.get("HUGGING_FACE_HUB_TOKEN")
if HF_TOKEN:
    os.environ["HF_TOKEN"] = HF_TOKEN
    os.environ["HUGGING_FACE_HUB_TOKEN"] = HF_TOKEN

# 官方转换仓库(只取 config / vae / text encoder / tokenizer / scheduler,绝不取它的 transformer 权重)
REPO_ID = "CalamitousFelicitousness/Anima-sdnext-diffusers"
BUCKET_RESOLVE_BASE = "https://huggingface.co/buckets/Haruka041/sdxl/resolve/models"
MODELS_MOUNT = "/data/models"

CACHE_ROOT = "/cache" if os.path.isdir("/cache") else os.path.join(os.getcwd(), "cache")
CACHE_DIR = os.path.join(CACHE_ROOT, "checkpoints")
LORA_CACHE_DIR = os.path.join(CACHE_ROOT, "loras")
DIFFUSERS_CACHE_DIR = os.path.join(CACHE_ROOT, "anima_diffusers")
for _d in (CACHE_DIR, LORA_CACHE_DIR, DIFFUSERS_CACHE_DIR):
    try:
        os.makedirs(_d, exist_ok=True)
    except Exception as _exc:  # pragma: no cover
        log(f"[Init Warning] 无法创建缓存目录 {_d}: {_exc}")

MODELS_CONFIG = {
    "ggmix_anima": {
        "label": "MALE-GGmix Anima v1.1",
        "filename": "anima1.1test_-000009.safetensors",
    },
    "homo_anima": {
        "label": "HomoSimile Anima v2.0",
        "filename": "homosimileAnima_v20.safetensors",
    },
}

# 采样器:第一项是默认值,也是任何未知值 / 任何异常的兜底
SAMPLERS = ["Flow Euler", "ER_SDE", "Euler", "Euler a", "DPM++ 2M SDE", "Flow Heun"]




def _runtime_device() -> torch.device:
    """在 @spaces.GPU 内部重新探测设备(import 期可能还没有 GPU)。"""
    try:
        if torch.cuda.is_available():
            return torch.device("cuda")
    except Exception:
        pass
    return torch.device("cpu")


def _num_params(module) -> int:
    try:
        return sum(p.numel() for p in module.parameters())
    except Exception:
        return 0

# -----------------------------------------------------------------------------
# 3. ckpt key -> diffusers key 映射表
#    (严格照取证报告 §2.6 的表;每条都逐 key / 逐 shape 校验过)
# -----------------------------------------------------------------------------
_ADAPTER_PREFIX = "net.llm_adapter."
_DROP_PREFIXES = ("net.pos_embedder.", "first_stage_model.")

# 顶层(非 block)7 条
_DIT_TOP_MAP = {
    "net.x_embedder.proj.1.weight": "patch_embed.proj.weight",
    "net.t_embedder.1.linear_1.weight": "time_embed.t_embedder.linear_1.weight",
    "net.t_embedder.1.linear_2.weight": "time_embed.t_embedder.linear_2.weight",
    "net.t_embedding_norm.weight": "time_embed.norm.weight",
    "net.final_layer.adaln_modulation.1.weight": "norm_out.linear_1.weight",
    "net.final_layer.adaln_modulation.2.weight": "norm_out.linear_2.weight",
    "net.final_layer.linear.weight": "proj_out.weight",
}

# 每个 block 的 20 条(28 blocks x 20 = 560)
_DIT_BLOCK_TAIL_MAP = {
    # self_attn -> attn1
    "self_attn.q_proj": "attn1.to_q",
    "self_attn.k_proj": "attn1.to_k",
    "self_attn.v_proj": "attn1.to_v",
    "self_attn.output_proj": "attn1.to_out.0",
    "self_attn.q_norm": "attn1.norm_q",
    "self_attn.k_norm": "attn1.norm_k",
    # cross_attn -> attn2(to_q 是 [2048,2048],to_k/to_v 是 [2048,1024])
    "cross_attn.q_proj": "attn2.to_q",
    "cross_attn.k_proj": "attn2.to_k",
    "cross_attn.v_proj": "attn2.to_v",
    "cross_attn.output_proj": "attn2.to_out.0",
    "cross_attn.q_norm": "attn2.norm_q",
    "cross_attn.k_norm": "attn2.norm_k",
    # mlp -> ff.net
    "mlp.layer1": "ff.net.0.proj",
    "mlp.layer2": "ff.net.2",
    # adaln_modulation_{self_attn,cross_attn,mlp}.{1,2} -> norm{1,2,3}.linear_{1,2}
    "adaln_modulation_self_attn.1": "norm1.linear_1",
    "adaln_modulation_self_attn.2": "norm1.linear_2",
    "adaln_modulation_cross_attn.1": "norm2.linear_1",
    "adaln_modulation_cross_attn.2": "norm2.linear_2",
    "adaln_modulation_mlp.1": "norm3.linear_1",
    "adaln_modulation_mlp.2": "norm3.linear_2",
}

_DIT_BLOCK_RE = re.compile(r"^net\.blocks\.(\d+)\.(.+)\.weight$")


def anima_key_to_diffusers(key: str) -> Optional[str]:
    """我们 ckpt 的一个 DiT key -> CosmosTransformer3DModel 的 key;无对应则 None。

    纯函数(只依赖 re / dict),方便离线校验映射表。
    """
    top = _DIT_TOP_MAP.get(key)
    if top is not None:
        return top
    m = _DIT_BLOCK_RE.match(key)
    if not m:
        return None
    idx, tail = m.group(1), m.group(2)
    dst = _DIT_BLOCK_TAIL_MAP.get(tail)
    if dst is None:
        return None
    return "transformer_blocks.%s.%s.weight" % (idx, dst)


def adapter_key_to_diffusers(key: str) -> Optional[str]:
    """net.llm_adapter.<rest> -> <rest>(官方 llm_adapter 权重就是这个命名)。"""
    if key.startswith(_ADAPTER_PREFIX):
        return key[len(_ADAPTER_PREFIX):]
    return None


# -----------------------------------------------------------------------------
# 4. 权重定位
# -----------------------------------------------------------------------------
def ensure_model_file(filename: str) -> str:
    """按「本地缓存 -> HF CDN HTTPS 下载 -> 只读挂载点」的顺序定位权重文件。

    顺序很关键:Storage Bucket 挂载点是网络文件系统,safetensors 在其上做 mmap 会退化成
    大量随机小读(实测读 4GB 超过十分钟读不完,直接导致启动超时退出)。所以:
        1) 本地磁盘缓存命中 -> 直接用(mmap 走本地盘,最快)
        2) HF CDN 直链流式下载到本地磁盘(实测 100~470 MB/s),.part 写完再原子改名
        3) 最后才回落挂载点(很慢,但至少能读)
    """
    import time as _time

    base = os.path.basename(filename)
    cached = os.path.join(CACHE_DIR, base)
    mounted = os.path.join(MODELS_MOUNT, base)

    # 1) 本地磁盘缓存命中:直接 mmap 本地文件
    if os.path.isfile(cached) and os.path.getsize(cached) > 100 * 1024 * 1024:
        log(f"[Model Fetch] {base} <- local cache ({os.path.getsize(cached) / 1e9:.2f} GB)")
        return cached

    # 2) HF CDN 直链流式下载到本地磁盘
    if requests is not None:
        headers = {"Authorization": f"Bearer {HF_TOKEN}"} if HF_TOKEN else {}
        url = f"{BUCKET_RESOLVE_BASE}/{base}?download=true"
        tmp_path = cached + ".part"
        started = _time.time()
        try:
            log(f"[Model Fetch] {base} <- HTTPS {url}")
            with requests.get(url, headers=headers, stream=True, timeout=1800) as resp:
                resp.raise_for_status()
                total = int(resp.headers.get("Content-Length") or 0)
                done = 0
                next_mark = 10
                with open(tmp_path, "wb") as out:
                    for chunk in resp.iter_content(chunk_size=16 * 1024 * 1024):
                        if not chunk:
                            continue
                        out.write(chunk)
                        done += len(chunk)
                        if total > 0:
                            pct = done * 100 // total
                            if pct >= next_mark:
                                speed = done / max(_time.time() - started, 1e-6) / 1e6
                                log(
                                    f"[Model Fetch] {base} {pct}% "
                                    f"({done / 1e9:.2f}/{total / 1e9:.2f} GB, {speed:.0f} MB/s)"
                                )
                                while next_mark <= pct:
                                    next_mark += 10
            os.replace(tmp_path, cached)
            size = os.path.getsize(cached)
            elapsed = max(_time.time() - started, 1e-6)
            log(
                f"[Model Fetch] {base} done {size / 1e9:.2f} GB "
                f"in {elapsed:.1f}s ({size / elapsed / 1e6:.0f} MB/s)"
            )
            return cached
        except Exception as exc:
            log(f"[Model Fetch] {base} HTTPS download failed: {exc!r}; falling back to mount")
            try:
                if os.path.isfile(tmp_path):
                    os.remove(tmp_path)
            except Exception:
                pass

    # 3) 最后兜底:只读挂载点
    if os.path.isfile(mounted):
        log(f"[Model Fetch] {base} <- MOUNT {mounted} (slow path)")
        return mounted

    raise RuntimeError(
        f"{base} unavailable: no local cache, HTTPS download failed, "
        f"and not found at {mounted}"
    )


# -----------------------------------------------------------------------------
# 5. 惰性注入:我们的 ckpt -> diffusers 模块
#    用 safe_open 逐个取张量,按 ~512MB 分块 load_state_dict(strict=False)
#    永远不 raise;missing / unmapped_source / no_such_param 全部只记录
# -----------------------------------------------------------------------------
_INJECT_CHUNK_BYTES = 512 * 1024 * 1024


def _tensor_nbytes(tensor) -> int:
    try:
        return int(tensor.numel()) * int(tensor.element_size())
    except Exception:
        return 0


def _flush_chunk(transformer, chunk: Dict[str, torch.Tensor]) -> None:
    if not chunk:
        return
    transformer.load_state_dict(chunk, strict=False)
    chunk.clear()


def inject_dit_weights(transformer, ckpt_path: str, label: str = "") -> Dict[str, object]:
    """把 ckpt 里 net.* 的 DiT 权重映射并注入 transformer。返回统计信息。

    stats 字段语义严格区分,不要混用:
        missing         transformer 有、ckpt 没映射到(真实缺失)
        unmapped_source ckpt 有、映射表 anima_key_to_diffusers 没覆盖的源 key
        no_such_param   映射到了目标名、但 transformer 里根本没有这个参数
        read_failed     单张量读取异常(跳过 + 计数,不写任何全局错误)
        ok              该基座是否可用(missing + read_failed 占比 > 5% 即不可用)
    """
    stats = {
        "label": label,
        "injected": 0,
        "chunks": 0,
        "dropped": 0,
        "missing": [],
        "unmapped_source": [],
        "no_such_param": [],
        "shape_mismatch": [],
        "read_failed": 0,
        "missing_ratio": 0.0,
        "error": "",
        "ok": True,
    }
    total_params = 0
    if safe_open is None:
        stats["error"] = "safetensors unavailable"
        stats["ok"] = False
        log(f"[Init] DiT inject({label}) 跳过:safetensors 不可用")
        return stats
    try:
        params = dict(transformer.named_parameters())
        total_params = len(params)
        with safe_open(ckpt_path, framework="pt", device="cpu") as handle:
            ckpt_keys = list(handle.keys())
            mapping = OrderedDict()  # diffusers_key -> ckpt_key
            for key in ckpt_keys:
                if key.startswith(_ADAPTER_PREFIX) or key.startswith(_DROP_PREFIXES):
                    stats["dropped"] += 1
                    continue
                target = anima_key_to_diffusers(key)
                if target is None:
                    stats["unmapped_source"].append(key)  # ckpt 有、映射表没覆盖
                    continue
                mapping[target] = key

            stats["missing"] = [k for k in params if k not in mapping]
            stats["no_such_param"] = [t for t in mapping if t not in params]  # 映射到了、模块没有

            chunk: Dict[str, torch.Tensor] = {}
            chunk_bytes = 0
            for target, source in mapping.items():
                param = params.get(target)
                if param is None:
                    continue
                try:
                    tensor = handle.get_tensor(source)
                except Exception as exc:
                    # 单张量读取异常:跳过 + 计数,绝不写全局 / 基座错误变量
                    stats["read_failed"] += 1
                    log(f"[Init] DiT inject({label}) 读取失败,跳过 {source}: {type(exc).__name__}: {exc}")
                    continue
                if tuple(tensor.shape) != tuple(param.shape):
                    stats["shape_mismatch"].append(
                        f"{source}{tuple(tensor.shape)} -> {target}{tuple(param.shape)}"
                    )
                    del tensor
                    continue
                chunk[target] = tensor.to(dtype=param.dtype)
                chunk_bytes += _tensor_nbytes(chunk[target])
                del tensor
                if chunk_bytes >= _INJECT_CHUNK_BYTES:
                    stats["injected"] += len(chunk)
                    stats["chunks"] += 1
                    _flush_chunk(transformer, chunk)
                    chunk_bytes = 0
            if chunk:
                stats["injected"] += len(chunk)
                stats["chunks"] += 1
                _flush_chunk(transformer, chunk)
    except Exception as exc:  # 绝不 raise;由 _build_base_model 决定是否标记该基座
        stats["error"] = f"[inject_dit_weights({label})] {type(exc).__name__}: {exc}"
        stats["ok"] = False
        log(f"[Init] DiT inject({label}) 失败: {stats['error']}")
        _log_traceback()
    finally:
        gc.collect()

    failed = len(stats["missing"]) + int(stats["read_failed"])
    if total_params > 0:
        stats["missing_ratio"] = round(failed / float(total_params), 4)
        # missing 比例 > 5% 才把该基座标记为不可用
        if not stats["error"] and failed > 0.05 * total_params:
            stats["ok"] = False
    elif not stats["error"]:
        stats["ok"] = False

    log(
        f"[Init] DiT inject({label}) injected={stats['injected']} chunks={stats['chunks']} "
        f"missing={len(stats['missing'])} no_such_param={len(stats['no_such_param'])} "
        f"unmapped_source={len(stats['unmapped_source'])} read_failed={stats['read_failed']} "
        f"dropped={stats['dropped']} shape_mismatch={len(stats['shape_mismatch'])} "
        f"missing_ratio={stats['missing_ratio']} ok={stats['ok']}"
    )
    if stats["missing"]:
        log(f"[Init] DiT inject({label}) missing[:10]={stats['missing'][:10]}")
    if stats["no_such_param"]:
        log(f"[Init] DiT inject({label}) no_such_param[:10]={stats['no_such_param'][:10]}")
    if stats["unmapped_source"]:
        log(f"[Init] DiT inject({label}) unmapped_source[:10]={stats['unmapped_source'][:10]}")
    if stats["shape_mismatch"]:
        log(f"[Init] DiT inject({label}) shape_mismatch[:10]={stats['shape_mismatch'][:10]}")
    if stats["error"]:
        log(f"[Init] DiT inject({label}) error={stats['error']}")
    return stats


def inject_adapter_weights(adapter, ckpt_path: str, label: str = "") -> Dict[str, object]:
    """把 ckpt 里 net.llm_adapter.*(118 个)注入 AnimaLLMAdapter。返回统计信息。

    stats 字段语义与 inject_dit_weights 严格一致(unmapped_source / no_such_param 分开)。
    """
    stats = {
        "label": label,
        "injected": 0,
        "missing": [],
        "unmapped_source": [],   # adapter 前缀以外的 key 属于 DiT,不算“未覆盖源”
        "no_such_param": [],     # 映射到了、但 adapter 里没有这个参数
        "shape_mismatch": [],
        "read_failed": 0,
        "missing_ratio": 0.0,
        "error": "",
        "ok": True,
    }
    total_params = 0
    if safe_open is None or adapter is None:
        stats["error"] = "safetensors/adapter unavailable"
        stats["ok"] = False
        log(f"[Init] Adapter inject({label}) 跳过:safetensors 或 adapter 不可用")
        return stats
    try:
        params = dict(adapter.named_parameters())
        total_params = len(params)
        state: Dict[str, torch.Tensor] = {}
        with safe_open(ckpt_path, framework="pt", device="cpu") as handle:
            for key in handle.keys():
                target = adapter_key_to_diffusers(key)
                if target is None:
                    continue
                param = params.get(target)
                if param is None:
                    stats["no_such_param"].append(key)   # 映射到了、模块没有
                    continue
                try:
                    tensor = handle.get_tensor(key)
                except Exception as exc:
                    # 单张量读取异常:跳过 + 计数,不写任何全局 / 基座错误变量
                    stats["read_failed"] += 1
                    log(f"[Init] Adapter inject({label}) 读取失败,跳过 {key}: {type(exc).__name__}: {exc}")
                    continue
                if tuple(tensor.shape) != tuple(param.shape):
                    stats["shape_mismatch"].append(
                        f"{key}{tuple(tensor.shape)} -> {target}{tuple(param.shape)}"
                    )
                    del tensor
                    continue
                state[target] = tensor.to(dtype=param.dtype)
                del tensor
        stats["missing"] = [k for k in params if k not in state]
        adapter.load_state_dict(state, strict=False)
        stats["injected"] = len(state)
        del state
    except Exception as exc:  # 绝不 raise;由 _build_base_model 决定是否标记该基座
        stats["error"] = f"[inject_adapter_weights({label})] {type(exc).__name__}: {exc}"
        stats["ok"] = False
        log(f"[Init] Adapter inject({label}) 失败: {stats['error']}")
        _log_traceback()
    finally:
        gc.collect()

    failed = len(stats["missing"]) + int(stats["read_failed"])
    if total_params > 0:
        stats["missing_ratio"] = round(failed / float(total_params), 4)
        if not stats["error"] and failed > 0.05 * total_params:
            stats["ok"] = False
    elif not stats["error"]:
        stats["ok"] = False

    log(
        f"[Init] Adapter inject({label}) injected={stats['injected']} "
        f"missing={len(stats['missing'])} no_such_param={len(stats['no_such_param'])} "
        f"unmapped_source={len(stats['unmapped_source'])} read_failed={stats['read_failed']} "
        f"shape_mismatch={len(stats['shape_mismatch'])} missing_ratio={stats['missing_ratio']} "
        f"ok={stats['ok']}"
    )
    if stats["missing"]:
        log(f"[Init] Adapter inject({label}) missing[:10]={stats['missing'][:10]}")
    if stats["no_such_param"]:
        log(f"[Init] Adapter inject({label}) no_such_param[:10]={stats['no_such_param'][:10]}")
    if stats["unmapped_source"]:
        log(f"[Init] Adapter inject({label}) unmapped_source[:10]={stats['unmapped_source'][:10]}")
    if stats["shape_mismatch"]:
        log(f"[Init] Adapter inject({label}) shape_mismatch[:10]={stats['shape_mismatch'][:10]}")
    if stats["error"]:
        log(f"[Init] Adapter inject({label}) error={stats['error']}")
    return stats


# -----------------------------------------------------------------------------
# 6. 官方组件加载 + 两个基座常驻
# -----------------------------------------------------------------------------
VAE = None
TEXT_ENCODER = None
TOKENIZER = None
T5_TOKENIZER = None
SCHEDULER = None
PIPE = None
TRANSFORMER_CONFIG: Dict[str, object] = {}
ADAPTER_CONFIG: Dict[str, object] = {}
BASE_SCHEDULER_CONFIG: Dict[str, object] = {}
CACHE_TRANSFORMERS: Dict[str, object] = {}
CACHE_ADAPTERS: Dict[str, object] = {}
CURRENT_ACTIVE_MODEL = "ggmix_anima"
PIPE_LOCK = threading.RLock()
MAX_CACHED_ADAPTERS = 50


def _download_components() -> str:
    """一次性 snapshot 官方仓库的必要文件(不含 transformer / llm_adapter 的权重)。"""
    allow_patterns = [
        "model_index.json",
        "vae/*",
        "text_encoder/*",
        "tokenizer/*",
        "t5_tokenizer/*",
        "scheduler/*",
        "transformer/config.json",
        "llm_adapter/config.json",
    ]
    log(f"[Init] snapshot_download({REPO_ID}) -> {DIFFUSERS_CACHE_DIR}")
    local_dir = snapshot_download(
        repo_id=REPO_ID,
        allow_patterns=allow_patterns,
        token=HF_TOKEN,
        cache_dir=DIFFUSERS_CACHE_DIR,
    )
    log(f"[Init] snapshot ready: {local_dir}")
    return local_dir


def _load_official_components(local_dir: str) -> None:
    """加载官方 diffusers 组件(模块级全局)。"""
    global VAE, TEXT_ENCODER, TOKENIZER, T5_TOKENIZER, SCHEDULER
    global TRANSFORMER_CONFIG, ADAPTER_CONFIG, BASE_SCHEDULER_CONFIG

    VAE = AutoencoderKLWan.from_pretrained(local_dir, subfolder="vae", torch_dtype=DTYPE)
    VAE = VAE.eval().requires_grad_(False)
    log(
        f"[Init] vae <- AutoencoderKLWan z_dim={getattr(VAE.config, 'z_dim', '?')} "
        f"dtype={VAE.dtype} params={_num_params(VAE):,}"
    )

    TEXT_ENCODER = Qwen3Model.from_pretrained(local_dir, subfolder="text_encoder", torch_dtype=DTYPE)
    TEXT_ENCODER = TEXT_ENCODER.eval().requires_grad_(False)
    log(
        f"[Init] text_encoder <- Qwen3Model hidden={getattr(TEXT_ENCODER.config, 'hidden_size', '?')} "
        f"dtype={TEXT_ENCODER.dtype} params={_num_params(TEXT_ENCODER):,}"
    )

    TOKENIZER = AutoTokenizer.from_pretrained(local_dir, subfolder="tokenizer")
    log(f"[Init] tokenizer <- {type(TOKENIZER).__name__} vocab={getattr(TOKENIZER, 'vocab_size', '?')}")

    T5_TOKENIZER = T5TokenizerFast.from_pretrained(local_dir, subfolder="t5_tokenizer")
    log(f"[Init] t5_tokenizer <- {type(T5_TOKENIZER).__name__} vocab={getattr(T5_TOKENIZER, 'vocab_size', '?')}")

    SCHEDULER = FlowMatchEulerDiscreteScheduler.from_pretrained(local_dir, subfolder="scheduler")
    BASE_SCHEDULER_CONFIG = dict(SCHEDULER.config)
    log(
        f"[Init] scheduler <- FlowMatchEulerDiscreteScheduler "
        f"num_train_timesteps={BASE_SCHEDULER_CONFIG.get('num_train_timesteps')} "
        f"shift={BASE_SCHEDULER_CONFIG.get('shift')}"
    )

    # 只读 config,不下载官方 transformer 权重
    TRANSFORMER_CONFIG = dict(CosmosTransformer3DModel.load_config(local_dir, subfolder="transformer"))
    log(
        f"[Init] transformer config <- in_channels={TRANSFORMER_CONFIG.get('in_channels')} "
        f"num_layers={TRANSFORMER_CONFIG.get('num_layers')} "
        f"heads={TRANSFORMER_CONFIG.get('num_attention_heads')}x{TRANSFORMER_CONFIG.get('attention_head_dim')} "
        f"text_embed_dim={TRANSFORMER_CONFIG.get('text_embed_dim')} "
        f"concat_padding_mask={TRANSFORMER_CONFIG.get('concat_padding_mask')}"
    )

    adapter_cfg_path = os.path.join(local_dir, "llm_adapter", "config.json")
    with open(adapter_cfg_path, "r", encoding="utf-8") as handle:
        raw_adapter_cfg = json.load(handle)
    ADAPTER_CONFIG = {k: v for k, v in raw_adapter_cfg.items() if not str(k).startswith("_")}
    log(f"[Init] llm_adapter config <- {ADAPTER_CONFIG}")


def _new_transformer():
    """按官方 config 构造空壳 CosmosTransformer3DModel(权重我们后面自己注入)。"""
    try:
        model = CosmosTransformer3DModel.from_config(TRANSFORMER_CONFIG, torch_dtype=DTYPE)
    except Exception:
        model = CosmosTransformer3DModel.from_config(TRANSFORMER_CONFIG)
    model = model.to(dtype=DTYPE)
    return model.eval().requires_grad_(False)


def _new_adapter():
    """按官方 config 构造 AnimaLLMAdapter(118 张量,权重我们后面自己注入)。"""
    return AnimaLLMAdapter(**ADAPTER_CONFIG).to(dtype=DTYPE).eval().requires_grad_(False)


def _build_base_model(key: str) -> None:
    """为一个基座构造 (transformer, llm_adapter) 并注入我们的权重。

    任何失败都只记录到 BASE_ERRORS[key] —— 一个基座坏了只影响它自己,绝不影响另一个。
    """
    entry = MODELS_CONFIG[key]
    try:
        ckpt_path = ensure_model_file(entry["filename"])
        log(f"[Init] base model {key} <- {ckpt_path} ({entry['label']})")

        transformer = _new_transformer()
        log(f"[Init] {key} transformer skeleton params={_num_params(transformer):,} dtype={transformer.dtype}")
        dit_stats = inject_dit_weights(transformer, ckpt_path, label=key)

        adapter = _new_adapter()
        log(f"[Init] {key} llm_adapter skeleton params={_num_params(adapter):,} dtype={getattr(adapter, 'dtype', DTYPE)}")
        adapter_stats = inject_adapter_weights(adapter, ckpt_path, label=key)

        log(
            f"[Init] base model {key} inject summary: dit(injected={dit_stats['injected']}, "
            f"missing={len(dit_stats['missing'])}, no_such_param={len(dit_stats['no_such_param'])}, "
            f"unmapped_source={len(dit_stats['unmapped_source'])}, read_failed={dit_stats['read_failed']}, "
            f"missing_ratio={dit_stats['missing_ratio']}) "
            f"adapter(injected={adapter_stats['injected']}, missing={len(adapter_stats['missing'])}, "
            f"no_such_param={len(adapter_stats['no_such_param'])}, "
            f"missing_ratio={adapter_stats['missing_ratio']})"
        )

        if not dit_stats["ok"] or not adapter_stats["ok"]:
            # 注入不完整(缺失比例 > 5% / 读取失败 / 直接异常)-> 只把这个基座标记为不可用
            reason = dit_stats["error"] or adapter_stats["error"] or (
                f"inject incomplete: dit_missing_ratio={dit_stats['missing_ratio']}, "
                f"adapter_missing_ratio={adapter_stats['missing_ratio']}"
            )
            CACHE_TRANSFORMERS.pop(key, None)
            CACHE_ADAPTERS.pop(key, None)
            _record_base_error(key, f"build_base_model({key})", RuntimeError(str(reason)))
            return

        CACHE_TRANSFORMERS[key] = transformer
        CACHE_ADAPTERS[key] = adapter
        log(f"[Init] base model {key} ready.")
    except Exception as exc:  # 单个基座失败不影响另一个
        CACHE_TRANSFORMERS.pop(key, None)
        CACHE_ADAPTERS.pop(key, None)
        _record_base_error(key, f"build_base_model({key})", exc)


def _bootstrap() -> None:
    """模块级初始化:任何一步失败都只记录(全局 FATAL_ERROR / 单基座 BASE_ERRORS),绝不 raise。"""
    global PIPE, SCHEDULER
    if not _STACK_OK:
        log("[Init] diffusers / transformers / pipeline 不可用,跳过初始化。")
        return
    try:
        local_dir = _download_components()
    except Exception as exc:
        _record_fatal_error("snapshot_download", exc)
        return
    try:
        _load_official_components(local_dir)
    except Exception as exc:
        _record_fatal_error("load_official_components", exc)
        return

    for key in MODELS_CONFIG:
        _build_base_model(key)

    # 用第一个可用的基座搭 pipeline 外壳(text_encoder / tokenizer / vae / scheduler 共用)
    try:
        first_key = next(iter(CACHE_TRANSFORMERS), None)
        if first_key is None:
            _record_fatal_error("build_pipeline", RuntimeError("no base model could be built"))
        else:
            scheduler = SCHEDULER if SCHEDULER is not None else FlowMatchEulerDiscreteScheduler.from_config(
                {**BASE_SCHEDULER_CONFIG, "shift": 3.0}
            )
            PIPE = AnimaTextToImagePipeline(
                text_encoder=TEXT_ENCODER,
                tokenizer=TOKENIZER,
                t5_tokenizer=T5_TOKENIZER,
                llm_adapter=CACHE_ADAPTERS[first_key],
                transformer=CACHE_TRANSFORMERS[first_key],
                vae=VAE,
                scheduler=scheduler,
            )
            log(
                f"[Init] AnimaTextToImagePipeline ready (transformer={first_key}, "
                f"vae_scale_factor_spatial={getattr(PIPE, 'vae_scale_factor_spatial', '?')}, "
                f"vae_scale_factor_temporal={getattr(PIPE, 'vae_scale_factor_temporal', '?')})"
            )
    except Exception as exc:
        _record_fatal_error("build_pipeline", exc)

    # 非 ZeroGPU(普通 GPU Space)时直接在 import 期搬到 GPU;ZeroGPU 下等 @spaces.GPU 调用
    if ZERO_GPU:
        log("[Init] SPACES_ZERO_GPU=1:权重留在内存,等 @spaces.GPU 调用时再上卡。")
        return
    if DEVICE != "cuda":
        log("[Init] 无 CUDA,权重留在内存。")
        return
    try:
        targets = [TEXT_ENCODER, VAE] + list(CACHE_TRANSFORMERS.values()) + list(CACHE_ADAPTERS.values())
        for module in targets:
            if module is not None:
                module.to(DEVICE)
        log("[Init] 所有组件已搬到 cuda。")
    except Exception as exc:  # 显存不足等:纯日志降级,绝不写 FATAL_ERROR / BASE_ERRORS
        log(f"[Init Warning] import 期上卡失败,将在每次调用时上卡: {type(exc).__name__}: {exc}")


_bootstrap()


# -----------------------------------------------------------------------------
# 7. 采样:denoise()
#    官方 pipeline.py:290-343 的语义逐行照抄:
#      - 初始 latent fp32 randn((B,16,1,H//8,W//8)),不做任何 scale
#      - scheduler.set_timesteps(steps),scheduler.sigmas[i] 直接当 timestep 喂 DiT
#      - x = x + (sigma_next - sigma) * v
#      - CFG 对 velocity 混合,正/负两次独立前向
#      - padding_mask = zeros(1,1,H,W)(像素分辨率)
# -----------------------------------------------------------------------------
_SAMPLER_ALIASES = {
    "flow euler": "Flow Euler",
    "flow_euler": "Flow Euler",
    "euler": "Euler",
    "euler a": "Euler a",
    "euler_a": "Euler a",
    "euler ancestral": "Euler a",
    "er sde": "ER_SDE",
    "er_sde": "ER_SDE",
    "ersde": "ER_SDE",
    "dpm++ 2m sde": "DPM++ 2M SDE",
    "dpm++_2m_sde": "DPM++ 2M SDE",
    "dpmpp 2m sde": "DPM++ 2M SDE",
    "dpmpp_2m_sde": "DPM++ 2M SDE",
    "flow heun": "Flow Heun",
    "flow_heun": "Flow Heun",
    "heun": "Flow Heun",
}


def normalize_sampler(name) -> str:
    """采样器名归一化;未知值一律回落 Flow Euler。"""
    raw = str(name or "").strip().lower()
    key = re.sub(r"\s+", " ", raw.replace("_", " "))
    if key in _SAMPLER_ALIASES:
        return _SAMPLER_ALIASES[key]
    return _SAMPLER_ALIASES.get(raw, "Flow Euler")


def _ancestral_step(sigma_from: float, sigma_to: float, eta: float = 1.0) -> Tuple[float, float]:
    """ComfyUI k_diffusion.sampling.get_ancestral_step 的公式。"""
    if eta <= 0.0 or sigma_to <= 0.0:
        return float(sigma_to), 0.0
    if sigma_from <= 0.0:
        return float(sigma_to), 0.0
    variance = (sigma_to ** 2) * max(sigma_from ** 2 - sigma_to ** 2, 0.0) / (sigma_from ** 2)
    sigma_up = min(float(sigma_to), float(eta) * math.sqrt(max(variance, 0.0)))
    sigma_down = math.sqrt(max(sigma_to ** 2 - sigma_up ** 2, 0.0))
    return sigma_down, sigma_up


@torch.no_grad()
def denoise(
    transformer,
    scheduler,
    prompt_embeds,
    negative_prompt_embeds=None,
    height: int = 1024,
    width: int = 1024,
    steps: int = 28,
    cfg_scale: float = 7.0,
    generator=None,
    sampler_name: str = "Flow Euler",
    latents=None,
    device=None,
    dtype=None,
    error_sink: Optional[List[str]] = None,
):
    """从纯噪声积分到 latent(5D: B,16,1,H/8,W/8,fp32)。

    返回 fp32 latents(尚未反归一化)。
    这里**不需要 adapter 参数**:文本侧条件由 PIPE.encode_prompt 经 self.llm_adapter 生效。
    error_sink:可选 list;采样核异常会以字符串形式追加进去,用于回传 UI 状态栏。
    """
    device = device if device is not None else _runtime_device()
    transformer_dtype = dtype if dtype is not None else transformer.dtype
    guidance_scale = float(cfg_scale if cfg_scale is not None else 1.0)
    do_cfg = guidance_scale > 1.0 and negative_prompt_embeds is not None
    num_steps = max(1, int(steps))
    sampler = normalize_sampler(sampler_name)

    scheduler.set_timesteps(num_steps, device=device)
    sigmas = scheduler.sigmas
    timesteps = scheduler.timesteps
    num_steps = len(timesteps)

    if latents is None:
        num_channels = int(getattr(transformer.config, "in_channels", 16))
        shape = (1, num_channels, 1, int(height) // 8, int(width) // 8)
        # 官方 prepare_latents 显式传 torch.float32,且不做任何 scale
        latents = torch.randn(shape, generator=generator, device=device, dtype=torch.float32)
    else:
        latents = latents.to(device=device, dtype=torch.float32)

    # 官方:padding_mask = latents.new_zeros(1, 1, height, width, dtype=transformer_dtype)
    padding_mask = torch.zeros(1, 1, int(height), int(width), device=device, dtype=transformer_dtype)

    log(
        f"[Sampler] {sampler} (requested={sampler_name!r}) steps={num_steps} "
        f"sigma0={float(sigmas[0]):.4f} last_sigma={float(sigmas[num_steps]):.6f} "
        f"latents={tuple(latents.shape)} cfg={guidance_scale if do_cfg else 1.0}"
    )

    def predict(x: torch.Tensor, sigma: torch.Tensor) -> torch.Tensor:
        """一次(条件 + 可选无条件)DiT 前向,返回 fp32 velocity。"""
        timestep = sigma.expand(x.shape[0]).to(transformer_dtype)
        model_input = x.to(transformer_dtype)
        velocity = transformer(
            hidden_states=model_input,
            timestep=timestep,
            encoder_hidden_states=prompt_embeds,
            padding_mask=padding_mask,
            return_dict=False,
        )[0].float()
        if do_cfg:
            velocity_uncond = transformer(
                hidden_states=model_input,
                timestep=timestep,
                encoder_hidden_states=negative_prompt_embeds,
                padding_mask=padding_mask,
                return_dict=False,
            )[0].float()
            velocity = velocity_uncond + guidance_scale * (velocity - velocity_uncond)
        return velocity

    def noise_like() -> torch.Tensor:
        return torch.randn(latents.shape, generator=generator, device=latents.device, dtype=torch.float32)

    v_prev = None

    for i in range(num_steps):
        sigma = sigmas[i]
        sigma_next = sigmas[i + 1]
        s = float(sigma)
        s_next = float(sigma_next)
        # 官方 scheduler.step 内部就是 `dt = sigma_next - sigma` 后 `sample + dt * model_output`;
        # 这里用同样的 0-dim fp32 张量减法,保证与官方逐位等价(不经 float 中转)。
        dt = sigma_next - sigma
        latents_next = None
        try:
            if sampler == "Flow Euler":
                # 官方 ODE:x_next = x + (sigma_next - sigma) * v
                v = predict(latents, sigma)
                latents_next = latents + dt * v
                v_prev = v
            elif sampler == "Euler":
                v = predict(latents, sigma)
                latents_next = latents + dt * v
                v_prev = v
            elif sampler == "Euler a":
                v = predict(latents, sigma)
                sigma_down, sigma_up = _ancestral_step(s, s_next, eta=1.0)
                latents_next = latents + (sigma_down - s) * v
                if sigma_up > 0.0:
                    latents_next = latents_next + noise_like() * sigma_up
                v_prev = v
            elif sampler == "ER_SDE":
                v = predict(latents, sigma)
                # 二阶(Adams-Bashforth 2)外推 + SDE 噪声注入
                v_hat = v if v_prev is None else (1.5 * v - 0.5 * v_prev)
                sigma_down, sigma_up = _ancestral_step(s, s_next, eta=1.0)
                latents_next = latents + (sigma_down - s) * v_hat
                if sigma_up > 0.0:
                    latents_next = latents_next + noise_like() * sigma_up
                v_prev = v
            elif sampler == "DPM++ 2M SDE":
                v = predict(latents, sigma)
                # 预测-校正(Heun)二阶速度 + SDE 噪声注入
                x_pred = latents + (s_next - s) * v
                v_corr = predict(x_pred, sigma_next) if s_next > 0.0 else v
                v_heun = 0.5 * (v + v_corr)
                sigma_down, sigma_up = _ancestral_step(s, s_next, eta=1.0)
                latents_next = latents + (sigma_down - s) * v_heun
                if sigma_up > 0.0:
                    latents_next = latents_next + noise_like() * sigma_up
                v_prev = v_heun
            elif sampler == "Flow Heun":
                v = predict(latents, sigma)
                x_pred = latents + (s_next - s) * v
                if s_next > 0.0:
                    v_corr = predict(x_pred, sigma_next)
                    latents_next = latents + 0.5 * (s_next - s) * (v + v_corr)
                else:
                    latents_next = x_pred
                v_prev = v
            else:  # 理论上到不了;兜底
                v = predict(latents, sigma)
                latents_next = latents + dt * v
                v_prev = v
        except Exception as e:
            # 采样核实现异常:完整 traceback 进日志 + 错误串进 error_sink(回传 UI 状态栏),
            # 本步与后续步骤回落官方 Flow Euler;若 Flow Euler 自己再失败,异常直接抛给 UI。
            log(f"[Sampler Error] {sampler} step {i} 失败,回落 Flow Euler: {type(e).__name__}: {e}")
            _log_traceback()
            if error_sink is not None:
                error_sink.append(f"{sampler} step {i}: {type(e).__name__}: {e}")
            sampler = "Flow Euler"
            v = predict(latents, sigma)
            latents_next = latents + dt * v
            v_prev = v

        latents = latents_next.to(torch.float32)

    return latents


@torch.no_grad()
def decode_latents(latents, vae, video_processor=None):
    """官方 pipeline.py:346-358:latents * latents_std + latents_mean -> vae.decode -> 第 0 帧 PIL。"""
    if vae is None:
        raise RuntimeError("VAE is not loaded")
    z_dim = int(getattr(vae.config, "z_dim", latents.shape[1]))
    mean = torch.tensor(vae.config.latents_mean, device=latents.device, dtype=torch.float32).view(1, z_dim, 1, 1, 1)
    std = torch.tensor(vae.config.latents_std, device=latents.device, dtype=torch.float32).view(1, z_dim, 1, 1, 1)
    # 官方写法是 latents_std = 1.0/std 然后 latents / latents_std,等价于 latents * std
    latents = latents * std + mean
    video = vae.decode(latents.to(vae.dtype), return_dict=False)[0]
    if video_processor is not None:
        pil_frames = video_processor.postprocess_video(video, output_type="pil")
        return pil_frames[0][0]
    # 手写兜底:(x*0.5+0.5).clamp(0,1) -> uint8
    frame = video[0].permute(1, 0, 2, 3)[0].float()
    frame = (frame * 0.5 + 0.5).clamp(0, 1).cpu().permute(1, 2, 0).numpy()
    return Image.fromarray((frame * 255).round().astype("uint8"))


def apply_sampler(name):
    """构造调度器(永远是官方 FlowMatchEulerDiscreteScheduler, shift=3.0)并返回描述串。

    具体采样核由 denoise() 按 sampler_name 选择:Flow Euler / Euler / Euler a /
    ER_SDE / DPM++ 2M SDE / Flow Heun。未知值回落 Flow Euler。
    """
    requested = normalize_sampler(name)
    scheduler = None
    try:
        scheduler = FlowMatchEulerDiscreteScheduler.from_config({**BASE_SCHEDULER_CONFIG, "shift": 3.0})
        cls_name = type(scheduler).__name__
    except Exception as exc:
        log(f"[Sampler Warning] 构建调度器失败,复用全局调度器: {exc}")
        scheduler = SCHEDULER
        cls_name = type(scheduler).__name__ if scheduler is not None else "FlowMatchEulerDiscreteScheduler"
    label = f"{requested} ({cls_name}, shift=3.0)"
    raw = str(name or "").strip()
    if raw and raw != requested:
        label += f" [requested={raw!r}]"
    return scheduler, label


# -----------------------------------------------------------------------------
# 8. Remacri 4x 超分
# -----------------------------------------------------------------------------
REMACRI_FILE = os.path.join(CACHE_ROOT, "remacri_original.safetensors")
upscaler_model = None
UPSCALE_LOCK = threading.Lock()


def _setup_remacri() -> None:
    global upscaler_model, REMACRI_FILE
    try:
        if not os.path.exists(REMACRI_FILE):
            mounted = os.path.join(MODELS_MOUNT, "remacri_original.safetensors")
            if os.path.isfile(mounted):
                REMACRI_FILE = mounted
            elif requests is not None:
                headers = {"Authorization": f"Bearer {HF_TOKEN}"} if HF_TOKEN else {}
                resp = requests.get(f"{BUCKET_RESOLVE_BASE}/remacri_original.safetensors?download=true",
                                    headers=headers, timeout=120)
                if resp.status_code == 200:
                    with open(REMACRI_FILE, "wb") as handle:
                        handle.write(resp.content)
        if os.path.exists(REMACRI_FILE):
            try:
                from spandrel import ModelLoader
            except ImportError as exc:
                # spandrel 是可选依赖:缺失时静默跳过 Remacri(enable_upscale 直接回原图)
                log(f"[Init] spandrel 不可用,Remacri 超分跳过: {exc}")
                return
            loader = ModelLoader()
            # import 期只在 CPU 上现形,绝不碰 CUDA 显存;
            # 设备对齐由 upscale_with_remacri 在 @spaces.GPU 内按输入张量就地完成。
            upscaler_model = loader.load_from_file(REMACRI_FILE).to(device="cpu", dtype=DTYPE).eval()
            log("[Init] Remacri 4x ready (cpu side, 调用时就地对齐设备).")
    except Exception as exc:
        log(f"[Init] Remacri setup skipped: {exc}")


def upscale_with_remacri(pil_img):
    """Remacri 超分;以输入张量所在设备为准就地搬模型,任何失败都返回原图(绝不 raise)。

    注意:spandrel 的 load_from_file 返回的是 ImageModelDescriptor 包装器,不是 nn.Module。
    真正的 nn.Module 在 .model 上;描述符本身是 callable,直接当函数用即可。
    """
    if upscaler_model is None or TF is None:
        return pil_img
    desc = upscaler_model
    try:
        device = _runtime_device()
        orig_w, orig_h = pil_img.size
        tensor = TF.to_tensor(pil_img).unsqueeze(0).to(device, dtype=DTYPE)

        # 取出真正的 nn.Module(兼容 spandrel 描述符 / 直接 nn.Module 两种形态)
        core = getattr(desc, "model", desc)
        try:
            model_device = next(core.parameters()).device
        except (AttributeError, StopIteration, TypeError):
            model_device = None
        if model_device is not None and model_device != tensor.device:
            core.to(tensor.device)
        # 描述符内部可能还缓存着别的张量,有 to() 就一并搬
        if core is not desc and hasattr(desc, "to"):
            try:
                desc = desc.to(tensor.device)
            except Exception:
                pass

        with torch.no_grad():
            out = desc(tensor)
        if isinstance(out, dict):
            out = out.get("img") or out.get("image") or next(iter(out.values()))
        out = out.squeeze(0).clamp(0, 1).to(torch.float32).cpu()
        up_img = TF.to_pil_image(out)
        return up_img.resize((orig_w * 2, orig_h * 2), Image.Resampling.LANCZOS)
    except Exception as exc:
        log(f"[Upscale Warning] Remacri 失败,返回未放大图: {type(exc).__name__}: {exc}")
        return pil_img
        out = out.squeeze(0).clamp(0, 1).to(torch.float32).cpu()
        up_img = TF.to_pil_image(out)
        return up_img.resize((orig_w * 2, orig_h * 2), Image.Resampling.LANCZOS)
    except Exception as exc:
        log(f"[Upscale Warning] Remacri 失败,返回未放大图: {type(exc).__name__}: {exc}")
        return pil_img


# -----------------------------------------------------------------------------
# 9. LoRA:解析(kohya lora_down/lora_up + LyCORIS LoKr)/ 缓存 / 低秩旁路注入
#    key 解析统一走 _split_lora_key + _resolve_lora_module(带/不带 lora_unet_ 前缀都支持),
#    LoKr 在加载阶段做 ΔW = W1 ⊗ W2 的截断 SVD 转成 lora_down/lora_up,
#    文件里的 <stem>.alpha 参与有效缩放 scale * (alpha / rank)。
#    一维加性增量 `<stem>_diff`(-> 目标模块 weight)/ `<stem>_diff_b`(-> 目标模块 bias)
#    不进低秩旁路,改由 _DeltaParam 在 forward 里临时叠加(andetail 实测 169 个,全是一维 BF16)。
# -----------------------------------------------------------------------------
# 说明:旧的 _LORA_BLOCK_RE / _LORA_GLOBAL_RE 已被统一解析器取代(见 _LORA_PAIR_KEY_RE)。
_LORA_TAIL = {
    "self_attn_q_proj": "attn1.to_q", "self_attn_k_proj": "attn1.to_k",
    "self_attn_v_proj": "attn1.to_v", "self_attn_output_proj": "attn1.to_out.0",
    "cross_attn_q_proj": "attn2.to_q", "cross_attn_k_proj": "attn2.to_k",
    "cross_attn_v_proj": "attn2.to_v", "cross_attn_output_proj": "attn2.to_out.0",
    "mlp_layer1": "ff.net.0.proj", "mlp_layer2": "ff.net.2",
    "adaln_modulation_self_attn_1": "norm1.linear_1", "adaln_modulation_self_attn_2": "norm1.linear_2",
    "adaln_modulation_cross_attn_1": "norm2.linear_1", "adaln_modulation_cross_attn_2": "norm2.linear_2",
    "adaln_modulation_mlp_1": "norm3.linear_1", "adaln_modulation_mlp_2": "norm3.linear_2",
    "time_embedder_1_linear_1": "time_embed.t_embedder.linear_1",
    "time_embedder_1_linear_2": "time_embed.t_embedder.linear_2",
    "final_layer_linear": "proj_out",
    "final_layer_adaln_modulation_1": "norm_out.linear_1",
    "final_layer_adaln_modulation_2": "norm_out.linear_2",
    # 顶层 x_embedder:LoRA stem 实测为 lora_unet_x_embedder_proj_1(ckpt 的 net.x_embedder.proj.1 在
    # diffusers 里是 patch_embed.proj,nn.Linear [2048, 68];实测 down [16,68] / up [2048,16] 直接匹配)
    "x_embedder_proj_1": "patch_embed.proj",
    # 一维加性增量(<stem>_norm_diff)的目标:attn 的 RMSNorm gamma + 时间嵌入 norm
    # (ckpt 侧 net.blocks.N.self_attn.q_norm.weight -> attn1.norm_q.weight,见 _DIT_BLOCK_TAIL_MAP)
    "self_attn_q_norm": "attn1.norm_q", "self_attn_k_norm": "attn1.norm_k",
    "cross_attn_q_norm": "attn2.norm_q", "cross_attn_k_norm": "attn2.norm_k",
    "t_embedding_norm": "time_embed.norm",
}

# --- llm_adapter 侧(AnimaLLMAdapter 是独立模块,注入目标是 CACHE_ADAPTERS 而不是 transformer)---------
# 解析结果前面加这个命名空间前缀,load_lora_matrix 据此把同一份 slots 分成 DiT / Adapter 两趟注入。
_ADAPTER_LORA_NS = "llm_adapter."
_ADAPTER_STEM_PREFIX = "llm_adapter"
_ADAPTER_BLOCK_STEM_RE = re.compile(r"^llm_adapter_blocks?[._](\d+)[._](.+)$")
# 实测(Haruka041/anturbo 与 Haruka041/andetail 的新文件)出现过的 adapter block tail -> 模块路径
_LORA_TAIL_ADAPTER = {
    "self_attn_q_proj": "self_attn.q_proj", "self_attn_k_proj": "self_attn.k_proj",
    "self_attn_v_proj": "self_attn.v_proj", "self_attn_o_proj": "self_attn.o_proj",
    "cross_attn_q_proj": "cross_attn.q_proj", "cross_attn_k_proj": "cross_attn.k_proj",
    "cross_attn_v_proj": "cross_attn.v_proj", "cross_attn_o_proj": "cross_attn.o_proj",
    "mlp_0": "mlp.0", "mlp_2": "mlp.2",
    # 一维加性增量:attn 内 RMSNorm gamma(q_norm/k_norm)+ block 级 norm gamma
    "self_attn_q_norm": "self_attn.q_norm", "self_attn_k_norm": "self_attn.k_norm",
    "cross_attn_q_norm": "cross_attn.q_norm", "cross_attn_k_norm": "cross_attn.k_norm",
    "norm_self_attn": "norm_self_attn", "norm_cross_attn": "norm_cross_attn", "norm_mlp": "norm_mlp",
}
# 非 block 的 adapter stem(实测:llm_adapter_embed -> nn.Embedding,llm_adapter_out_proj -> nn.Linear)
_LORA_GLOBAL_ADAPTER = {
    "llm_adapter_embed": "embed",
    "llm_adapter_out_proj": "out_proj",
    "llm_adapter_norm": "norm",          # 顶层 RMSNorm gamma(_diff 一维增量)
}

_LORA_DIRECTIVE_RE = re.compile(r"LORA:[A-Za-z0-9_\-./]+(?:\|[\d.\-]+)?(?:;[A-Za-z0-9_\-./]+(?:\|[\d.\-]+)?)*")


def canonical_lora_name(raw: str) -> str:
    val = str(raw or "").strip().replace("\\", "/").rstrip("/")
    if val.lower().endswith(".safetensors"):
        val = val.rsplit("/", 1)[0]
    return val.lower()


def ensure_lora_cached(raw: str) -> str:
    raw = str(raw or "").strip()
    if not raw:
        return ""
    if os.path.isfile(raw):
        return raw
    safe_key = re.sub(r"[^\w\-.]", "_", raw)
    local_dir = os.path.join(LORA_CACHE_DIR, safe_key)
    if os.path.isdir(local_dir):
        cands = [n for n in os.listdir(local_dir) if n.endswith(".safetensors")]
        # 优先原始文件:*_converted.safetensors 是 LoKr 转换缓存,别把它当原文件返回
        cands.sort(key=lambda n: (n.endswith("_converted.safetensors"), n))
        if cands:
            return os.path.join(local_dir, cands[0])
    parts = raw.split("/", 1)
    if len(parts) == 2 and HfApi is not None and hf_hub_download is not None:
        try:
            files = HfApi(token=HF_TOKEN).list_repo_files(repo_id=raw)
            st = [f for f in files if f.endswith(".safetensors")]
            if st:
                return hf_hub_download(repo_id=raw, filename=st[0], token=HF_TOKEN, local_dir=local_dir)
        except Exception as exc:
            log(f"[LoRA Fetch Error] {raw}: {exc}")
    return raw


class _LoRALinear(torch.nn.Module):
    def __init__(self, base):
        super().__init__()
        self.base = base
        self.adapters = []

    def add_adapter(self, down, up, scale):
        # dtype/设备安全:一律落到 CPU + DTYPE(bf16)存储,前向时再临时对齐到输入设备;
        # 这样 fp32/fp16 的 LoRA 文件都不会在 x @ down 时炸 dtype 不匹配。
        down = down.detach().to(device="cpu", dtype=DTYPE).contiguous()
        up = up.detach().to(device="cpu", dtype=DTYPE).contiguous()
        self.adapters.append([down, up, float(scale)])

    def forward(self, x, *args, **kwargs):
        if isinstance(self.base, torch.nn.Embedding):
            # Embedding 的 LoRA(实测 llm_adapter.embed:down [r, dim] / up [vocab, r])等价于把
            # ΔW = up @ down 加在整张 token 表上;输入 x 是 int64 token id,不能走 F.linear(x, ...)。
            # 设备/dtype 对齐一律按 base.weight 走(不能用 x:x 是整型),同样绝不回写 item。
            weight = self.base.weight
            for item in self.adapters:
                down, up, scale = item[0], item[1], item[2]
                if down.device != weight.device or down.dtype != weight.dtype:
                    down = down.to(device=weight.device, dtype=weight.dtype)
                if up.device != weight.device or up.dtype != weight.dtype:
                    up = up.to(device=weight.device, dtype=weight.dtype)
                weight = weight + torch.matmul(up, down) * scale
            return torch.nn.functional.embedding(x, weight)
        out = self.base(x, *args, **kwargs)
        for item in self.adapters:
            down, up, scale = item[0], item[1], item[2]
            # CPU 侧缓存永远是 CPU 张量:每次前向按输入张量设备/ dtype 临时对齐,
            # 但**绝不回写 item**(否则 down/up 会跨调用长期滞留在 GPU 上,
            # 既不是 buffer 也不是 param,任何 .to()/.cpu() 都管不到)。
            if down.device != x.device or down.dtype != x.dtype:
                down = down.to(device=x.device, dtype=x.dtype)
            if up.device != x.device or up.dtype != x.dtype:
                up = up.to(device=x.device, dtype=x.dtype)
            y = torch.nn.functional.linear(x, down)
            y = torch.nn.functional.linear(y, up)
            out = out + y * scale
        return out


class _DeltaParam(torch.nn.Module):
    """给目标模块的 weight(`*_diff`)或 bias(`*_diff_b`)加一维加性增量,按 scale 叠加。

    - 只持有 base 的引用(不复制权重);多个 LoRA 的增量用 [[delta, scale], ...] 列表累加;
    - forward 里临时把 base.<attr> 设成 orig + Σ(scale*delta),跑完在 finally 里**原样**还原:
      orig 为 None 的 bias(bias=False 的 nn.Linear)也从零构造,还原回 None;
    - 永不回写 base 的参数注册表以外的任何东西,可逆、可重复调用;
    - delta 一律 CPU + DTYPE 缓存,前向时按 orig(没有 orig 时按 base.weight)的 dtype/device 对齐。

    为什么直接改 base._parameters:nn.Module 不允许把普通 Tensor setattr 到参数名上
    (TypeError: cannot assign ... as parameter),而 base 的 forward 又是从 self.<attr> 读值,
    所以只有临时替换注册表里那一项(Parameter(requires_grad=False) 只是同一份显存的包装)。
    """

    def __init__(self, base, attr: str):
        super().__init__()
        self.base = base
        self.attr = str(attr)              # "weight" 或 "bias"
        self.deltas = []                   # [[delta_cpu, scale], ...]

    def add_delta(self, delta, scale) -> None:
        delta = delta.detach().to(device="cpu", dtype=DTYPE).contiguous()
        self.deltas.append([delta, float(scale)])

    def clear_deltas(self) -> None:
        self.deltas.clear()

    def _registry(self):
        """base 的参数注册表(nn.Module._parameters);不是 nn.Module 时返回 None。"""
        reg = getattr(self.base, "_parameters", None)
        return reg if isinstance(reg, dict) else None

    def _orig(self):
        reg = self._registry()
        if reg is not None:
            return reg.get(self.attr)
        return getattr(self.base, self.attr, None)

    def _reference(self, orig):
        """dtype/device 对齐用的参考张量:orig 本身,其次 base.weight(bias=None 的情形)。

        只用于对齐,**绝不**当成 orig 参与相加:bias 为 None 时必须从零开始构造。
        """
        if isinstance(orig, torch.Tensor):
            return orig
        weight = getattr(self.base, "weight", None)
        return weight if isinstance(weight, torch.Tensor) else None

    def forward(self, *args, **kwargs):
        if not self.deltas:
            return self.base(*args, **kwargs)
        orig = self._orig()
        align = self._reference(orig)
        total = None
        for item in self.deltas:
            delta, scale = item[0], item[1]
            dev = align.device if align is not None else delta.device
            dt = align.dtype if align is not None else delta.dtype
            if delta.device != dev or delta.dtype != dt:
                delta = delta.to(device=dev, dtype=dt)
            total = delta * scale if total is None else total + delta * scale
        if total is None:
            return self.base(*args, **kwargs)
        # orig 存在:orig + Σ(scale*delta);orig 为 None:完全由增量构造
        value = orig + total if isinstance(orig, torch.Tensor) else total
        reg = self._registry()
        try:
            if reg is not None:
                reg[self.attr] = torch.nn.Parameter(value.detach(), requires_grad=False)
            else:
                setattr(self.base, self.attr, value)
            return self.base(*args, **kwargs)
        finally:
            if reg is not None:
                reg[self.attr] = orig                     # orig 可能是 None(bias=False),照原样放回
            else:
                setattr(self.base, self.attr, orig)


def _core_module(node):
    """穿透 _LoRALinear / _DeltaParam 包装层,拿到真正持有 weight/bias 的模块。"""
    guard = 0
    while isinstance(node, (_LoRALinear, _DeltaParam)) and guard < 16:
        node = node.base
        guard += 1
    return node


_NO_PARAM_SLOT = object()                  # 「目标模块压根没有这个参数位」(如 RMSNorm 没有 bias)


def _param_of(module, attr: str):
    """模块参数注册表里的 <attr>(可能本来就是 None);模块没有这个参数位时返回 _NO_PARAM_SLOT。"""
    reg = getattr(module, "_parameters", None)
    if isinstance(reg, dict):
        return reg[attr] if attr in reg else _NO_PARAM_SLOT
    return getattr(module, attr, None) if hasattr(module, attr) else _NO_PARAM_SLOT


def _find_delta_wrapper(node, attr: str):
    """包装链上已挂的同 attr 的 _DeltaParam(多个 LoRA 叠加到同一目标);没有返回 None。"""
    guard = 0
    while isinstance(node, (_LoRALinear, _DeltaParam)) and guard < 16:
        if isinstance(node, _DeltaParam) and node.attr == attr:
            return node
        node = node.base
        guard += 1
    return None


def _stack_wrapper(holder, name: str, node, core, wrapper):
    """把 wrapper 插到 (holder, name) 这条包装链上 core 原来的位置,返回链的新顶层。

    - 之前没包过(node is core):直接把 (holder, name) 换成 wrapper;
    - 之前被 _LoRALinear / _DeltaParam 包过:把「base 指向 core」的那一层改成指向 wrapper,
      这样 _LoRALinear 的 LoRA 增量与 _DeltaParam 的参数增量都还在同一条调用链上(互不覆盖)。
    """
    if node is core:
        setattr(holder, name, wrapper)
        return wrapper
    probe, guard = node, 0
    while isinstance(probe, (_LoRALinear, _DeltaParam)) and probe.base is not core and guard < 16:
        probe = probe.base
        guard += 1
    if isinstance(probe, (_LoRALinear, _DeltaParam)) and probe.base is core:
        probe.base = wrapper                                  # ... -> wrapper -> core
        return node
    setattr(holder, name, wrapper)                            # 兜底(链上没有 core,构造上不会发生)
    return wrapper


BASE_ADAPTER_CACHES: Dict[str, OrderedDict] = {k: OrderedDict() for k in MODELS_CONFIG}


def _module_by_path(root, path: str):
    cur = root
    for part in path.split("."):
        if part.isdigit():
            cur = cur[int(part)]
        else:
            cur = getattr(cur, part, None)
        if cur is None:
            return None
    return cur


def _unpatch(transformer):
    """把 _anima_patched 里记的所有包装(_LoRALinear / _DeltaParam)还原成原始模块。

    两类包装都要清干净:_LoRALinear 的 adapters、_DeltaParam 的 deltas;然后把 backup
    (永远是**原始模块**,见 _apply_lora_slots 的 setdefault)挂回父模块。
    """
    patched = getattr(transformer, "_anima_patched", {}) or {}
    for mod_path, backup in list(patched.items()):
        parent, _, name = mod_path.rpartition(".")
        holder = _module_by_path(transformer, parent) if parent else transformer
        if holder is not None:
            cur = getattr(holder, name, None)
            if isinstance(cur, _LoRALinear):
                cur.adapters.clear()
            node, guard = cur, 0
            while isinstance(node, (_LoRALinear, _DeltaParam)) and guard < 16:   # 链上的增量也要清
                if isinstance(node, _DeltaParam):
                    node.clear_deltas()
                node = node.base
                guard += 1
            setattr(holder, name, backup)
    transformer._anima_patched = {}

# --- LoRA key 解析(kohya lora_down/lora_up + LyCORIS LoKr)与 LoKr -> LoRA 等价转换 ------
_LOKR_KEY_RE = re.compile(r"^(?P<stem>.+?)_lokr_(?P<kind>w1_a|w1_b|w2_a|w2_b|w1|w2)$")
_LOKR_DOT_KEY_RE = re.compile(r"^(?P<stem>.+?)\.(?P<kind>lokr_w1_a|lokr_w1_b|lokr_w2_a|lokr_w2_b|lokr_w1|lokr_w2)$")
_LORA_PAIR_KEY_RE = re.compile(r"^(?P<stem>.+?)\.(?P<kind>alpha|lora_down|lora_up)$")
# 不同训练器/导出脚本的前缀习惯,全部剥掉后再匹配 _LORA_TAIL(lora_unet_ 可省)
_LORA_STEM_PREFIXES = (
    "base_model.model.", "diffusion_model.", "lora_unet_", "lora_unet.",
    "lora_transformer_", "transformer.", "unet.", "model.",
)
_BLOCK_STEM_RE = re.compile(r"^(?:transformer_)?blocks?[._](\d+)[._](.+)$")
_LOKR_MAX_RANK = 128                   # 转换后 LoRA 的 rank 上限(= 保留的奇异值个数);ranks(ΔW)=ranks(W1)*ranks(W2)
_LOKR_MAX_LORA_ELEMS = 4_000_000       # 单个模块 down+up 的元素数预算,超了按比例降 rank(防止爆内存)
_LOKR_EXPLICIT_MAX_ELEMS = 2_000_000   # ΔW 元素数不超过它就显式构造 kron 再 SVD(小矩阵,便于核对)
_LOKR_HUGE_ELEMS = 4096 * 4096         # 超过它:只取前 _LOKR_MAX_RANK 个奇异值的低秩近似
LORA_CONVERT_STATS = {"files": 0, "lokr_files": 0, "converted": 0, "skipped": 0, "huge": 0, "seconds": 0.0}


def _split_lora_key(key: str) -> Tuple[str, str]:
    """safetensors 的 key -> (模块 stem, 件种类);认不出来的返回 (None, None) 由调用方计数跳过。

    kind ∈ lora_down / lora_up / alpha / lokr_w1 / lokr_w2 / lokr_w1_a / lokr_w1_b / lokr_w2_a / lokr_w2_b
           / delta_w(`<stem>_diff`,一维加性增量加到目标模块的 weight)
           / delta_b(`<stem>_diff_b`,一维加性增量加到目标模块的 bias)
    """
    k = str(key or "")
    if not k:
        return None, None
    if k.endswith(".alpha"):                                  # kohya: <stem>.alpha
        stem = k[: -len(".alpha")]
        return (stem[: -len("_lokr")] if stem.endswith("_lokr") else stem), "alpha"
    body = k[: -len(".weight")] if k.endswith(".weight") else k
    m = _LOKR_KEY_RE.match(body)                              # LyCORIS: <stem>_lokr_w1/_w2/_w2_a/_w2_b
    if m:
        return m.group("stem"), "lokr_" + m.group("kind")
    m = _LOKR_DOT_KEY_RE.match(body)                          # diffusers 风格: <stem>.lokr_w1 等
    if m:
        return m.group("stem"), m.group("kind")
    if body.endswith("_alpha"):                                # LyCORIS 的另一种 alpha 写法
        stem = body[: -len("_alpha")]
        return (stem[: -len("_lokr")] if stem.endswith("_lokr") else stem), "alpha"
    # 一维加性增量(实测 andetail 169 个,全是一维 BF16):_diff_b 必须比 _diff 先判,
    # 否则 "..._norm_diff_b" 会被当成 stem "..._norm_diff" 的 weight 增量。
    if body.endswith("_diff_b"):
        return body[: -len("_diff_b")], "delta_b"
    if body.endswith("_diff"):
        return body[: -len("_diff")], "delta_w"
    m = _LORA_PAIR_KEY_RE.match(body)                         # kohya: <stem>.lora_down / .lora_up
    if m:
        return m.group("stem"), m.group("kind")
    return None, None


def _resolve_lora_module(stem: str) -> Optional[str]:
    """模块 stem -> 注入目标路径(如 transformer_blocks.3.attn1.to_q)。

    DiT 目标返回 transformer 里的真实模块路径;llm_adapter 的 stem 返回带 _ADAPTER_LORA_NS
    前缀的路径(如 llm_adapter.blocks.0.cross_attn.k_proj),由 load_lora_matrix 分流到
    CACHE_ADAPTERS 那一趟。
    """
    s = str(stem or "")
    for _ in range(4):                                        # 前缀可能叠了 base_model.model. 之类
        low = s.lower()
        for p in _LORA_STEM_PREFIXES:
            if low.startswith(p):
                s = s[len(p):]
                break
        else:
            break
    if not s:
        return None
    # adapter 分支 1:llm_adapter_blocks.N.<tail>
    m_ad = _ADAPTER_BLOCK_STEM_RE.match(s)
    if m_ad:
        tail = _LORA_TAIL_ADAPTER.get(m_ad.group(2))
        return f"{_ADAPTER_LORA_NS}blocks.{m_ad.group(1)}.{tail}" if tail else None
    # adapter 分支 2:非 block 的 adapter stem(llm_adapter_embed / llm_adapter_out_proj)
    if s.lower().startswith(_ADAPTER_STEM_PREFIX):
        tail = _LORA_GLOBAL_ADAPTER.get(s)
        return f"{_ADAPTER_LORA_NS}{tail}" if tail else None
    m = _BLOCK_STEM_RE.match(s)
    if m:
        tail = _LORA_TAIL.get(m.group(2))
        return f"transformer_blocks.{m.group(1)}.{tail}" if tail else None
    return _LORA_TAIL.get(s)


def _collect_lora_slots(weights) -> Tuple[Dict[str, Dict[str, object]], int, int]:
    """把文件里的张量按目标模块归并成 {模块路径: {kind: tensor, "kind": 槽类型}}。

    返回 (slots, 命中数, 丢弃数)。每个 slot 额外带一个字符串字段 slot["kind"]:
        "pair"    原来的 lora_down/lora_up/alpha/lokr_*(走 _LoRALinear)
        "delta_w" 只有 `<stem>_diff`(一维增量加到 weight,走 _DeltaParam)
        "delta_b" 只有 `<stem>_diff_b`(一维增量加到 bias,走 _DeltaParam)
    增量与 pair 落在同一个模块时会并存:pair 一律把 kind 标成 "pair"(_LoRALinear 负责模块级包装,
    增量再由 _DeltaParam 插到它里层),因此 _apply_lora_slots 只按实际存在的张量键分流。
    """
    slots: Dict[str, Dict[str, object]] = {}
    used = dropped = 0
    for key, value in (weights or {}).items():
        stem, kind = _split_lora_key(key)
        mod = _resolve_lora_module(stem) if stem is not None else None
        if mod is None or not isinstance(value, torch.Tensor):
            dropped += 1
            continue
        slot = slots.setdefault(mod, {})
        slot[kind] = value
        if kind in ("delta_w", "delta_b"):
            slot.setdefault("kind", kind)
        else:
            slot["kind"] = "pair"
        used += 1
    return slots, used, dropped


def _svd_to_lora_parts(u, s, vh, k_max: int = _LOKR_MAX_RANK):
    """截断 SVD -> (down [k, in], up [out, k]),满足 up @ down ≈ ΔW。"""
    k = int(min(k_max, int(u.shape[1]), int(vh.shape[0])))
    if k <= 0:
        return None
    s = s[:k].to(torch.float32).clamp_min(0).sqrt()            # sqrt(奇异值)
    up = (u[:, :k] * s.unsqueeze(0)).contiguous().to(DTYPE)     # [out, k]
    down = (s.unsqueeze(1) * vh[:k, :]).contiguous().to(DTYPE)   # [k, in]
    return down, up


def _svd_truncate(delta: torch.Tensor, k_max: int = _LOKR_MAX_RANK):
    """显式 ΔW 的截断 SVD(小矩阵走这条,便于数值核对)。"""
    try:
        u, s, vh = torch.linalg.svd(delta.to(torch.float32), full_matrices=False)
    except Exception as exc:
        log(f"[LoKr SVD Error] {type(exc).__name__}: {exc}")
        return None
    return _svd_to_lora_parts(u, s, vh, k_max)


def _kron_svd_truncate(w1: torch.Tensor, w2: torch.Tensor, k_max: int = _LOKR_MAX_RANK):
    """不显式构造 ΔW 的**等价**截断 SVD。

    kron(A, B) = kron(Ua, Ub) @ diag(kron(sa, sb)) @ kron(Vha, Vhb),奇异值是两个因子奇异值的
    两两乘积;按乘积降序取前 k 个 == 对 ΔW = W1 ⊗ W2 直接截断到前 k 个奇异值。
    每个模块只做两次小 SVD(W1: [r, in/r]、W2: [out/r, r]),不会在启动时对 448 个
    3072x3072 的 ΔW 做完整 SVD。
    """
    try:
        u1, s1, vh1 = torch.linalg.svd(w1, full_matrices=False)
        u2, s2, vh2 = torch.linalg.svd(w2, full_matrices=False)
    except Exception as exc:
        log(f"[LoKr SVD Error] {type(exc).__name__}: {exc}")
        return None
    k2 = int(s2.numel())
    k = int(min(k_max, int(s1.numel()) * k2))
    if k <= 0:
        return None
    prod = torch.outer(s1, s2).reshape(-1)                     # == kron(s1, s2)
    top = torch.topk(prod, k=k, largest=True, sorted=True).indices.tolist()
    up_cols, down_rows = [], []
    for idx in top:
        i, j = divmod(int(idx), k2)                            # kron 的列序号 i*k2+j
        up_cols.append(torch.outer(u1[:, i], u2[:, j]).reshape(-1))      # [out]
        down_rows.append(torch.outer(vh1[i, :], vh2[j, :]).reshape(-1))  # [in]
    s = prod[top].to(torch.float32).clamp_min(0).sqrt()
    up = (torch.stack(up_cols, dim=1) * s.unsqueeze(0)).contiguous().to(DTYPE)
    down = (s.unsqueeze(1) * torch.stack(down_rows, dim=0)).contiguous().to(DTYPE)
    return down, up


def _lokr_factor(group: Dict[str, torch.Tensor], direct: str) -> Optional[torch.Tensor]:
    """取 LoKr 的一个因子:优先完整张量,否则用 *_a @ *_b 还原。"""
    full = group.get(direct)
    if full is not None:
        return full.detach().to(device="cpu", dtype=torch.float32)
    a, b = group.get(f"{direct}_a"), group.get(f"{direct}_b")
    if a is not None and b is not None:
        try:
            return torch.mm(
                a.detach().to(device="cpu", dtype=torch.float32),
                b.detach().to(device="cpu", dtype=torch.float32),
            )
        except Exception as exc:
            log(f"[LoKr Error] {direct}_a @ {direct}_b 失败: {type(exc).__name__}: {exc}")
    return None


def _lokr_group_view(group: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]:
    """LoKr 槽位 -> 统一的 {w1 / w2 / w1_a / w2_a / ...} 视图。

    _collect_lora_slots 存的 kind 带 lokr_ 前缀(lokr_w1 / lokr_w2_a),convert_lokr_weights 存的
    已经剥过前缀;这里统一剥一次,两条调用链拿到同样的 key,_lokr_factor/_alpha_scale 不用各写一套。
    """
    view: Dict[str, torch.Tensor] = {}
    for key, value in (group or {}).items():
        name = str(key)
        if name.startswith("lokr_"):
            name = name[len("lokr_"):]
        view.setdefault(name, value)          # 带前缀的写法优先保留先到的那个
    return view


def _lokr_rank_bound(group: Dict[str, torch.Tensor], direct: str, full: torch.Tensor) -> int:
    """因子的秩上界:分解形式取 min(行, 列, 内维),整张量取 min(行, 列)。

    w2_a [p, d] @ w2_b [d, q] 的秩不可能超过 min(p, q, d)——puo2 里就是 min(512, 256, 32) = 32。
    """
    a, b = group.get(f"{direct}_a"), group.get(f"{direct}_b")
    if isinstance(a, torch.Tensor) and isinstance(b, torch.Tensor) and a.ndim == 2 and b.ndim == 2:
        return int(max(0, min(int(a.shape[0]), int(b.shape[1]), int(a.shape[1]))))
    return int(max(0, min(int(full.shape[0]), int(full.shape[1]))))


def _lokr_slot_to_lora(group: Dict[str, torch.Tensor]):
    """LoKr 槽位 -> (down, up, rank_for_alpha);转换不了返回 None(调用方计数跳过,绝不抛异常)。

    LoKr / LyCORIS 的数学是 ΔW = W1 ⊗ W2:W1 [a, b]、W2 [c, d] -> ΔW [a*c, b*d]。
    W2 可能是整张量 <stem>.lokr_w2,也可能是分解形式 <stem>.lokr_w2_a @ <stem>.lokr_w2_b
    (puo2 就是后者:W1 [4,4]、W2 [512,32]@[32,256] -> ΔW [2048, 1024])。
    两个因子之间**没有**「w1.shape[0] == w2.shape[1]」这类约束:目标形状只由 kron 的行列乘积决定,
    旧代码却要求 w1.shape[0] == w2.shape[1](puo2 是 4 == 256,不成立)才继续,于是每组都返回 None。
    """
    view = _lokr_group_view(group)
    w1 = _lokr_factor(view, "w1")
    w2 = _lokr_factor(view, "w2")
    if w1 is None or w2 is None:
        return None
    if w1.ndim != 2 or w2.ndim != 2:                           # Conv2d 的 4D LoKr 不注入(本图只挂 Linear)
        return None
    out_dim = int(w1.shape[0]) * int(w2.shape[0])              # kron(W1, W2) 的 [out, in]
    in_dim = int(w1.shape[1]) * int(w2.shape[1])
    if out_dim <= 0 or in_dim <= 0:
        return None
    elems = out_dim * in_dim                                   # ΔW = W1 ⊗ W2 的元素数
    # rank(ΔW) = rank(W1) * rank(W2),所以截断上限取 min(上限, min(out,in), 秩上界),两条路径结果一致。
    # puo2: min(128, 1024, 4*32=128) = 128 == 真实秩 -> 无损(k=64 会丢 17%~31% 的 Frobenius 能量)。
    k_cap = int(min(_LOKR_MAX_RANK, min(out_dim, in_dim),
                    _lokr_rank_bound(view, "w1", w1) * _lokr_rank_bound(view, "w2", w2)))
    # 单模块 down+up 的元素预算:k*(out+in) 超预算就降 k(宁可 rank 低一点也不要把内存打爆)
    k_cap = int(max(1, min(k_cap, _LOKR_MAX_LORA_ELEMS // max(1, out_dim + in_dim))))
    parts = None
    if elems <= _LOKR_EXPLICIT_MAX_ELEMS:
        parts = _svd_truncate(torch.kron(w1, w2), k_cap)      # 显式构造 ΔW = W1 ⊗ W2 再截断 SVD
    if parts is None:
        if elems > _LOKR_HUGE_ELEMS:                          # 大 ΔW:走谐波分解,只取前 k_cap 个奇异值
            LORA_CONVERT_STATS["huge"] = int(LORA_CONVERT_STATS.get("huge", 0)) + 1
        parts = _kron_svd_truncate(w1, w2, k_cap)
    if parts is None:
        return None
    # rank_for_alpha 用转换后 LoRA 的真实 rank(= down.shape[0]),与 lora_down/lora_up 分支的
    # rank 定义保持一致,alpha/rank 缩放才能对上。
    return parts[0], parts[1], int(parts[0].shape[0])


def _alpha_scale(group: Dict[str, torch.Tensor], rank: Optional[int]) -> Optional[float]:
    """文件里的 alpha 张量 -> alpha/rank;没有 alpha(或 rank 未知)返回 None,调用方视为 1.0。"""
    alpha = group.get("alpha")
    if alpha is None or not rank or rank <= 0:
        return None
    try:
        return float(alpha.reshape(-1)[0].item()) / float(rank)
    except Exception:
        return None


def _converted_lora_path(src: str) -> str:
    d, name = os.path.split(str(src or ""))
    if name.endswith(".safetensors"):
        name = name[: -len(".safetensors")] + "_converted.safetensors"
    else:
        name = name + "_converted.safetensors"
    return os.path.join(d, name)


def _needs_lokr_conversion(weights) -> bool:
    """文件里是否含 LoKr 张量(_lokr_w1 与 .lokr_w1 两种写法都算)。"""
    for key in (weights or {}).keys():
        _stem, kind = _split_lora_key(key)
        if str(kind).startswith("lokr_"):
            return True
    return False


def convert_lokr_weights(weights) -> Tuple[Dict[str, torch.Tensor], Dict[str, int]]:
    """LoKr 张量组 -> kohya 的 <stem>.lora_down/.lora_up;非 LoKr 张量原样保留(含 alpha)。"""
    out: Dict[str, torch.Tensor] = {}
    groups: Dict[str, Dict[str, torch.Tensor]] = {}
    for key, value in (weights or {}).items():
        stem, kind = _split_lora_key(key)
        if stem is not None and str(kind).startswith("lokr_"):
            groups.setdefault(stem, {})[kind[len("lokr_"):]] = value
        else:
            out[key] = value
    stats = {"converted": 0, "skipped": 0}
    for stem, group in groups.items():
        parts = _lokr_slot_to_lora(group)
        if parts is None:
            stats["skipped"] += len(group)
            continue
        down, up, _rank = parts
        out[f"{stem}.lora_down.weight"] = down
        out[f"{stem}.lora_up.weight"] = up
        stats["converted"] += 1
    if stats["skipped"]:
        log(f"[LoKr Warning] {stats['skipped']} 个 LoKr 张量无法转换,已跳过(不抛异常)")
    return out, stats


def _load_lora_weights(src: str) -> Dict[str, torch.Tensor]:
    """加载 LoRA:先看 *_converted.safetensors 磁盘缓存,否则读原文件并按需做 LoKr 转换后回写缓存。"""
    from safetensors.torch import load_file, save_file

    cache_path = _converted_lora_path(src)
    if os.path.isfile(cache_path):
        try:
            t0 = time.time()
            conv = load_file(cache_path)
            LORA_CONVERT_STATS["files"] = int(LORA_CONVERT_STATS.get("files", 0)) + 1
            log(f"[LoRA Cache] 命中转换缓存 {os.path.basename(cache_path)}: {len(conv)} 张量, {time.time() - t0:.2f}s")
            return conv
        except Exception as exc:
            log(f"[LoRA Cache Warning] 读取 {cache_path} 失败,回落原文件: {type(exc).__name__}: {exc}")

    t0 = time.time()
    weights = load_file(src)
    LORA_CONVERT_STATS["files"] = int(LORA_CONVERT_STATS.get("files", 0)) + 1
    if not _needs_lokr_conversion(weights):
        return weights

    conv, stats = convert_lokr_weights(weights)
    elapsed = time.time() - t0
    LORA_CONVERT_STATS["lokr_files"] = int(LORA_CONVERT_STATS.get("lokr_files", 0)) + 1
    LORA_CONVERT_STATS["converted"] = int(LORA_CONVERT_STATS.get("converted", 0)) + stats["converted"]
    LORA_CONVERT_STATS["skipped"] = int(LORA_CONVERT_STATS.get("skipped", 0)) + stats["skipped"]
    LORA_CONVERT_STATS["seconds"] = float(LORA_CONVERT_STATS.get("seconds", 0.0)) + elapsed
    log(
        f"[LoKr→LoRA] {os.path.basename(src)}: 转换 {stats['converted']} 个模块 / "
        f"跳过 {stats['skipped']} 个张量, 耗时 {elapsed:.2f}s, 输出 {len(conv)} 张量"
    )
    if stats["converted"] <= 0:
        log("[LoKr→LoRA] 没有可转换模块,按原文件继续")
        return weights
    try:
        save_file(conv, cache_path)
        log(f"[LoKr→LoRA] 转换结果已缓存: {cache_path}")
    except Exception as exc:
        log(f"[LoKr→LoRA] 写缓存失败(忽略,下次重新转换): {type(exc).__name__}: {exc}")
    return conv


def _apply_lora_slots(root, slots: Dict[str, Dict[str, object]], scale: float) -> Dict[str, object]:
    """把一份 slots 注入到 root(transformer 或 llm_adapter)里的目标模块,返回统计。

    低秩对(lora_down/lora_up 或 LoKr)走 _LoRALinear / add_adapter,一维加性增量
    (delta_w -> weight / delta_b -> bias)走 _DeltaParam / add_delta;设备/dtype 对齐在两个
    wrapper 的 forward 里做,root._anima_patched 记录**原始模块**供 _unpatch 统一回收。
    同一个模块既有低秩对又有增量时:_LoRALinear 在外、_DeltaParam 在内,两者互不覆盖。
    root 为 None 时全部计入 missing,绝不 raise。
    """
    stats: Dict[str, object] = {
        "hit": 0,           # 本次成功注入的模块数(= 层数)
        "delta": 0,         # 本次成功注入的一维增量个数(参数增量,不算层)
        "lokr_skipped": 0,  # 无法转换成 LoRA 的 LoKr 模块数
        "bad_shape": 0,     # lora_down/lora_up(或增量)与目标参数形状不一致
        "missing": 0,       # 目标模块不存在 / 没有 weight / 没有该参数位
        "ratios": [],       # 每个模块的 alpha/rank
        "alpha_hits": 0,    # 真正读到 alpha 张量的模块数
    }
    if not slots:
        return stats
    if root is None:
        stats["missing"] = len(slots)
        return stats
    for mod_path, kv in slots.items():
        if not isinstance(kv, dict):
            continue
        parent, _, name = mod_path.rpartition(".")
        holder = _module_by_path(root, parent) if parent else root
        cur = getattr(holder, name, None) if holder is not None else None
        if cur is None:
            stats["missing"] = int(stats["missing"]) + 1
            continue

        # ---- 低秩对(lora_down/lora_up 或 LoKr)------------------------------------
        down = kv.get("lora_down")
        up = kv.get("lora_up")
        has_delta = any(isinstance(kv.get(k), torch.Tensor) for k in ("delta_w", "delta_b"))
        has_lokr = any(str(k).startswith("lokr_") for k in kv.keys())
        rank: Optional[int] = None
        if down is not None and up is not None and down.ndim == 2 and up.ndim == 2:
            rank = int(down.shape[0])
            if rank <= 0 or int(up.shape[1]) != rank:
                stats["bad_shape"] = int(stats["bad_shape"]) + 1
                continue
        elif has_lokr or not has_delta:
            # LoKr:ΔW = W1 ⊗ W2 -> 截断 SVD -> lora_down/lora_up
            # (rank = 转换后 LoRA 的真实 rank,用来算 alpha/rank)
            conv = _lokr_slot_to_lora(kv)
            if conv is None:
                stats["lokr_skipped"] = int(stats["lokr_skipped"]) + 1
                continue
            down, up, rank = conv
        # 纯增量 slot(只有 _diff / _diff_b):rank 保持 None,跳过低秩注入直接走增量分支

        if rank is not None:
            # D1:_LoRALinear / _DeltaParam 都没有 .weight,必须先判 isinstance 再取 weight
            # (_core_module 就是这条判定,只是多穿了一层 _DeltaParam 的包装)
            base = _core_module(cur)
            weight = getattr(base, "weight", None)
            if weight is None:
                stats["missing"] = int(stats["missing"]) + 1
                continue
            if int(down.shape[1]) != int(weight.shape[1]) or int(up.shape[0]) != int(weight.shape[0]):
                stats["bad_shape"] = int(stats["bad_shape"]) + 1
                continue

            # D3:有效缩放 = scale * (alpha / rank);文件里没有 alpha 时视为 1.0
            ratio = _alpha_scale(kv, rank)
            if ratio is None:
                ratio = 1.0
            else:
                stats["alpha_hits"] = int(stats["alpha_hits"]) + 1
            eff = float(scale) * float(ratio)
            stats["ratios"].append(float(ratio))
            if isinstance(cur, _LoRALinear):
                # 已经挂过 LoRA:直接叠加到同一个 wrapper 上(多 LoRA 叠加的关键)
                cur.add_adapter(down, up, eff)
            else:
                wrapper = _LoRALinear(cur)
                if not hasattr(root, "_anima_patched"):
                    root._anima_patched = {}
                root._anima_patched.setdefault(mod_path, _core_module(cur))
                setattr(holder, name, wrapper)
                wrapper.add_adapter(down, up, eff)
                cur = wrapper
            stats["hit"] = int(stats["hit"]) + 1

        # ---- 一维加性增量(_diff -> weight / _diff_b -> bias)------------------------
        for kind, attr in (("delta_w", "weight"), ("delta_b", "bias")):
            delta = kv.get(kind)
            if not isinstance(delta, torch.Tensor):
                continue
            wrapped = _find_delta_wrapper(cur, attr)      # 同一目标已有同 attr 的增量 -> 追加
            if wrapped is None:
                core = _core_module(cur)
                orig = _param_of(core, attr)
                if orig is _NO_PARAM_SLOT:
                    stats["missing"] = int(stats["missing"]) + 1     # 目标模块没有这个参数位
                    continue
                # orig 为 None(bias=False 的 nn.Linear)时按 weight 的 [out] 形状与 dtype/device
                # 对齐,从零开始构造;前向结束后 _DeltaParam 会把 bias 还原回 None。
                weight = getattr(core, "weight", None)
                ref = orig if isinstance(orig, torch.Tensor) else weight
                if isinstance(orig, torch.Tensor):
                    expect = tuple(orig.shape)
                elif isinstance(weight, torch.Tensor):
                    expect = tuple(weight.shape[:1])          # 没有 bias 时形状只能是 [out]
                else:
                    expect = ()
                if not isinstance(ref, torch.Tensor) or not expect or tuple(delta.shape) != expect:
                    stats["bad_shape"] = int(stats["bad_shape"]) + 1
                    continue
                wrapped = _DeltaParam(core, attr)
                if not hasattr(root, "_anima_patched"):
                    root._anima_patched = {}
                root._anima_patched.setdefault(mod_path, core)     # backup 永远是原始模块
                cur = _stack_wrapper(holder, name, cur, core, wrapped)
            wrapped.add_delta(delta, scale)                # 增量的缩放就是 LoRA 的 scale(无 alpha/rank)
            stats["delta"] = int(stats["delta"]) + 1
    return stats


def load_lora_matrix(target_key: str, lora_list: List[Tuple[str, float]]) -> int:
    """对 transformer(第一趟)和 llm_adapter(第二趟)各做一遍 _LoRALinear 注入,返回两类合计层数。"""
    transformer = CACHE_TRANSFORMERS.get(target_key)
    if transformer is None:
        return 0
    adapter = CACHE_ADAPTERS.get(target_key)
    cache = BASE_ADAPTER_CACHES.setdefault(target_key, OrderedDict())
    _unpatch(transformer)
    if adapter is not None:
        _unpatch(adapter)

    applied = 0          # DiT + Adapter 合计层数(回传状态栏的 M)
    for raw_repo, scale in lora_list[:12]:
        canon = canonical_lora_name(raw_repo)
        if not canon:
            continue
        ad_id = f"{target_key}__{hashlib.md5(canon.encode()).hexdigest()[:10]}"
        t_lora = time.time()
        if ad_id not in cache:
            if len(cache) >= MAX_CACHED_ADAPTERS:
                cache.popitem(last=False)
            src = ensure_lora_cached(raw_repo)
            try:
                # 含 LoKr -> LoRA 转换(首次)与 *_converted.safetensors 磁盘缓存(二次)
                cache[ad_id] = _load_lora_weights(src)
            except Exception as exc:
                log(f"[LoRA Load Error] {raw_repo}: {exc}")
                continue
        cache.move_to_end(ad_id)
        weights = cache[ad_id]

        slots, used, dropped = _collect_lora_slots(weights)
        if dropped:
            log(f"[LoRA Parse] {canon}: 命中 {used} 个张量, {dropped} 个 key 无法映射, 跳过")

        # 分流:带 _ADAPTER_LORA_NS 前缀的路径属于 AnimaLLMAdapter,其余属于 transformer
        dit_slots: Dict[str, Dict[str, object]] = {}
        ad_slots: Dict[str, Dict[str, object]] = {}
        for mod_path, kv in slots.items():
            if mod_path.startswith(_ADAPTER_LORA_NS):
                ad_slots[mod_path[len(_ADAPTER_LORA_NS):]] = kv
            else:
                dit_slots[mod_path] = kv

        dit_stats = _apply_lora_slots(transformer, dit_slots, scale)   # 第一趟:DiT
        ad_stats = _apply_lora_slots(adapter, ad_slots, scale)         # 第二趟:llm_adapter
        applied += int(dit_stats["hit"]) + int(ad_stats["hit"])        # 增量不算层(参数增量)
        delta_cnt = int(dit_stats["delta"]) + int(ad_stats["delta"])

        ratios: List[float] = list(dit_stats["ratios"]) + list(ad_stats["ratios"])
        alpha_hits = int(dit_stats["alpha_hits"]) + int(ad_stats["alpha_hits"])
        avg_ratio = (sum(ratios) / len(ratios)) if ratios else 1.0
        alpha_txt = f"{avg_ratio:.4f}({alpha_hits}/{len(ratios)})" if alpha_hits else "1.0000(无 alpha)"
        log(
            f"[LoRA] {canon}: scale={float(scale):.2f} alpha/rank={alpha_txt} "
            f"有效缩放={float(scale) * avg_ratio:.3f} • "
            f"DiT 注入={int(dit_stats['hit'])} 层 • Adapter 注入={int(ad_stats['hit'])} 层 • "
            f"增量注入={delta_cnt} 个 • 不支持={dropped} • "
            f"形状不匹配={int(dit_stats['bad_shape']) + int(ad_stats['bad_shape'])} • "
            f"模块缺失={int(dit_stats['missing']) + int(ad_stats['missing'])} • "
            f"LoKr跳过={int(dit_stats['lokr_skipped']) + int(ad_stats['lokr_skipped'])} • "
            f"耗时={time.time() - t_lora:.2f}s"
        )
    return applied


def parse_lora_directives(prompt: str, extra_cmds: str = "") -> Tuple[str, List[Tuple[str, float]]]:
    entries: List[Tuple[str, float]] = []
    combined = f"{prompt or ''}\n{extra_cmds or ''}"
    for block in _LORA_DIRECTIVE_RE.findall(combined):
        for bit in block[len("LORA:"):].split(";"):
            parts = bit.strip().split("|", 1)
            repo = parts[0].strip()
            if not repo:
                continue
            try:
                scale = float(parts[1].strip()) if len(parts) > 1 else 0.8
            except (ValueError, TypeError):
                scale = 0.8
            entries.append((repo, min(2.0, max(-2.0, scale))))
    return _LORA_DIRECTIVE_RE.sub("", str(prompt or "")).strip(), entries


DEFAULT_PRELOAD_LORAS = """Haruka041/anref|0.8
Haruka041/danzi|0.8
Haruka041/betm|0.8
Haruka041/erofg|0.8
Haruka041/yeej|0.8
Haruka041/nayo|0.8
Haruka041/sanao|0.8
Haruka041/illix|0.8
Haruka041/artsn|0.8
Haruka041/decon|0.8
Haruka041/gpti2|0.8
Haruka041/atoms|0.8
Haruka041/nijre|0.8
Haruka041/cyan|0.8
Haruka041/minm|0.8
Haruka041/jnkk|0.8
Haruka041/puo2|0.8
Haruka041/gsan|0.8
Haruka041/anirl|0.8
Haruka041/anbst|0.8
Haruka041/ansld|1.0
Haruka041/an2k|0.8
Haruka041/anturbo|1.0
Haruka041/andetail|0.8
Haruka041/anpose|0.8
Haruka041/antweak|0.5
Haruka041/anbold|0.5
Haruka041/anpiece|0.8
Haruka041/anscreen|0.85
Haruka041/anlight|0.8"""


def preload_loras_on_startup() -> None:
    raw = os.environ.get("PRELOAD_LORAS", DEFAULT_PRELOAD_LORAS) or ""
    ok = 0
    for line in raw.splitlines():
        line = line.strip()
        if not line or line.startswith("#"):
            continue
        repo = line.split("|")[0].strip()
        try:
            ensure_lora_cached(repo)
            ok += 1
        except Exception as exc:
            log(f"[Preload Skip] {repo}: {exc}")
    log(f"[Init] LoRA cache warmed: {ok}")


def _post_init_side_effects() -> None:
    try:
        _setup_remacri()
    except Exception as exc:  # pragma: no cover
        log(f"[Init] Remacri setup skipped: {exc}")
    try:
        preload_loras_on_startup()
    except Exception as exc:  # pragma: no cover
        log(f"[Init] LoRA preload skipped: {exc}")


_post_init_side_effects()


# -----------------------------------------------------------------------------
# 10. 生成入口(保持 36 参数顺序不变,供 hf-token-farm/backend/api/bridge.py 调用)
# -----------------------------------------------------------------------------
@spaces.GPU(duration=60)
def generate_anima(
    code_input, base_model_choice, prompt, negative_prompt,
    width, height, steps, cfg_scale, sampler_name, seed,
    enable_upscale, lora_directive, *lora_slot_args,
):
    if gr is None:
        raise RuntimeError(f"gradio is unavailable: {FATAL_ERROR}")

    supplied = str(code_input or "").strip()
    for src in (prompt, lora_directive, negative_prompt):
        m = re.search(r"AUTH:([^\s;]+)", str(src or ""))
        if m:
            supplied = m.group(1).strip()
            break
    prompt = re.sub(r"AUTH:[^\s;]+", "", str(prompt or "")).strip()
    negative_prompt = re.sub(r"AUTH:[^\s;]+", "", str(negative_prompt or "")).strip()
    lora_directive = re.sub(r"AUTH:[^\s;]+", "", str(lora_directive or "")).strip()
    if not SPACE_AUTH_SECRET:
        # 未配置 secret:一律拒绝(空串 == 空串 绝不放行);UI 上给明确提示,不 raise
        log("[Auth] SPACE_AUTH_SECRET 未配置,拒绝全部生成请求。")
        return (None, 0, 0.0,
                "[403] SPACE_AUTH_SECRET is not configured on this Space. "
                "Set it in Space Settings -> Variables and secrets, then retry.")
    if supplied != SPACE_AUTH_SECRET:
        raise gr.Error("403 Forbidden: Invalid Code.")
    if not prompt:
        raise gr.Error("Prompt is empty.")
    if FATAL_ERROR:
        raise gr.Error(f"Global initialisation failed:\n{FATAL_ERROR}")

    w = max(256, (int(width) // 16) * 16)
    h = max(256, (int(height) // 16) * 16)

    global CURRENT_ACTIVE_MODEL
    target_key = "homo_anima" if ("homo" in str(base_model_choice).lower()
                                  or "2.0" in str(base_model_choice)) else "ggmix_anima"
    if target_key in BASE_ERRORS:
        # 只有“请求指定的这个基座”坏了才拒绝;另一个基座照常可用
        raise gr.Error(
            f"Base model '{target_key}' failed to initialise. Pick the other base model.\n"
            f"{BASE_ERRORS[target_key]}"
        )

    with PIPE_LOCK:
        curr_dev = _runtime_device()
        transformer = CACHE_TRANSFORMERS.get(target_key)
        adapter = CACHE_ADAPTERS.get(target_key)
        if transformer is None or adapter is None:
            raise gr.Error(f"Base model '{target_key}' is not available on this Space.")
        active_transformer = transformer.to(curr_dev)
        adapter.to(curr_dev)
        # 关键:编码阶段走的是 PIPE.text_encoder / PIPE.llm_adapter,必须把当前选中的基座
        # 组件挂回 pipeline,否则切到第二个基座时 PIPE.llm_adapter 仍指向第一个基座的 adapter
        # (停在 CPU),而 text ids 已在 GPU -> index_select 设备不一致 RuntimeError。
        if PIPE is not None:
            PIPE.transformer = active_transformer
            PIPE.llm_adapter = adapter
        if TEXT_ENCODER is not None:
            TEXT_ENCODER.to(curr_dev)
        if VAE is not None:
            VAE.to(curr_dev)

        clean_prompt, dynamic = parse_lora_directives(prompt, lora_directive)

        CURRENT_ACTIVE_MODEL = target_key
        entries = []
        for i in range(0, min(24, len(lora_slot_args)), 2):
            repo = str(lora_slot_args[i] or "").strip()
            try:
                scale = float(lora_slot_args[i + 1]) if i + 1 < len(lora_slot_args) else 0.8
            except (ValueError, TypeError):
                scale = 0.8
            if repo:
                entries.append((repo, min(2.0, max(-2.0, scale))))
        entries.extend(dynamic)
        uniq = {}
        for repo, scale in entries:
            canon = canonical_lora_name(repo)
            if canon:
                uniq[canon] = (repo, scale)
        final_loras = list(uniq.values())[:12]
        applied = load_lora_matrix(target_key, final_loras)

        try:
            actual_seed = (int(seed) % (2 ** 31)) if (seed is not None and int(seed) >= 0) else int(time.time() * 1000) % (2 ** 31)
        except Exception:
            actual_seed = int(time.time() * 1000) % (2 ** 31)

        gen = torch.Generator(device=curr_dev).manual_seed(actual_seed)
        do_cfg = float(cfg_scale) > 1.0

        if PIPE is None:
            raise gr.Error("Pipeline is not initialised.")

        # 文本侧完全走官方 _encode_prompt:Qwen tokenizer -> Qwen3Model -> adapter(T5 ids) -> F.pad 到 512
        prompt_embeds, negative_prompt_embeds = PIPE.encode_prompt(
            prompt=clean_prompt,
            negative_prompt=negative_prompt or "",
            do_classifier_free_guidance=do_cfg,
            num_images_per_prompt=1,
            prompt_embeds=None,
            negative_prompt_embeds=None,
            device=curr_dev,
            max_sequence_length=512,
        )

        scheduler, sched_name = apply_sampler(sampler_name)
        sampler_errors: List[str] = []   # 采样核异常回传 UI(见 M2)
        t0 = time.time()
        latents = denoise(
            transformer=active_transformer,
            scheduler=scheduler,
            prompt_embeds=prompt_embeds,
            negative_prompt_embeds=negative_prompt_embeds,
            height=h,
            width=w,
            steps=max(1, int(steps)),
            cfg_scale=float(cfg_scale),
            generator=gen,
            sampler_name=sampler_name,
            latents=None,
            device=curr_dev,
            error_sink=sampler_errors,
        )
        image = decode_latents(latents, VAE, getattr(PIPE, "video_processor", None))
        t_diff = time.time() - t0

        if enable_upscale:
            with UPSCALE_LOCK:
                image = upscale_with_remacri(image)

        dur = round(time.time() - t0, 2)
        status = (f"[OK] {target_key} | {dur}s (diffuse {t_diff:.2f}s) | seed {actual_seed} "
                  f"| sched {sched_name} | LoRA {len(final_loras)} loras / {applied} layers")
        if sampler_errors:
            # 采样核异常不静默:traceback 已在日志里,这里把摘要一并回传给 UI
            status += " | sampler_error: " + " ;; ".join(sampler_errors[:3])
        return image, actual_seed, dur, status


# -----------------------------------------------------------------------------
# 11. UI
# -----------------------------------------------------------------------------
MODEL_NAMES = [v["label"] for v in MODELS_CONFIG.values()]

demo = None
if gr is not None:
    try:
        with gr.Blocks(title="A-Studio", css="footer {visibility: hidden}") as demo:
            if FATAL_ERROR:
                gr.Markdown(
                    "### ⚠️ Global initialisation error\n"
                    "The Space container is up, but the global dependency stack failed. Details:\n"
                    "```\n" + FATAL_ERROR + "\n```"
                )
            if BASE_ERRORS:
                gr.Markdown(
                    "### ⚠️ Base model unavailable\n"
                    "Only the base model(s) listed below are broken; the others still work:\n"
                    "```\n" + "\n".join(f"{k}: {v}" for k, v in BASE_ERRORS.items()) + "\n```"
                )
            with gr.Row():
                with gr.Column(scale=5):
                    gr.Markdown("### Control Panel")
                    with gr.Row():
                        code = gr.Textbox(label="Code", placeholder="···", type="password", scale=3)
                        model_sel = gr.Dropdown(MODEL_NAMES, value=MODEL_NAMES[0], label="Base Model", scale=5)
                    prompt_input = gr.Textbox(label="Prompt", lines=4)
                    neg_input = gr.Textbox(label="Negative Prompt", lines=2,
                                           value="low quality, blurry, bad anatomy, watermark")
                    with gr.Row():
                        width_s = gr.Slider(256, 2048, 1024, step=16, label="Width")
                        height_s = gr.Slider(256, 2048, 1024, step=16, label="Height")
                    with gr.Row():
                        steps_s = gr.Slider(4, 60, 28, step=1, label="Steps")
                        cfg_s = gr.Slider(1.0, 12.0, 7.0, step=0.5, label="CFG")
                        sampler_sel = gr.Dropdown(SAMPLERS, value=SAMPLERS[0], label="Sampler")
                        seed_in = gr.Number(label="Seed (-1 random)", value=-1, precision=0)
                    with gr.Accordion("Advanced", open=False):
                        upscale_chk = gr.Checkbox(label="4X Remacri Ultra-Resolution", value=False)
                        lora_cmd_input = gr.Textbox(label="Dynamic LORA Directives",
                                                    placeholder="LORA:repo|scale;...")
                    with gr.Accordion("LoRA Matrix (Up to 12 Slots)", open=False):
                        slot_components = []
                        for row_i in range(3):
                            with gr.Row():
                                for col_j in range(4):
                                    idx = row_i * 4 + col_j + 1
                                    with gr.Column(scale=1, min_width=180):
                                        r_in = gr.Textbox(label=f"#{idx} Repo", placeholder="Haruka041/...", lines=1)
                                        s_in = gr.Slider(-2.0, 2.0, 0.8, step=0.05, label=f"#{idx} Weight")
                                        slot_components.extend([r_in, s_in])
                    gen_btn = gr.Button("Generate", variant="primary", size="lg")

                with gr.Column(scale=5):
                    gr.Markdown("### Result")
                    img_out = gr.Image(label="Output", type="pil", interactive=False)
                    status_box = gr.Textbox(label="Status", interactive=False, lines=2)
                    with gr.Row():
                        out_seed = gr.Number(label="Used Seed", interactive=False)
                        out_dur = gr.Number(label="GPU Duration (s)", interactive=False)

            gen_btn.click(
                fn=generate_anima,
                inputs=[code, model_sel, prompt_input, neg_input, width_s, height_s,
                        steps_s, cfg_s, sampler_sel, seed_in, upscale_chk, lora_cmd_input] + slot_components,
                outputs=[img_out, out_seed, out_dur, status_box],
                api_name="run_anima",
            )
    except Exception as exc:  # 界面构建失败也不许把容器搞死:纯日志降级,不写任何全局错误变量
        demo = None
        log(f"[Init Warning] UI 构建失败(容器仍会起来): {type(exc).__name__}: {exc}")
        _log_traceback()

if __name__ == "__main__":
    if demo is None:
        log(f"[Init Warning] demo is None, cannot launch. FATAL_ERROR={FATAL_ERROR} BASE_ERRORS={BASE_ERRORS}")
    else:
        demo.queue().launch(ssr_mode=False)