File size: 77,558 Bytes
c009d4f
 
 
 
 
 
 
 
 
 
b7d4bc8
 
c009d4f
 
b7d4bc8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c009d4f
b7d4bc8
 
 
 
 
c009d4f
b7d4bc8
 
 
 
 
 
 
 
 
 
 
 
 
 
b2fb908
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b7d4bc8
 
 
 
 
 
 
 
 
 
 
 
 
c009d4f
b7d4bc8
 
 
c009d4f
b7d4bc8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c009d4f
b7d4bc8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c009d4f
b7d4bc8
 
 
 
 
 
 
 
 
 
 
 
 
c009d4f
b7d4bc8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c009d4f
b7d4bc8
 
 
 
 
 
 
 
 
 
 
 
c009d4f
b7d4bc8
 
c009d4f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b7d4bc8
 
 
 
 
 
 
 
 
 
 
 
 
 
953922c
 
b7d4bc8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
953922c
 
 
b7d4bc8
 
 
953922c
b7d4bc8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
953922c
 
 
b7d4bc8
 
 
953922c
b7d4bc8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2fb908
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b7d4bc8
 
 
 
 
 
 
 
 
 
 
 
 
 
953922c
 
b7d4bc8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
953922c
 
 
b7d4bc8
 
 
953922c
b7d4bc8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
953922c
 
 
b7d4bc8
 
 
953922c
b7d4bc8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c009d4f
b7d4bc8
 
c009d4f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b7d4bc8
 
c009d4f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b7d4bc8
 
 
 
 
 
 
 
 
 
 
 
c009d4f
 
 
 
b7d4bc8
 
 
 
c009d4f
 
 
b7d4bc8
 
c009d4f
 
 
 
b7d4bc8
 
c009d4f
 
b7d4bc8
b2fb908
b7d4bc8
 
 
 
 
c009d4f
 
b7d4bc8
c009d4f
 
 
 
 
 
 
b7d4bc8
b2fb908
b7d4bc8
 
 
 
 
 
c009d4f
 
 
 
 
 
b7d4bc8
 
 
 
 
 
 
 
b2fb908
b7d4bc8
 
 
 
 
 
 
 
c009d4f
 
 
b7d4bc8
 
 
 
 
 
 
 
 
b2fb908
b7d4bc8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2fb908
b7d4bc8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2fb908
 
 
 
 
 
 
 
b7d4bc8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2fb908
b7d4bc8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2fb908
b7d4bc8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2fb908
 
 
 
 
 
 
 
b7d4bc8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c009d4f
 
 
 
 
 
 
b7d4bc8
 
 
 
 
 
 
 
 
 
 
 
 
b2fb908
 
 
 
b7d4bc8
 
 
 
 
 
b2fb908
b7d4bc8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2fb908
b7d4bc8
 
 
b2fb908
b7d4bc8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2fb908
b7d4bc8
b2fb908
b7d4bc8
 
 
 
 
 
 
c009d4f
b7d4bc8
 
 
 
 
 
 
 
b2fb908
b7d4bc8
 
 
b2fb908
b7d4bc8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b2fb908
b7d4bc8
b2fb908
b7d4bc8
c009d4f
b7d4bc8
c009d4f
b7d4bc8
 
b2fb908
b7d4bc8
 
 
 
 
 
 
c009d4f
 
 
 
 
 
 
 
b7d4bc8
 
c009d4f
 
 
 
 
b7d4bc8
 
 
 
 
 
 
 
 
 
 
 
 
c009d4f
b7d4bc8
 
 
 
c009d4f
b7d4bc8
 
 
 
 
 
 
 
c009d4f
b7d4bc8
 
 
 
 
 
c009d4f
b7d4bc8
b2fb908
b7d4bc8
c009d4f
b7d4bc8
 
 
 
 
 
 
 
 
b2fb908
 
 
 
 
 
 
 
b7d4bc8
 
 
 
 
 
 
 
 
 
c009d4f
b7d4bc8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c009d4f
 
 
b7d4bc8
 
 
 
 
 
b2fb908
 
 
 
b7d4bc8
 
 
 
 
 
 
 
c009d4f
 
 
 
 
b7d4bc8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
import yaml
import os
import shutil
from functools import lru_cache
from core.settings import *
from utils.app_utils import *
from core.generation_logic import *
from comfy_integration.nodes import SAMPLER_CHOICES, SCHEDULER_CHOICES

from utils.app_utils import save_uploaded_file_with_hash
from ui.shared.ui_components import RESOLUTION_MAP, MAX_CONTROLNETS, MAX_IPADAPTERS, MAX_EMBEDDINGS, MAX_CONDITIONINGS, MAX_LORAS


@lru_cache(maxsize=1)
def load_controlnet_config():
    _PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    _CN_MODEL_LIST_PATH = os.path.join(_PROJECT_ROOT, 'yaml', 'controlnet_models.yaml')
    try:
        print("--- Loading controlnet_models.yaml ---")
        with open(_CN_MODEL_LIST_PATH, 'r', encoding='utf-8') as f:
            config = yaml.safe_load(f)
        print("--- ✅ controlnet_models.yaml loaded successfully ---")
        return config.get("ControlNet", {})
    except Exception as e:
        print(f"Error loading controlnet_models.yaml: {e}")
        return {}


def get_cn_defaults(arch_val):
    cn_full_config = load_controlnet_config()
    cn_config = cn_full_config.get(arch_val, [])
    
    if not cn_config:
        return [], None, [], None, "None"
        
    all_types = sorted(list(set(t for model in cn_config for t in model.get("Type", []))))
    default_type = all_types[0] if all_types else None
    
    series_choices = []
    if default_type:
        series_choices = sorted(list(set(model.get("Series", "Default") for model in cn_config if default_type in model.get("Type", []))))
    default_series = series_choices[0] if series_choices else None
    
    filepath = "None"
    if default_series and default_type:
        for model in cn_config:
            if model.get("Series") == default_series and default_type in model.get("Type", []):
                filepath = model.get("Filepath")
                break
                
    return all_types, default_type, series_choices, default_series, filepath

@lru_cache(maxsize=1)
def load_anima_controlnet_lllite_config():
    _PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    _CN_MODEL_LIST_PATH = os.path.join(_PROJECT_ROOT, 'yaml', 'anima_controlnet_lllite_models.yaml')
    try:
        print("--- Loading anima_controlnet_lllite_models.yaml ---")
        with open(_CN_MODEL_LIST_PATH, 'r', encoding='utf-8') as f:
            config = yaml.safe_load(f)
        print("--- ✅ anima_controlnet_lllite_models.yaml loaded successfully ---")
        return config.get("Anima_ControlNet_Lllite", [])
    except Exception as e:
        print(f"Error loading anima_controlnet_lllite_models.yaml: {e}")
        return []

def get_anima_cn_defaults():
    cn_config = load_anima_controlnet_lllite_config()
    if not cn_config:
        return [], None, [], None, "None"
    all_types = sorted(list(set(t for model in cn_config for t in model.get("Type", []))))
    default_type = all_types[0] if all_types else None
    series_choices = []
    if default_type:
        series_choices = sorted(list(set(model.get("Series", "Default") for model in cn_config if default_type in model.get("Type", []))))
    default_series = series_choices[0] if series_choices else None
    filepath = "None"
    if default_series and default_type:
        for model in cn_config:
            if model.get("Series") == default_series and default_type in model.get("Type", []):
                filepath = model.get("Filepath")
                break
    return all_types, default_type, series_choices, default_series, filepath

@lru_cache(maxsize=1)
def load_diffsynth_controlnet_config():
    _PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    _CN_MODEL_LIST_PATH = os.path.join(_PROJECT_ROOT, 'yaml', 'diffsynth_controlnet_models.yaml')
    try:
        print("--- Loading diffsynth_controlnet_models.yaml ---")
        with open(_CN_MODEL_LIST_PATH, 'r', encoding='utf-8') as f:
            config = yaml.safe_load(f)
        print("--- ✅ diffsynth_controlnet_models.yaml loaded successfully ---")
        return config.get("DiffSynth_ControlNet", {})
    except Exception as e:
        print(f"Error loading diffsynth_controlnet_models.yaml: {e}")
        return {}

def get_diffsynth_cn_defaults(arch_val):
    cn_full_config = load_diffsynth_controlnet_config()
    cn_config = cn_full_config.get(arch_val, [])
    
    if not cn_config:
        return [], None, [], None, "None"
        
    all_types = sorted(list(set(t for model in cn_config for t in model.get("Type", []))))
    default_type = all_types[0] if all_types else None
    
    series_choices = []
    if default_type:
        series_choices = sorted(list(set(model.get("Series", "Default") for model in cn_config if default_type in model.get("Type", []))))
    default_series = series_choices[0] if series_choices else None
    
    filepath = "None"
    if default_series and default_type:
        for model in cn_config:
            if model.get("Series") == default_series and default_type in model.get("Type", []):
                filepath = model.get("Filepath")
                break
                
    return all_types, default_type, series_choices, default_series, filepath


@lru_cache(maxsize=1)
def load_ipadapter_config():
    _PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    _IPA_MODEL_LIST_PATH = os.path.join(_PROJECT_ROOT, 'yaml', 'ipadapter.yaml')
    try:
        print("--- Loading ipadapter.yaml ---")
        with open(_IPA_MODEL_LIST_PATH, 'r', encoding='utf-8') as f:
            config = yaml.safe_load(f)
        print("--- ✅ ipadapter.yaml loaded successfully ---")
        return config
    except Exception as e:
        print(f"Error loading ipadapter.yaml: {e}")
        return {}


def apply_data_to_ui(data, prefix, ui_components):
    final_sampler = data.get('sampler') if data.get('sampler') in SAMPLER_CHOICES else SAMPLER_CHOICES[0]
    default_scheduler = 'normal' if 'normal' in SCHEDULER_CHOICES else SCHEDULER_CHOICES[0]
    final_scheduler = data.get('scheduler') if data.get('scheduler') in SCHEDULER_CHOICES else default_scheduler

    updates = {}
    base_model_name = data.get('base_model')
    
    model_map = MODEL_MAP_CHECKPOINT

    if f'base_model_{prefix}' in ui_components:
        model_dropdown_component = ui_components[f'base_model_{prefix}']
        if base_model_name and base_model_name in model_map:
            updates[model_dropdown_component] = base_model_name
            if f'model_arch_{prefix}' in ui_components:
                m_type = MODEL_TYPE_MAP.get(base_model_name, "SDXL")
                updates[ui_components[f'model_arch_{prefix}']] = m_type
            if f'model_cat_{prefix}' in ui_components:
                m_info = model_map.get(base_model_name)
                m_cat = m_info[4] if m_info and len(m_info) > 4 else None
                updates[ui_components[f'model_cat_{prefix}']] = m_cat if m_cat else "ALL"
        else:
            updates[model_dropdown_component] = gr.update()
    
    common_params = {
        f'prompt_{prefix}': data.get('prompt', ''),
        f'neg_prompt_{prefix}': data.get('negative_prompt', ''),
        f'seed_{prefix}': data.get('seed', -1),
        f'cfg_{prefix}': data.get('cfg_scale', 7.5),
        f'steps_{prefix}': data.get('steps', 28),
        f'sampler_{prefix}': final_sampler,
        f'scheduler_{prefix}': final_scheduler,
    }
    
    for comp_name, value in common_params.items():
        if comp_name in ui_components:
            updates[ui_components[comp_name]] = value
    
    if prefix == 'txt2img':
         if f'width_{prefix}' in ui_components:
             updates[ui_components[f'width_{prefix}']] = data.get('width', 1024)
         if f'height_{prefix}' in ui_components:
             updates[ui_components[f'height_{prefix}']] = data.get('height', 1024)

    tab_indices = {"txt2img": 0, "img2img": 1, "inpaint": 2, "outpaint": 3, "hires_fix": 4}
    tab_index = tab_indices.get(prefix, 0)

    updates[ui_components['tabs']] = gr.Tabs(selected=tab_index)
    
    return updates


def send_info_to_tab(image, prefix, ui_components):
    if not image or not image.info.get('parameters', ''):
        all_comps = [comp for comp_or_list in ui_components.values() for comp in (comp_or_list if isinstance(comp_or_list, list) else [comp_or_list])]
        return {comp: gr.update() for comp in all_comps}
    
    data = parse_parameters(image.info['parameters'])
    
    image_input_map = {
        "img2img": 'input_image_img2img',
        "inpaint": 'input_image_dict_inpaint',
        "outpaint": 'input_image_outpaint',
        "hires_fix": 'input_image_hires_fix'
    }
    
    updates = apply_data_to_ui(data, prefix, ui_components)
    
    if prefix in image_input_map and image_input_map[prefix] in ui_components:
        component_key = image_input_map[prefix]
        updates[ui_components[component_key]] = gr.update(value=image)
        
    return updates


def send_info_by_hash(image, ui_components):
    if not image or not image.info.get('parameters', ''):
        all_comps = [comp for comp_or_list in ui_components.values() for comp in (comp_or_list if isinstance(comp_or_list, list) else [comp_or_list])]
        return {comp: gr.update() for comp in all_comps}

    data = parse_parameters(image.info['parameters'])
    
    return apply_data_to_ui(data, "txt2img", ui_components)


def attach_event_handlers(ui_components, demo):
    
    def create_lora_event_handlers(prefix):
        lora_rows = ui_components.get(f'lora_rows_{prefix}')
        if not lora_rows: return
        lora_ids = ui_components[f'lora_ids_{prefix}']
        lora_scales = ui_components[f'lora_scales_{prefix}']
        lora_uploads = ui_components[f'lora_uploads_{prefix}']
        count_state = ui_components[f'lora_count_state_{prefix}']
        add_button = ui_components[f'add_lora_button_{prefix}']
        del_button = ui_components[f'delete_lora_button_{prefix}']

        def add_lora_row(c):
            updates = {}
            if c < MAX_LORAS:
                c += 1
                updates[lora_rows[c - 1]] = gr.update(visible=True)
            
            updates[count_state] = c
            updates[add_button] = gr.update(visible=c < MAX_LORAS)
            updates[del_button] = gr.update(visible=c > 1)
            return updates

        def del_lora_row(c):
            updates = {}
            if c > 1:
                updates[lora_rows[c - 1]] = gr.update(visible=False)
                updates[lora_ids[c - 1]] = ""
                updates[lora_scales[c - 1]] = 0.0
                updates[lora_uploads[c - 1]] = None
                c -= 1

            updates[count_state] = c
            updates[add_button] = gr.update(visible=True)
            updates[del_button] = gr.update(visible=c > 1)
            return updates
        
        add_outputs = [count_state, add_button, del_button] + lora_rows
        del_outputs = [count_state, add_button, del_button] + lora_rows + lora_ids + lora_scales + lora_uploads

        add_button.click(add_lora_row, [count_state], add_outputs, show_progress=False)
        del_button.click(del_lora_row, [count_state], del_outputs, show_progress=False)
        
    def create_controlnet_event_handlers(prefix):
        cn_rows = ui_components.get(f'controlnet_rows_{prefix}')
        if not cn_rows: return
        cn_types = ui_components[f'controlnet_types_{prefix}']
        cn_series = ui_components[f'controlnet_series_{prefix}']
        cn_filepaths = ui_components[f'controlnet_filepaths_{prefix}']
        cn_images = ui_components[f'controlnet_images_{prefix}']
        cn_strengths = ui_components[f'controlnet_strengths_{prefix}']
        
        count_state = ui_components[f'controlnet_count_state_{prefix}']
        add_button = ui_components[f'add_controlnet_button_{prefix}']
        del_button = ui_components[f'delete_controlnet_button_{prefix}']
        accordion = ui_components[f'controlnet_accordion_{prefix}']

        base_model_comp = ui_components.get(f'base_model_{prefix}')
        actual_arch_comp = base_model_comp if base_model_comp else gr.State("SDXL")

        def add_cn_row(c):
            c += 1
            updates = {
                count_state: c,
                cn_rows[c-1]: gr.update(visible=True),
                add_button: gr.update(visible=c < MAX_CONTROLNETS),
                del_button: gr.update(visible=True)
            }
            return updates

        def del_cn_row(c):
            c -= 1
            updates = {
                count_state: c,
                cn_rows[c]: gr.update(visible=False),
                cn_images[c]: None,
                cn_strengths[c]: 1.0,
                add_button: gr.update(visible=True),
                del_button: gr.update(visible=c > 0)
            }
            return updates
            
        add_outputs = [count_state, add_button, del_button] + cn_rows
        del_outputs = [count_state, add_button, del_button] + cn_rows + cn_images + cn_strengths
        add_button.click(fn=add_cn_row, inputs=[count_state], outputs=add_outputs, show_progress=False)
        del_button.click(fn=del_cn_row, inputs=[count_state], outputs=del_outputs, show_progress=False)
        
        def on_cn_type_change(selected_type, model_name):
            from core.settings import MODEL_TYPE_MAP
            m_type = MODEL_TYPE_MAP.get(model_name, "SDXL") if model_name else "SDXL"
            cn_full_config = load_controlnet_config()
            
            architectures_dict = ARCHITECTURES_CONFIG.get('architectures', {})
            controlnet_key = architectures_dict.get(m_type, {}).get("controlnet_key", m_type)

            cn_config = cn_full_config.get(controlnet_key, [])
            series_choices = []
            if selected_type:
                series_choices = sorted(list(set(
                    model.get("Series", "Default") for model in cn_config
                    if selected_type in model.get("Type", [])
                )))
            default_series = series_choices[0] if series_choices else None
            filepath = "None"
            if default_series:
                for model in cn_config:
                    if model.get("Series") == default_series and selected_type in model.get("Type", []):
                        filepath = model.get("Filepath")
                        break
            return gr.update(choices=series_choices, value=default_series), filepath

        def on_cn_series_change(selected_series, selected_type, model_name):
            from core.settings import MODEL_TYPE_MAP
            m_type = MODEL_TYPE_MAP.get(model_name, "SDXL") if model_name else "SDXL"
            cn_full_config = load_controlnet_config()
            
            architectures_dict = ARCHITECTURES_CONFIG.get('architectures', {})
            controlnet_key = architectures_dict.get(m_type, {}).get("controlnet_key", m_type)

            cn_config = cn_full_config.get(controlnet_key, [])
            filepath = "None"
            if selected_series and selected_type:
                for model in cn_config:
                    if model.get("Series") == selected_series and selected_type in model.get("Type", []):
                        filepath = model.get("Filepath")
                        break
            return filepath
            
        for i in range(MAX_CONTROLNETS):
            cn_types[i].change(
                fn=on_cn_type_change,
                inputs=[cn_types[i], actual_arch_comp],
                outputs=[cn_series[i], cn_filepaths[i]],
                show_progress=False
            )
            cn_series[i].change(
                fn=on_cn_series_change,
                inputs=[cn_series[i], cn_types[i], actual_arch_comp],
                outputs=[cn_filepaths[i]],
                show_progress=False
            )

        def on_accordion_expand(*images):
            return [gr.update() for _ in images]
        
        accordion.expand(
            fn=on_accordion_expand,
            inputs=cn_images,
            outputs=cn_images,
            show_progress=False
        )

    def create_anima_controlnet_lllite_event_handlers(prefix):
        cn_rows = ui_components.get(f'anima_controlnet_lllite_rows_{prefix}')
        if not cn_rows: return
        cn_types = ui_components[f'anima_controlnet_lllite_types_{prefix}']
        cn_series = ui_components[f'anima_controlnet_lllite_series_{prefix}']
        cn_filepaths = ui_components[f'anima_controlnet_lllite_filepaths_{prefix}']
        cn_images = ui_components[f'anima_controlnet_lllite_images_{prefix}']
        cn_strengths = ui_components[f'anima_controlnet_lllite_strengths_{prefix}']
        
        count_state = ui_components[f'anima_controlnet_lllite_count_state_{prefix}']
        add_button = ui_components[f'add_anima_controlnet_lllite_button_{prefix}']
        del_button = ui_components[f'delete_anima_controlnet_lllite_button_{prefix}']
        accordion = ui_components[f'anima_controlnet_lllite_accordion_{prefix}']

        def add_cn_row(c):
            c += 1
            updates = {
                count_state: c,
                cn_rows[c-1]: gr.update(visible=True),
                add_button: gr.update(visible=c < MAX_CONTROLNETS),
                del_button: gr.update(visible=True)
            }
            return updates

        def del_cn_row(c):
            c -= 1
            updates = {
                count_state: c,
                cn_rows[c]: gr.update(visible=False),
                cn_images[c]: None,
                cn_strengths[c]: 1.0,
                add_button: gr.update(visible=True),
                del_button: gr.update(visible=c > 0)
            }
            return updates
            
        add_outputs = [count_state, add_button, del_button] + cn_rows
        del_outputs = [count_state, add_button, del_button] + cn_rows + cn_images + cn_strengths
        add_button.click(fn=add_cn_row, inputs=[count_state], outputs=add_outputs, show_progress=False)
        del_button.click(fn=del_cn_row, inputs=[count_state], outputs=del_outputs, show_progress=False)
        
        def on_cn_type_change(selected_type):
            cn_config = load_anima_controlnet_lllite_config()
            series_choices = []
            if selected_type:
                series_choices = sorted(list(set(
                    model.get("Series", "Default") for model in cn_config
                    if selected_type in model.get("Type", [])
                )))
            default_series = series_choices[0] if series_choices else None
            filepath = "None"
            if default_series:
                for model in cn_config:
                    if model.get("Series") == default_series and selected_type in model.get("Type", []):
                        filepath = model.get("Filepath")
                        break
            return gr.update(choices=series_choices, value=default_series), filepath

        def on_cn_series_change(selected_series, selected_type):
            cn_config = load_anima_controlnet_lllite_config()
            filepath = "None"
            if selected_series and selected_type:
                for model in cn_config:
                    if model.get("Series") == selected_series and selected_type in model.get("Type", []):
                        filepath = model.get("Filepath")
                        break
            return filepath
            
        for i in range(MAX_CONTROLNETS):
            cn_types[i].change(
                fn=on_cn_type_change,
                inputs=[cn_types[i]],
                outputs=[cn_series[i], cn_filepaths[i]],
                show_progress=False
            )
            cn_series[i].change(
                fn=on_cn_series_change,
                inputs=[cn_series[i], cn_types[i]],
                outputs=[cn_filepaths[i]],
                show_progress=False
            )

        def on_accordion_expand(*images):
            return [gr.update() for _ in images]
        
        accordion.expand(
            fn=on_accordion_expand,
            inputs=cn_images,
            outputs=cn_images,
            show_progress=False
        )

    def create_diffsynth_controlnet_event_handlers(prefix):
        cn_rows = ui_components.get(f'diffsynth_controlnet_rows_{prefix}')
        if not cn_rows: return
        cn_types = ui_components[f'diffsynth_controlnet_types_{prefix}']
        cn_series = ui_components[f'diffsynth_controlnet_series_{prefix}']
        cn_filepaths = ui_components[f'diffsynth_controlnet_filepaths_{prefix}']
        cn_images = ui_components[f'diffsynth_controlnet_images_{prefix}']
        cn_strengths = ui_components[f'diffsynth_controlnet_strengths_{prefix}']
        
        count_state = ui_components[f'diffsynth_controlnet_count_state_{prefix}']
        add_button = ui_components[f'add_diffsynth_controlnet_button_{prefix}']
        del_button = ui_components[f'delete_diffsynth_controlnet_button_{prefix}']
        accordion = ui_components[f'diffsynth_controlnet_accordion_{prefix}']

        base_model_comp = ui_components.get(f'base_model_{prefix}')
        actual_arch_comp = base_model_comp if base_model_comp else gr.State("SDXL")

        def add_cn_row(c):
            c += 1
            updates = {
                count_state: c,
                cn_rows[c-1]: gr.update(visible=True),
                add_button: gr.update(visible=c < MAX_CONTROLNETS),
                del_button: gr.update(visible=True)
            }
            return updates

        def del_cn_row(c):
            c -= 1
            updates = {
                count_state: c,
                cn_rows[c]: gr.update(visible=False),
                cn_images[c]: None,
                cn_strengths[c]: 1.0,
                add_button: gr.update(visible=True),
                del_button: gr.update(visible=c > 0)
            }
            return updates
            
        add_outputs = [count_state, add_button, del_button] + cn_rows
        del_outputs = [count_state, add_button, del_button] + cn_rows + cn_images + cn_strengths
        add_button.click(fn=add_cn_row, inputs=[count_state], outputs=add_outputs, show_progress=False)
        del_button.click(fn=del_cn_row, inputs=[count_state], outputs=del_outputs, show_progress=False)
        
        def on_cn_type_change(selected_type, model_name):
            from core.settings import MODEL_TYPE_MAP
            m_type = MODEL_TYPE_MAP.get(model_name, "SDXL") if model_name else "SDXL"
            cn_full_config = load_diffsynth_controlnet_config()
            
            architectures_dict = ARCHITECTURES_CONFIG.get('architectures', {})
            controlnet_key = architectures_dict.get(m_type, {}).get("controlnet_key", m_type)

            cn_config = cn_full_config.get(controlnet_key, [])
            series_choices = []
            if selected_type:
                series_choices = sorted(list(set(
                    model.get("Series", "Default") for model in cn_config
                    if selected_type in model.get("Type", [])
                )))
            default_series = series_choices[0] if series_choices else None
            filepath = "None"
            if default_series:
                for model in cn_config:
                    if model.get("Series") == default_series and selected_type in model.get("Type", []):
                        filepath = model.get("Filepath")
                        break
            return gr.update(choices=series_choices, value=default_series), filepath

        def on_cn_series_change(selected_series, selected_type, model_name):
            from core.settings import MODEL_TYPE_MAP
            m_type = MODEL_TYPE_MAP.get(model_name, "SDXL") if model_name else "SDXL"
            cn_full_config = load_diffsynth_controlnet_config()
            
            architectures_dict = ARCHITECTURES_CONFIG.get('architectures', {})
            controlnet_key = architectures_dict.get(m_type, {}).get("controlnet_key", m_type)

            cn_config = cn_full_config.get(controlnet_key, [])
            filepath = "None"
            if selected_series and selected_type:
                for model in cn_config:
                    if model.get("Series") == selected_series and selected_type in model.get("Type", []):
                        filepath = model.get("Filepath")
                        break
            return filepath
            
        for i in range(MAX_CONTROLNETS):
            cn_types[i].change(
                fn=on_cn_type_change,
                inputs=[cn_types[i], actual_arch_comp],
                outputs=[cn_series[i], cn_filepaths[i]],
                show_progress=False
            )
            cn_series[i].change(
                fn=on_cn_series_change,
                inputs=[cn_series[i], cn_types[i], actual_arch_comp],
                outputs=[cn_filepaths[i]],
                show_progress=False
            )

        def on_accordion_expand(*images):
            return [gr.update() for _ in images]
        
        accordion.expand(
            fn=on_accordion_expand,
            inputs=cn_images,
            outputs=cn_images,
            show_progress=False
        )

    def create_flux1_ipadapter_event_handlers(prefix):
        fipa_rows = ui_components.get(f'flux1_ipadapter_rows_{prefix}')
        if not fipa_rows: return
        count_state = ui_components[f'flux1_ipadapter_count_state_{prefix}']
        add_button = ui_components[f'add_flux1_ipadapter_button_{prefix}']
        del_button = ui_components[f'delete_flux1_ipadapter_button_{prefix}']

        def add_fipa_row(c):
            c += 1
            return {
                count_state: c,
                fipa_rows[c - 1]: gr.update(visible=True),
                add_button: gr.update(visible=c < MAX_IPADAPTERS),
                del_button: gr.update(visible=True),
            }

        def del_fipa_row(c):
            c -= 1
            return {
                count_state: c,
                fipa_rows[c]: gr.update(visible=False),
                add_button: gr.update(visible=True),
                del_button: gr.update(visible=c > 0),
            }

        add_outputs = [count_state, add_button, del_button] + fipa_rows
        del_outputs = [count_state, add_button, del_button] + fipa_rows
        add_button.click(fn=add_fipa_row, inputs=[count_state], outputs=add_outputs, show_progress=False)
        del_button.click(fn=del_fipa_row, inputs=[count_state], outputs=del_outputs, show_progress=False)

    def create_style_event_handlers(prefix):
        style_rows = ui_components.get(f'style_rows_{prefix}')
        if not style_rows: return
        count_state = ui_components[f'style_count_state_{prefix}']
        add_button = ui_components[f'add_style_button_{prefix}']
        del_button = ui_components[f'delete_style_button_{prefix}']

        def add_style_row(c):
            c += 1
            return {
                count_state: c,
                style_rows[c - 1]: gr.update(visible=True),
                add_button: gr.update(visible=c < 5),
                del_button: gr.update(visible=True),
            }

        def del_style_row(c):
            c -= 1
            return {
                count_state: c,
                style_rows[c]: gr.update(visible=False),
                add_button: gr.update(visible=True),
                del_button: gr.update(visible=c > 0),
            }

        add_outputs = [count_state, add_button, del_button] + style_rows
        del_outputs = [count_state, add_button, del_button] + style_rows
        add_button.click(fn=add_style_row, inputs=[count_state], outputs=add_outputs, show_progress=False)
        del_button.click(fn=del_style_row, inputs=[count_state], outputs=del_outputs, show_progress=False)

    def create_ipadapter_event_handlers(prefix):
        ipa_rows = ui_components.get(f'ipadapter_rows_{prefix}')
        if not ipa_rows: return
        ipa_lora_strengths = ui_components[f'ipadapter_lora_strengths_{prefix}']
        ipa_final_preset = ui_components[f'ipadapter_final_preset_{prefix}']
        ipa_final_lora_strength = ui_components[f'ipadapter_final_lora_strength_{prefix}']
        count_state = ui_components[f'ipadapter_count_state_{prefix}']
        add_button = ui_components[f'add_ipadapter_button_{prefix}']
        del_button = ui_components[f'delete_ipadapter_button_{prefix}']
        accordion = ui_components[f'ipadapter_accordion_{prefix}']

        def add_ipa_row(c):
            c += 1
            return {
                count_state: c,
                ipa_rows[c - 1]: gr.update(visible=True),
                add_button: gr.update(visible=c < MAX_IPADAPTERS),
                del_button: gr.update(visible=True),
            }

        def del_ipa_row(c):
            c -= 1
            return {
                count_state: c,
                ipa_rows[c]: gr.update(visible=False),
                add_button: gr.update(visible=True),
                del_button: gr.update(visible=c > 0),
            }

        add_outputs = [count_state, add_button, del_button] + ipa_rows
        del_outputs = [count_state, add_button, del_button] + ipa_rows
        add_button.click(fn=add_ipa_row, inputs=[count_state], outputs=add_outputs, show_progress=False)
        del_button.click(fn=del_ipa_row, inputs=[count_state], outputs=del_outputs, show_progress=False)

        def on_preset_change(preset_value):
            config = load_ipadapter_config()
            faceid_presets = []
            if config:
                faceid_presets.extend(config.get("IPAdapter_FaceID_presets", {}).get("SDXL", []))
                faceid_presets.extend(config.get("IPAdapter_FaceID_presets", {}).get("SD1.5", []))

            is_visible = preset_value in faceid_presets
            updates = [gr.update(visible=is_visible)] * (MAX_IPADAPTERS + 1)
            return updates

        all_lora_strength_sliders = [ipa_final_lora_strength] + ipa_lora_strengths
        ipa_final_preset.change(fn=on_preset_change, inputs=[ipa_final_preset], outputs=all_lora_strength_sliders, show_progress=False)
        
        accordion.expand(fn=lambda *imgs: [gr.update() for _ in imgs], inputs=ui_components[f'ipadapter_images_{prefix}'], outputs=ui_components[f'ipadapter_images_{prefix}'], show_progress=False)

    def create_reference_latent_event_handlers(prefix):
        ref_rows = ui_components.get(f'reference_latent_rows_{prefix}')
        if not ref_rows: return
        count_state = ui_components[f'reference_latent_count_state_{prefix}']
        add_button = ui_components[f'add_reference_latent_button_{prefix}']
        del_button = ui_components[f'delete_reference_latent_button_{prefix}']
        images = ui_components[f'reference_latent_images_{prefix}']

        def add_ref_row(c):
            c += 1
            return {
                count_state: c,
                ref_rows[c - 1]: gr.update(visible=True),
                add_button: gr.update(visible=c < 10),
                del_button: gr.update(visible=True),
            }

        def del_ref_row(c):
            c -= 1
            return {
                count_state: c,
                ref_rows[c]: gr.update(visible=False),
                images[c]: None,
                add_button: gr.update(visible=True),
                del_button: gr.update(visible=c > 0),
            }

        add_outputs = [count_state, add_button, del_button] + ref_rows
        del_outputs = [count_state, add_button, del_button] + ref_rows + images
        add_button.click(fn=add_ref_row, inputs=[count_state], outputs=add_outputs, show_progress=False)
        del_button.click(fn=del_ref_row, inputs=[count_state], outputs=del_outputs, show_progress=False)


    def create_embedding_event_handlers(prefix):
        rows = ui_components.get(f'embedding_rows_{prefix}')
        if not rows: return
        ids = ui_components[f'embeddings_ids_{prefix}']
        files = ui_components[f'embeddings_files_{prefix}']
        count_state = ui_components[f'embedding_count_state_{prefix}']
        add_button = ui_components[f'add_embedding_button_{prefix}']
        del_button = ui_components[f'delete_embedding_button_{prefix}']

        def add_row(c):
            c += 1
            return {
                count_state: c,
                rows[c - 1]: gr.update(visible=True),
                add_button: gr.update(visible=c < MAX_EMBEDDINGS),
                del_button: gr.update(visible=True)
            }

        def del_row(c):
            c -= 1
            return {
                count_state: c,
                rows[c]: gr.update(visible=False),
                ids[c]: "",
                files[c]: None,
                add_button: gr.update(visible=True),
                del_button: gr.update(visible=c > 0)
            }
        
        add_outputs = [count_state, add_button, del_button] + rows
        del_outputs = [count_state, add_button, del_button] + rows + ids + files
        add_button.click(fn=add_row, inputs=[count_state], outputs=add_outputs, show_progress=False)
        del_button.click(fn=del_row, inputs=[count_state], outputs=del_outputs, show_progress=False)
    
    def create_conditioning_event_handlers(prefix):
        rows = ui_components.get(f'conditioning_rows_{prefix}')
        if not rows: return
        prompts = ui_components[f'conditioning_prompts_{prefix}']
        count_state = ui_components[f'conditioning_count_state_{prefix}']
        add_button = ui_components[f'add_conditioning_button_{prefix}']
        del_button = ui_components[f'delete_conditioning_button_{prefix}']
        
        def add_row(c):
            c += 1
            return {
                count_state: c,
                rows[c - 1]: gr.update(visible=True),
                add_button: gr.update(visible=c < MAX_CONDITIONINGS),
                del_button: gr.update(visible=True),
            }

        def del_row(c):
            c -= 1
            return {
                count_state: c,
                rows[c]: gr.update(visible=False),
                prompts[c]: "",
                add_button: gr.update(visible=True),
                del_button: gr.update(visible=c > 0),
            }

        add_outputs = [count_state, add_button, del_button] + rows
        del_outputs = [count_state, add_button, del_button] + rows + prompts
        add_button.click(fn=add_row, inputs=[count_state], outputs=add_outputs, show_progress=False)
        del_button.click(fn=del_row, inputs=[count_state], outputs=del_outputs, show_progress=False)
    
    def on_vae_upload(file_obj):
        if not file_obj:
            return gr.update(), gr.update(), None
        
        hashed_filename = save_uploaded_file_with_hash(file_obj, VAE_DIR)
        return hashed_filename, "File", file_obj
    
    def on_lora_upload(file_obj):
        if not file_obj:
            return gr.update(), gr.update()
        
        hashed_filename = save_uploaded_file_with_hash(file_obj, LORA_DIR)
        return hashed_filename, "File"

    def on_embedding_upload(file_obj):
        if not file_obj:
            return gr.update(), gr.update(), None
        
        hashed_filename = save_uploaded_file_with_hash(file_obj, EMBEDDING_DIR)
        return hashed_filename, "File", file_obj


    def create_run_event(prefix: str, task_type: str):
        run_inputs_map = {
            'model_display_name': ui_components[f'base_model_{prefix}'],
            'positive_prompt': ui_components.get(f'prompt_{prefix}') or ui_components.get(f'{prefix}_positive_prompt'),
            'negative_prompt': ui_components.get(f'neg_prompt_{prefix}') or ui_components.get(f'{prefix}_negative_prompt'),
            'seed': ui_components.get(f'seed_{prefix}') or ui_components.get(f'{prefix}_seed'),
            'batch_size': ui_components.get(f'batch_size_{prefix}') or ui_components.get(f'{prefix}_batch_size'),
            'guidance_scale': ui_components.get(f'cfg_{prefix}') or ui_components.get(f'{prefix}_cfg'),
            'num_inference_steps': ui_components.get(f'steps_{prefix}') or ui_components.get(f'{prefix}_steps'),
            'sampler': ui_components.get(f'sampler_{prefix}') or ui_components.get(f'{prefix}_sampler_name'),
            'scheduler': ui_components.get(f'scheduler_{prefix}') or ui_components.get(f'{prefix}_scheduler'),
            'zero_gpu_duration': ui_components.get(f'zero_gpu_{prefix}'),

            'clip_skip': ui_components.get(f'clip_skip_{prefix}'),
            'guidance': ui_components.get(f'guidance_{prefix}'),
            'task_type': gr.State(task_type)
        }
        
        if task_type not in ['img2img', 'inpaint']:
            run_inputs_map.update({
                'width': ui_components.get(f'width_{prefix}') or ui_components.get(f'{prefix}_width'), 
                'height': ui_components.get(f'height_{prefix}') or ui_components.get(f'{prefix}_height')
            })
        
        task_specific_map = {
            'img2img': {'img2img_image': f'input_image_{prefix}', 'img2img_denoise': f'denoise_{prefix}'},
            'inpaint': {'inpaint_image_dict': f'input_image_dict_{prefix}', 'grow_mask_by': f'grow_mask_by_{prefix}'},
            'outpaint': {'outpaint_image': f'input_image_{prefix}', 'left': f'left_{prefix}', 'top': f'top_{prefix}', 'right': f'right_{prefix}', 'bottom': f'bottom_{prefix}', 'feathering': f'feathering_{prefix}'},
            'hires_fix': {'hires_image': f'input_image_{prefix}', 'hires_upscaler': f'hires_upscaler_{prefix}', 'hires_scale_by': f'hires_scale_by_{prefix}', 'hires_denoise': f'denoise_{prefix}'}
        }
        if task_type in task_specific_map:
            for key, comp_name in task_specific_map[task_type].items():
                if comp_name in ui_components:
                    run_inputs_map[key] = ui_components[comp_name]
        
        lora_data_components = ui_components.get(f'all_lora_components_flat_{prefix}', [])
        controlnet_data_components = ui_components.get(f'all_controlnet_components_flat_{prefix}', [])
        anima_controlnet_lllite_data_components = ui_components.get(f'all_anima_controlnet_lllite_components_flat_{prefix}', [])
        diffsynth_controlnet_data_components = ui_components.get(f'all_diffsynth_controlnet_components_flat_{prefix}', [])
        ipadapter_data_components = ui_components.get(f'all_ipadapter_components_flat_{prefix}', [])
        sd3_ipadapter_data_components = ui_components.get(f'all_sd3_ipadapter_components_flat_{prefix}', [])
        flux1_ipadapter_data_components = ui_components.get(f'all_flux1_ipadapter_components_flat_{prefix}', [])
        style_data_components = ui_components.get(f'all_style_components_flat_{prefix}', [])
        embedding_data_components = ui_components.get(f'all_embedding_components_flat_{prefix}', [])
        conditioning_data_components = ui_components.get(f'all_conditioning_components_flat_{prefix}', [])
        reference_latent_data_components = ui_components.get(f'all_reference_latent_components_flat_{prefix}', [])
        
        run_inputs_map['vae_source'] = ui_components.get(f'vae_source_{prefix}')
        run_inputs_map['vae_id'] = ui_components.get(f'vae_id_{prefix}')
        run_inputs_map['vae_file'] = ui_components.get(f'vae_file_{prefix}')

        input_keys = list(run_inputs_map.keys())
        input_list_flat = [v for v in run_inputs_map.values() if v is not None]
        all_chains = [
            lora_data_components, controlnet_data_components, anima_controlnet_lllite_data_components, diffsynth_controlnet_data_components, ipadapter_data_components,
            sd3_ipadapter_data_components, flux1_ipadapter_data_components, style_data_components,
            embedding_data_components, conditioning_data_components, reference_latent_data_components
        ]
        for chain in all_chains:
            if chain:
                input_list_flat.extend(chain)

        def create_ui_inputs_dict(*args):
            valid_keys = [k for k in input_keys if run_inputs_map[k] is not None]
            ui_dict = dict(zip(valid_keys, args[:len(valid_keys)]))
            arg_idx = len(valid_keys)

            def assign_chain_data(chain_key, components_list):
                nonlocal arg_idx
                if components_list:
                    ui_dict[chain_key] = list(args[arg_idx : arg_idx + len(components_list)])
                    arg_idx += len(components_list)

            assign_chain_data('lora_data', lora_data_components)
            assign_chain_data('controlnet_data', controlnet_data_components)
            assign_chain_data('anima_controlnet_lllite_data', anima_controlnet_lllite_data_components)
            assign_chain_data('diffsynth_controlnet_data', diffsynth_controlnet_data_components)
            assign_chain_data('ipadapter_data', ipadapter_data_components)
            assign_chain_data('sd3_ipadapter_chain', sd3_ipadapter_data_components)
            assign_chain_data('flux1_ipadapter_data', flux1_ipadapter_data_components)
            assign_chain_data('style_data', style_data_components)
            assign_chain_data('embedding_data', embedding_data_components)
            assign_chain_data('conditioning_data', conditioning_data_components)
            assign_chain_data('reference_latent_data', reference_latent_data_components)

            return ui_dict

        run_btn = ui_components.get(f'run_{prefix}') or ui_components.get(f'{prefix}_run_button')
        res_gal = ui_components.get(f'result_{prefix}') or ui_components.get(f'{prefix}_output_gallery')
        if run_btn and res_gal:
            run_btn.click(
                fn=lambda *args, progress=gr.Progress(track_tqdm=True): generate_image_wrapper(create_ui_inputs_dict(*args), progress),
                inputs=input_list_flat,
                outputs=[res_gal]
            )

    def make_update_fn(m_comp, cat_comp, cs_comp, ar_comp, width_comp, height_comp, cn_types, cn_series, cn_filepaths, anima_cn_types, anima_cn_series, anima_cn_filepaths, diffsynth_cn_types, diffsynth_cn_series, diffsynth_cn_filepaths, ipa_preset, lora_acc, cn_acc, anima_cn_acc, diffsynth_cn_acc, ipa_acc, sd3_ipa_acc, flux1_ipa_acc, style_acc, embed_acc, cond_acc, ref_latent_acc, guidance_comp, prompt_comp, neg_prompt_comp, steps_comp, cfg_comp, sampler_comp, scheduler_comp):
        def update_fn(*args):
            arch = args[0]
            category = args[1]
            current_ar = args[2] if len(args) > 2 else None
            from core.settings import MODEL_TYPE_MAP, MODEL_MAP_CHECKPOINT, FEATURES_CONFIG, ARCHITECTURES_CONFIG, MODEL_DEFAULTS_CONFIG, ARCH_CATEGORIES_MAP
            from utils.app_utils import get_model_generation_defaults
            
            if arch == "ALL":
                valid_cats = list(set(cat for cats in ARCH_CATEGORIES_MAP.values() for cat in cats))
            else:
                valid_cats = ARCH_CATEGORIES_MAP.get(arch, [])
            
            cat_choices = ["ALL"] + sorted(valid_cats)
            new_category = category if category in cat_choices else "ALL"

            choices = []
            for name, info in MODEL_MAP_CHECKPOINT.items():
                m_arch = info[2]
                m_cat = info[4] if len(info) > 4 else None
                arch_match = (arch == "ALL" or m_arch == arch)
                cat_match = (new_category == "ALL" or m_cat == new_category)
                if arch_match and cat_match:
                    choices.append(name)
            
            val = choices[0] if choices else None
            
            updates = {
                m_comp: gr.update(choices=choices, value=val),
                cat_comp: gr.update(choices=cat_choices, value=new_category)
            }

            m_type = MODEL_TYPE_MAP.get(val, "SDXL") if val else "SDXL"
            
            architectures_dict = ARCHITECTURES_CONFIG.get('architectures', {})
            arch_model_type = architectures_dict.get(m_type, {}).get("model_type", m_type.lower().replace(" ", "").replace(".", ""))

            arch_features = FEATURES_CONFIG.get(arch_model_type, FEATURES_CONFIG.get('default', {}))
            enabled_chains = arch_features.get('enabled_chains', [])

            if lora_acc: updates[lora_acc] = gr.update(visible=('lora' in enabled_chains))
            if cn_acc: updates[cn_acc] = gr.update(visible=('controlnet' in enabled_chains))
            if anima_cn_acc: updates[anima_cn_acc] = gr.update(visible=('anima_controlnet_lllite' in enabled_chains))
            if diffsynth_cn_acc: updates[diffsynth_cn_acc] = gr.update(visible=('controlnet_model_patch' in enabled_chains))
            if ipa_acc: updates[ipa_acc] = gr.update(visible=('ipadapter' in enabled_chains))
            if flux1_ipa_acc: updates[flux1_ipa_acc] = gr.update(visible=('flux1_ipadapter' in enabled_chains))
            if sd3_ipa_acc: updates[sd3_ipa_acc] = gr.update(visible=('sd3_ipadapter' in enabled_chains))
            if style_acc: updates[style_acc] = gr.update(visible=('style' in enabled_chains))
            if embed_acc: updates[embed_acc] = gr.update(visible=('embedding' in enabled_chains))
            if cond_acc: updates[cond_acc] = gr.update(visible=('conditioning' in enabled_chains))
            if ref_latent_acc: updates[ref_latent_acc] = gr.update(visible=('reference_latent' in enabled_chains))

            if cs_comp:
                updates[cs_comp] = gr.update(visible=(arch_model_type == "sd15"))
            if guidance_comp:
                updates[guidance_comp] = gr.update(visible=(arch_model_type == "flux1"))
            
            if ar_comp:
                res_key = arch_model_type
                if res_key not in RESOLUTION_MAP:
                    res_key = 'sdxl'
                res_map = RESOLUTION_MAP.get(res_key, {})
                target_ar = current_ar if current_ar in res_map else (list(res_map.keys())[0] if res_map else "1:1 (Square)")
                updates[ar_comp] = gr.update(choices=list(res_map.keys()), value=target_ar)
                if width_comp and height_comp and target_ar in res_map:
                    updates[width_comp] = gr.update(value=res_map[target_ar][0])
                    updates[height_comp] = gr.update(value=res_map[target_ar][1])
            
            controlnet_key = architectures_dict.get(m_type, {}).get("controlnet_key", m_type)
            
            all_types, default_type, series_choices, default_series, filepath = get_cn_defaults(controlnet_key)
            for t_comp in cn_types:
                updates[t_comp] = gr.update(choices=all_types, value=default_type)
            for s_comp in cn_series:
                updates[s_comp] = gr.update(choices=series_choices, value=default_series)
            for f_comp in cn_filepaths:
                updates[f_comp] = filepath

            anima_all_types, anima_default_type, anima_series_choices, anima_default_series, anima_filepath = get_anima_cn_defaults()
            for t_comp in anima_cn_types:
                updates[t_comp] = gr.update(choices=anima_all_types, value=anima_default_type)
            for s_comp in anima_cn_series:
                updates[s_comp] = gr.update(choices=anima_series_choices, value=anima_default_series)
            for f_comp in anima_cn_filepaths:
                updates[f_comp] = anima_filepath
                
            diffsynth_all_types, diffsynth_default_type, diffsynth_series_choices, diffsynth_default_series, diffsynth_filepath = get_diffsynth_cn_defaults(controlnet_key)
            for t_comp in diffsynth_cn_types:
                updates[t_comp] = gr.update(choices=diffsynth_all_types, value=diffsynth_default_type)
            for s_comp in diffsynth_cn_series:
                updates[s_comp] = gr.update(choices=diffsynth_series_choices, value=diffsynth_default_series)
            for f_comp in diffsynth_cn_filepaths:
                updates[f_comp] = diffsynth_filepath
            
            if ipa_preset and (arch_model_type in ["sdxl", "sd15", "sd35"]):
                config = load_ipadapter_config()
                ipa_arch_key = "SDXL" if arch_model_type in ["sdxl", "sd35"] else "SD1.5"
                std_presets = config.get("IPAdapter_presets", {}).get(ipa_arch_key, [])
                face_presets = config.get("IPAdapter_FaceID_presets", {}).get(ipa_arch_key, [])
                all_ipa_presets = std_presets + face_presets
                default_ipa = all_ipa_presets[0] if all_ipa_presets else None
                updates[ipa_preset] = gr.update(choices=all_ipa_presets, value=default_ipa)
            
            defaults = get_model_generation_defaults(val, arch_model_type, MODEL_DEFAULTS_CONFIG)
            if steps_comp: updates[steps_comp] = gr.update(value=defaults.get('steps'))
            if cfg_comp: updates[cfg_comp] = gr.update(value=defaults.get('cfg'))
            if sampler_comp: updates[sampler_comp] = gr.update(value=defaults.get('sampler_name'))
            if scheduler_comp: updates[scheduler_comp] = gr.update(value=defaults.get('scheduler'))
            if prompt_comp: updates[prompt_comp] = gr.update(value=defaults.get('positive_prompt'))
            if neg_prompt_comp: updates[neg_prompt_comp] = gr.update(value=defaults.get('negative_prompt'))
                
            return updates
        return update_fn

    def make_model_change_fn(cat_comp_ref, cs_comp, ar_comp, width_comp, height_comp, cn_types, cn_series, cn_filepaths, anima_cn_types, anima_cn_series, anima_cn_filepaths, diffsynth_cn_types, diffsynth_cn_series, diffsynth_cn_filepaths, arch_comp_ref, ipa_preset, lora_acc, cn_acc, anima_cn_acc, diffsynth_cn_acc, ipa_acc, sd3_ipa_acc, flux1_ipa_acc, style_acc, embed_acc, cond_acc, ref_latent_acc, guidance_comp, prompt_comp, neg_prompt_comp, steps_comp, cfg_comp, sampler_comp, scheduler_comp):
        def change_fn(*args):
            model_name = args[0]
            idx = 1
            current_arch = args[idx] if arch_comp_ref and idx < len(args) else None
            if arch_comp_ref: idx += 1
            current_cat = args[idx] if cat_comp_ref and idx < len(args) else None
            if cat_comp_ref: idx += 1
            current_ar = args[idx] if idx < len(args) else None
            from core.settings import MODEL_TYPE_MAP, FEATURES_CONFIG, ARCHITECTURES_CONFIG, MODEL_DEFAULTS_CONFIG, ARCH_CATEGORIES_MAP, MODEL_MAP_CHECKPOINT
            from utils.app_utils import get_model_generation_defaults
            m_type = MODEL_TYPE_MAP.get(model_name, "SDXL")
            
            m_info = MODEL_MAP_CHECKPOINT.get(model_name)
            m_cat = m_info[4] if m_info and len(m_info) > 4 else None
            if not m_cat: m_cat = "ALL"
            
            updates = {}
            target_arch = m_type
            if arch_comp_ref:
                if current_arch == "ALL":
                    updates[arch_comp_ref] = gr.update()
                    target_arch = "ALL"
                else:
                    updates[arch_comp_ref] = m_type
                    
            if cat_comp_ref:
                if target_arch == "ALL":
                    valid_cats = list(set(cat for cats in ARCH_CATEGORIES_MAP.values() for cat in cats))
                else:
                    valid_cats = ARCH_CATEGORIES_MAP.get(target_arch, [])
                cat_choices = ["ALL"] + sorted(valid_cats)
                
                if current_cat == "ALL":
                    updates[cat_comp_ref] = gr.update(choices=cat_choices)
                else:
                    updates[cat_comp_ref] = gr.update(choices=cat_choices, value=m_cat)
            
            architectures_dict = ARCHITECTURES_CONFIG.get('architectures', {})
            arch_model_type = architectures_dict.get(m_type, {}).get("model_type", m_type.lower().replace(" ", "").replace(".", ""))

            arch_features = FEATURES_CONFIG.get(arch_model_type, FEATURES_CONFIG.get('default', {}))
            enabled_chains = arch_features.get('enabled_chains', [])

            if lora_acc: updates[lora_acc] = gr.update(visible=('lora' in enabled_chains))
            if cn_acc: updates[cn_acc] = gr.update(visible=('controlnet' in enabled_chains))
            if anima_cn_acc: updates[anima_cn_acc] = gr.update(visible=('anima_controlnet_lllite' in enabled_chains))
            if diffsynth_cn_acc: updates[diffsynth_cn_acc] = gr.update(visible=('controlnet_model_patch' in enabled_chains))
            if ipa_acc: updates[ipa_acc] = gr.update(visible=('ipadapter' in enabled_chains))
            if flux1_ipa_acc: updates[flux1_ipa_acc] = gr.update(visible=('flux1_ipadapter' in enabled_chains))
            if sd3_ipa_acc: updates[sd3_ipa_acc] = gr.update(visible=('sd3_ipadapter' in enabled_chains))
            if style_acc: updates[style_acc] = gr.update(visible=('style' in enabled_chains))
            if embed_acc: updates[embed_acc] = gr.update(visible=('embedding' in enabled_chains))
            if cond_acc: updates[cond_acc] = gr.update(visible=('conditioning' in enabled_chains))
            if ref_latent_acc: updates[ref_latent_acc] = gr.update(visible=('reference_latent' in enabled_chains))

            if cs_comp:
                updates[cs_comp] = gr.update(visible=(arch_model_type == "sd15"))
            if guidance_comp:
                updates[guidance_comp] = gr.update(visible=(arch_model_type == "flux1"))
            
            if ar_comp:
                res_key = arch_model_type
                if res_key not in RESOLUTION_MAP:
                    res_key = 'sdxl'
                res_map = RESOLUTION_MAP.get(res_key, {})
                target_ar = current_ar if current_ar in res_map else (list(res_map.keys())[0] if res_map else "1:1 (Square)")
                updates[ar_comp] = gr.update(choices=list(res_map.keys()), value=target_ar)
                if width_comp and height_comp and target_ar in res_map:
                    updates[width_comp] = gr.update(value=res_map[target_ar][0])
                    updates[height_comp] = gr.update(value=res_map[target_ar][1])
            
            controlnet_key = architectures_dict.get(m_type, {}).get("controlnet_key", m_type)
            
            all_types, default_type, series_choices, default_series, filepath = get_cn_defaults(controlnet_key)
            for t_comp in cn_types:
                updates[t_comp] = gr.update(choices=all_types, value=default_type)
            for s_comp in cn_series:
                updates[s_comp] = gr.update(choices=series_choices, value=default_series)
            for f_comp in cn_filepaths:
                updates[f_comp] = filepath

            anima_all_types, anima_default_type, anima_series_choices, anima_default_series, anima_filepath = get_anima_cn_defaults()
            for t_comp in anima_cn_types:
                updates[t_comp] = gr.update(choices=anima_all_types, value=anima_default_type)
            for s_comp in anima_cn_series:
                updates[s_comp] = gr.update(choices=anima_series_choices, value=anima_default_series)
            for f_comp in anima_cn_filepaths:
                updates[f_comp] = anima_filepath
                
            diffsynth_all_types, diffsynth_default_type, diffsynth_series_choices, diffsynth_default_series, diffsynth_filepath = get_diffsynth_cn_defaults(controlnet_key)
            for t_comp in diffsynth_cn_types:
                updates[t_comp] = gr.update(choices=diffsynth_all_types, value=diffsynth_default_type)
            for s_comp in diffsynth_cn_series:
                updates[s_comp] = gr.update(choices=diffsynth_series_choices, value=diffsynth_default_series)
            for f_comp in diffsynth_cn_filepaths:
                updates[f_comp] = diffsynth_filepath
            
            if ipa_preset and (arch_model_type in ["sdxl", "sd15", "sd35"]):
                config = load_ipadapter_config()
                ipa_arch_key = "SDXL" if arch_model_type in ["sdxl", "sd35"] else "SD1.5"
                std_presets = config.get("IPAdapter_presets", {}).get(ipa_arch_key, [])
                face_presets = config.get("IPAdapter_FaceID_presets", {}).get(ipa_arch_key, [])
                all_ipa_presets = std_presets + face_presets
                default_ipa = all_ipa_presets[0] if all_ipa_presets else None
                updates[ipa_preset] = gr.update(choices=all_ipa_presets, value=default_ipa)
            
            defaults = get_model_generation_defaults(model_name, arch_model_type, MODEL_DEFAULTS_CONFIG)
            if steps_comp: updates[steps_comp] = gr.update(value=defaults.get('steps'))
            if cfg_comp: updates[cfg_comp] = gr.update(value=defaults.get('cfg'))
            if sampler_comp: updates[sampler_comp] = gr.update(value=defaults.get('sampler_name'))
            if scheduler_comp: updates[scheduler_comp] = gr.update(value=defaults.get('scheduler'))
            if prompt_comp: updates[prompt_comp] = gr.update(value=defaults.get('positive_prompt'))
            if neg_prompt_comp: updates[neg_prompt_comp] = gr.update(value=defaults.get('negative_prompt'))
                
            return updates
        return change_fn


    for prefix, task_type in [
        ("txt2img", "txt2img"), ("img2img", "img2img"), ("inpaint", "inpaint"),
        ("outpaint", "outpaint"), ("hires_fix", "hires_fix"),
    ]:

        arch_comp = ui_components.get(f'model_arch_{prefix}')
        cat_comp = ui_components.get(f'model_cat_{prefix}')
        model_comp = ui_components.get(f'base_model_{prefix}')
        clip_skip_comp = ui_components.get(f'clip_skip_{prefix}') or ui_components.get(f'{prefix}_clip_skip')
        guidance_comp = ui_components.get(f'guidance_{prefix}') or ui_components.get(f'{prefix}_guidance')
        aspect_ratio_comp = ui_components.get(f'aspect_ratio_{prefix}') or ui_components.get(f'{prefix}_aspect_ratio_dropdown')
        width_comp = ui_components.get(f'width_{prefix}') or ui_components.get(f'{prefix}_width')
        height_comp = ui_components.get(f'height_{prefix}') or ui_components.get(f'{prefix}_height')
        
        cn_types_list = ui_components.get(f'controlnet_types_{prefix}', [])
        cn_series_list = ui_components.get(f'controlnet_series_{prefix}', [])
        cn_filepaths_list = ui_components.get(f'controlnet_filepaths_{prefix}', [])
        
        anima_cn_types_list = ui_components.get(f'anima_controlnet_lllite_types_{prefix}', [])
        anima_cn_series_list = ui_components.get(f'anima_controlnet_lllite_series_{prefix}', [])
        anima_cn_filepaths_list = ui_components.get(f'anima_controlnet_lllite_filepaths_{prefix}', [])

        diffsynth_cn_types_list = ui_components.get(f'diffsynth_controlnet_types_{prefix}', [])
        diffsynth_cn_series_list = ui_components.get(f'diffsynth_controlnet_series_{prefix}', [])
        diffsynth_cn_filepaths_list = ui_components.get(f'diffsynth_controlnet_filepaths_{prefix}', [])
        
        lora_accordion = ui_components.get(f'lora_accordion_{prefix}')
        cn_accordion = ui_components.get(f'controlnet_accordion_{prefix}')
        anima_cn_accordion = ui_components.get(f'anima_controlnet_lllite_accordion_{prefix}')
        diffsynth_cn_accordion = ui_components.get(f'diffsynth_controlnet_accordion_{prefix}')
        ipa_accordion = ui_components.get(f'ipadapter_accordion_{prefix}')
        sd3_ipa_accordion = ui_components.get(f'sd3_ipadapter_accordion_{prefix}')
        flux1_ipa_accordion = ui_components.get(f'flux1_ipadapter_accordion_{prefix}')
        style_accordion = ui_components.get(f'style_accordion_{prefix}')
        embedding_accordion = ui_components.get(f'embedding_accordion_{prefix}')
        conditioning_accordion = ui_components.get(f'conditioning_accordion_{prefix}')
        ref_latent_accordion = ui_components.get(f'reference_latent_accordion_{prefix}')
        
        ipa_preset_list = ui_components.get(f'ipadapter_final_preset_{prefix}')
        
        prompt_comp = ui_components.get(f'prompt_{prefix}') or ui_components.get(f'{prefix}_positive_prompt')
        neg_prompt_comp = ui_components.get(f'neg_prompt_{prefix}') or ui_components.get(f'{prefix}_negative_prompt')
        steps_comp = ui_components.get(f'steps_{prefix}') or ui_components.get(f'{prefix}_steps')
        cfg_comp = ui_components.get(f'cfg_{prefix}') or ui_components.get(f'{prefix}_cfg')
        sampler_comp = ui_components.get(f'sampler_{prefix}') or ui_components.get(f'{prefix}_sampler_name')
        scheduler_comp = ui_components.get(f'scheduler_{prefix}') or ui_components.get(f'{prefix}_scheduler')
        
        extra_comps = [prompt_comp, neg_prompt_comp, steps_comp, cfg_comp, sampler_comp, scheduler_comp, width_comp, height_comp]
        valid_extra_comps = [c for c in extra_comps if c is not None]
        
        if arch_comp and cat_comp and model_comp:
            outputs = [model_comp, cat_comp]
            if clip_skip_comp: outputs.append(clip_skip_comp)
            if guidance_comp: outputs.append(guidance_comp)
            if aspect_ratio_comp: outputs.append(aspect_ratio_comp)
            outputs.extend(cn_types_list + cn_series_list + cn_filepaths_list)
            outputs.extend(anima_cn_types_list + anima_cn_series_list + anima_cn_filepaths_list)
            outputs.extend(diffsynth_cn_types_list + diffsynth_cn_series_list + diffsynth_cn_filepaths_list)
            if lora_accordion: outputs.append(lora_accordion)
            if cn_accordion: outputs.append(cn_accordion)
            if anima_cn_accordion: outputs.append(anima_cn_accordion)
            if diffsynth_cn_accordion: outputs.append(diffsynth_cn_accordion)
            if ipa_accordion: outputs.append(ipa_accordion)
            if sd3_ipa_accordion: outputs.append(sd3_ipa_accordion)
            if flux1_ipa_accordion: outputs.append(flux1_ipa_accordion)
            if style_accordion: outputs.append(style_accordion)
            if embedding_accordion: outputs.append(embedding_accordion)
            if conditioning_accordion: outputs.append(conditioning_accordion)
            if ref_latent_accordion: outputs.append(ref_latent_accordion)
            if ipa_preset_list: outputs.append(ipa_preset_list)
            
            outputs.extend(valid_extra_comps)
            
            update_fn = make_update_fn(
                model_comp, cat_comp, clip_skip_comp, aspect_ratio_comp, width_comp, height_comp, 
                cn_types_list, cn_series_list, cn_filepaths_list, 
                anima_cn_types_list, anima_cn_series_list, anima_cn_filepaths_list,
                diffsynth_cn_types_list, diffsynth_cn_series_list, diffsynth_cn_filepaths_list, 
                ipa_preset_list, lora_accordion, cn_accordion, anima_cn_accordion, diffsynth_cn_accordion, ipa_accordion, sd3_ipa_accordion, flux1_ipa_accordion, style_accordion, embedding_accordion, conditioning_accordion,
                ref_latent_accordion, guidance_comp, prompt_comp, neg_prompt_comp, steps_comp, cfg_comp, sampler_comp, scheduler_comp
            )
            inputs = [arch_comp, cat_comp]
            if aspect_ratio_comp:
                inputs.append(aspect_ratio_comp)
            arch_comp.change(fn=update_fn, inputs=inputs, outputs=outputs)
            cat_comp.change(fn=update_fn, inputs=inputs, outputs=outputs)

        if model_comp:
            outputs2 = []
            if arch_comp: outputs2.append(arch_comp)
            if cat_comp: outputs2.append(cat_comp)
            if clip_skip_comp: outputs2.append(clip_skip_comp)
            if guidance_comp: outputs2.append(guidance_comp)
            if aspect_ratio_comp: outputs2.append(aspect_ratio_comp)
            outputs2.extend(cn_types_list + cn_series_list + cn_filepaths_list)
            outputs2.extend(anima_cn_types_list + anima_cn_series_list + anima_cn_filepaths_list)
            outputs2.extend(diffsynth_cn_types_list + diffsynth_cn_series_list + diffsynth_cn_filepaths_list)
            if lora_accordion: outputs2.append(lora_accordion)
            if cn_accordion: outputs2.append(cn_accordion)
            if anima_cn_accordion: outputs2.append(anima_cn_accordion)
            if diffsynth_cn_accordion: outputs2.append(diffsynth_cn_accordion)
            if ipa_accordion: outputs2.append(ipa_accordion)
            if sd3_ipa_accordion: outputs2.append(sd3_ipa_accordion)
            if flux1_ipa_accordion: outputs2.append(flux1_ipa_accordion)
            if style_accordion: outputs2.append(style_accordion)
            if embedding_accordion: outputs2.append(embedding_accordion)
            if conditioning_accordion: outputs2.append(conditioning_accordion)
            if ref_latent_accordion: outputs2.append(ref_latent_accordion)
            if ipa_preset_list: outputs2.append(ipa_preset_list)
            
            outputs2.extend(valid_extra_comps)
            
            if outputs2:
                inputs2 = [model_comp]
                if arch_comp: inputs2.append(arch_comp)
                if cat_comp: inputs2.append(cat_comp)
                if aspect_ratio_comp: inputs2.append(aspect_ratio_comp)
                change_fn = make_model_change_fn(
                    cat_comp, clip_skip_comp, aspect_ratio_comp, width_comp, height_comp, 
                    cn_types_list, cn_series_list, cn_filepaths_list, 
                    anima_cn_types_list, anima_cn_series_list, anima_cn_filepaths_list,
                    diffsynth_cn_types_list, diffsynth_cn_series_list, diffsynth_cn_filepaths_list, 
                    arch_comp, ipa_preset_list, lora_accordion, cn_accordion, anima_cn_accordion, diffsynth_cn_accordion, ipa_accordion, sd3_ipa_accordion, flux1_ipa_accordion, style_accordion, embedding_accordion, conditioning_accordion,
                    ref_latent_accordion, guidance_comp, prompt_comp, neg_prompt_comp, steps_comp, cfg_comp, sampler_comp, scheduler_comp
                )
                model_comp.change(fn=change_fn, inputs=inputs2, outputs=outputs2)

        create_lora_event_handlers(prefix)
        create_controlnet_event_handlers(prefix)
        create_anima_controlnet_lllite_event_handlers(prefix)
        create_diffsynth_controlnet_event_handlers(prefix)
        create_ipadapter_event_handlers(prefix)
        create_embedding_event_handlers(prefix)
        create_conditioning_event_handlers(prefix)
        create_flux1_ipadapter_event_handlers(prefix)
        create_style_event_handlers(prefix)
        create_reference_latent_event_handlers(prefix)
        create_run_event(prefix, task_type)


    if 'view_mode_inpaint' in ui_components:
        def toggle_inpaint_fullscreen_view(view_mode):
            is_fullscreen = (view_mode == "Fullscreen View")
            other_elements_visible = not is_fullscreen
            editor_height = 800 if is_fullscreen else 272
            
            updates = {
                ui_components['prompts_column_inpaint']: gr.update(visible=other_elements_visible),
                ui_components['params_and_gallery_row_inpaint']: gr.update(visible=other_elements_visible),
                ui_components['accordion_wrapper_inpaint']: gr.update(visible=other_elements_visible),
                ui_components['input_image_dict_inpaint']: gr.update(height=editor_height),
            }
            
            model_and_run_rows = ui_components.get('model_and_run_row_inpaint', [])
            for row in model_and_run_rows:
                updates[row] = gr.update(visible=other_elements_visible)
            
            return updates
        
        output_components = []
        model_and_run_rows = ui_components.get('model_and_run_row_inpaint', [])
        if isinstance(model_and_run_rows, list):
            output_components.extend(model_and_run_rows)
        else:
            output_components.append(model_and_run_rows)
        
        output_components.extend([
            ui_components['prompts_column_inpaint'],
            ui_components['params_and_gallery_row_inpaint'], 
            ui_components['accordion_wrapper_inpaint'],
            ui_components['input_image_dict_inpaint']
        ])
        
        ui_components['view_mode_inpaint'].change(
            fn=toggle_inpaint_fullscreen_view, 
            inputs=[ui_components['view_mode_inpaint']], 
            outputs=output_components, 
            show_progress=False
        )

    def initialize_all_cn_dropdowns():
        from core.settings import MODEL_TYPE_MAP, MODEL_MAP_CHECKPOINT, ARCHITECTURES_CONFIG
        default_model_name = list(MODEL_MAP_CHECKPOINT.keys())[0] if MODEL_MAP_CHECKPOINT else None
        default_m_type = MODEL_TYPE_MAP.get(default_model_name, "SDXL") if default_model_name else "SDXL"
        architectures_dict = ARCHITECTURES_CONFIG.get('architectures', {})
        controlnet_key = architectures_dict.get(default_m_type, {}).get("controlnet_key", default_m_type)
        
        all_types, default_type, series_choices, default_series, filepath = get_cn_defaults(controlnet_key)
        anima_all_types, anima_default_type, anima_series_choices, anima_default_series, anima_filepath = get_anima_cn_defaults()
        diffsynth_all_types, diffsynth_default_type, diffsynth_series_choices, diffsynth_default_series, diffsynth_filepath = get_diffsynth_cn_defaults(controlnet_key)
        
        updates = {}
        for prefix in ["txt2img", "img2img", "inpaint", "outpaint", "hires_fix"]:
            if f'controlnet_types_{prefix}' in ui_components:
                for type_dd in ui_components[f'controlnet_types_{prefix}']:
                    updates[type_dd] = gr.update(choices=all_types, value=default_type)
                for series_dd in ui_components[f'controlnet_series_{prefix}']:
                    updates[series_dd] = gr.update(choices=series_choices, value=default_series)
                for filepath_state in ui_components[f'controlnet_filepaths_{prefix}']:
                    updates[filepath_state] = filepath

            if f'anima_controlnet_lllite_types_{prefix}' in ui_components:
                for type_dd in ui_components[f'anima_controlnet_lllite_types_{prefix}']:
                    updates[type_dd] = gr.update(choices=anima_all_types, value=anima_default_type)
                for series_dd in ui_components[f'anima_controlnet_lllite_series_{prefix}']:
                    updates[series_dd] = gr.update(choices=anima_series_choices, value=anima_default_series)
                for filepath_state in ui_components[f'anima_controlnet_lllite_filepaths_{prefix}']:
                    updates[filepath_state] = anima_filepath
            
            if f'diffsynth_controlnet_types_{prefix}' in ui_components:
                for type_dd in ui_components[f'diffsynth_controlnet_types_{prefix}']:
                    updates[type_dd] = gr.update(choices=diffsynth_all_types, value=diffsynth_default_type)
                for series_dd in ui_components[f'diffsynth_controlnet_series_{prefix}']:
                    updates[series_dd] = gr.update(choices=diffsynth_series_choices, value=diffsynth_default_series)
                for filepath_state in ui_components[f'diffsynth_controlnet_filepaths_{prefix}']:
                    updates[filepath_state] = diffsynth_filepath
                    
        return updates

    def initialize_all_ipa_dropdowns():
        config = load_ipadapter_config()
        if not config: return {}
        
        from core.settings import MODEL_TYPE_MAP, MODEL_MAP_CHECKPOINT, ARCHITECTURES_CONFIG
        default_model_name = list(MODEL_MAP_CHECKPOINT.keys())[0] if MODEL_MAP_CHECKPOINT else None
        default_m_type = MODEL_TYPE_MAP.get(default_model_name, "SDXL") if default_model_name else "SDXL"
        architectures_dict = ARCHITECTURES_CONFIG.get('architectures', {})
        arch_model_type = architectures_dict.get(default_m_type, {}).get("model_type", default_m_type.lower().replace(" ", "").replace(".", ""))
        ipa_arch_key = "SDXL" if arch_model_type in ["sdxl", "sd35"] else "SD1.5"

        unified_presets = config.get("IPAdapter_presets", {}).get(ipa_arch_key, [])
        faceid_presets = config.get("IPAdapter_FaceID_presets", {}).get(ipa_arch_key, [])
        
        all_presets = unified_presets + faceid_presets
        default_preset = all_presets[0] if all_presets else None
        is_faceid_default = default_preset in faceid_presets

        lora_strength_update = gr.update(visible=is_faceid_default)
        
        updates = {}
        for prefix in ["txt2img", "img2img", "inpaint", "outpaint", "hires_fix"]:
            if f'ipadapter_final_preset_{prefix}' in ui_components:
                for lora_strength_slider in ui_components[f'ipadapter_lora_strengths_{prefix}']:
                    updates[lora_strength_slider] = lora_strength_update
                updates[ui_components[f'ipadapter_final_preset_{prefix}']] = gr.update(choices=all_presets, value=default_preset)
                updates[ui_components[f'ipadapter_final_lora_strength_{prefix}']] = lora_strength_update
        return updates

    def run_on_load():
        cn_updates = initialize_all_cn_dropdowns()
        ipa_updates = initialize_all_ipa_dropdowns()
        
        all_updates = {**cn_updates, **ipa_updates}
        
        return all_updates
    
    all_load_outputs = []
    for prefix in ["txt2img", "img2img", "inpaint", "outpaint", "hires_fix"]:
        if f'controlnet_types_{prefix}' in ui_components:
            all_load_outputs.extend(ui_components[f'controlnet_types_{prefix}'])
            all_load_outputs.extend(ui_components[f'controlnet_series_{prefix}'])
            all_load_outputs.extend(ui_components[f'controlnet_filepaths_{prefix}'])
        if f'anima_controlnet_lllite_types_{prefix}' in ui_components:
            all_load_outputs.extend(ui_components[f'anima_controlnet_lllite_types_{prefix}'])
            all_load_outputs.extend(ui_components[f'anima_controlnet_lllite_series_{prefix}'])
            all_load_outputs.extend(ui_components[f'anima_controlnet_lllite_filepaths_{prefix}'])
        if f'diffsynth_controlnet_types_{prefix}' in ui_components:
            all_load_outputs.extend(ui_components[f'diffsynth_controlnet_types_{prefix}'])
            all_load_outputs.extend(ui_components[f'diffsynth_controlnet_series_{prefix}'])
            all_load_outputs.extend(ui_components[f'diffsynth_controlnet_filepaths_{prefix}'])
        if f'ipadapter_final_preset_{prefix}' in ui_components:
            all_load_outputs.extend(ui_components[f'ipadapter_lora_strengths_{prefix}'])
            all_load_outputs.append(ui_components[f'ipadapter_final_preset_{prefix}'])
            all_load_outputs.append(ui_components[f'ipadapter_final_lora_strength_{prefix}'])

    if all_load_outputs:
        demo.load(
            fn=run_on_load,
            outputs=all_load_outputs
        )

    def on_aspect_ratio_change(ratio_key, model_display_name):
        from core.settings import MODEL_TYPE_MAP, ARCHITECTURES_CONFIG
        m_type = MODEL_TYPE_MAP.get(model_display_name, 'SDXL')
        architectures_dict = ARCHITECTURES_CONFIG.get('architectures', {})
        arch_model_type = architectures_dict.get(m_type, {}).get("model_type", m_type.lower().replace(" ", "").replace(".", ""))
        
        res_map = RESOLUTION_MAP.get(arch_model_type, RESOLUTION_MAP.get("sdxl", {}))
        w, h = res_map.get(ratio_key, (1024, 1024))
        return w, h

    for prefix in ["txt2img", "img2img", "inpaint", "outpaint", "hires_fix"]:
        aspect_ratio_dropdown = ui_components.get(f'aspect_ratio_{prefix}') or ui_components.get(f'{prefix}_aspect_ratio_dropdown')
        width_component = ui_components.get(f'width_{prefix}') or ui_components.get(f'{prefix}_width')
        height_component = ui_components.get(f'height_{prefix}') or ui_components.get(f'{prefix}_height')
        model_dropdown = ui_components.get(f'base_model_{prefix}')
        if aspect_ratio_dropdown and width_component and height_component and model_dropdown:
            aspect_ratio_dropdown.change(fn=on_aspect_ratio_change, inputs=[aspect_ratio_dropdown, model_dropdown], outputs=[width_component, height_component], show_progress=False)