File size: 85,061 Bytes
1f7ffd5
 
 
 
 
 
 
 
 
f5d659d
1f7ffd5
5b5b5fe
 
1f7ffd5
 
 
 
 
18e10c2
1f7ffd5
 
 
 
18e10c2
1f7ffd5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18e10c2
1f7ffd5
 
 
 
18e10c2
 
 
 
1f7ffd5
 
 
 
 
 
 
 
 
 
 
18e10c2
 
 
 
 
 
 
 
 
1f7ffd5
 
67c7b1f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18e10c2
 
1f7ffd5
 
 
18e10c2
1f7ffd5
 
 
 
 
 
18e10c2
1318560
cee611a
 
 
 
 
 
 
1f7ffd5
18e10c2
 
 
1f7ffd5
18e10c2
1318560
18e10c2
1318560
515964d
e173e7b
515964d
e173e7b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
515964d
e173e7b
515964d
e173e7b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18e10c2
6587064
18e10c2
6587064
 
 
18e10c2
 
 
 
 
 
6587064
18e10c2
 
6587064
18e10c2
6587064
 
 
 
18e10c2
 
 
 
 
 
 
 
 
 
6587064
 
18e10c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6587064
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18e10c2
 
 
 
 
 
1f7ffd5
1318560
18e10c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e173e7b
18e10c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1f7ffd5
 
18e10c2
 
 
 
 
 
 
 
 
1f7ffd5
 
18e10c2
 
 
 
 
 
 
 
 
 
 
1f7ffd5
 
18e10c2
 
 
1f7ffd5
 
18e10c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1f7ffd5
 
18e10c2
 
 
 
 
 
 
 
 
 
 
1f7ffd5
 
18e10c2
 
 
1f7ffd5
 
1318560
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e173e7b
1318560
 
 
 
 
 
e173e7b
1318560
e173e7b
18e10c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e173e7b
18e10c2
 
 
 
 
 
 
 
 
 
 
 
6587064
18e10c2
6587064
 
18e10c2
 
 
 
 
6587064
18e10c2
 
6587064
18e10c2
 
 
6587064
18e10c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6587064
18e10c2
1318560
18e10c2
 
 
 
 
 
 
 
 
6587064
18e10c2
 
 
 
 
 
6587064
18e10c2
1318560
18e10c2
 
 
 
 
 
 
 
 
5b5b5fe
 
 
 
6587064
5b5b5fe
515964d
 
 
 
5b5b5fe
 
515964d
 
 
 
 
 
 
 
 
 
6587064
18e10c2
 
 
 
 
 
 
 
5b5b5fe
18e10c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e173e7b
 
 
 
 
18e10c2
 
1318560
18e10c2
1318560
18e10c2
 
 
 
 
1318560
18e10c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5b5b5fe
18e10c2
 
 
 
 
 
 
 
 
 
 
1318560
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1f7ffd5
1318560
 
 
 
 
e173e7b
1318560
 
 
 
 
 
 
e173e7b
1318560
1f7ffd5
1318560
 
1f7ffd5
 
 
d88a980
1f7ffd5
d88a980
18e10c2
d88a980
 
 
 
 
cee611a
d88a980
e173e7b
4bc2b89
18e10c2
e173e7b
 
18e10c2
4bc2b89
7a24597
18e10c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e173e7b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18e10c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1318560
 
 
 
 
 
 
e173e7b
 
 
 
 
 
 
1318560
 
 
 
 
 
 
 
 
 
 
 
e173e7b
1318560
 
 
18e10c2
 
 
 
 
 
 
 
 
 
 
e173e7b
 
 
 
 
 
 
 
18e10c2
 
 
515964d
e173e7b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1f7ffd5
7a24597
18e10c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3351453
18e10c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
515964d
18e10c2
4b1e9b9
1f7ffd5
18e10c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e173e7b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18e10c2
 
 
 
 
1318560
18e10c2
1318560
18e10c2
 
 
 
 
 
 
1318560
18e10c2
 
 
 
 
 
 
1318560
18e10c2
1318560
18e10c2
 
 
 
 
 
 
1318560
18e10c2
1318560
18e10c2
 
 
 
 
 
 
 
 
 
1318560
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18e10c2
 
 
1318560
18e10c2
 
 
 
 
 
1318560
18e10c2
e173e7b
18e10c2
 
 
515964d
 
e173e7b
 
 
 
 
515964d
 
 
 
1318560
515964d
1318560
515964d
 
 
 
 
 
 
 
 
 
 
 
 
1318560
515964d
1318560
515964d
 
 
 
 
1318560
515964d
1318560
515964d
 
 
 
 
 
1318560
515964d
 
 
 
 
 
1318560
515964d
1318560
515964d
 
 
 
 
e173e7b
515964d
e173e7b
515964d
 
18e10c2
 
 
 
 
 
 
 
 
 
 
e173e7b
 
 
 
 
 
 
 
18e10c2
 
 
515964d
e173e7b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18e10c2
d88a980
18e10c2
 
 
e173e7b
18e10c2
 
e173e7b
 
 
 
18e10c2
 
 
 
 
 
e173e7b
 
 
 
18e10c2
 
 
 
 
 
e173e7b
 
 
 
18e10c2
 
 
 
 
 
e173e7b
 
 
 
18e10c2
 
 
 
 
 
e173e7b
 
 
 
18e10c2
 
 
 
 
 
e173e7b
 
 
 
18e10c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3351453
18e10c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
515964d
edb13a9
18e10c2
1f7ffd5
18e10c2
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
import os
import random
import sys
from typing import Sequence, Mapping, Any, Union
import torch
import gradio as gr
from PIL import Image
import numpy as np

import spaces

# Import FreeU for quality improvements
from comfy_extras.nodes_freelunch import FreeU_V2

from huggingface_hub import hf_hub_download

hf_hub_download(repo_id="stable-diffusion-v1-5/stable-diffusion-v1-5", filename="v1-5-pruned-emaonly.ckpt", local_dir="models/checkpoints")
hf_hub_download(repo_id="Lykon/DreamShaper", filename="DreamShaper_3.32_baked_vae_clip_fix_half.safetensors", local_dir="models/checkpoints")
hf_hub_download(repo_id="Lykon/DreamShaper", filename="DreamShaper_6.31_BakedVae_pruned.safetensors", local_dir="models/checkpoints")
hf_hub_download(repo_id="latentcat/latentcat-controlnet", filename="models/control_v1p_sd15_brightness.safetensors", local_dir="models/controlnet")
hf_hub_download(repo_id="comfyanonymous/ControlNet-v1-1_fp16_safetensors", filename="control_v11f1e_sd15_tile_fp16.safetensors", local_dir="models/controlnet")
hf_hub_download(repo_id="Lykon/dreamshaper-7", filename="vae/diffusion_pytorch_model.fp16.safetensors", local_dir="models")
hf_hub_download(repo_id="stabilityai/sd-vae-ft-mse-original", filename="vae-ft-mse-840000-ema-pruned.safetensors", local_dir="models/vae")
hf_hub_download(repo_id="lllyasviel/Annotators", filename="RealESRGAN_x4plus.pth", local_dir="models/upscale_models")

def get_value_at_index(obj: Union[Sequence, Mapping], index: int) -> Any:
    """Returns the value at the given index of a sequence or mapping.

    If the object is a sequence (like list or string), returns the value at the given index.
    If the object is a mapping (like a dictionary), returns the value at the index-th key.

    Some return a dictionary, in these cases, we look for the "results" key

    Args:
        obj (Union[Sequence, Mapping]): The object to retrieve the value from.
        index (int): The index of the value to retrieve.

    Returns:
        Any: The value at the given index.

    Raises:
        IndexError: If the index is out of bounds for the object and the object is not a mapping.
    """
    try:
        return obj[index]
    except KeyError:
        return obj["result"][index]


def find_path(name: str, path: str = None) -> str:
    """
    Recursively looks at parent folders starting from the given path until it finds the given name.
    Returns the path as a Path object if found, or None otherwise.
    """
    # If no path is given, use the current working directory
    if path is None:
        path = os.getcwd()

    # Check if the current directory contains the name
    if name in os.listdir(path):
        path_name = os.path.join(path, name)
        print(f"{name} found: {path_name}")
        return path_name

    # Get the parent directory
    parent_directory = os.path.dirname(path)

    # If the parent directory is the same as the current directory, we've reached the root and stop the search
    if parent_directory == path:
        return None

    # Recursively call the function with the parent directory
    return find_path(name, parent_directory)


def add_comfyui_directory_to_sys_path() -> None:
    """
    Add 'ComfyUI' to the sys.path
    """
    comfyui_path = find_path("ComfyUI")
    if comfyui_path is not None and os.path.isdir(comfyui_path):
        sys.path.append(comfyui_path)
        print(f"'{comfyui_path}' added to sys.path")


def add_extra_model_paths() -> None:
    """
    Parse the optional extra_model_paths.yaml file and add the parsed paths to the sys.path.
    """
    try:
        from main import load_extra_path_config
    except ImportError:
        print(
            "Could not import load_extra_path_config from main.py. Looking in utils.extra_config instead."
        )
        from utils.extra_config import load_extra_path_config

    extra_model_paths = find_path("extra_model_paths.yaml")

    if extra_model_paths is not None:
        load_extra_path_config(extra_model_paths)
    else:
        print("Could not find the extra_model_paths config file.")


add_comfyui_directory_to_sys_path()
add_extra_model_paths()


def import_custom_nodes() -> None:
    """Find all custom nodes in the custom_nodes folder and add those node objects to NODE_CLASS_MAPPINGS

    This function sets up a new asyncio event loop, initializes the PromptServer,
    creates a PromptQueue, and initializes the custom nodes.
    """
    import asyncio
    import execution
    from nodes import init_extra_nodes
    import server

    # Creating a new event loop and setting it as the default loop
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)

    # Creating an instance of PromptServer with the loop
    server_instance = server.PromptServer(loop)
    execution.PromptQueue(server_instance)

    # Initializing custom nodes
    init_extra_nodes()


from nodes import NODE_CLASS_MAPPINGS

# Initialize common nodes
checkpointloadersimple = NODE_CLASS_MAPPINGS["CheckpointLoaderSimple"]()
checkpointloadersimple_4 = checkpointloadersimple.load_checkpoint(
    ckpt_name="DreamShaper_3.32_baked_vae_clip_fix_half.safetensors"
)
checkpointloadersimple_artistic = checkpointloadersimple.load_checkpoint(
    ckpt_name="DreamShaper_6.31_BakedVae_pruned.safetensors"
)

emptylatentimage = NODE_CLASS_MAPPINGS["EmptyLatentImage"]()
cliptextencode = NODE_CLASS_MAPPINGS["CLIPTextEncode"]()
controlnetloader = NODE_CLASS_MAPPINGS["ControlNetLoader"]()
controlnetapplyadvanced = NODE_CLASS_MAPPINGS["ControlNetApplyAdvanced"]()
ksampler = NODE_CLASS_MAPPINGS["KSampler"]()
vaedecode = NODE_CLASS_MAPPINGS["VAEDecode"]()

import_custom_nodes()
comfy_qr_by_module_size = NODE_CLASS_MAPPINGS["comfy-qr-by-module-size"]()
tilepreprocessor = NODE_CLASS_MAPPINGS["TilePreprocessor"]()

# Load upscale model and additional nodes for artistic pipeline
upscalemodelloader = NODE_CLASS_MAPPINGS["UpscaleModelLoader"]()
upscalemodelloader_30 = upscalemodelloader.load_model(
    model_name="RealESRGAN_x4plus.pth"
)
imageupscalewithmodel = NODE_CLASS_MAPPINGS["ImageUpscaleWithModel"]()
imagescale = NODE_CLASS_MAPPINGS["ImageScale"]()
latentupscaleby = NODE_CLASS_MAPPINGS["LatentUpscaleBy"]()

from comfy import model_management

# MPS (Apple Silicon) comprehensive workaround for black QR code bug
# Issue: PyTorch 2.6+ FP16 handling on MPS causes black images in samplers
# Additional issue: MPS tensor operations can produce NaN/inf values (PyTorch bug #84364)
# Solution: Monkey-patch dtype functions to force fp32, enable MPS fallback
# References: https://civitai.com/articles/11106, https://github.com/pytorch/pytorch/issues/84364

import os
os.environ['PYTORCH_ENABLE_MPS_FALLBACK'] = '1'

from comfy.cli_args import args

if torch.backends.mps.is_available():
    print(f"MPS device detected (PyTorch {torch.__version__})")

    # Store original dtype functions
    _original_unet_dtype = model_management.unet_dtype
    _original_vae_dtype = model_management.vae_dtype
    _original_text_encoder_dtype = model_management.text_encoder_dtype

    # Monkey-patch dtype functions to force fp32 for MPS
    def mps_safe_unet_dtype(device=None, *args_inner, **kwargs):
        if device is not None and model_management.is_device_mps(device):
            return torch.float32
        if model_management.mps_mode():
            return torch.float32
        return _original_unet_dtype(device, *args_inner, **kwargs)

    def mps_safe_vae_dtype(device=None, *args_inner, **kwargs):
        if device is not None and model_management.is_device_mps(device):
            return torch.float32
        if model_management.mps_mode():
            return torch.float32
        return _original_vae_dtype(device, *args_inner, **kwargs)

    def mps_safe_text_encoder_dtype(device=None, *args_inner, **kwargs):
        if device is not None and model_management.is_device_mps(device):
            return torch.float32
        if model_management.mps_mode():
            return torch.float32
        return _original_text_encoder_dtype(device, *args_inner, **kwargs)

    # Replace functions in model_management module
    model_management.unet_dtype = mps_safe_unet_dtype
    model_management.vae_dtype = mps_safe_vae_dtype
    model_management.text_encoder_dtype = mps_safe_text_encoder_dtype

    # Set args for additional stability
    args.force_fp32 = True
    args.fp32_vae = True
    args.fp32_unet = True
    args.force_upcast_attention = True

    # Performance settings: Tune these for speed vs stability
    # Try uncommenting these one at a time for better speed:
    args.lowvram = False              # Set to False for FASTER (try this first!)
    args.use_split_cross_attention = False  # Set to False for even FASTER (might cause black images)

    lowvram_status = "enabled" if args.lowvram else "disabled (faster)"
    split_attn_status = "enabled" if args.use_split_cross_attention else "disabled (faster)"
    print("  ✓ Enabled global fp32 dtype enforcement (monkey-patched)")
    print("  ✓ Enabled MPS fallback mode")
    print(f"  ✓ lowvram: {lowvram_status}, split-cross-attention: {split_attn_status}")

# Add all the models that load a safetensors file
model_loaders = [checkpointloadersimple_4, checkpointloadersimple_artistic]

# Check which models are valid and how to best load them
valid_models = [
    getattr(loader[0], 'patcher', loader[0])
    for loader in model_loaders
    if not isinstance(loader[0], dict) and not isinstance(getattr(loader[0], 'patcher', None), dict)
]

model_management.load_models_gpu(valid_models)

@spaces.GPU(duration=30)
def generate_qr_code_unified(prompt: str, text_input: str, input_type: str = "URL", image_size: int = 512, border_size: int = 4, error_correction: str = "Medium (15%)", module_size: int = 12, module_drawer: str = "Square", use_custom_seed: bool = False, seed: int = 0, pipeline: str = "standard", enable_upscale: bool = False, freeu_b1: float = 1.4, freeu_b2: float = 1.3, freeu_s1: float = 0.0, freeu_s2: float = 1.3, enable_sag: bool = True, sag_scale: float = 0.5, sag_blur_sigma: float = 1.5, controlnet_strength_first: float = 0.45, controlnet_strength_final: float = 0.7):
    # Only manipulate the text if it's a URL input type
    qr_text = text_input
    if input_type == "URL":
        if "https://" in qr_text:
            qr_text = qr_text.replace("https://", "")
        if "http://" in qr_text:
            qr_text = qr_text.replace("http://", "")

    # Use custom seed or random
    actual_seed = seed if use_custom_seed else random.randint(1, 2**64)

    with torch.inference_mode():
        if pipeline == "standard":
            yield from _pipeline_standard(prompt, qr_text, input_type, image_size, border_size, error_correction, module_size, module_drawer, actual_seed, enable_upscale)
        else:  # artistic
            yield from _pipeline_artistic(prompt, qr_text, input_type, image_size, border_size, error_correction, module_size, module_drawer, actual_seed, enable_upscale, freeu_b1, freeu_b2, freeu_s1, freeu_s2, enable_sag, sag_scale, sag_blur_sigma, controlnet_strength_first, controlnet_strength_final)

def generate_standard_qr(prompt: str, text_input: str, input_type: str = "URL", image_size: int = 512, border_size: int = 4, error_correction: str = "Medium (15%)", module_size: int = 12, module_drawer: str = "Square", use_custom_seed: bool = False, seed: int = 0, enable_upscale: bool = False, enable_freeu: bool = False):
    """Wrapper function for standard QR generation"""
    # Get actual seed used (custom or random)
    actual_seed = seed if use_custom_seed else random.randint(1, 2**64)

    # Create settings JSON once
    settings_dict = {
        "pipeline": "standard",
        "prompt": prompt,
        "text_input": text_input,
        "input_type": input_type,
        "image_size": image_size,
        "border_size": border_size,
        "error_correction": error_correction,
        "module_size": module_size,
        "module_drawer": module_drawer,
        "seed": actual_seed,
        "use_custom_seed": True,
        "enable_upscale": enable_upscale,
        "enable_freeu": enable_freeu
    }
    settings_json = generate_settings_json(settings_dict)

    # Generate QR and yield progressive results
    generator = generate_qr_code_unified(prompt, text_input, input_type, image_size, border_size, error_correction, module_size, module_drawer, use_custom_seed, seed, pipeline="standard", enable_upscale=enable_upscale)

    final_image = None
    final_status = None

    for image, status in generator:
        final_image = image
        final_status = status
        # Show progressive updates but don't show accordion yet
        yield (image, status, gr.update(), gr.update())

    # After all steps complete, show the accordion with JSON
    if final_image is not None:
        yield (
            final_image,
            final_status,
            gr.update(value=settings_json),  # Update textbox content
            gr.update(visible=True)  # Make accordion visible only at the end
        )

def generate_artistic_qr(prompt: str, text_input: str, input_type: str = "URL", image_size: int = 512, border_size: int = 4, error_correction: str = "Medium (15%)", module_size: int = 12, module_drawer: str = "Square", use_custom_seed: bool = False, seed: int = 0, enable_upscale: bool = True, enable_freeu: bool = True, freeu_b1: float = 1.4, freeu_b2: float = 1.3, freeu_s1: float = 0.0, freeu_s2: float = 1.3, enable_sag: bool = True, sag_scale: float = 0.5, sag_blur_sigma: float = 0.5, controlnet_strength_first: float = 0.45, controlnet_strength_final: float = 0.7):
    """Wrapper function for artistic QR generation with FreeU and SAG parameters"""
    # Get actual seed used (custom or random)
    actual_seed = seed if use_custom_seed else random.randint(1, 2**64)

    # Create settings JSON once
    settings_dict = {
        "pipeline": "artistic",
        "prompt": prompt,
        "text_input": text_input,
        "input_type": input_type,
        "image_size": image_size,
        "border_size": border_size,
        "error_correction": error_correction,
        "module_size": module_size,
        "module_drawer": module_drawer,
        "seed": actual_seed,
        "use_custom_seed": True,
        "enable_upscale": enable_upscale,
        "enable_freeu": enable_freeu,
        "freeu_b1": freeu_b1,
        "freeu_b2": freeu_b2,
        "freeu_s1": freeu_s1,
        "freeu_s2": freeu_s2,
        "enable_sag": enable_sag,
        "sag_scale": sag_scale,
        "sag_blur_sigma": sag_blur_sigma
    }
    settings_json = generate_settings_json(settings_dict)

    # Generate QR and yield progressive results
    generator = generate_qr_code_unified(prompt, text_input, input_type, image_size, border_size, error_correction, module_size, module_drawer, use_custom_seed, seed, pipeline="artistic", enable_upscale=enable_upscale, freeu_b1=freeu_b1, freeu_b2=freeu_b2, freeu_s1=freeu_s1, freeu_s2=freeu_s2, enable_sag=enable_sag, sag_scale=sag_scale, sag_blur_sigma=sag_blur_sigma, controlnet_strength_first=controlnet_strength_first, controlnet_strength_final=controlnet_strength_final)

    final_image = None
    final_status = None

    for image, status in generator:
        final_image = image
        final_status = status
        # Show progressive updates but don't show accordion yet
        yield (image, status, gr.update(), gr.update())

    # After all steps complete, show the accordion with JSON
    if final_image is not None:
        yield (
            final_image,
            final_status,
            gr.update(value=settings_json),  # Update textbox content
            gr.update(visible=True)  # Make accordion visible only at the end
        )

# Helper functions for shareable settings JSON
import json

def generate_settings_json(params_dict: dict) -> str:
    """Generate a formatted JSON string from parameters dictionary"""
    try:
        return json.dumps(params_dict, indent=2, ensure_ascii=False)
    except Exception as e:
        return json.dumps({"error": f"Failed to generate JSON: {str(e)}"}, indent=2)

def parse_settings_json(json_string: str) -> dict:
    """Parse JSON string and return parameters dictionary with validation"""
    try:
        if not json_string or not json_string.strip():
            return {}

        params = json.loads(json_string)
        if not isinstance(params, dict):
            return {}

        return params
    except json.JSONDecodeError as e:
        return {"error": f"Invalid JSON: {str(e)}"}
    except Exception as e:
        return {"error": f"Failed to parse JSON: {str(e)}"}

def load_settings_from_json_standard(json_string: str):
    """Load settings from JSON for Standard pipeline"""
    try:
        params = json.loads(json_string)

        # Validate pipeline type
        pipeline = params.get("pipeline", "standard")  # Default to standard for backward compatibility
        if pipeline != "standard":
            error_msg = f"❌ Error: You're trying to load {pipeline.upper()} pipeline settings into the STANDARD pipeline. Please use the correct tab."
            # Return empty updates for all fields + error message + make status visible
            return (
                gr.update(), gr.update(), gr.update(), gr.update(), gr.update(),
                gr.update(), gr.update(), gr.update(), gr.update(), gr.update(),
                gr.update(), gr.update(),
                gr.update(value=error_msg, visible=True)
            )

        # Extract parameters with defaults
        prompt = params.get("prompt", "")
        text_input = params.get("text_input", "")
        input_type = params.get("input_type", "URL")
        image_size = params.get("image_size", 512)
        border_size = params.get("border_size", 4)
        error_correction = params.get("error_correction", "Medium (15%)")
        module_size = params.get("module_size", 12)
        module_drawer = params.get("module_drawer", "Square")
        use_custom_seed = params.get("use_custom_seed", True)
        seed = params.get("seed", 718313)
        enable_upscale = params.get("enable_upscale", False)
        enable_freeu = params.get("enable_freeu", False)

        success_msg = "✅ Settings loaded successfully!"
        return (
            prompt, text_input, input_type, image_size, border_size,
            error_correction, module_size, module_drawer, use_custom_seed,
            seed, enable_upscale, enable_freeu,
            gr.update(value=success_msg, visible=True)
        )

    except json.JSONDecodeError as e:
        error_msg = f"❌ Invalid JSON format: {str(e)}"
        return (
            gr.update(), gr.update(), gr.update(), gr.update(), gr.update(),
            gr.update(), gr.update(), gr.update(), gr.update(), gr.update(),
            gr.update(), gr.update(),
            gr.update(value=error_msg, visible=True)
        )
    except Exception as e:
        error_msg = f"❌ Error loading settings: {str(e)}"
        return (
            gr.update(), gr.update(), gr.update(), gr.update(), gr.update(),
            gr.update(), gr.update(), gr.update(), gr.update(), gr.update(),
            gr.update(), gr.update(),
            gr.update(value=error_msg, visible=True)
        )

def load_settings_from_json_artistic(json_string: str):
    """Load settings from JSON for Artistic pipeline"""
    try:
        params = json.loads(json_string)

        # Validate pipeline type
        pipeline = params.get("pipeline", "artistic")  # Default to artistic for backward compatibility
        if pipeline != "artistic":
            error_msg = f"❌ Error: You're trying to load {pipeline.upper()} pipeline settings into the ARTISTIC pipeline. Please use the correct tab."
            # Return empty updates for all fields + error message + make status visible
            return (
                gr.update(), gr.update(), gr.update(), gr.update(), gr.update(),
                gr.update(), gr.update(), gr.update(), gr.update(), gr.update(),
                gr.update(), gr.update(), gr.update(), gr.update(), gr.update(),
                gr.update(), gr.update(), gr.update(), gr.update(),
                gr.update(value=error_msg, visible=True)
            )

        # Extract parameters with defaults
        prompt = params.get("prompt", "")
        text_input = params.get("text_input", "")
        input_type = params.get("input_type", "URL")
        image_size = params.get("image_size", 704)
        border_size = params.get("border_size", 6)
        error_correction = params.get("error_correction", "High (30%)")
        module_size = params.get("module_size", 16)
        module_drawer = params.get("module_drawer", "Square")
        use_custom_seed = params.get("use_custom_seed", True)
        seed = params.get("seed", 718313)
        enable_upscale = params.get("enable_upscale", True)
        enable_freeu = params.get("enable_freeu", True)
        freeu_b1 = params.get("freeu_b1", 1.4)
        freeu_b2 = params.get("freeu_b2", 1.3)
        freeu_s1 = params.get("freeu_s1", 0.0)
        freeu_s2 = params.get("freeu_s2", 1.3)
        enable_sag = params.get("enable_sag", True)
        sag_scale = params.get("sag_scale", 0.5)
        sag_blur_sigma = params.get("sag_blur_sigma", 0.5)

        success_msg = "✅ Settings loaded successfully!"
        return (
            prompt, text_input, input_type, image_size, border_size,
            error_correction, module_size, module_drawer, use_custom_seed,
            seed, enable_upscale, enable_freeu, freeu_b1, freeu_b2, freeu_s1,
            freeu_s2, enable_sag, sag_scale, sag_blur_sigma,
            gr.update(value=success_msg, visible=True)
        )

    except json.JSONDecodeError as e:
        error_msg = f"❌ Invalid JSON format: {str(e)}"
        return (
            gr.update(), gr.update(), gr.update(), gr.update(), gr.update(),
            gr.update(), gr.update(), gr.update(), gr.update(), gr.update(),
            gr.update(), gr.update(), gr.update(), gr.update(), gr.update(),
            gr.update(), gr.update(), gr.update(), gr.update(),
            gr.update(value=error_msg, visible=True)
        )
    except Exception as e:
        error_msg = f"❌ Error loading settings: {str(e)}"
        return (
            gr.update(), gr.update(), gr.update(), gr.update(), gr.update(),
            gr.update(), gr.update(), gr.update(), gr.update(), gr.update(),
            gr.update(), gr.update(), gr.update(), gr.update(), gr.update(),
            gr.update(), gr.update(), gr.update(), gr.update(),
            gr.update(value=error_msg, visible=True)
        )

def add_noise_to_border_only(image_tensor, seed: int, border_size: int, image_size: int, module_size: int = 12):
    """
    Add QR-like cubic patterns ONLY to the border region of a QR code image.
    Creates black squares that resemble QR modules for a smooth transition.
    The density of border cubics automatically matches the QR code interior density.

    Args:
        image_tensor: ComfyUI image tensor (batch, height, width, channels) with values 0-1
        seed: Random seed for reproducible noise
        border_size: Border size in QR modules (from QR generation settings)
        image_size: Image size in pixels
        module_size: Size of QR modules in pixels (for cubic pattern)

    Returns:
        Modified tensor with QR-like cubic patterns in border region
    """
    # Early return if no border
    if border_size == 0:
        return image_tensor

    # Convert to numpy for manipulation
    img_np = image_tensor.cpu().numpy()

    # Set random seed for reproducibility (ensure it's within numpy's valid range)
    np.random.seed(seed % (2**32))

    # Work with first image in batch
    img = img_np[0]  # (height, width, channels)
    height, width, channels = img.shape

    # Calculate border region in pixels using exact QR parameters
    border_thickness = border_size * module_size  # Exact border size in pixels

    # Create border mask (1 for border region, 0 for QR code interior)
    border_mask = np.zeros((height, width), dtype=bool)

    # Top border
    border_mask[0:border_thickness, :] = True
    # Bottom border
    border_mask[height-border_thickness:height, :] = True
    # Left border
    border_mask[:, 0:border_thickness] = True
    # Right border
    border_mask[:, width-border_thickness:width] = True

    # Only apply to white/light areas in the border (threshold > 240)
    img_255 = (img * 255).astype(np.uint8)
    white_mask = np.all(img_255 > 240, axis=-1)

    # Combine: only border AND white areas
    final_mask = border_mask & white_mask

    # Calculate QR code interior density to determine border cubic density
    interior_mask = ~border_mask  # Inverse of border = QR interior
    interior_pixels = img_255[interior_mask][:, 0]  # Get first channel (grayscale)
    black_count = (interior_pixels < 128).sum()  # Count black pixels (< 128)
    total_count = len(interior_pixels)
    qr_density = float(black_count) / float(total_count) if total_count > 0 else 0.5

    # Use QR interior density as probability for placing border cubics
    # This creates a natural transition matching the QR pattern density

    # Generate QR-like cubic pattern noise
    # Create a grid based on module_size
    for y in range(0, height, module_size):
        for x in range(0, width, module_size):
            # Check if this module position is mostly in the border area
            y_end = min(y + module_size, height)
            x_end = min(x + module_size, width)

            # Count how many pixels in this module are in the final_mask
            module_region = final_mask[y:y_end, x:x_end]

            # If at least 50% of the module is in the border, we can place a cubic here
            if module_region.sum() > (module_size * module_size * 0.5):
                # Randomly decide to place a black cubic based on QR interior density
                if np.random.random() < qr_density:
                    # Place a black square (cubic) - set all channels to 0 (black)
                    for c in range(channels):
                        img[y:y_end, x:x_end, c] = 0

    # Put modified image back into batch array
    img_np[0] = img

    # Convert back to tensor
    return torch.from_numpy(img_np).to(image_tensor.device)

def _pipeline_standard(prompt: str, qr_text: str, input_type: str, image_size: int, border_size: int, error_correction: str, module_size: int, module_drawer: str, seed: int, enable_upscale: bool = False):
    emptylatentimage_5 = emptylatentimage.generate(
        width=image_size, height=image_size, batch_size=1
    )

    cliptextencode_6 = cliptextencode.encode(
        text=prompt,
        clip=get_value_at_index(checkpointloadersimple_4, 1),
    )

    cliptextencode_7 = cliptextencode.encode(
        text="ugly, tiling, poorly drawn hands, poorly drawn feet, poorly drawn face, out of frame, extra limbs, body out of frame, blurry, bad anatomy, blurred, watermark, grainy, signature, cut off, draft, closed eyes, text, logo",
        clip=get_value_at_index(checkpointloadersimple_4, 1),
    )

    controlnetloader_10 = controlnetloader.load_controlnet(
        control_net_name="models/control_v1p_sd15_brightness.safetensors"
    )

    controlnetloader_12 = controlnetloader.load_controlnet(
        control_net_name="control_v11f1e_sd15_tile_fp16.safetensors"
    )

    # Set protocol based on input type: None for plain text, Https for URLs
    qr_protocol = "None" if input_type == "Plain Text" else "Https"

    try:
        comfy_qr_by_module_size_15 = comfy_qr_by_module_size.generate_qr(
            protocol=qr_protocol,
            text=qr_text,
            module_size=module_size,
            max_image_size=image_size,
            fill_hexcolor="#000000",
            back_hexcolor="#FFFFFF",
            error_correction=error_correction,
            border=border_size,
            module_drawer=module_drawer,
        )
    except RuntimeError as e:
        error_msg = (
            f"Error generating QR code: {str(e)}\n"
            "Try with a shorter text, increase the image size, or decrease the border size, module size, and error correction level under Change Settings Manually."
        )
        yield None, error_msg
        return

    # 1) Yield the base QR image as the first intermediate result
    base_qr_tensor = get_value_at_index(comfy_qr_by_module_size_15, 0)
    base_qr_np = (base_qr_tensor.cpu().numpy() * 255).astype(np.uint8)
    base_qr_np = base_qr_np[0]
    base_qr_pil = Image.fromarray(base_qr_np)
    yield base_qr_pil, "Generated base QR pattern… enhancing with AI (step 1/3)"

    emptylatentimage_17 = emptylatentimage.generate(
        width=image_size*2, height=image_size*2, batch_size=1
    )

    controlnetloader_19 = controlnetloader.load_controlnet(
        control_net_name="control_v11f1e_sd15_tile_fp16.safetensors"
    )

    for q in range(1):
        controlnetapplyadvanced_11 = controlnetapplyadvanced.apply_controlnet(
            strength=0.45,
            start_percent=0,
            end_percent=1,
            positive=get_value_at_index(cliptextencode_6, 0),
            negative=get_value_at_index(cliptextencode_7, 0),
            control_net=get_value_at_index(controlnetloader_10, 0),
            image=get_value_at_index(comfy_qr_by_module_size_15, 0),
            vae=get_value_at_index(checkpointloadersimple_4, 2),
        )

        tilepreprocessor_14 = tilepreprocessor.execute(
            pyrUp_iters=3,
            resolution=image_size,
            image=get_value_at_index(comfy_qr_by_module_size_15, 0),
        )

        controlnetapplyadvanced_13 = controlnetapplyadvanced.apply_controlnet(
            strength=0.45,
            start_percent=0,
            end_percent=1,
            positive=get_value_at_index(controlnetapplyadvanced_11, 0),
            negative=get_value_at_index(controlnetapplyadvanced_11, 1),
            control_net=get_value_at_index(controlnetloader_12, 0),
            image=get_value_at_index(tilepreprocessor_14, 0),
            vae=get_value_at_index(checkpointloadersimple_4, 2),
        )

        ksampler_3 = ksampler.sample(
            seed=seed,
            steps=20,
            cfg=7,
            sampler_name="dpmpp_2m",
            scheduler="karras",
            denoise=1,
            model=get_value_at_index(checkpointloadersimple_4, 0),
            positive=get_value_at_index(controlnetapplyadvanced_13, 0),
            negative=get_value_at_index(controlnetapplyadvanced_13, 1),
            latent_image=get_value_at_index(emptylatentimage_5, 0),
        )

        vaedecode_8 = vaedecode.decode(
            samples=get_value_at_index(ksampler_3, 0),
            vae=get_value_at_index(checkpointloadersimple_4, 2),
        )

        # 2) Yield the first decoded image as a second intermediate result
        mid_tensor = get_value_at_index(vaedecode_8, 0)
        mid_np = (mid_tensor.cpu().numpy() * 255).astype(np.uint8)
        mid_np = mid_np[0]
        mid_pil = Image.fromarray(mid_np)
        yield mid_pil, "First enhancement pass complete (step 2/3)… refining details"

        controlnetapplyadvanced_20 = controlnetapplyadvanced.apply_controlnet(
            strength=1,
            start_percent=0,
            end_percent=1,
            positive=get_value_at_index(cliptextencode_6, 0),
            negative=get_value_at_index(cliptextencode_7, 0),
            control_net=get_value_at_index(controlnetloader_19, 0),
            image=get_value_at_index(vaedecode_8, 0),
            vae=get_value_at_index(checkpointloadersimple_4, 2),
        )

        ksampler_18 = ksampler.sample(
            seed=seed + 1,
            steps=20,
            cfg=7,
            sampler_name="dpmpp_2m",
            scheduler="karras",
            denoise=1,
            model=get_value_at_index(checkpointloadersimple_4, 0),
            positive=get_value_at_index(controlnetapplyadvanced_20, 0),
            negative=get_value_at_index(controlnetapplyadvanced_20, 1),
            latent_image=get_value_at_index(emptylatentimage_17, 0),
        )

        vaedecode_21 = vaedecode.decode(
            samples=get_value_at_index(ksampler_18, 0),
            vae=get_value_at_index(checkpointloadersimple_4, 2),
        )

        # 3) Optionally upscale if enabled
        if enable_upscale:
            # Show pre-upscale result
            pre_upscale_tensor = get_value_at_index(vaedecode_21, 0)
            pre_upscale_np = (pre_upscale_tensor.cpu().numpy() * 255).astype(np.uint8)
            pre_upscale_np = pre_upscale_np[0]
            pre_upscale_pil = Image.fromarray(pre_upscale_np)
            yield pre_upscale_pil, "Enhancement complete (step 3/4)... upscaling image"

            # Upscale the final image
            upscaled = imageupscalewithmodel.upscale(
                upscale_model=get_value_at_index(upscalemodelloader_30, 0),
                image=get_value_at_index(vaedecode_21, 0),
            )

            image_tensor = get_value_at_index(upscaled, 0)
            image_np = (image_tensor.cpu().numpy() * 255).astype(np.uint8)
            image_np = image_np[0]
            pil_image = Image.fromarray(image_np)
            yield pil_image, "No errors, all good! Final QR art generated and upscaled. (step 4/4)"
        else:
            # No upscaling
            image_tensor = get_value_at_index(vaedecode_21, 0)
            image_np = (image_tensor.cpu().numpy() * 255).astype(np.uint8)
            image_np = image_np[0]
            pil_image = Image.fromarray(image_np)
            yield pil_image, "No errors, all good! Final QR art generated."

def _pipeline_artistic(prompt: str, qr_text: str, input_type: str, image_size: int, border_size: int, error_correction: str, module_size: int, module_drawer: str, seed: int, enable_upscale: bool = True, freeu_b1: float = 1.4, freeu_b2: float = 1.3, freeu_s1: float = 0.0, freeu_s2: float = 1.3, enable_sag: bool = True, sag_scale: float = 0.5, sag_blur_sigma: float = 0.5, controlnet_strength_first: float = 0.45, controlnet_strength_final: float = 0.7):
    # Generate QR code
    qr_protocol = "None" if input_type == "Plain Text" else "Https"

    try:
        comfy_qr = comfy_qr_by_module_size.generate_qr(
            protocol=qr_protocol,
            text=qr_text,
            module_size=module_size,
            max_image_size=image_size,
            fill_hexcolor="#000000",
            back_hexcolor="#FFFFFF",
            error_correction=error_correction,
            border=border_size,
            module_drawer=module_drawer,
        )
    except RuntimeError as e:
        error_msg = (
            f"Error generating QR code: {str(e)}\n"
            "Try with a shorter text, increase the image size, or decrease the border size, module size, and error correction level under Change Settings Manually."
        )
        yield None, error_msg
        return

    # Show the base QR code
    base_qr_tensor = get_value_at_index(comfy_qr, 0)
    base_qr_np = (base_qr_tensor.cpu().numpy() * 255).astype(np.uint8)
    base_qr_np = base_qr_np[0]
    base_qr_pil = Image.fromarray(base_qr_np)

    # Only add noise if there's a border (border_size > 0)
    if border_size > 0:
        yield base_qr_pil, "Generated base QR pattern... adding QR-like cubics to border (step 1/5)"

        # Add QR-like cubic patterns ONLY to border region (extends QR structure into border)
        # Density automatically matches QR code interior density for natural transition
        qr_with_border_noise = add_noise_to_border_only(
            get_value_at_index(comfy_qr, 0),
            seed=seed + 100,
            border_size=border_size,
            image_size=image_size,
            module_size=module_size,  # Use same module size as QR code
        )

        # Show the noisy QR so you can see the border cubic pattern effect
        noisy_qr_np = (qr_with_border_noise.cpu().numpy() * 255).astype(np.uint8)
        noisy_qr_np = noisy_qr_np[0]
        noisy_qr_pil = Image.fromarray(noisy_qr_np)
        yield noisy_qr_pil, "Added QR-like cubics to border... enhancing with AI (step 2/5)"
    else:
        # No border, skip noise
        qr_with_border_noise = get_value_at_index(comfy_qr, 0)
        yield base_qr_pil, "Generated base QR pattern (no border)... enhancing with AI (step 1/4)"

    # Generate latent image
    latent_image = emptylatentimage.generate(
        width=image_size, height=image_size, batch_size=1
    )

    # Encode text prompts
    positive_prompt = cliptextencode.encode(
        text=prompt,
        clip=get_value_at_index(checkpointloadersimple_artistic, 1),
    )

    negative_prompt = cliptextencode.encode(
        text="ugly, tiling, poorly drawn hands, poorly drawn feet, poorly drawn face, out of frame, extra limbs, body out of frame, blurry, bad anatomy, blurred, watermark, grainy, signature, cut off, draft, closed eyes, text, logo",
        clip=get_value_at_index(checkpointloadersimple_artistic, 1),
    )

    # Load controlnets
    brightness_controlnet = controlnetloader.load_controlnet(
        control_net_name="models/control_v1p_sd15_brightness.safetensors"
    )

    tile_controlnet = controlnetloader.load_controlnet(
        control_net_name="control_v11f1e_sd15_tile_fp16.safetensors"
    )

    # First ControlNet pass (using QR with border cubics)
    controlnet_apply = controlnetapplyadvanced.apply_controlnet(
        strength=controlnet_strength_first,
        start_percent=0,
        end_percent=1,
        positive=get_value_at_index(positive_prompt, 0),
        negative=get_value_at_index(negative_prompt, 0),
        control_net=get_value_at_index(brightness_controlnet, 0),
        image=qr_with_border_noise,
        vae=get_value_at_index(checkpointloadersimple_artistic, 2),
    )

    # Tile preprocessor (using QR with border cubics)
    tile_processed = tilepreprocessor.execute(
        pyrUp_iters=3,
        resolution=image_size,
        image=qr_with_border_noise,
    )

    # Second ControlNet pass (using tile processed from QR with border cubics)
    controlnet_apply = controlnetapplyadvanced.apply_controlnet(
        strength=controlnet_strength_first,
        start_percent=0,
        end_percent=1,
        positive=get_value_at_index(controlnet_apply, 0),
        negative=get_value_at_index(controlnet_apply, 1),
        control_net=get_value_at_index(tile_controlnet, 0),
        image=get_value_at_index(tile_processed, 0),
        vae=get_value_at_index(checkpointloadersimple_artistic, 2),
    )

    # Apply FreeU_V2 for enhanced quality (better detail, texture, and cleaner output)
    base_model = get_value_at_index(checkpointloadersimple_artistic, 0)

    freeu = FreeU_V2()
    freeu_model = freeu.patch(
        model=base_model,
        b1=freeu_b1,  # Backbone feature enhancement - customizable
        b2=freeu_b2,  # Backbone feature enhancement (layer 2) - customizable
        s1=freeu_s1,  # Skip connection dampening - customizable structure hiding
        s2=freeu_s2   # Skip connection dampening (layer 2) - customizable scannability balance
    )[0]

    # Apply SAG (Self-Attention Guidance) for improved structural coherence (if enabled)
    if enable_sag:
        smoothed_energy = NODE_CLASS_MAPPINGS["SelfAttentionGuidance"]()
        enhanced_model = smoothed_energy.patch(
            model=freeu_model,
            scale=sag_scale,  # SAG guidance scale - customizable
            blur_sigma=sag_blur_sigma,  # Blur amount - customizable artistic blending
        )[0]
    else:
        enhanced_model = freeu_model

    # First sampling pass
    samples = ksampler.sample(
        seed=seed,
        steps=30,
        cfg=7,
        sampler_name="dpmpp_3m_sde",
        scheduler="karras",
        denoise=1,
        model=enhanced_model,  # Using FreeU + SAG enhanced model
        positive=get_value_at_index(controlnet_apply, 0),
        negative=get_value_at_index(controlnet_apply, 1),
        latent_image=get_value_at_index(latent_image, 0),
    )

    # First decode
    decoded = vaedecode.decode(
        samples=get_value_at_index(samples, 0),
        vae=get_value_at_index(checkpointloadersimple_artistic, 2),
    )

    # Show first pass result
    first_pass_tensor = get_value_at_index(decoded, 0)
    first_pass_np = (first_pass_tensor.cpu().numpy() * 255).astype(np.uint8)
    first_pass_np = first_pass_np[0]
    first_pass_pil = Image.fromarray(first_pass_np)
    # Calculate step based on border and upscale
    if enable_upscale:
        step_msg = "First enhancement pass complete (step 3/5)... final refinement pass" if border_size > 0 else "First enhancement pass complete (step 2/4)... final refinement pass"
    else:
        step_msg = "First enhancement pass complete (step 3/4)... final refinement pass" if border_size > 0 else "First enhancement pass complete (step 2/3)... final refinement pass"
    yield first_pass_pil, step_msg

    # Final ControlNet pass (second pass - refinement)
    controlnet_apply_final = controlnetapplyadvanced.apply_controlnet(
        strength=controlnet_strength_final,
        start_percent=0,
        end_percent=1,
        positive=get_value_at_index(positive_prompt, 0),
        negative=get_value_at_index(negative_prompt, 0),
        control_net=get_value_at_index(tile_controlnet, 0),
        image=get_value_at_index(decoded, 0),
        vae=get_value_at_index(checkpointloadersimple_artistic, 2),
    )

    # Upscale latent
    upscaled_latent = latentupscaleby.upscale(
        upscale_method="area",
        scale_by=2.0,
        samples=get_value_at_index(samples, 0),
    )

    # Final sampling pass
    final_samples = ksampler.sample(
        seed=seed + 1,
        steps=30,
        cfg=7,
        sampler_name="dpmpp_3m_sde",
        scheduler="karras",
        denoise=0.8,
        model=enhanced_model,  # Using FreeU + SAG enhanced model
        positive=get_value_at_index(controlnet_apply_final, 0),
        negative=get_value_at_index(controlnet_apply_final, 1),
        latent_image=get_value_at_index(upscaled_latent, 0),
    )

    # Final decode
    final_decoded = vaedecode.decode(
        samples=get_value_at_index(final_samples, 0),
        vae=get_value_at_index(checkpointloadersimple_artistic, 2),
    )

    # Optionally upscale if enabled
    if enable_upscale:
        # Show result before upscaling
        pre_upscale_tensor = get_value_at_index(final_decoded, 0)
        pre_upscale_np = (pre_upscale_tensor.cpu().numpy() * 255).astype(np.uint8)
        pre_upscale_np = pre_upscale_np[0]
        pre_upscale_pil = Image.fromarray(pre_upscale_np)
        step_msg = "Final refinement complete (step 4/5)... upscaling image" if border_size > 0 else "Final refinement complete (step 3/4)... upscaling image"
        yield pre_upscale_pil, step_msg

        # Upscale image with model (after final samples, before returning)
        upscaled = imageupscalewithmodel.upscale(
            upscale_model=get_value_at_index(upscalemodelloader_30, 0),
            image=get_value_at_index(final_decoded, 0),
        )

        # Convert upscaled image to PIL Image and return
        image_tensor = get_value_at_index(upscaled, 0)
        image_np = (image_tensor.cpu().numpy() * 255).astype(np.uint8)
        image_np = image_np[0]
        final_image = Image.fromarray(image_np)
        step_msg = "No errors, all good! Final artistic QR code generated and upscaled. (step 5/5)" if border_size > 0 else "No errors, all good! Final artistic QR code generated and upscaled. (step 4/4)"
        yield final_image, step_msg
    else:
        # No upscaling
        image_tensor = get_value_at_index(final_decoded, 0)
        image_np = (image_tensor.cpu().numpy() * 255).astype(np.uint8)
        image_np = image_np[0]
        final_image = Image.fromarray(image_np)
        step_msg = "No errors, all good! Final artistic QR code generated. (step 4/4)" if border_size > 0 else "No errors, all good! Final artistic QR code generated. (step 3/3)"
        yield final_image, step_msg


if __name__ == "__main__" and not os.environ.get('QR_TESTING_MODE'):

    # Start your Gradio app
    with gr.Blocks() as app:
        # Add a title and description
        gr.Markdown("# QR Code Art Generator")
        gr.Markdown("""
        This is an AI-powered QR code generator that creates artistic QR codes using Stable Diffusion 1.5 and ControlNet models.
        The application uses a custom ComfyUI workflow to generate QR codes.

        ### Tips:
        - Use detailed prompts for better results
        - Include style keywords like 'photorealistic', 'detailed', '8k'
        - Choose **URL** mode for web links or **Plain Text** mode for VCARD, WiFi credentials, calendar events, etc.
        - Try the examples below for inspiration
        - **Copy/paste settings**: After generation, copy the JSON settings string that appears below the image and paste it into "Import Settings from JSON" to reproduce exact results or share with others

        ### Two Modes:
        - **Standard QR**: Stable, accurate QR code generation (faster, more scannable, less creative)
        - **Artistic QR**: More artistic and creative results with upscaling (slower, more creative, less scannable)

        ### Note:
        Feel free to share your suggestions or feedback on how to improve the app! Thanks!
        """)

        # Add tabs for different generation methods
        with gr.Tabs():
            # STANDARD QR TAB
            with gr.TabItem("Standard QR"):
                with gr.Row():
                    with gr.Column():
                        # Add input type selector
                        input_type = gr.Radio(
                            choices=["URL", "Plain Text"],
                            value="URL",
                            label="Input Type",
                            info="URL: For web links (auto-removes https://). Plain Text: For VCARD, WiFi, calendar, location, etc. (no manipulation)"
                        )

                        # Add inputs
                        prompt_input = gr.Textbox(
                            label="Prompt",
                            placeholder="Describe the image you want to generate (check examples below for inspiration)",
                            value="Enter your prompt here... For example: 'a beautiful sunset over mountains, photorealistic, detailed landscape'",
                            lines=3
                        )
                        text_input = gr.Textbox(
                            label="QR Code Content",
                            placeholder="Enter URL or plain text",
                            value="Enter your URL or text here... For example: https://github.com",
                            lines=3
                        )

                        # Import Settings section - separate accordion
                        with gr.Accordion("Import Settings from JSON", open=False):
                            gr.Markdown("Paste a settings JSON string (copied from a previous generation) to load all parameters at once.")
                            import_json_input_standard = gr.Textbox(
                                label="Paste Settings JSON",
                                placeholder='{"pipeline": "standard", "prompt": "...", "seed": 718313, ...}',
                                lines=3
                            )
                            import_status_standard = gr.Textbox(
                                label="Import Status",
                                interactive=False,
                                visible=False,
                                lines=2
                            )
                            with gr.Row():
                                load_settings_btn_standard = gr.Button("Load Settings", variant="primary")
                                clear_json_btn_standard = gr.Button("Clear", variant="secondary")

                        # Change Settings Manually - separate accordion
                        with gr.Accordion("Change Settings Manually", open=False):
                            # Add image size slider
                            image_size = gr.Slider(
                                minimum=512,
                                maximum=1024,
                                step=64,
                                value=512,
                                label="Image Size",
                                info="Base size of the generated image. Final output will be 2x this size (e.g., 512 → 1024) due to the two-step enhancement process. Higher values use more VRAM and take longer to process."
                            )

                            # Add border size slider
                            border_size = gr.Slider(
                                minimum=0,
                                maximum=8,
                                step=1,
                                value=4,
                                label="QR Code Border Size",
                                info="Number of modules (squares) to use as border around the QR code. Higher values add more whitespace."
                            )

                            # Add error correction dropdown
                            error_correction = gr.Dropdown(
                                choices=["Low (7%)", "Medium (15%)", "Quartile (25%)", "High (30%)"],
                                value="Medium (15%)",
                                label="Error Correction Level",
                                info="Higher error correction makes the QR code more scannable when damaged or obscured, but increases its size and complexity. Medium (15%) is a good starting point for most uses."
                            )

                            # Add module size slider
                            module_size = gr.Slider(
                                minimum=4,
                                maximum=16,
                                step=1,
                                value=12,
                                label="QR Module Size",
                                info="Pixel width of the smallest QR code unit. Larger values improve readability but require a larger image size. 12 is a good starting point."
                            )

                            # Add module drawer dropdown with style examples
                            module_drawer = gr.Dropdown(
                                choices=["Square", "Gapped Square", "Circle", "Rounded", "Vertical bars", "Horizontal bars"],
                                value="Square",
                                label="QR Code Style",
                                info="Select the style of the QR code modules (squares). See examples below. Different styles can give your QR code a unique look while maintaining scannability."
                            )

                            # Add style examples with labels
                            gr.Markdown("### Style Examples:")

                            # First row of examples
                            with gr.Row():
                                with gr.Column(scale=1, min_width=0):
                                    gr.Markdown("**Square**", show_label=False)
                                    gr.Image("custom_nodes/ComfyQR/img/square.png", width=100, show_label=False, show_download_button=False)
                                with gr.Column(scale=1, min_width=0):
                                    gr.Markdown("**Gapped Square**", show_label=False)
                                    gr.Image("custom_nodes/ComfyQR/img/gapped_square.png", width=100, show_label=False, show_download_button=False)
                                with gr.Column(scale=1, min_width=0):
                                    gr.Markdown("**Circle**", show_label=False)
                                    gr.Image("custom_nodes/ComfyQR/img/circle.png", width=100, show_label=False, show_download_button=False)

                            # Second row of examples
                            with gr.Row():
                                with gr.Column(scale=1, min_width=0):
                                    gr.Markdown("**Rounded**", show_label=False)
                                    gr.Image("custom_nodes/ComfyQR/img/rounded.png", width=100, show_label=False, show_download_button=False)
                                with gr.Column(scale=1, min_width=0):
                                    gr.Markdown("**Vertical Bars**", show_label=False)
                                    gr.Image("custom_nodes/ComfyQR/img/vertical-bars.png", width=100, show_label=False, show_download_button=False)
                                with gr.Column(scale=1, min_width=0):
                                    gr.Markdown("**Horizontal Bars**", show_label=False)
                                    gr.Image("custom_nodes/ComfyQR/img/horizontal-bars.png", width=100, show_label=False, show_download_button=False)

                            # Add upscale checkbox
                            enable_upscale = gr.Checkbox(
                                label="Enable Upscaling",
                                value=False,
                                info="Enable upscaling with RealESRGAN for higher quality output (disabled by default for standard pipeline)"
                            )

                            # Add FreeU checkbox
                            enable_freeu_standard = gr.Checkbox(
                                label="Enable FreeU",
                                value=False,
                                info="Enable FreeU quality enhancement (disabled by default for standard pipeline)"
                            )

                            # Add seed controls
                            use_custom_seed = gr.Checkbox(
                                label="Use Custom Seed",
                                value=True,
                                info="Enable to use a specific seed for reproducible results"
                            )
                            seed = gr.Slider(
                                minimum=0,
                                maximum=2000000,
                                step=1,
                                value=718313,
                                label="Seed",
                                visible=True,  # Initially visible since use_custom_seed=True
                                info="Seed value for reproducibility. Same seed with same settings will produce the same result."
                            )

                        # The generate button
                        generate_btn = gr.Button("Generate Standard QR", variant="primary")

                    with gr.Column():
                        # The output image
                        output_image = gr.Image(label="Generated Standard QR Code")
                        error_message = gr.Textbox(
                            label="Status / Errors",
                            interactive=False,
                            lines=3,
                        )
                        # Wrap settings output in accordion (initially hidden)
                        with gr.Accordion("Shareable Settings (JSON)", open=True, visible=False) as settings_accordion_standard:
                            settings_output_standard = gr.Textbox(
                                label="Copy this JSON to share your exact settings",
                                interactive=True,
                                lines=5,
                                show_copy_button=True
                            )

                # When clicking the button, it will trigger the main function
                generate_btn.click(
                    fn=generate_standard_qr,
                    inputs=[prompt_input, text_input, input_type, image_size, border_size, error_correction, module_size, module_drawer, use_custom_seed, seed, enable_upscale, enable_freeu_standard],
                    outputs=[output_image, error_message, settings_output_standard, settings_accordion_standard]
                )

                # Load Settings button event handler
                load_settings_btn_standard.click(
                    fn=load_settings_from_json_standard,
                    inputs=[import_json_input_standard],
                    outputs=[
                        prompt_input,
                        text_input,
                        input_type,
                        image_size,
                        border_size,
                        error_correction,
                        module_size,
                        module_drawer,
                        use_custom_seed,
                        seed,
                        enable_upscale,
                        enable_freeu_standard,
                        import_status_standard
                    ]
                )

                # Clear button event handler
                clear_json_btn_standard.click(
                    fn=lambda: ("", gr.update(visible=False)),
                    inputs=[],
                    outputs=[import_json_input_standard, import_status_standard]
                )

                # Seed slider visibility toggle
                use_custom_seed.change(
                    fn=lambda x: gr.update(visible=x),
                    inputs=[use_custom_seed],
                    outputs=[seed]
                )

                # Add examples
                examples = [
                    [
                        "some clothes spread on ropes, realistic, great details, out in the open air sunny day realistic, great details,absence of people, Detailed and Intricate, CGI, Photoshoot,rim light, 8k, 16k, ultra detail",
                        "https://www.google.com",
                        "URL",
                        512,
                        4,
                        "Medium (15%)",
                        12,
                        "Square"
                    ],
                    [
                        "some cards on poker tale, realistic, great details, realistic, great details,absence of people, Detailed and Intricate, CGI, Photoshoot,rim light, 8k, 16k, ultra detail",
                        "https://store.steampowered.com",
                        "URL",
                        512,
                        4,
                        "Medium (15%)",
                        12,
                        "Square"
                    ],
                    [
                        "a beautiful sunset over mountains, photorealistic, detailed landscape, golden hour, dramatic lighting, 8k, ultra detailed",
                        "https://github.com",
                        "URL",
                        512,
                        4,
                        "Medium (15%)",
                        12,
                        "Square"
                    ],
                    [
                        "underwater scene with coral reef and tropical fish, photorealistic, detailed, crystal clear water, sunlight rays, 8k, ultra detailed",
                        "https://twitter.com",
                        "URL",
                        512,
                        4,
                        "Medium (15%)",
                        12,
                        "Square"
                    ],
                    [
                        "futuristic cityscape with flying cars and neon lights, cyberpunk style, detailed architecture, night scene, 8k, ultra detailed",
                        "https://linkedin.com",
                        "URL",
                        512,
                        4,
                        "Medium (15%)",
                        12,
                        "Square"
                    ],
                    [
                        "vintage camera on wooden table, photorealistic, detailed textures, soft lighting, bokeh background, 8k, ultra detailed",
                        "https://instagram.com",
                        "URL",
                        512,
                        4,
                        "Medium (15%)",
                        12,
                        "Square"
                    ],
                    [
                        "business card design, professional, modern, clean layout, corporate style, detailed, 8k, ultra detailed",
                        "BEGIN:VCARD\nVERSION:3.0\nFN:John Doe\nORG:Acme Corporation\nTITLE:Software Engineer\nTEL:+1-555-123-4567\nEMAIL:john.doe@example.com\nEND:VCARD",
                        "Plain Text",
                        832,
                        4,
                        "Medium (15%)",
                        12,
                        "Square"
                    ],
                    [
                        "wifi network symbol, modern tech, digital art, glowing blue, detailed, 8k, ultra detailed",
                        "WIFI:T:WPA;S:MyNetwork;P:MyPassword123;;",
                        "Plain Text",
                        576,
                        4,
                        "Medium (15%)",
                        12,
                        "Square"
                    ],
                    [
                        "calendar appointment reminder, organized planner, professional office, detailed, 8k, ultra detailed",
                        "BEGIN:VEVENT\nSUMMARY:Team Meeting\nDTSTART:20251115T140000Z\nDTEND:20251115T150000Z\nLOCATION:Conference Room A\nEND:VEVENT",
                        "Plain Text",
                        832,
                        4,
                        "Medium (15%)",
                        12,
                        "Square"
                    ],
                    [
                        "location pin on map, travel destination, scenic view, detailed cartography, 8k, ultra detailed",
                        "geo:37.7749,-122.4194",
                        "Plain Text",
                        512,
                        4,
                        "Medium (15%)",
                        12,
                        "Square"
                    ]
                ]

                gr.Examples(
                    examples=examples,
                    inputs=[
                        prompt_input,
                        text_input,
                        input_type,
                        image_size,
                        border_size,
                        error_correction,
                        module_size,
                        module_drawer
                    ],
                    outputs=[output_image, error_message],
                    fn=generate_standard_qr,
                    cache_examples=False
                )

            # ARTISTIC QR TAB
            with gr.TabItem("Artistic QR"):
                with gr.Row():
                    with gr.Column():
                        # Add input type selector for artistic QR
                        artistic_input_type = gr.Radio(
                            choices=["URL", "Plain Text"],
                            value="URL",
                            label="Input Type",
                            info="URL: For web links (auto-removes https://). Plain Text: For VCARD, WiFi, calendar, location, etc. (no manipulation)"
                        )

                        # Add inputs for artistic QR
                        artistic_prompt_input = gr.Textbox(
                            label="Prompt",
                            placeholder="Describe the image you want to generate (check examples below for inspiration)",
                            value="Enter your prompt here... For example: 'a beautiful sunset over mountains, photorealistic, detailed landscape'",
                            lines=3
                        )
                        artistic_text_input = gr.Textbox(
                            label="QR Code Content",
                            placeholder="Enter URL or plain text",
                            value="Enter your URL or text here... For example: https://github.com",
                            lines=3
                        )

                        # Import Settings section - separate accordion
                        with gr.Accordion("Import Settings from JSON", open=False):
                            gr.Markdown("Paste a settings JSON string (copied from a previous generation) to load all parameters at once.")
                            import_json_input_artistic = gr.Textbox(
                                label="Paste Settings JSON",
                                placeholder='{"pipeline": "artistic", "prompt": "...", "seed": 718313, ...}',
                                lines=3
                            )
                            import_status_artistic = gr.Textbox(
                                label="Import Status",
                                interactive=False,
                                visible=False,
                                lines=2
                            )
                            with gr.Row():
                                load_settings_btn_artistic = gr.Button("Load Settings", variant="primary")
                                clear_json_btn_artistic = gr.Button("Clear", variant="secondary")

                        # Change Settings Manually - separate accordion
                        with gr.Accordion("Change Settings Manually", open=False):
                            # Add image size slider for artistic QR
                            artistic_image_size = gr.Slider(
                                minimum=512,
                                maximum=1024,
                                step=64,
                                value=704,
                                label="Image Size",
                                info="Base size of the generated image. Final output will be 2x this size (e.g., 704 → 1408) due to the two-step enhancement process. Higher values use more VRAM and take longer to process."
                            )

                            # Add border size slider for artistic QR
                            artistic_border_size = gr.Slider(
                                minimum=0,
                                maximum=8,
                                step=1,
                                value=6,
                                label="QR Code Border Size",
                                info="Number of modules (squares) to use as border around the QR code. Higher values add more whitespace."
                            )

                            # Add error correction dropdown for artistic QR
                            artistic_error_correction = gr.Dropdown(
                                choices=["Low (7%)", "Medium (15%)", "Quartile (25%)", "High (30%)"],
                                value="High (30%)",
                                label="Error Correction Level",
                                info="Higher error correction makes the QR code more scannable when damaged or obscured, but increases its size and complexity. High (30%) is recommended for artistic QR codes."
                            )

                            # Add module size slider for artistic QR
                            artistic_module_size = gr.Slider(
                                minimum=4,
                                maximum=16,
                                step=1,
                                value=16,
                                label="QR Module Size",
                                info="Pixel width of the smallest QR code unit. Larger values improve readability but require a larger image size. 16 is a good starting point."
                            )

                            # Add module drawer dropdown with style examples for artistic QR
                            artistic_module_drawer = gr.Dropdown(
                                choices=["Square", "Gapped Square", "Circle", "Rounded", "Vertical bars", "Horizontal bars"],
                                value="Square",
                                label="QR Code Style",
                                info="Select the style of the QR code modules (squares). See examples below. Different styles can give your QR code a unique look while maintaining scannability."
                            )

                            # Add style examples with labels
                            gr.Markdown("### Style Examples:")

                            # First row of examples
                            with gr.Row():
                                with gr.Column(scale=1, min_width=0):
                                    gr.Markdown("**Square**", show_label=False)
                                    gr.Image("custom_nodes/ComfyQR/img/square.png", width=100, show_label=False, show_download_button=False)
                                with gr.Column(scale=1, min_width=0):
                                    gr.Markdown("**Gapped Square**", show_label=False)
                                    gr.Image("custom_nodes/ComfyQR/img/gapped_square.png", width=100, show_label=False, show_download_button=False)
                                with gr.Column(scale=1, min_width=0):
                                    gr.Markdown("**Circle**", show_label=False)
                                    gr.Image("custom_nodes/ComfyQR/img/circle.png", width=100, show_label=False, show_download_button=False)

                            # Second row of examples
                            with gr.Row():
                                with gr.Column(scale=1, min_width=0):
                                    gr.Markdown("**Rounded**", show_label=False)
                                    gr.Image("custom_nodes/ComfyQR/img/rounded.png", width=100, show_label=False, show_download_button=False)
                                with gr.Column(scale=1, min_width=0):
                                    gr.Markdown("**Vertical Bars**", show_label=False)
                                    gr.Image("custom_nodes/ComfyQR/img/vertical-bars.png", width=100, show_label=False, show_download_button=False)
                                with gr.Column(scale=1, min_width=0):
                                    gr.Markdown("**Horizontal Bars**", show_label=False)
                                    gr.Image("custom_nodes/ComfyQR/img/horizontal-bars.png", width=100, show_label=False, show_download_button=False)

                            # Add upscale checkbox
                            artistic_enable_upscale = gr.Checkbox(
                                label="Enable Upscaling",
                                value=True,
                                info="Enable upscaling with RealESRGAN for higher quality output (enabled by default for artistic pipeline)"
                            )

                            # Add seed controls for artistic QR
                            artistic_use_custom_seed = gr.Checkbox(
                                label="Use Custom Seed",
                                value=True,
                                info="Enable to use a specific seed for reproducible results"
                            )
                            artistic_seed = gr.Slider(
                                minimum=0,
                                maximum=2000000,
                                step=1,
                                value=718313,
                                label="Seed",
                                visible=True,  # Initially visible since artistic_use_custom_seed=True
                                info="Seed value for reproducibility. Same seed with same settings will produce the same result."
                            )

                            # FreeU Parameters
                            gr.Markdown("### FreeU Quality Enhancement")
                            enable_freeu_artistic = gr.Checkbox(
                                label="Enable FreeU",
                                value=True,
                                info="Enable FreeU quality enhancement (enabled by default for artistic pipeline)"
                            )
                            freeu_b1 = gr.Slider(
                                minimum=1.0,
                                maximum=1.6,
                                step=0.01,
                                value=1.4,
                                label="FreeU B1 (Backbone 1)",
                                info="Backbone feature enhancement for first layer. Higher values improve detail but may reduce blending. Range: 1.0-1.6, Default: 1.4"
                            )
                            freeu_b2 = gr.Slider(
                                minimum=1.0,
                                maximum=1.6,
                                step=0.01,
                                value=1.3,
                                label="FreeU B2 (Backbone 2)",
                                info="Backbone feature enhancement for second layer. Higher values improve texture. Range: 1.0-1.6, Default: 1.3"
                            )
                            freeu_s1 = gr.Slider(
                                minimum=0.0,
                                maximum=1.5,
                                step=0.01,
                                value=0.0,
                                label="FreeU S1 (Skip 1)",
                                info="Skip connection dampening for first layer. Lower values hide QR structure more. Range: 0.0-1.5, Default: 0.0"
                            )
                            freeu_s2 = gr.Slider(
                                minimum=0.0,
                                maximum=1.5,
                                step=0.01,
                                value=1.3,
                                label="FreeU S2 (Skip 2)",
                                info="Skip connection dampening for second layer. Balances scannability. Range: 0.0-1.5, Default: 1.3"
                            )

                            # SAG (Self-Attention Guidance) Parameters
                            gr.Markdown("### SAG (Self-Attention Guidance)")
                            enable_sag = gr.Checkbox(
                                label="Enable SAG",
                                value=True,
                                info="Enable Self-Attention Guidance for improved structural coherence and artistic blending"
                            )
                            sag_scale = gr.Slider(
                                minimum=0.0,
                                maximum=3.0,
                                step=0.1,
                                value=0.5,
                                label="SAG Scale",
                                info="Guidance strength. Higher values provide more structural coherence. Range: 0.0-3.0, Default: 0.5"
                            )
                            sag_blur_sigma = gr.Slider(
                                minimum=0.0,
                                maximum=5.0,
                                step=0.1,
                                value=0.5,
                                label="SAG Blur Sigma",
                                info="Blur amount for artistic blending. Higher values create softer, more artistic effects. Range: 0.0-5.0, Default: 0.5"
                            )

                        # The generate button for artistic QR
                        artistic_generate_btn = gr.Button("Generate Artistic QR", variant="primary")

                    with gr.Column():
                        # The output image for artistic QR
                        artistic_output_image = gr.Image(label="Generated Artistic QR Code")
                        artistic_error_message = gr.Textbox(
                            label="Status / Errors",
                            interactive=False,
                            lines=3,
                        )
                        # Wrap settings output in accordion (initially hidden)
                        with gr.Accordion("Shareable Settings (JSON)", open=True, visible=False) as settings_accordion_artistic:
                            settings_output_artistic = gr.Textbox(
                                label="Copy this JSON to share your exact settings",
                                interactive=True,
                                lines=5,
                                show_copy_button=True
                            )

                # When clicking the button, it will trigger the artistic function
                artistic_generate_btn.click(
                    fn=generate_artistic_qr,
                    inputs=[artistic_prompt_input, artistic_text_input, artistic_input_type, artistic_image_size, artistic_border_size, artistic_error_correction, artistic_module_size, artistic_module_drawer, artistic_use_custom_seed, artistic_seed, artistic_enable_upscale, enable_freeu_artistic, freeu_b1, freeu_b2, freeu_s1, freeu_s2, enable_sag, sag_scale, sag_blur_sigma],
                    outputs=[artistic_output_image, artistic_error_message, settings_output_artistic, settings_accordion_artistic]
                )

                # Load Settings button event handler
                load_settings_btn_artistic.click(
                    fn=load_settings_from_json_artistic,
                    inputs=[import_json_input_artistic],
                    outputs=[
                        artistic_prompt_input,
                        artistic_text_input,
                        artistic_input_type,
                        artistic_image_size,
                        artistic_border_size,
                        artistic_error_correction,
                        artistic_module_size,
                        artistic_module_drawer,
                        artistic_use_custom_seed,
                        artistic_seed,
                        artistic_enable_upscale,
                        enable_freeu_artistic,
                        freeu_b1,
                        freeu_b2,
                        freeu_s1,
                        freeu_s2,
                        enable_sag,
                        sag_scale,
                        sag_blur_sigma,
                        import_status_artistic
                    ]
                )

                # Clear button event handler for artistic tab
                clear_json_btn_artistic.click(
                    fn=lambda: ("", gr.update(visible=False)),
                    inputs=[],
                    outputs=[import_json_input_artistic, import_status_artistic]
                )

                # Seed slider visibility toggle for artistic tab
                artistic_use_custom_seed.change(
                    fn=lambda x: gr.update(visible=x),
                    inputs=[artistic_use_custom_seed],
                    outputs=[artistic_seed]
                )

                # Add examples for artistic QR
                artistic_examples = [
                    [
                        "some clothes spread on ropes, Japanese girl sits inside in the middle of the image, few sakura flowers, realistic, great details, out in the open air sunny day realistic, great details, absence of people, Detailed and Intricate, CGI, Photoshoot, rim light, 8k, 16k, ultra detail",
                        "https://www.google.com",
                        "URL",
                        640,  # Image size
                        6,    # Border
                        "Medium (15%)",  # Error correction
                        14,   # Module size
                        "Square"
                    ],
                    [
                        "some cards on poker tale, realistic, great details, realistic, great details,absence of people, Detailed and Intricate, CGI, Photoshoot,rim light, 8k, 16k, ultra detail",
                        "https://store.steampowered.com",
                        "URL",
                        768,  # Image size
                        6,    # Border
                        "High (30%)",  # Error correction
                        16,   # Module size
                        "Square"
                    ],
                    [
                        "a beautiful sunset over mountains, photorealistic, detailed landscape, golden hour, dramatic lighting, 8k, ultra detailed",
                        "https://github.com",
                        "URL",
                        704,  # Image size (default)
                        6,    # Border
                        "High (30%)",  # Error correction
                        16,   # Module size
                        "Square"
                    ],
                    [
                        "underwater scene with coral reef and tropical fish, photorealistic, detailed, crystal clear water, sunlight rays, 8k, ultra detailed",
                        "https://twitter.com",
                        "URL",
                        704,  # Image size (default)
                        6,    # Border
                        "High (30%)",  # Error correction
                        16,   # Module size
                        "Square"
                    ],
                    [
                        "futuristic cityscape with flying cars and neon lights, cyberpunk style, detailed architecture, night scene, 8k, ultra detailed",
                        "https://linkedin.com",
                        "URL",
                        704,  # Image size (default)
                        6,    # Border
                        "High (30%)",  # Error correction
                        16,   # Module size
                        "Square"
                    ],
                    [
                        "vintage camera on wooden table, photorealistic, detailed textures, soft lighting, bokeh background, 8k, ultra detailed",
                        "https://instagram.com",
                        "URL",
                        704,  # Image size (default)
                        6,    # Border
                        "High (30%)",  # Error correction
                        16,   # Module size
                        "Square"
                    ],
                    [
                        "business card design, professional, modern, clean layout, corporate style, detailed, 8k, ultra detailed",
                        "BEGIN:VCARD\nVERSION:3.0\nFN:John Doe\nORG:Acme Corporation\nTITLE:Software Engineer\nTEL:+1-555-123-4567\nEMAIL:john.doe@example.com\nEND:VCARD",
                        "Plain Text",
                        832,
                        4,
                        "Medium (15%)",
                        12,
                        "Square"
                    ],
                    [
                        "wifi network symbol, modern tech, digital art, glowing blue, detailed, 8k, ultra detailed",
                        "WIFI:T:WPA;S:MyNetwork;P:MyPassword123;;",
                        "Plain Text",
                        576,
                        4,
                        "Medium (15%)",
                        12,
                        "Square"
                    ],
                    [
                        "calendar appointment reminder, organized planner, professional office, detailed, 8k, ultra detailed",
                        "BEGIN:VEVENT\nSUMMARY:Team Meeting\nDTSTART:20251115T140000Z\nDTEND:20251115T150000Z\nLOCATION:Conference Room A\nEND:VEVENT",
                        "Plain Text",
                        832,
                        4,
                        "Medium (15%)",
                        12,
                        "Square"
                    ],
                    [
                        "location pin on map, travel destination, scenic view, detailed cartography, 8k, ultra detailed",
                        "geo:37.7749,-122.4194",
                        "Plain Text",
                        512,
                        4,
                        "Medium (15%)",
                        12,
                        "Square"
                    ]
                ]

                gr.Examples(
                    examples=artistic_examples,
                    inputs=[
                        artistic_prompt_input,
                        artistic_text_input,
                        artistic_input_type,
                        artistic_image_size,
                        artistic_border_size,
                        artistic_error_correction,
                        artistic_module_size,
                        artistic_module_drawer
                    ],
                    outputs=[artistic_output_image, artistic_error_message],
                    fn=generate_artistic_qr,
                    cache_examples=False
                )

    app.launch(share=False, mcp_server=True)