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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
import numpy as np
import requests
import torch
import torchvision.transforms.v2 as T
# from PIL import Image, ImageDraw
from PIL import Image, ImageOps,ImageFilter,ImageEnhance,ImageDraw,ImageSequence, ImageFont
from PIL.PngImagePlugin import PngInfo
import base64,os,random
from io import BytesIO
import folder_paths
import json,io
import comfy.utils
from comfy.cli_args import args
import cv2
import string
import math,glob
from .Watcher import FolderWatcher

from itertools import product


# 将PIL图片转换为OpenCV格式
def pil_to_opencv(image):
    open_cv_image = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
    return open_cv_image

# 将OpenCV格式图片转换为PIL格式
def opencv_to_pil(image):
    pil_image = Image.fromarray(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
    return pil_image

# 列出目录下面的所有文件
def get_files_with_extension(directory, extension):
    file_list = []
    for root, dirs, files in os.walk(directory):
        for file in files:
            if file.endswith(extension):
                file = os.path.splitext(file)[0]
                file_path = os.path.join(root, file)
                file_name = os.path.relpath(file_path, directory)
                file_list.append(file_name)
    return file_list

def composite_images(foreground, background, mask, is_multiply_blend=False, position="overall", scale=0.25):
    width, height = foreground.size
    bg_image = background
    bwidth, bheight = bg_image.size

    scale=max(scale,1/bwidth)
    scale=max(scale,1/bheight)

    def determine_scale_option(width, height):
        return 'height' if height > width else 'width'

    if position == "overall":
        layer = {
            "x": 0,
            "y": 0,
            "width": bwidth,
            "height": bheight,
            "z_index": 88,
            "scale_option": 'overall',
            "image": foreground,
            "mask": mask
        }
    else:
        scale_option = determine_scale_option(width, height)
        if scale_option == 'height':
            scale = int(bheight * scale) / height
        else:
            scale = int(bwidth * scale) / width

        new_width = int(width * scale)
        new_height = int(height * scale)

        if position == 'center_bottom':
            x_position = int((bwidth - new_width) * 0.5)
            y_position = bheight - new_height - 24
        elif position == 'right_bottom':
            x_position = bwidth - new_width - 24
            y_position = bheight - new_height - 24
        elif position == 'center_top':
            x_position = int((bwidth - new_width) * 0.5)
            y_position = 24
        elif position == 'right_top':
            x_position = bwidth - new_width - 24
            y_position = 24
        elif position == 'left_top':
            x_position = 24
            y_position = 24
        elif position == 'left_bottom':
            x_position = 24
            y_position = bheight - new_height - 24
        elif position == 'center_center':
            x_position = int((bwidth - new_width) * 0.5)
            y_position = int((bheight - new_height) * 0.5)

        layer = {
            "x": x_position,
            "y": y_position,
            "width": new_width,
            "height": new_height,
            "z_index": 88,
            "scale_option": scale_option,
            "image": foreground,
            "mask": mask
        }

    layer_image = layer['image']
    layer_mask = layer['mask']

    bg_image = merge_images(bg_image,
                            layer_image,
                            layer_mask,
                            layer['x'],
                            layer['y'],
                            layer['width'],
                            layer['height'],
                            layer['scale_option'],
                            is_multiply_blend)

    bg_image = bg_image.convert('RGB')

    return bg_image



def count_files_in_directory(directory):
    file_count = 0
    for _, _, files in os.walk(directory):
        file_count += len(files)
    return file_count

def save_json_to_file(data, file_path):
    with open(file_path, 'w') as file:
        json.dump(data, file)

def draw_rectangle(image, grid, color,width):
    x, y, w, h = grid
    draw = ImageDraw.Draw(image)
    draw.rectangle([(x, y), (x+w, y+h)], outline=color,width=width)

def generate_random_string(length):
    letters = string.ascii_letters + string.digits
    return ''.join(random.choice(letters) for _ in range(length))

def padding_rectangle(grid, padding):
    x, y, w, h = grid
    x -= padding
    y -= padding
    w += 2 * padding
    h += 2 * padding
    return (x, y, w, h)

class AnyType(str):
  """A special class that is always equal in not equal comparisons. Credit to pythongosssss"""

  def __ne__(self, __value: object) -> bool:
    return False

any_type = AnyType("*")


FONT_PATH= os.path.abspath(os.path.join(os.path.dirname(__file__),'../assets/fonts'))


MAX_RESOLUTION=8192

# Tensor to PIL
def tensor2pil(image):
    return Image.fromarray(np.clip(255. * image.cpu().numpy().squeeze(), 0, 255).astype(np.uint8))

# Convert PIL to Tensor
def pil2tensor(image):
    return torch.from_numpy(np.array(image).astype(np.float32) / 255.0).unsqueeze(0)


# 颜色迁移
# Color-Transfer-between-Images https://github.com/chia56028/Color-Transfer-between-Images/blob/master/color_transfer.py

def get_mean_and_std(x):
	x_mean, x_std = cv2.meanStdDev(x)
	x_mean = np.hstack(np.around(x_mean,2))
	x_std = np.hstack(np.around(x_std,2))
	return x_mean, x_std

def color_transfer(source,target):
	# sources = ['s1','s2','s3','s4','s5','s6']
	# targets = ['t1','t2','t3','t4','t5','t6']

     # 将PIL的Image类型转换为OpenCV的numpy数组
    source = cv2.cvtColor(np.array(source), cv2.COLOR_RGB2LAB)
    target = cv2.cvtColor(np.array(target), cv2.COLOR_RGB2LAB)

    s_mean, s_std = get_mean_and_std(source)
    t_mean, t_std = get_mean_and_std(target)

    height, width, channel = source.shape
	
    for i in range(0,height):
        for j in range(0,width):
            for k in range(0,channel):
                x = source[i,j,k]
                x = ((x-s_mean[k])*(t_std[k]/s_std[k]))+t_mean[k]
				# round or +0.5
                x = round(x)
				# boundary check
                x = 0 if x<0 else x
                x = 255 if x>255 else x
                source[i,j,k] = x
    
    source = cv2.cvtColor(source,cv2.COLOR_LAB2RGB)
 
    # 创建PIL图像对象
    image_pil = Image.fromarray(source)
    
    return image_pil



# 组合
def create_big_image(image_folder, image_count):
    # 计算行数和列数
    rows = math.ceil(math.sqrt(image_count))
    cols = math.ceil(image_count / rows)

    # 获取每个小图的尺寸
    small_width = 100
    small_height = 100

    # 计算大图的尺寸
    big_width = small_width * cols
    big_height = small_height * rows

    # 创建一个新的大图
    big_image = Image.new('RGB', (big_width, big_height))

    # 获取所有图片文件的路径
    image_files = [f for f in os.listdir(image_folder) if os.path.isfile(os.path.join(image_folder, f))]

    # 遍历所有图片文件
    for i, image_file in enumerate(image_files):
        # 打开图片并调整大小
        image = Image.open(os.path.join(image_folder, image_file))
        image = image.resize((small_width, small_height))

        # 计算当前小图的位置
        row = i // cols
        col = i % cols
        x = col * small_width
        y = row * small_height

        # 将小图粘贴到大图上
        big_image.paste(image, (x, y))

    return big_image

# # 调用方法并保存大图
# image_folder = 'path/to/folder/containing/images'
# image_count = 100
# big_image = create_big_image(image_folder, image_count)
# big_image.save('path/to/save/big_image.jpg')



def naive_cutout(img, mask,invert=True):
    """
    Perform a simple cutout operation on an image using a mask.

    This function takes a PIL image `img` and a PIL image `mask` as input.
    It uses the mask to create a new image where the pixels from `img` are
    cut out based on the mask.

    The function returns a PIL image representing the cutout of the original
    image using the mask.
    """

    # img=img.convert("RGBA")
    mask=mask.convert("RGBA")

    empty = Image.new("RGBA", (mask.size), 0)

    red, green, blue, alpha = mask.split()

    mask = mask.convert('L')
    # 黑白,要可调
    if invert==True:
        mask = mask.point(lambda x: 255 if x > 128 else 0)
    else:
        mask = mask.point(lambda x: 255 if x < 128 else 0)

    new_image = Image.merge('RGBA', (red, green, blue, mask))

    cutout = Image.composite(img.convert("RGBA"), empty,new_image)

    return cutout


# (h,w)
# (1072, 512) -- > [(536, 512),(536, 512)]
def split_mask_by_new_height(masks,new_height):
    split_masks = torch.split(masks, new_height, dim=0)
    return split_masks


def doMask(image,mask,save_image=False,filename_prefix="Mixlab",invert="yes",save_mask=False,prompt=None, extra_pnginfo=None):
   
    output_dir = (
            folder_paths.get_output_directory()
            if save_image
            else folder_paths.get_temp_directory()
        )

    (
        full_output_folder,
        filename,
        counter,
        subfolder,
         _,
    ) = folder_paths.get_save_image_path(filename_prefix, output_dir)

    

    image=tensor2pil(image)

    mask = mask.reshape((-1, 1, mask.shape[-2], mask.shape[-1])).movedim(1, -1).expand(-1, -1, -1, 3)
        
    mask=tensor2pil(mask)

    im=naive_cutout(image, mask,invert=='yes')

    # format="image/png",
    end="1" if invert=='yes' else ""
    image_file = f"{filename}_{counter:05}_{end}.png"
    mask_file = f"{filename}_{counter:05}_{end}_mask.png"

    image_path=os.path.join(full_output_folder, image_file)

    metadata = None
    if not args.disable_metadata:
        metadata = PngInfo()
        if prompt is not None:
            metadata.add_text("prompt", json.dumps(prompt))
        if extra_pnginfo is not None:
            for x in extra_pnginfo:
                metadata.add_text(x, json.dumps(extra_pnginfo[x]))

    im.save(image_path,pnginfo=metadata, compress_level=4)
    
    result= [{
                "filename": image_file,
                "subfolder": subfolder,
                "type": "output" if save_image else "temp"
            }]
    
    if save_mask:
        mask_path=os.path.join(full_output_folder, mask_file)
        mask.save(mask_path,
                    compress_level=4)
        
        result.append({
                "filename": mask_file,
                "subfolder": subfolder,
                "type": "output" if save_image else "temp"
            })
    
 
    return {
        "result":result,
        "image_path":image_path,
        "im_tensor":pil2tensor(im.convert('RGB')),
        "im_rgba_tensor":pil2tensor(im)
    }


# 提取不透明部分
def get_not_transparent_area(image):
    # 将PIL的Image类型转换为OpenCV的numpy数组
    image_np = cv2.cvtColor(np.array(image), cv2.COLOR_RGBA2BGRA)

    # 分离图像的RGBA通道
    rgba = cv2.split(image_np)
    alpha = rgba[3]

    # 使用阈值将非透明部分转换为纯白色(255),透明部分转换为纯黑色(0)
    _, mask = cv2.threshold(alpha, 1, 255, cv2.THRESH_BINARY)

    # 获取非透明区域的边界框
    coords = cv2.findNonZero(mask)
    x, y, w, h = cv2.boundingRect(coords)

    return (x, y, w, h)




def generate_gradient_image(width, height, start_color_hex, end_color_hex):
    image = Image.new('RGBA', (width, height))
    draw = ImageDraw.Draw(image)

    if len(start_color_hex) == 7:
        start_color_hex += "FF"
    if len(end_color_hex) == 7:
        end_color_hex += "FF"

    start_color_hex = start_color_hex.lstrip("#")
    end_color_hex = end_color_hex.lstrip("#")

    # 将十六进制颜色代码转换为RGBA元组,包括透明度
    start_color = tuple(int(start_color_hex[i:i+2], 16) for i in (0, 2, 4, 6))
    end_color = tuple(int(end_color_hex[i:i+2], 16) for i in (0, 2, 4, 6))

    for y in range(height):
        # 计算当前行的颜色
        r = int(start_color[0] + (end_color[0] - start_color[0]) * y / height)
        g = int(start_color[1] + (end_color[1] - start_color[1]) * y / height)
        b = int(start_color[2] + (end_color[2] - start_color[2]) * y / height)
        a = int(start_color[3] + (end_color[3] - start_color[3]) * y / height)

        # 绘制当前行的渐变色
        draw.line((0, y, width, y), fill=(r, g, b, a))

    # Create a mask from the image's alpha channel
    mask = image.split()[-1]

    # Convert the mask to a black and white image
    mask = mask.convert('L')

    image=image.convert('RGB')

    return (image, mask)

# 示例用法
# width = 500
# height = 200
# start_color_hex = 'FF0000FF'  # 红色,完全不透明
# end_color_hex = '0000FFFF'  # 蓝色,完全不透明

# gradient_image = generate_gradient_image(width, height, start_color_hex, end_color_hex)
# gradient_image.save('gradient_image.png')

def rgb_to_hex(rgb):
    r, g, b = rgb
    hex_color = "#{:02x}{:02x}{:02x}".format(r, g, b)
    return hex_color


# 读取不了分层
def load_psd(image):
    layers=[]
    print('load_psd',image.format)
    if image.format=='PSD':
        layers = [frame.copy() for frame in ImageSequence.Iterator(image)]
        print('#PSD',len(layers))
    else:
        image = ImageOps.exif_transpose(image) #校对方向
    layers.append(image)
    return layers


def load_image(fp,white_bg=False):
    im = Image.open(fp)

    # ims=load_psd(im)
    im = ImageOps.exif_transpose(im) #校对方向
    ims=[im]

    images=[]
 
    for i in ims:
        image = i.convert("RGB")
        image = np.array(image).astype(np.float32) / 255.0
        image = torch.from_numpy(image)[None,]
        if 'A' in i.getbands():
            mask = np.array(i.getchannel('A')).astype(np.float32) / 255.0
            mask = 1. - torch.from_numpy(mask)
            if white_bg==True:
                nw = mask.unsqueeze(0).unsqueeze(-1).repeat(1, 1, 1, 3)
                # 将mask的黑色部分对image进行白色处理
                image[nw == 1] = 1.0
        else:
            mask = torch.zeros((64,64), dtype=torch.float32, device="cpu")
        
        images.append({
            "image":image,
            "mask":mask
        })
        
    return images

def load_image_and_mask_from_url(url, timeout=10):
    # Load the image from the URL
    response = requests.get(url, timeout=timeout)

    content_type = response.headers.get('Content-Type')
    
    image = Image.open(BytesIO(response.content))

    # Create a mask from the image's alpha channel
    mask = image.convert('RGBA').split()[-1]

    # Convert the mask to a black and white image
    mask = mask.convert('L')

    image=image.convert('RGB')

    return (image, mask)


# 获取图片s
def get_images_filepath(f,white_bg=False):
    images = []
 
    if os.path.isdir(f):
        for root, dirs, files in os.walk(f):
            for file in files:
                file_path = os.path.join(root, file)
                file_name=os.path.basename(file_path)
                try:
                    imgs=load_image(file_path,white_bg)
                    for img in imgs:
                        images.append({
                            "image":img['image'],
                            "mask":img['mask'],
                            "file_path":file_path,
                            "file_name":file_name,
                            "psd":len(imgs)>1
                        })
                except:
                    print('非图片',file_path)
 
    elif os.path.isfile(f):
        try:
            file_path = os.path.join(root, f)
            file_name=os.path.basename(file_path)
            imgs=load_image(f,white_bg)
            for img in imgs:
                images.append({
                    "image":img['image'],
                    "mask":img['mask'],
                    "file_path":file_path,
                    "file_name":file_name,
                    "psd":len(imgs)>1
                })
        except:
            print('非图片',f)
    else:
        print('路径不存在或无效',f)

    return images



def get_average_color_image(image):
    # 打开图片
    # image = Image.open(image_path)

    # 将图片转换为RGB模式
    image = image.convert("RGB")

    # 获取图片的像素值
    pixel_data = image.load()

    # 初始化颜色总和和像素数量
    total_red = 0
    total_green = 0
    total_blue = 0
    pixel_count = 0

    # 遍历图片的每个像素
    for i in range(image.width):
        for j in range(image.height):
            # 获取像素的RGB值
            r, g, b = pixel_data[i, j]

            # 累加颜色值
            total_red += r
            total_green += g
            total_blue += b

            # 像素数量加1
            pixel_count += 1

    # 计算平均颜色值
    average_red = int(total_red // pixel_count)
    average_green = int(total_green // pixel_count)
    average_blue = int(total_blue // pixel_count)

    # 返回平均颜色值

    im = Image.new("RGB", (image.width, image.height), (average_red, average_green, average_blue))

    hex=rgb_to_hex((average_red, average_green, average_blue))
    return (im,hex)



# 创建噪声图像
def create_noisy_image(width, height, mode="RGB", noise_level=128, background_color="#FFFFFF"):
    
    background_rgb = tuple(int(background_color[i:i+2], 16) for i in (1, 3, 5))
    image = Image.new(mode, (width, height), background_rgb)

    # 创建空白图像
    # image = Image.new(mode, (width, height))

    # 遍历每个像素,并随机设置像素值
    pixels = image.load()
    for i in range(width):
        for j in range(height):
            # 随机生成噪声值
            noise_r = random.randint(-noise_level, noise_level)
            noise_g = random.randint(-noise_level, noise_level)
            noise_b = random.randint(-noise_level, noise_level)

            # 像素值加上噪声值,并限制在0-255的范围内
            r = max(0, min(pixels[i, j][0] + noise_r, 255))
            g = max(0, min(pixels[i, j][1] + noise_g, 255))
            b = max(0, min(pixels[i, j][2] + noise_b, 255))

            # 设置像素值
            pixels[i, j] = (r, g, b)

    image=image.convert(mode)
    return image


# 对轮廓进行平滑
def smooth_edges(alpha_channel, smoothness):

    # 将图像中的不透明物体提取出来
    # alpha_channel = image_rgba[:, :, 3]
    # 0:表示设定的阈值,即像素值小于或等于这个阈值的像素将被设置为0。
    # 255:表示设置的最大值,即像素值大于阈值的像素将被设置为255。
    _, mask = cv2.threshold(alpha_channel, 127, 255, cv2.THRESH_BINARY)

    # 对提取的不透明物体进行边缘检测
    # edges = cv2.Canny(mask, 100, 200)

    
    # 将一个整数变成最接近的奇数
    smoothness = smoothness if smoothness % 2 != 0 else smoothness + 1
    # 进行光滑处理
    smoothed_mask = cv2.GaussianBlur(mask, (smoothness, smoothness), 0)

    return smoothed_mask

 
def enhance_depth_map(depth_map, contrast):
    # 打开深度图像
    # depth_map = Image.open(im)
    
    # 创建对比度增强对象
    enhancer = ImageEnhance.Contrast(depth_map)
    
    # 对深度图像进行对比度增强
    enhanced_depth_map = enhancer.enhance(contrast)
    
    return enhanced_depth_map


def detect_faces(image):
    # Read the image
    # image = cv2.imread('people1.jpg')
    image = cv2.cvtColor(np.array(image), cv2.COLOR_RGBA2BGRA)

    # Convert the image to grayscale
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

    # Load the pre-trained face detector
    face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')

    # Detect faces in the image
    faces = face_cascade.detectMultiScale(gray, scaleFactor=1.05, minNeighbors=5, minSize=(50, 50))

    # Create a black and white mask image
    mask = np.zeros_like(gray)

    # Loop over all detected faces
    for (x, y, w, h) in faces:
        # Draw rectangles around the detected faces
        cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)

        # Set the corresponding region in the mask image to white
        mask[y:y+h, x:x+w] = 255

    # Display the number of faces detected
    print('Faces Detected:', len(faces))

    mask = Image.fromarray(cv2.cvtColor(mask, cv2.COLOR_BGRA2RGBA))

    return mask


def areaToMask(x,y,w,h,image):
    # 创建一个与原图片大小相同的空白图片
    mask = Image.new('L', image.size)

    # 创建一个可用于绘制的对象
    draw = ImageDraw.Draw(mask)

    # 在空白图片上绘制一个矩形,表示要处理的区域
    draw.rectangle((x, y, x+w, y+h), fill=255)

    # 将处理区域之外的部分填充为黑色
    draw.rectangle((0, 0, image.width, y), fill=0)
    draw.rectangle((0, y+h, image.width, image.height), fill=0)
    draw.rectangle((0, y, x, y+h), fill=0)
    draw.rectangle((x+w, y, image.width, y+h), fill=0)
    return mask


# def merge_images(bg_image, layer_image,mask, x, y, width, height):
#     # 打开底图
#     # bg_image = Image.open(background)
#     bg_image=bg_image.convert("RGBA")

#     # 打开图层
#     layer_image=layer_image.convert("RGBA")
#     layer_image = layer_image.resize((width, height))
#     # mask = Image.new("L", layer_image.size, 255)
#     mask = mask.resize((width, height))
#     # 在底图上粘贴图层
#     bg_image.paste(layer_image, (x, y), mask=mask)

#     # 输出合成后的图片
#     # bg_image.save("output.jpg")
#     return bg_image


import cv2
import numpy as np

# ps的正片叠底
# 可以基于https://www.cnblogs.com/jsxyhelu/p/16947810.html ,用gpt写python代码
def multiply_blend(image1, image2):
    image1=pil_to_opencv(image1)
    image2=pil_to_opencv(image2)
    # 将图像转换为浮点型
    image1 = image1.astype(float)
    image2 = image2.astype(float)
    if image1.shape != image2.shape:
        image1 = cv2.resize(image1, (image2.shape[1], image2.shape[0]))
        
    # 归一化图像
    image1 /= 255.0
    image2 /= 255.0

    # 正片叠底混合
    blended = image1 * image2

    # 将图像还原为8位无符号整数
    blended = (blended * 255).astype(np.uint8)

    blended=opencv_to_pil(blended)
    return blended

# # 读取图像
# image1 = cv2.imread('1.png')
# image2 = cv2.imread('3.png')

# # 进行正片叠底混合
# result = multiply_blend(image1, image2)

# cv2.imwrite('result.jpg', result)

# 使用gpt4o优化代码
# 为了消除图像合并时出现的灰色描边,可以使用以下方法:
# 调整透明度:确保透明像素不会引入不需要的颜色。
# 预处理图像:在缩放图像之前,可以先将图像的边缘进行预处理,例如扩展边缘颜色,减少抗锯齿带来的过渡效果。

def merge_images(bg_image, layer_image, mask, x, y, width, height, scale_option, is_multiply_blend=False):
    # 打开底图
    bg_image = bg_image.convert("RGBA")

    # 打开图层
    layer_image = layer_image.convert("RGBA")
   
    # 根据缩放选项调整图像大小
    if scale_option == "height":
        # 按照高度比例缩放
        original_width, original_height = layer_image.size
        scale = height / original_height
        new_width = int(original_width * scale)
        layer_image = layer_image.resize((new_width, height), Image.NEAREST)
    elif scale_option == "width":
        # 按照宽度比例缩放
        original_width, original_height = layer_image.size
        scale = width / original_width
        new_height = int(original_height * scale)
        layer_image = layer_image.resize((width, new_height), Image.NEAREST)
    elif scale_option == "overall":
        # 整体缩放
        layer_image = layer_image.resize((width, height), Image.NEAREST)
    elif scale_option == "longest":
        original_width, original_height = layer_image.size
        if original_width > original_height:
            new_width = width
            scale = width / original_width
            new_height = int(original_height * scale)
            x = 0
            y = int((height - new_height) * 0.5)
        else:
            new_height = height
            scale = height / original_height
            new_width = int(original_height * scale)
            x = int((width - new_width) * 0.5)
            y = 0

    # 调整mask的大小
    nw, nh = layer_image.size
    mask = mask.resize((nw, nh), Image.NEAREST)

    # 预处理图像边缘以减少灰色描边
    layer_image = layer_image.filter(ImageFilter.SMOOTH)

    if is_multiply_blend:
        bg_image_white = Image.new("RGB", bg_image.size, (255, 255, 255))

        bg_image_white.paste(layer_image, (x, y), mask=mask)
        bg_image = multiply_blend(bg_image_white, bg_image)
        bg_image = bg_image.convert("RGBA")
    else:
        transparent_img = Image.new("RGBA", layer_image.size, (255, 255, 255, 0))
        # 调整透明度处理
        for i in range(transparent_img.size[0]):
            for j in range(transparent_img.size[1]):
                r, g, b, a = transparent_img.getpixel((i, j))
                if a > 0:
                    transparent_img.putpixel((i, j), (r, g, b, 255))

        transparent_img.paste(layer_image, (0, 0), mask)
        bg_image.paste(transparent_img, (x, y), transparent_img)

    # 输出合成后的图片
    return bg_image

#MixCopilot

def resize_2(img):
    # 检查图像的高度是否是2的倍数,如果不是,则调整高度
    if img.height % 2 != 0:
        img = img.resize((img.width, img.height + 1))

    # 检查图像的宽度是否是2的倍数,如果不是,则调整宽度
    if img.width % 2 != 0:
        img = img.resize((img.width + 1, img.height))

    return img

# TODO 几个像素点的底
def resize_image(layer_image, scale_option, width, height,color="white"):
    layer_image = layer_image.convert("RGB")
    original_width, original_height = layer_image.size
    
    if scale_option == "height":
        # Scale image based on height
        scale = height / original_height
        new_width = int(original_width * scale)
        layer_image = layer_image.resize((new_width, height))
        
    elif scale_option == "width":
        # Scale image based on width
        scale = width / original_width
        new_height = int(original_height * scale)
        layer_image = layer_image.resize((width, new_height))
        
    elif scale_option == "overall":
        # Scale image overall
        layer_image = layer_image.resize((width, height))
        
    elif scale_option == "center":
        # Scale image to minimum of width and height, center it, and fill extra area with black
        scale = min(width / original_width, height / original_height)
        new_width = math.ceil(original_width * scale)
        new_height = math.ceil(original_height * scale)
        resized_image = Image.new("RGB", (width, height), color=color)
        resized_image.paste(layer_image.resize((new_width, new_height)), ((width - new_width) // 2, (height - new_height) // 2))
        resized_image = resized_image.convert("RGB")
        resized_image=resize_2(resized_image)
        return resized_image
    elif scale_option == "longest":
    #暂时不用,  
        if original_width > original_height:
            new_width=width
            scale = width / original_width
            new_height = int(original_height * scale)
            x=0
            y=int((new_height-height)*0.5)
            resized_image = Image.new("RGB", (new_width, new_height), color=color)
            resized_image.paste(layer_image.resize((new_width, new_height)), (x,y))
            resized_image = resized_image.convert("RGB")
            resized_image=resize_2(resized_image)
            return resized_image
        else:
            new_height=height
            scale = height / original_height
            new_width = int(original_height * scale)
            x=int((new_width-width)*0.5)
            y=0
            resized_image = Image.new("RGB", (new_width, new_height), color=color)
            resized_image.paste(layer_image.resize((new_width, new_height)), (x,y))
            resized_image = resized_image.convert("RGB")
            resized_image=resize_2(resized_image)
            return resized_image

    
    layer_image=resize_2(layer_image)
    return layer_image


def generate_text_image(text, font_path, font_size, text_color, vertical=True, stroke=False, stroke_color=(0, 0, 0), stroke_width=1, spacing=0, padding=4):
    # Split text into lines based on line breaks
    lines = text.split("\n")

    # Load font
    font = ImageFont.truetype(font_path, font_size)

    # 1. Determine layout direction
    if vertical:
        layout = "vertical"
    else:
        layout = "horizontal"

    # 2. Calculate absolute coordinates for each character
    char_coordinates = []
    x, y = padding, padding
    max_width, max_height = 0, 0

    if layout == "vertical":
        for line in lines:
            max_char_width = max(font.getsize(char)[0] for char in line)
            for char in line:
                char_width, char_height = font.getsize(char)
                char_coordinates.append((x, y))
                y += char_height + spacing
                max_height = max(max_height, y + padding)
            x += max_char_width + spacing
            y = padding
        max_width = x
    else:
        for line in lines:
            line_width, line_height = font.getsize(line)
            for char in line:
                char_width, char_height = font.getsize(char)
                char_coordinates.append((x, y))
                x += char_width + spacing
                max_width = max(max_width, x + padding)
            y += line_height + spacing
            x = padding
        max_height = y

    # 3. Create image with calculated width and height
    image = Image.new('RGBA', (max_width, max_height), (255, 255, 255, 0))
    draw = ImageDraw.Draw(image)

    # 4. Draw each character on the image
    index = 0
    for line in lines:
        for char in line:
            x, y = char_coordinates[index]
            if stroke:
                draw.text((x-stroke_width, y), char, font=font, fill=text_color)
                draw.text((x+stroke_width, y), char, font=font, fill=text_color)
                draw.text((x, y-stroke_width), char, font=font, fill=text_color)
                draw.text((x, y+stroke_width), char, font=font, fill=text_color)
            
            draw.text((x, y), char, font=font, fill=text_color)
            index += 1

    # Separate alpha channel
    alpha_channel = image.split()[3]

    # Create a new image with only the alpha channel
    alpha_image = Image.new('L', image.size)
    alpha_image.putdata(alpha_channel.getdata())

    image = image.convert('RGB')

    return (image, alpha_image)



def base64_to_image(base64_string):
    # 去除前缀
    prefix, base64_data = base64_string.split(",", 1)
    
    # 从base64字符串中解码图像数据
    image_data = base64.b64decode(base64_data)
    
    # 创建一个内存流对象
    image_stream = io.BytesIO(image_data)
    
    # 使用PIL的Image模块打开图像数据
    image = Image.open(image_stream)
    
    return image


def create_temp_file(image):
    output_dir = folder_paths.get_temp_directory()

    (
            full_output_folder,
            filename,
            counter,
            subfolder,
            _,
        ) = folder_paths.get_save_image_path('material', output_dir)

    
    image=tensor2pil(image)
 
    image_file = f"{filename}_{counter:05}.png"
     
    image_path=os.path.join(full_output_folder, image_file)

    image.save(image_path,compress_level=4)

    return [{
                "filename": image_file,
                "subfolder": subfolder,
                "type": "temp"
                }]


class SmoothMask:
    @classmethod
    def INPUT_TYPES(s):
        return {
                "required": {
                                "mask": ("MASK",),
                                "smoothness":("INT", {"default": 1, 
                                                        "min":0, 
                                                        "max": 150, 
                                                        "step": 1,
                                                        "display": "slider"})
                            }
            }
    
    RETURN_TYPES = ('MASK',)

    FUNCTION = "run"

    CATEGORY = "♾️Mixlab/Mask"

    INPUT_IS_LIST = False

    OUTPUT_IS_LIST = (False,)
  
    # 运行的函数
    def run(self,mask,smoothness):
        # result = mask.reshape((-1, 1, mask.shape[-2], mask.shape[-1])).movedim(1, -1).expand(-1, -1, -1, 3)
        print('SmoothMask',mask.shape)
        mask=tensor2pil(mask)
    
        # 打开图像并将其转换为黑白图
        # image = mask.convert('L')

        # 应用羽化效果
        feathered_image = mask.filter(ImageFilter.GaussianBlur(smoothness))

        mask=pil2tensor(feathered_image)
           
        return (mask,)






class SplitLongMask:

    @classmethod
    def INPUT_TYPES(s):
        return {
                "required": {
                                "long_mask": ("MASK",),
                                "count":("INT", {"default": 1, "min": 1, "max": 1024, "step": 1})
                            }
            }
    
    RETURN_TYPES = ('MASK',)

    FUNCTION = "run"

    CATEGORY = "♾️Mixlab/Mask"

    OUTPUT_IS_LIST = (True,)
  
    # 运行的函数
    def run(self,long_mask,count):
        masks=[]
        nh=long_mask.shape[0]//count

        if nh*count==long_mask.shape[0]:
            masks=split_mask_by_new_height(long_mask,nh)
        else:
            masks=split_mask_by_new_height(long_mask,long_mask.shape[0])

        return (masks,)



# 一个batch传进来 INPUT_IS_LIST = False
# mask始终会被拍平,([2, 568, 512]) -- > ([1136, 512])
# 原因是一个batch传来的
class TransparentImage:
    @classmethod
    def INPUT_TYPES(s):
        return {
                "required": {
                                "images": ("IMAGE",),
                                "masks": ("MASK",),
                                "invert": (["yes", "no"],),
                                "save": (["yes", "no"],),
                            },
                "optional":{
                    "filename_prefix":("STRING", {"multiline": False,"default": "Mixlab_save"})
                },
                "hidden": {"prompt": "PROMPT", "extra_pnginfo": "EXTRA_PNGINFO"}
            }
    
    RETURN_TYPES = ('STRING','IMAGE','RGBA')
    RETURN_NAMES = ("file_path","IMAGE","RGBA",)

    OUTPUT_NODE = True

    FUNCTION = "run"

    CATEGORY = "♾️Mixlab/Image"

    # INPUT_IS_LIST = True, 一个batch传进来
    OUTPUT_IS_LIST = (True,True,True,)
    # OUTPUT_NODE = True

    # 运行的函数
    def run(self,images,masks,invert,save,filename_prefix,prompt=None, extra_pnginfo=None):
        # print('TransparentImage',images.shape,images.size(),masks.shape,masks.size())
        # print(masks.shape,masks.size())

        ui_images=[]
        image_paths=[]
        
        count=images.shape[0]
        masks_new=[]
        nh=masks.shape[0]//count

        masks_new=masks

        if images.shape[0]==masks.shape[0] and  images.shape[1]==masks.shape[1] and  images.shape[2]==masks.shape[2]:
            print('TransparentImage',images.shape,images.size(),masks.shape,masks.size())
        else:
            #INPUT_IS_LIST = False, 一个batch传进来
            if nh*count==masks.shape[0]:
                masks_new=split_mask_by_new_height(masks,nh)
            else:
                masks_new=split_mask_by_new_height(masks,masks.shape[0])


        is_save=True if save=='yes' else False
        # filename_prefix += self.prefix_append

        images_rgb=[]
        images_rgba=[]

        for i in range(len(images)):
            image=images[i]
            mask=masks_new[i]

            result=doMask(image,mask,is_save,filename_prefix,invert,not is_save,prompt, extra_pnginfo)

            for item in result["result"]:
                ui_images.append(item)

            image_paths.append(result['image_path'])

            images_rgb.append(result['im_tensor'])
            images_rgba.append(result['im_rgba_tensor'])
        
        # ui.images 节点里显示图片,和 传参,image_path自定义的数据,需要写节点的自定义ui
        # result 里输出给下个节点的数据 
        # print('TransparentImage',len(images_rgb))
        
        return {"ui":{"images": ui_images,"image_paths":image_paths},"result": (image_paths,images_rgb,images_rgba)}



class ImagesPrompt:
    @classmethod
    def INPUT_TYPES(s):
        # input_dir = folder_paths.get_input_directory()
        # files = [f for f in os.listdir(input_dir) if os.path.isfile(os.path.join(input_dir, f))]
        return {
            "required": { 
               "image_base64": ("STRING",{"multiline": False,"default": "","dynamicPrompts": False}),
               "text": ("STRING",{"multiline": True,"default": "","dynamicPrompts": True}),
            }
            }
    
    RETURN_TYPES = ("IMAGE","STRING",)
    RETURN_NAMES = ("image","text",)

    FUNCTION = "run"

    CATEGORY = "♾️Mixlab/Input"

    INPUT_IS_LIST = False
    OUTPUT_IS_LIST = (False,False,)
    OUTPUT_NODE = False

    # 运行的函数
    def run(self,image_base64,text):
        image = base64_to_image(image_base64)
        image=image.convert('RGB')
        image=pil2tensor(image)
        return (image,text,)


class EnhanceImage:
    @classmethod
    def INPUT_TYPES(s):
        return {
                "required": {
                                "image": ("IMAGE",),
                                "contrast":("FLOAT", {"default": 0.5, 
                                                        "min":0, 
                                                        "max": 10, 
                                                        "step": 0.01,
                                                        "display": "slider"})
                            }
            }
    
    RETURN_TYPES = ('IMAGE',)

    FUNCTION = "run"

    CATEGORY = "♾️Mixlab/Image"

    INPUT_IS_LIST = True

    OUTPUT_IS_LIST = (True,)
  
    # 运行的函数
    def run(self,image,contrast):
        # print('EnhanceImage',len(image),image[0].shape)
        contrast=contrast[0]
        res=[]
        for ims in image:
            for im in ims:

                image=tensor2pil(im)
            
                image=enhance_depth_map(image,contrast)

                image=pil2tensor(image)

                res.append(image)
           
        return (res,)




class LoadImages_:
    @classmethod
    def INPUT_TYPES(s):
        
        return {"required":
                    {"images": ("IMAGEBASE64",), 
                     },
                }

    CATEGORY = "♾️Mixlab/Image"

    INPUT_IS_LIST = False
    OUTPUT_IS_LIST = (False,)

    RETURN_TYPES = ("IMAGE",)
    FUNCTION = "load_image"
    def load_image(self, images):

        # print(images)
        ims=[]
        for im in images['base64']:
            image = base64_to_image(im)
            image=image.convert('RGB')
            image=pil2tensor(image)
            ims.append(image)

        image1 = ims[0]
        for image2 in ims[1:]:
            if image1.shape[1:] != image2.shape[1:]:
                image2 = comfy.utils.common_upscale(image2.movedim(-1, 1), image1.shape[2], image1.shape[1], "bilinear", "center").movedim(1, -1)
            image1 = torch.cat((image1, image2), dim=0)
        return (image1,)
        
 


''' 
("STRING",{"multiline": False,"default": "Hello World!"})
对应 widgets.js 里:
const defaultVal = inputData[1].default || ""; 
const multiline = !!inputData[1].multiline;
    '''

# 支持按照时间排序
# 支持输出1张
#
class LoadImagesFromPath:
 
    @classmethod
    def INPUT_TYPES(s):
        return {
                "required": {
                                "file_path": ("STRING",{"multiline": False,"default": "","dynamicPrompts": False}),
                            },
                "optional":{
                    "white_bg": (["disable","enable"],),
                    "newest_files": (["enable", "disable"],),
                    "index_variable":("INT", {
                        "default": 0, 
                        "min": -1, #Minimum value
                        "max": 2048, #Maximum value
                        "step": 1, #Slider's step
                        "display": "number" # Cosmetic only: display as "number" or "slider"
                    }),
                    "watcher":(["disable","enable"],),
                    "result": ("WATCHER",),#为了激活本节点运行
                     "prompt": ("PROMPT",),
                    # "seed": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff}),
                }
            }
    
    RETURN_TYPES = ('IMAGE','MASK','STRING','STRING',)
    RETURN_NAMES = ("IMAGE","MASK","prompt_for_FloatingVideo","filepaths",)

    FUNCTION = "run"

    CATEGORY = "♾️Mixlab/Image"

    # INPUT_IS_LIST = True
    OUTPUT_IS_LIST = (True,True,False,True,)
  
    global watcher_folder
    watcher_folder=None

    # 运行的函数
    def run(self,file_path,white_bg,newest_files,index_variable,watcher,result,prompt):
        global watcher_folder
        # print('###监听:',watcher_folder,watcher,file_path,result)

        if watcher_folder==None:
            watcher_folder = FolderWatcher(file_path)

        watcher_folder.set_folder_path(file_path)
        
        if watcher=='enable': 
            # 在这里可以进行其他操作,监听会在后台持续
            watcher_folder.set_folder_path(file_path)
            watcher_folder.start()
        else:
            if watcher_folder!=None:
                watcher_folder.stop()

        #TODO 修bug: ps6477. tmp 
        images=get_images_filepath(file_path,white_bg=='enable')

        # 当开启了监听,则取最新的,第一个文件
        if watcher=='enable':
            index_variable=0
            newest_files='enable'

        # 排序
        sorted_files = sorted(images, key=lambda x: os.path.getmtime(x['file_path']), reverse=(newest_files=='enable'))

        imgs=[]
        masks=[]
        file_names=[]

        for im in sorted_files:
            imgs.append(im['image'])
            masks.append(im['mask'])
            file_names.append(im['file_name'])
        
        # print('index_variable',index_variable)
        
        try:
            if index_variable!=-1:
                imgs=[imgs[index_variable]] if index_variable < len(imgs) else None
                masks=[masks[index_variable]] if index_variable < len(masks) else None
                file_names=[file_names[index_variable]] if index_variable < len(file_names) else None
        except Exception as e:
            print("发生了一个未知的错误:", str(e))

        # print('#prompt::::',prompt)
        return  {"ui": {"seed": [1]}, "result":(imgs,masks,prompt,file_names,)}


# TODO 扩大选区的功能,重新输出mask
class ImageCropByAlpha:
    @classmethod
    def INPUT_TYPES(s):
        return {"required": { "image": ("IMAGE",),
                             "RGBA": ("RGBA",),  },
                }
    
    RETURN_TYPES = ("IMAGE","MASK","MASK","INT","INT","INT","INT",)
    RETURN_NAMES = ("IMAGE","MASK","AREA_MASK","x","y","width","height",)

    FUNCTION = "run"

    CATEGORY = "♾️Mixlab/Image"

    INPUT_IS_LIST = True
    OUTPUT_IS_LIST = (True,True,True,True,True,True,True,)

    def run(self,image,RGBA):
        # print(image.shape,RGBA.shape)

        image=image[0]
        RGBA=RGBA[0]

        bf_im = tensor2pil(image)

        # print(RGBA)
        im=tensor2pil(RGBA)

        # 要把im的alpha通道转为mask
        im=im.convert('RGBA')
        red, green, blue, alpha = im.split()

        im=naive_cutout(bf_im,alpha)
        x, y, w, h=get_not_transparent_area(im)
        # print('#ForImageCrop:',w, h,x, y,)

        x = min(x, image.shape[2] - 1)
        y = min(y, image.shape[1] - 1)
        to_x = w + x
        to_y = h + y

        x_1=x
        y_1=y
        width_1=w
        height_1=h

        img = image[:,y:to_y, x:to_x, :]
        # tensor2pil(img).save('test2.png')

        # 原图的mask
        ori=RGBA[:,y:to_y, x:to_x, :]
        ori=tensor2pil(ori)
        # ori.save('test.png')

        # 创建一个新的图像对象,大小和模式与原始图像相同
        new_image = Image.new("RGBA", ori.size)

        # 获取原始图像的像素数据
        pixel_data = ori.load()

        # 获取新图像的像素数据
        new_pixel_data = new_image.load()

        # 遍历图像的每个像素
        for y in range(ori.size[1]):
            for x in range(ori.size[0]):
                # 获取当前像素的RGBA值
                r, g, b, a = pixel_data[x, y]

                # 如果a通道不为0(不透明),将当前像素设置为白色
                if a != 0:
                    new_pixel_data[x, y] = (255, 255, 255, 255)
                else:
                    new_pixel_data[x, y] = (0,0,0,0)

        # 保存修改后的图像
        # new_image.save("output.png")
                    
        ori=new_image.convert('L')
        # threshold = 128
        # ori = ori.point(lambda x: 0 if x < threshold else 255, '1')
        ori=pil2tensor(ori)

        # 矩形区域,mask
        b_image =AreaToMask_run(RGBA)
        # img=None
        # b_image=None
        return ([img],[ori],[b_image],[x_1],[y_1],[width_1],[height_1],)



# get_files_with_extension(FONT_PATH,'.ttf')

class TextImage:
    @classmethod
    def INPUT_TYPES(s):
        return {"required": { 
            
                    "text": ("STRING",{"multiline": True,"default": "龍馬精神迎新歲","dynamicPrompts": False}),
                    "font": (get_files_with_extension(FONT_PATH,'.ttf'),),#后缀为 ttf
                    "font_size": ("INT",{
                                "default":100, 
                                "min": 100, #Minimum value
                                "max": 1000, #Maximum value
                                "step": 1, #Slider's step
                                "display": "number" # Cosmetic only: display as "number" or "slider"
                                }), 
                    "spacing": ("INT",{
                                "default":12, 
                                "min": -200, #Minimum value
                                "max": 200, #Maximum value
                                "step": 1, #Slider's step
                                "display": "number" # Cosmetic only: display as "number" or "slider"
                                }), 
                    "padding": ("INT",{
                                "default":8, 
                                "min": 0, #Minimum value
                                "max": 200, #Maximum value
                                "step": 1, #Slider's step
                                "display": "number" # Cosmetic only: display as "number" or "slider"
                                }), 
                    "text_color":("STRING",{"multiline": False,"default": "#000000","dynamicPrompts": False}),
                    "vertical":("BOOLEAN", {"default": True},),
                    "stroke":("BOOLEAN", {"default": False},),
                             },
                }
    
    RETURN_TYPES = ("IMAGE","MASK",)
    RETURN_NAMES = ("image","mask",)

    FUNCTION = "run"

    CATEGORY = "♾️Mixlab/Image"

    INPUT_IS_LIST = False
    OUTPUT_IS_LIST = (False,False,)

    def run(self,text,font,font_size,spacing,padding,text_color,vertical,stroke):
        
        font_path=os.path.join(FONT_PATH,font+'.ttf')

        if text=="":
            text=" "
        # stroke=False, stroke_color=(0, 0, 0), stroke_width=1, spacing=0
        img,mask=generate_text_image(text,font_path,font_size,text_color,vertical,stroke,(0, 0, 0),1,spacing,padding)
        
        img=pil2tensor(img)
        mask=pil2tensor(mask)

        return (img,mask,)

class LoadImagesFromURL:
    @classmethod
    def INPUT_TYPES(s):
        return {"required": { 
                    "url": ("STRING",{"multiline": True,"default": "https://","dynamicPrompts": False}),
                             },
                "optional":{
                    "seed": (any_type,  {"default": 0, "min": 0, "max": 0xffffffffffffffff}),
                }
                }
    
    RETURN_TYPES = ("IMAGE","MASK",)
    RETURN_NAMES = ("images","masks",)

    FUNCTION = "run"

    CATEGORY = "♾️Mixlab/Image"

    INPUT_IS_LIST = False
    OUTPUT_IS_LIST = (True,True,)


    global urls_image
    urls_image={}

    def run(self,url,seed=0):
        global urls_image
        print(urls_image)
        def filter_http_urls(urls):
            filtered_urls = []
            for url in urls.split('\n'):
                if url.startswith('http'):
                    filtered_urls.append(url)
            return filtered_urls

        filtered_urls = filter_http_urls(url)

        images=[]
        masks=[]

        for img_url in filtered_urls:
            try:
                if img_url in urls_image:
                    img,mask=urls_image[img_url]
                else:
                    img,mask=load_image_and_mask_from_url(img_url)
                    urls_image[img_url]=(img,mask)

                img1=pil2tensor(img)
                mask1=pil2tensor(mask)

                images.append(img1)
                masks.append(mask1)
            except Exception as e:
                print("发生了一个未知的错误:", str(e))
            
        return (images,masks,)




class SvgImage:
    @classmethod
    def INPUT_TYPES(s):
        return {"required": { 
                    "upload":("SVG",),},
                }
    
    RETURN_TYPES = ("IMAGE","LAYER")
    RETURN_NAMES = ("IMAGE","layers",)

    FUNCTION = "run"

    CATEGORY = "♾️Mixlab/Image"

    INPUT_IS_LIST = False
    OUTPUT_IS_LIST = (False,True,)

    def run(self,upload):
        layers=[]

        image = base64_to_image(upload['image'])
        image=image.convert('RGB')
        image=pil2tensor(image)

        for layer in upload['data']:
            layers.append(layer)
    
        return (image,layers,)



class Image3D:
    @classmethod
    def INPUT_TYPES(s):
        return {"required": { 
                    "upload":("THREED",),}, 
                "optional":{
                    "material": ("IMAGE",),
                    }
                }
    
    RETURN_TYPES = ("IMAGE","MASK","IMAGE","IMAGE",)
    RETURN_NAMES = ("IMAGE","MASK","BG_IMAGE","MATERIAL",)

    FUNCTION = "run"

    CATEGORY = "♾️Mixlab/3D"

    INPUT_IS_LIST = False
    OUTPUT_IS_LIST = (False,False,False,False,)
    OUTPUT_NODE = True

    def run(self,upload,material=None):
        # print('material',material)
        # print(upload )
        image = base64_to_image(upload['image'])

        mat=None
        if 'material' in upload and upload['material']:
            mat=base64_to_image(upload['material'])
            mat=mat.convert('RGB')
            mat=pil2tensor(mat)

        mask = image.split()[3]
        image=image.convert('RGB')
        
        mask=mask.convert('L')

        bg_image=None
        if 'bg_image' in upload and upload['bg_image']:
            bg_image = base64_to_image(upload['bg_image'])
            bg_image=bg_image.convert('RGB')
            bg_image=pil2tensor(bg_image)


        mask=pil2tensor(mask)
        image=pil2tensor(image)
        
        m=[]
        if not material is None:
            m=create_temp_file(material[0])
        
        return {"ui":{"material": m},"result": (image,mask,bg_image,mat,)}



def AreaToMask_run(RGBA):
    # print(RGBA)
    im=tensor2pil(RGBA)
    im=naive_cutout(im,im)
    x, y, w, h=get_not_transparent_area(im)
        
    im=im.convert("RGBA")
        # print('#AreaToMask:',im)
    img=areaToMask(x,y,w,h,im)
    img=img.convert("RGBA")
    mask=pil2tensor(img)

    channels = ["red", "green", "blue", "alpha"]
    # print(mask,mask.shape)
    mask = mask[:, :, :, channels.index("green")]

    return mask


class AreaToMask:
    @classmethod
    def INPUT_TYPES(s):
        return {"required": { "RGBA": ("RGBA",),  },
                }
    
    RETURN_TYPES = ("MASK",)
    # RETURN_NAMES = ("WIDTH","HEIGHT","X","Y",)

    FUNCTION = "run"

    CATEGORY = "♾️Mixlab/Mask"

    INPUT_IS_LIST = False
    OUTPUT_IS_LIST = (False,)

    def run(self,RGBA):

        mask =AreaToMask_run(RGBA)

        return (mask,)


class FaceToMask:
    @classmethod
    def INPUT_TYPES(s):
        return {"required": { "image": ("IMAGE",)},
                }
    
    RETURN_TYPES = ("MASK",)
    # RETURN_NAMES = ("WIDTH","HEIGHT","X","Y",)

    FUNCTION = "run"

    CATEGORY = "♾️Mixlab/Mask"

    INPUT_IS_LIST = False
    OUTPUT_IS_LIST = (False,)

    def run(self,image):
        # print(image)
        im=tensor2pil(image)
        mask=detect_faces(im)

        mask=pil2tensor(mask)
        channels = ["red", "green", "blue", "alpha"]
        mask = mask[:, :, :, channels.index("green")]

        return (mask,)


class CompositeImages:
    @classmethod
    def INPUT_TYPES(s):
        return {
            "required": { 
                    "foreground": (any_type,),
                    "mask":("MASK",),
                    "background": ("IMAGE",),
                    },
             "optional":{ 
                  "is_multiply_blend":  ("BOOLEAN", {"default": False}),
                  "position":  (['overall',"center_center","left_bottom","center_bottom","right_bottom","left_top","center_top","right_top"],),
                   "scale": ("FLOAT",{
                                "default":0.35, 
                                "min": 0.01, #Minimum value
                                "max": 1, #Maximum value
                                "step": 0.01, #Slider's step
                                "display": "number" # Cosmetic only: display as "number" or "slider"
                            }), 
                    }
                }
    
    RETURN_TYPES = ("IMAGE",)
    RETURN_NAMES = ("IMAGE",)

    FUNCTION = "run"

    CATEGORY = "♾️Mixlab/Layer"

    # OUTPUT_IS_LIST = (True,)

    # def run(self, foreground,mask,background,is_multiply_blend,position,scale):
    #     foreground= tensor2pil(foreground)
    #     mask= tensor2pil(mask)
    #     background= tensor2pil(background)
    #     res=composite_images(foreground,background,mask,is_multiply_blend,position,scale)
        
    #     return (pil2tensor(res),)

    def run(self, foreground,mask,background, is_multiply_blend, position, scale):
        results = []
        
        f1=[]
        for fg, mask in zip(foreground, mask ):
            f1.append([fg,mask])

        
        for f, bg in product(f1, background):
            [fg,mask]=f
            fg_pil = tensor2pil(fg)
            mask_pil = tensor2pil(mask)
            bg_pil = tensor2pil(bg)
            res = composite_images(fg_pil, bg_pil, mask_pil, is_multiply_blend, position, scale)
            results.append(pil2tensor(res))
        
        output_image = torch.cat(results, dim=0)

        return (output_image,)


class EmptyLayer:
    @classmethod
    def INPUT_TYPES(s):
        return {
            "required": { 
                "width": ("INT",{
                    "default":512, 
                    "min": 1, #Minimum value
                    "max": 8192, #Maximum value
                    "step": 1, #Slider's step
                    "display": "number" # Cosmetic only: display as "number" or "slider"
                }),
               "height": ("INT",{
                    "default": 512, 
                    "min": 1, #Minimum value
                    "max": 8192, #Maximum value
                    "step": 1, #Slider's step
                    "display": "number" # Cosmetic only: display as "number" or "slider"
                }),
            },
        
                }
    
    RETURN_TYPES = ("LAYER",)
    RETURN_NAMES = ("layers",)

    FUNCTION = "run"

    CATEGORY = "♾️Mixlab/Layer"

    OUTPUT_IS_LIST = (True,)

    def run(self, width,height):
        blank_image = Image.new("RGB", (width, height))
        
        mask=blank_image.convert('L')

        blank_image=pil2tensor(blank_image)
        mask=pil2tensor(mask)

        layer_n=[{
            "x":0,
            "y":0,
            "width":width,
            "height":height,
            "z_index":0,
            "scale_option":'width',
            "image":blank_image,
            "mask":mask
        }]
        return (layer_n,)


class NewLayer:
    @classmethod
    def INPUT_TYPES(s):
        return {
            
            "required": { 
                "x": ("INT",{
                    "default": 0, 
                    "min": -1024, #Minimum value
                    "max": 8192, #Maximum value
                    "step": 1, #Slider's step
                    "display": "number" # Cosmetic only: display as "number" or "slider"
                }),
                "y": ("INT",{
                    "default": 0, 
                    "min": -1024, #Minimum value
                    "max": 8192, #Maximum value
                    "step": 1, #Slider's step
                    "display": "number" # Cosmetic only: display as "number" or "slider"
                }),
                "width": ("INT",{
                    "default": 512, 
                    "min": 1, #Minimum value
                    "max": 8192, #Maximum value
                    "step": 1, #Slider's step
                    "display": "number" # Cosmetic only: display as "number" or "slider"
                }),
                "height": ("INT",{
                    "default": 512, 
                    "min": 1, #Minimum value
                    "max": 8192, #Maximum value
                    "step": 1, #Slider's step
                    "display": "number" # Cosmetic only: display as "number" or "slider"
                }),
                "z_index": ("INT",{
                    "default": 0, 
                    "min":0, #Minimum value
                    "max": 100, #Maximum value
                    "step": 1, #Slider's step
                    "display": "number" # Cosmetic only: display as "number" or "slider"
                }),
                "scale_option": (["width","height",'overall'],),
                "image": (any_type,),
            },
             "optional":{
                    "mask": ("MASK",{"default": None}),
                    "layers": ("LAYER",{"default": None}), 
                    "canvas": ("IMAGE",{"default": None}), 
                }
                }
    
    RETURN_TYPES = ("LAYER",)
    RETURN_NAMES = ("layers",)

    FUNCTION = "run"

    CATEGORY = "♾️Mixlab/Layer"

    INPUT_IS_LIST = True
    OUTPUT_IS_LIST = (True,)

    def run(self,x,y,width,height,z_index,scale_option,image,mask=None,layers=None,canvas=None):
        # print(x,y,width,height,z_index,image,mask)
        
        if mask==None:
            im=tensor2pil(image[0])
            mask=im.convert('L')
            mask=pil2tensor(mask)
        else:
            mask=mask[0]
        
        layer_n=[{
            "x":x[0],
            "y":y[0],
            "width":width[0],
            "height":height[0],
            "z_index":z_index[0],
            "scale_option":scale_option[0],
            "image":image[0],
            "mask":mask
        }]

        if layers!=None:
            layer_n=layer_n+layers

        return (layer_n,)



def createMask(image,x,y,w,h):
    mask = Image.new("L", image.size)
    pixels = mask.load()
    # 遍历指定区域的像素,将其设置为黑色(0 表示黑色)
    for i in range(int(x), int(x + w)):
        for j in range(int(y), int(y + h)):
            pixels[i, j] = 255
    # mask.save("mask.png")
    return mask

def splitImage(image, num):
    width, height = image.size

    num_rows = int(num ** 0.5)
    num_cols = int(num / num_rows)
    
    grid_width = int(width // num_cols)
    grid_height = int(height // num_rows)

    grid_coordinates = []
    for i in range(num_rows):
        for j in range(num_cols):
            x = int(j * grid_width)
            y = int(i * grid_height)
            grid_coordinates.append((x, y, grid_width, grid_height))

    return grid_coordinates


def centerImage(margin,canvas):
    w,h=canvas.size

    l,t,r,b=margin

    x=l
    y=t
    width=w-r-l
    height=h-t-b

    return (x,y,width,height)

# # 读取图片
# image = Image.open("path_to_your_image.jpg")

# # 定义要切割的区域数量
# num = 9

# # 切割图片
# grid_coordinates = splitImage(image, num)

# # 输出切割区域坐标
# for i, coordinates in enumerate(grid_coordinates):
#     print(f"Region {i + 1}: x={coordinates[0]}, y={coordinates[1]}, width={coordinates[2]}, height={coordinates[3]}")


class SplitImage:
    @classmethod
    def INPUT_TYPES(s):
        return { 
            "required": { 
                "image": ("IMAGE",), 
                "num": ("INT",{
                    "default": 4, 
                    "min": 1, #Minimum value
                    "max": 500, #Maximum value
                    "step": 1, #Slider's step
                    "display": "number" # Cosmetic only: display as "number" or "slider"
                }),
                "seed": ("INT",{
                    "default": 4, 
                    "min": 1, #Minimum value
                    "max": 500, #Maximum value
                    "step": 1, #Slider's step
                    "display": "number" # Cosmetic only: display as "number" or "slider"
                }),
            }
                }
    
    RETURN_TYPES = ("_GRID","_GRID","MASK",)
    RETURN_NAMES = ("grids","grid","mask",)

    FUNCTION = "run"

    CATEGORY = "♾️Mixlab/Layer"

    INPUT_IS_LIST = False
    # OUTPUT_IS_LIST = (True,)

    def run(self,image,num,seed):
        
        if type(seed) == list and len(seed)==1:
            seed=seed[0]

        image=tensor2pil(image)
        
        grids=splitImage(image,num)

        if seed>num:
            num=seed % (num + 1)
        else:
            num=seed-1
        
        print('#SplitImage',seed)

        num=max(0,num) 
        num=min(num,len(grids)-1)
        
        g=grids[num]

        x,y,w,h=g
        mask=createMask(image, x,y,w,h)
        mask=pil2tensor(mask)

        return (grids,g,mask,)



class CenterImage:
    @classmethod
    def INPUT_TYPES(s):
        return { 
            "required": { 
                "canvas": ("IMAGE",), 
                "left": ("INT",{
                    "default":24, 
                    "min": 0, #Minimum value
                    "max": 5000, #Maximum value
                    "step": 1, #Slider's step
                    "display": "number" # Cosmetic only: display as "number" or "slider"
                }),
               "top": ("INT",{
                    "default":24, 
                    "min": 0, #Minimum value
                    "max": 5000, #Maximum value
                    "step": 1, #Slider's step
                    "display": "number" # Cosmetic only: display as "number" or "slider"
                }),
                "right": ("INT",{
                    "default": 24, 
                    "min": 0, #Minimum value
                    "max": 5000, #Maximum value
                    "step": 1, #Slider's step
                    "display": "number" # Cosmetic only: display as "number" or "slider"
                }),
                 "bottom": ("INT",{
                    "default": 24, 
                    "min": 0, #Minimum value
                    "max": 5000, #Maximum value
                    "step": 1, #Slider's step
                    "display": "number" # Cosmetic only: display as "number" or "slider"
                }),
            }
                }
    
    RETURN_TYPES = ("_GRID","MASK",)
    RETURN_NAMES = ("grid","mask",)

    FUNCTION = "run"

    CATEGORY = "♾️Mixlab/Layer"

    INPUT_IS_LIST = False
    # OUTPUT_IS_LIST = (True,)

    def run(self,canvas,left,top,right,bottom):
        canvas=tensor2pil(canvas)

        grid=centerImage((left,top,right,bottom),canvas)

        mask=createMask(canvas,left,top,canvas.width-left-right,canvas.height-top-bottom)

        return (grid,pil2tensor(mask),)

class GridDisplayAndSave:
    @classmethod
    def INPUT_TYPES(s):
        return { 
            "required": {
                "labels": ("STRING", 
                                        {
                                            "multiline": True, 
                                            "default": "",
                                            "forceInput": True,
                                            "dynamicPrompts": False
                                        }),
                "grids": ("_GRID",),
                
                "image": ("IMAGE",),
                "filename_prefix": ("STRING", {"default": "mixlab/grids"})
            }
                }
    
    RETURN_TYPES = ( )
    RETURN_NAMES = ( )

    FUNCTION = "run"

    CATEGORY = "♾️Mixlab/Layer"

    INPUT_IS_LIST = True
    OUTPUT_NODE = True
    # OUTPUT_IS_LIST = (True,)

    def run(self,labels,grids,image,filename_prefix):

        # print(image.shape)

        img= tensor2pil(image[0])

        for grid in grids:
            draw_rectangle(img, grid, 'red',8)

        #获取临时目录:temp
        output_dir = folder_paths.get_temp_directory()

        (
            full_output_folder,
            filename,
            counter,
            subfolder,
            _,
        ) = folder_paths.get_save_image_path('tmp_', output_dir)
        
        image_file = f"{filename}_{counter:05}.png"

        image_path=os.path.join(full_output_folder, image_file)
        # 保存图片
        img.save(image_path,compress_level=6)
        width, height = img.size

        (
            full_output_folder,
            filename,
            counter,
            _,
            _,
        ) = folder_paths.get_save_image_path(filename_prefix[0], output_dir)


        data_converted = [{
            "label":labels[i],
            "grid":[float(grids[i][0]),
                           float(grids[i][1]),
                           float(grids[i][2]),
                           float(grids[i][3])
                           ]
        } for i in range(len(grids))]

        data={
            "width":int(width),
            "height":int(height),
            "grids":data_converted
        }

        save_json_to_file(data,os.path.join(full_output_folder,f"${filename}_{counter:05}.json"))

        return {"ui":{"image": [{
                "filename": image_file,
                "subfolder": subfolder,
                "type":"temp"
            }],
            "json":[data["width"],data['height'],data["grids"]]
            },"result": ()}
        # return {"ui":{"image": [ ],
             
        #     },"result": ()}

class GridInput:
    @classmethod
    def INPUT_TYPES(s):
        return { 
            "required": {
                "grids": ("STRING", 
                                        {
                                            "multiline": True, 
                                            "default": "",
                                            "dynamicPrompts": False
                                        }),
                "padding":("INT",{
                    "default": 24, 
                    "min": -500, #Minimum value
                    "max": 5000, #Maximum value
                    "step": 1, #Slider's step
                    "display": "number" # Cosmetic only: display as "number" or "slider"
                }),
                
            },
            "optional":{
                    "width":("INT",{
                        "forceInput": True,
                    }),
                     "height":("INT",{
                        "forceInput": True,
                    }),
                }

                }
    
    RETURN_TYPES = ("_GRID","STRING","IMAGE",)
    RETURN_NAMES = ("grids","labels","image",)

    FUNCTION = "run"

    CATEGORY = "♾️Mixlab/Input"

    INPUT_IS_LIST = True
    OUTPUT_IS_LIST = (True,True,False,)
    OUTPUT_NODE = True

    def run(self,grids,padding,width=[-1],height=[-1]):
        # print(padding[0],grids[0])
        width=width[0]
        height=height[0]

        grids=grids[0]
        data=json.loads(grids)
        grids=data['grids']

        if width>-1:
            data['width']=width
        if height>-1:
            data['height']=height
    
        new_grids=[]
        labels=[]
        
        for g in grids:
            labels.append(g['label'])
            new_grids.append(padding_rectangle(g['grid'],padding[0]))

        image = Image.new("RGB", (int(data['width']),int(data["height"])), "white")
        im=pil2tensor(image)
        # image=create_temp_file(im)

        data_converted = [{
            "label":labels[i],
            "grid":[float(new_grids[i][0]),
                           float(new_grids[i][1]),
                           float(new_grids[i][2]),
                           float(new_grids[i][3])
                           ]
        } for i in range(len(new_grids))]

        # 传递到前端节点的数据 报错,需要处理成 key:[x,x,x,x]
        return {"ui":{
            "json":[data["width"],data["height"],data_converted]
            },"result": (new_grids,labels,im,)}
    
        # return (new_grids,labels,pil2tensor(image),)

class GridOutput:
    @classmethod
    def INPUT_TYPES(s):
        return { 
            "required": {
                "grid": ("_GRID",),
                
            },
            "optional":{
                  "bg_image":("IMAGE",)
                }
                }
    
    RETURN_TYPES = ("INT","INT","INT","INT","MASK",)
    RETURN_NAMES = ("x","y","width","height","mask",)

    FUNCTION = "run"

    CATEGORY = "♾️Mixlab/Layer"

    INPUT_IS_LIST = False
    # OUTPUT_IS_LIST = (True,)

    def run(self,grid,bg_image=None):
        x,y,w,h=grid
        x=int(x)
        y=int(y)
        w=int(w)
        h=int(h)

        masks=[]
        if bg_image!=None:
            for i in range(len(bg_image)):
                im=bg_image[i]
                #增加输出mask
                im=tensor2pil(im)
                mask=areaToMask(x,y,w,h,im)
                mask=pil2tensor(mask)
                masks.append(mask)
        out=None
        if len(masks)>0:
            out = torch.cat(masks, dim=0)
        return (x,y,w,h,out,)




class ShowLayer:
    @classmethod
    def INPUT_TYPES(s):
        return {
            
            "required": { 
                "edit": ("EDIT",),
               
                "x": ("INT",{
                    "default": 0, 
                    "min": -100, #Minimum value
                    "max": 8192, #Maximum value
                    "step": 1, #Slider's step
                    "display": "number" # Cosmetic only: display as "number" or "slider"
                }),
                "y": ("INT",{
                    "default": 0, 
                    "min": 0, #Minimum value
                    "max": 8192, #Maximum value
                    "step": 1, #Slider's step
                    "display": "number" # Cosmetic only: display as "number" or "slider"
                }),
                "width": ("INT",{
                    "default": 512, 
                    "min": 1, #Minimum value
                    "max": 8192, #Maximum value
                    "step": 1, #Slider's step
                    "display": "number" # Cosmetic only: display as "number" or "slider"
                }),
                "height": ("INT",{
                    "default": 512, 
                    "min": 1, #Minimum value
                    "max": 8192, #Maximum value
                    "step": 1, #Slider's step
                    "display": "number" # Cosmetic only: display as "number" or "slider"
                }),
                "z_index": ("INT",{
                    "default": 0, 
                    "min":0, #Minimum value
                    "max": 100, #Maximum value
                    "step": 1, #Slider's step
                    "display": "number" # Cosmetic only: display as "number" or "slider"
                }),
                "scale_option": (["width","height",'overall'],),
                # "image": ("IMAGE",),
            },
             "optional":{
                    # "mask": ("MASK",{"default": None}),
                    "layers": ("LAYER",{"default": None}), 
                }
                }
    
    RETURN_TYPES = ( )
    RETURN_NAMES = ( )

    FUNCTION = "run"

    CATEGORY = "♾️Mixlab/Layer"

    INPUT_IS_LIST = True
    # OUTPUT_IS_LIST = (True,)

    def run(self,edit,x,y,width,height,z_index,scale_option,layers):
        # print(x,y,width,height,z_index,image,mask)
        
        # if mask==None:
        #     im=tensor2pil(image)
        #     mask=im.convert('L')
        #     mask=pil2tensor(mask)
        # else:
        #     mask=mask[0]

        # layers[edit[0]]={
        #     "x":x[0],
        #     "y":y[0],
        #     "width":width[0],
        #     "height":height[0],
        #     "z_index":z_index[0],
        #     "scale_option":scale_option[0],
        #     "image":image[0],
        #     "mask":mask
        # }

        return ( )


class MergeLayers:
    @classmethod
    def INPUT_TYPES(s):
        return {"required": { 
                            "layers": ("LAYER",),
                            "images": ("IMAGE",),
                                            },
            "optional":{
                           
                            "is_multiply_blend":  ("BOOLEAN", {"default": False}),
                            
                    }
                }
    
    RETURN_TYPES = ("IMAGE","MASK",)
    RETURN_NAMES = ("IMAGE","MASK",)

    FUNCTION = "run"

    CATEGORY = "♾️Mixlab/Layer"

    INPUT_IS_LIST = True
    # OUTPUT_IS_LIST = (False,)

    def run(self,layers,images,is_multiply_blend):

        bg_images=[]
        masks=[]
        
        is_multiply_blend=is_multiply_blend[0]
        # print(len(images),images[0].shape)
        # 1  torch.Size([2, 512, 512, 3])
        # 4  torch.Size([1, 1024, 768, 3])

        for img in images:

            for bg_image in img:
                # bg_image=image[0]
                bg_image=tensor2pil(bg_image)
                # 按z-index排序
                layers_new = sorted(layers, key=lambda x: x["z_index"])
                
                width, height = bg_image.size
                final_mask= Image.new('L', (width, height), 0)

                for layer in layers_new:
                    image=layer['image']
                    mask=layer['mask']
                    if 'type' in layer and layer['type']=='base64' and type(image) == str:
                        im=base64_to_image(image)
                        im=im.convert('RGB')
                        image=pil2tensor(im)

                        mask=base64_to_image(mask)
                        mask=mask.convert('L')
                        mask=pil2tensor(mask)
                    
                    
                    layer_image=tensor2pil(image)
                    layer_mask=tensor2pil(mask)
                    # t=layer_image.convert("RGBA")
                    # t.save('test.png') 如果layerimage传入的是rgba,则是透明的
                    bg_image=merge_images(bg_image,
                                        layer_image,
                                        layer_mask,
                                        layer['x'],
                                        layer['y'],
                                        layer['width'],
                                        layer['height'],
                                        layer['scale_option'],
                                        is_multiply_blend
                                        )
                    
                    final_mask=merge_images(final_mask,
                                        layer_mask.convert('RGB'),
                                        layer_mask,
                                        layer['x'],
                                        layer['y'],
                                        layer['width'],
                                        layer['height'],
                                        layer['scale_option']
                                        )
                    
                    final_mask=final_mask.convert('L')
                    
                # mask=bg_image.convert('RGBA')
                final_mask=pil2tensor(final_mask)
                
                bg_image=bg_image.convert('RGB')
                bg_image=pil2tensor(bg_image)

                bg_images.append(bg_image)
                masks.append(final_mask)
        
        bg_images=torch.cat(bg_images, dim=0)
        masks=torch.cat(masks, dim=0)
        return (bg_images,masks,)
    

class GradientImage:
    @classmethod
    def INPUT_TYPES(s):
        return {"required": {
                "width": ("INT",{
                    "default": 512, 
                    "min": 1, # 最小值
                    "max": 8192, # 最大值
                    "step": 1, # 间隔
                    "display": "number" # 控件类型: 输入框 number、滑块 slider
                }),
                "height": ("INT",{
                    "default": 512, 
                    "min": 1,
                    "max": 8192,
                    "step": 1,
                    "display": "number"
                }),
                "start_color_hex": ("STRING",{"multiline": False,"default": "#FFFFFF","dynamicPrompts": False}),
                "end_color_hex": ("STRING",{"multiline": False,"default": "#000000","dynamicPrompts": False}),
                },
                }
    
    # 输出的数据类型
    RETURN_TYPES = ("IMAGE","MASK",)

    # 运行时方法名称
    FUNCTION = "run"

    # 右键菜单目录
    CATEGORY = "♾️Mixlab/Image"

    # 输入是否为列表
    INPUT_IS_LIST = False

    # 输出是否为列表
    OUTPUT_IS_LIST = (False,False,)

    def run(self,width,height,start_color_hex, end_color_hex):

        im,mask=generate_gradient_image(width, height, start_color_hex, end_color_hex)

        #获取临时目录:temp
        output_dir = folder_paths.get_temp_directory()

        (
            full_output_folder,
            filename,
            counter,
            subfolder,
            _,
        ) = folder_paths.get_save_image_path('tmp_', output_dir)
        
        image_file = f"{filename}_{counter:05}.png"

        image_path=os.path.join(full_output_folder, image_file)
        # 保存图片
        im.save(image_path,compress_level=6)

        # 把PIL数据类型转为tensor
        im=pil2tensor(im)

        mask=pil2tensor(mask)

        # 定义ui字段,数据将回传到web前端的 nodeType.prototype.onExecuted
        # result是节点的输出
        return {"ui":{"images": [{
                "filename": image_file,
                "subfolder": subfolder,
                "type":"temp"
            }]},"result": (im,mask,)}



class NoiseImage:
    @classmethod
    def INPUT_TYPES(s):
        return {"required": {
                "width": ("INT",{
                    "default": 512, 
                    "min": 1, # 最小值
                    "max": 8192, # 最大值
                    "step": 1, # 间隔
                    "display": "number" # 控件类型: 输入框 number、滑块 slider
                }),
                "height": ("INT",{
                    "default": 512, 
                    "min": 1,
                    "max": 8192,
                    "step": 1,
                    "display": "number"
                }),
                "noise_level": ("INT",{
                    "default": 128, 
                    "min": 0,
                    "max": 8192,
                    "step": 1,
                    "display": "slider"
                }),
                "color_hex": ("STRING",{"multiline": False,"default": "#FFFFFF","dynamicPrompts": False}),
                },
                }
    
    # 输出的数据类型
    RETURN_TYPES = ("IMAGE",)

    # 运行时方法名称
    FUNCTION = "run"

    # 右键菜单目录
    CATEGORY = "♾️Mixlab/Image"

    # 输入是否为列表
    INPUT_IS_LIST = False

    # 输出是否为列表
    OUTPUT_IS_LIST = (False,)

    def run(self,width,height,noise_level,color_hex):
        # 创建噪声图像
        im=create_noisy_image(width,height,"RGB",noise_level,color_hex)
        
        #获取临时目录:temp
        output_dir = folder_paths.get_temp_directory()

        (
            full_output_folder,
            filename,
            counter,
            subfolder,
            _,
        ) = folder_paths.get_save_image_path('tmp_', output_dir)
        
        image_file = f"{filename}_{counter:05}.png"

        image_path=os.path.join(full_output_folder, image_file)
        # 保存图片
        im.save(image_path,compress_level=6)

        # 把PIL数据类型转为tensor
        im=pil2tensor(im)

        # 定义ui字段,数据将回传到web前端的 nodeType.prototype.onExecuted
        # result是节点的输出
        return {"ui":{"images": [{
                "filename": image_file,
                "subfolder": subfolder,
                "type":"temp"
            }]},"result": (im,)}


class ResizeImage:
    @classmethod
    def INPUT_TYPES(s):
        return {"required": {
            "width": ("INT",{
                    "default": 512, 
                    "min": 1, #Minimum value
                    "max": 8192, #Maximum value
                    "step": 8, #Slider's step
                    "display": "number" # Cosmetic only: display as "number" or "slider"
                }),
                "height": ("INT",{
                    "default": 512, 
                    "min": 1, #Minimum value
                    "max": 8192, #Maximum value
                    "step": 8, #Slider's step
                    "display": "number" # Cosmetic only: display as "number" or "slider"
                }),
                "scale_option": (["width","height",'overall','center'],),

                             },

            "optional":{
                    "image": ("IMAGE",),
                    "average_color": (["on",'off'],),
                    "fill_color":("STRING",{"multiline": False,"default": "#FFFFFF","dynamicPrompts": False}),
                    "mask": ("MASK",),
            }
                }
    
    RETURN_TYPES = ("IMAGE","IMAGE","STRING","MASK",)
    RETURN_NAMES = ("image","average_image","average_hex","mask",)

    FUNCTION = "run"

    CATEGORY = "♾️Mixlab/Image"

    INPUT_IS_LIST = True
    OUTPUT_IS_LIST = (True,True,True,True,)

    def run(self,width,height,scale_option,image=None,average_color=['on'],fill_color=["#FFFFFF"],mask=None):
        
        w=width[0]
        h=height[0]
        scale_option=scale_option[0]
        average_color=average_color[0]
        fill_color=fill_color[0]

        imgs=[]
        masks=[]
        average_images=[]
        hexs=[]

        if image==None:
            im=create_noisy_image(w,h,"RGB")
            a_im,hex=get_average_color_image(im)
            
            im=pil2tensor(im)
            imgs.append(im)

            a_im=pil2tensor(a_im)
            average_images.append(a_im)
            hexs.append(hex)
        else:
            for ims in image:
                for im in ims:
                    im=tensor2pil(im)

                    im=im.convert('RGB')
                    a_im,hex=get_average_color_image(im)

                    if average_color=='on':
                        fill_color=hex
                        
                    im=resize_image(im,scale_option,w,h,fill_color)

                    im=pil2tensor(im)
                    imgs.append(im)

                    a_im=pil2tensor(a_im)
                    average_images.append(a_im)
                    hexs.append(hex)

            try:
                for mas in mask:
                    for ma in mas:
                        ma=tensor2pil(ma)
                        ma=ma.convert('RGB')
                        ma=resize_image(ma,scale_option,w,h,fill_color)
                        ma=ma.convert('L')
                        ma=pil2tensor(ma)
                        masks.append(ma)
            except:
                print('')
        
        return (imgs,average_images,hexs,masks,)


class MirroredImage:
    @classmethod
    def INPUT_TYPES(s):
        return {"required": {
                "image": ("IMAGE",),
                },
                }
    
    # 输出的数据类型
    RETURN_TYPES = ("IMAGE",)

    # 运行时方法名称
    FUNCTION = "run"

    # 右键菜单目录
    CATEGORY = "♾️Mixlab/Image"

    # 输入是否为列表
    INPUT_IS_LIST = True

    # 输出是否为列表
    OUTPUT_IS_LIST = (True,)

    def run(self,image):
        res=[]
        for ims in image:
            for im in ims:
                img=tensor2pil(im)
                mirrored_image = img.transpose(Image.FLIP_LEFT_RIGHT)
                img=pil2tensor(mirrored_image)
                res.append(img)
        return (res,)



class GetImageSize_:
    @classmethod
    def INPUT_TYPES(cls):
        return {
            "required": {
                "image": ("IMAGE",),
            },
             "optional":{
                    "min_width":("INT", {
                        "default": 512, 
                        "min":1, #Minimum value
                        "max": 2048, #Maximum value
                        "step": 8, #Slider's step
                        "display": "number" # Cosmetic only: display as "number" or "slider"
                    })
                },
        }

    RETURN_TYPES = ("INT", "INT","INT", "INT",)
    RETURN_NAMES = ("width", "height","min_width", "min_height",)

    FUNCTION = "get_size"

    CATEGORY = "♾️Mixlab/Image"

    def get_size(self, image,min_width):
        _, height, width, _ = image.shape
        
        # 如果比min_widht,还小,则输出 min width
        if min_width>width:
            im=tensor2pil(image)
            im=resize_image(im,'width',min_width,min_width,"white")
            im=im.convert('RGB')

            min_width,min_height=im.size

        else:
            min_width=width
            min_height=height

        return (width, height,min_width,min_height,)

class SaveImageAndMetadata:
    def __init__(self):
        self.output_dir = folder_paths.get_output_directory()
        self.type = "output"
        self.prefix_append = ""
        self.compress_level = 4

    @classmethod
    def INPUT_TYPES(s):
        return {"required": 
                    {"images": ("IMAGE", ),
                     "filename_prefix": ("STRING", {"default": "Mixlab"}),
                     "metadata": (["disable","enable"],),
                     },
                "hidden": {"prompt": "PROMPT", "extra_pnginfo": "EXTRA_PNGINFO"},
                }

    RETURN_TYPES = ()
    FUNCTION = "save_images"

    OUTPUT_NODE = True

    CATEGORY = "♾️Mixlab/Output"

    def save_images(self, images, filename_prefix="Mixlab",metadata="disable", prompt=None, extra_pnginfo=None):
        filename_prefix += self.prefix_append
        full_output_folder, filename, counter, subfolder, filename_prefix = folder_paths.get_save_image_path(filename_prefix, self.output_dir, images[0].shape[1], images[0].shape[0])
        results = list()
        for image in images:
            i = 255. * image.cpu().numpy()
            img = Image.fromarray(np.clip(i, 0, 255).astype(np.uint8))
            metadata = None
            if (not args.disable_metadata) and (metadata=="enable"):
                print('##enable_metadata')
                metadata = PngInfo()
                if prompt is not None:
                    metadata.add_text("prompt", json.dumps(prompt))
                if extra_pnginfo is not None:
                    for x in extra_pnginfo:
                        metadata.add_text(x, json.dumps(extra_pnginfo[x]))

            file = f"{filename}_{counter:05}_.png"
            img.save(os.path.join(full_output_folder, file), pnginfo=metadata, compress_level=self.compress_level)
            results.append({
                "filename": file,
                "subfolder": subfolder,
                "type": self.type
            })
            counter += 1

        return { "ui": { "images": results } }

class ComparingTwoFrames:
    def __init__(self):
        self.output_dir = folder_paths.get_output_directory()
        self.type = "output"
        self.prefix_append = "ComparingTwoFrames"
        self.compress_level = 4

    @classmethod
    def INPUT_TYPES(s):
        return {"required": 
                    {"before_image": ("IMAGE", ),
                    "after_image": ("IMAGE", )
                     }, 
                }

    RETURN_TYPES = ()
    FUNCTION = "comparingImages"

    OUTPUT_NODE = True

    CATEGORY = "♾️Mixlab/Output"

    def comparingImages(self, before_image,after_image):
        filename_prefix = self.prefix_append
        full_output_folder, filename, counter, subfolder, filename_prefix = folder_paths.get_save_image_path(
            filename_prefix, self.output_dir, after_image[0].shape[1], after_image[0].shape[0])
        
        bresults = list()
        
        for bimage in before_image:
            i = 255. * bimage.cpu().numpy()
            img = Image.fromarray(np.clip(i, 0, 255).astype(np.uint8))
         
            file = f"{filename}_{counter:05}_.png"
            img.save(os.path.join(full_output_folder, file), pnginfo=None, compress_level=self.compress_level)
            bresults.append({
                "filename": file,
                "subfolder": subfolder,
                "type": self.type
            })
            counter += 1


        results = list()
        for aimage in after_image:
            i = 255. * aimage.cpu().numpy()
            img = Image.fromarray(np.clip(i, 0, 255).astype(np.uint8))
         
            file = f"{filename}_{counter:05}_.png"
            img.save(os.path.join(full_output_folder, file), pnginfo=None, compress_level=self.compress_level)
            results.append({
                "filename": file,
                "subfolder": subfolder,
                "type": self.type
            })
            counter += 1

        return { "ui": { "after_images": results,"before_images":bresults } }

class ImageColorTransfer:
    @classmethod
    def INPUT_TYPES(s):
        return {"required": {
                "source": ("IMAGE",),
                "target": ("IMAGE",),
                "weight": ("FLOAT", {"default": 0.5, "min": 0.0, "max": 1.0, "step": 0.01}),
                },
                }
    
    # 输出的数据类型
    RETURN_TYPES = ("IMAGE",)

    # 运行时方法名称
    FUNCTION = "run"

    # 右键菜单目录
    CATEGORY = "♾️Mixlab/Color"

    # 输入是否为列表
    # INPUT_IS_LIST = True

    # 输出是否为列表
    # OUTPUT_IS_LIST = (True,)

    def run(self,source,target,weight):

        res=[]

        #batch-list
        source_list = [source[i:i + 1, ...] for i in range(source.shape[0])]
        target_list = [target[i:i + 1, ...] for i in range(target.shape[0])]

        # 长度纠正为相等
        if len(target_list) != len(source_list):
            target_list = target_list * (len(source_list) // len(target_list)) + target_list[:len(source_list) % len(target_list)]
        
        for i in range(len(source_list)):
            target=target_list[i]
            source=source_list[i]
            target=tensor2pil(target)

            image=tensor2pil(source)

            image_res=color_transfer(image,target)

            # weight Blend image # contributors:@ning
            blend_mask = Image.new(mode="L", size=image.size,
                                    color=(round(weight * 255)))
            blend_mask = ImageOps.invert(blend_mask)
            img_result = Image.composite(image, image_res, blend_mask)
            del image, image_res, blend_mask
            
            img_result=pil2tensor(img_result)

            res.append(img_result)

        # list - batch
        res=torch.cat(res, dim=0)

        return (res,)



class SaveImageToLocal:
    def __init__(self):
        self.output_dir = folder_paths.get_output_directory()
        self.type = "output"
        self.compress_level = 4

    @classmethod
    def INPUT_TYPES(s):
        return {"required": 
                    {"images": ("IMAGE", ),
                     "file_path": ("STRING",{"multiline": True,"default": "","dynamicPrompts": False}),
                     },
                "hidden": {"prompt": "PROMPT", "extra_pnginfo": "EXTRA_PNGINFO"},
                
                }

    RETURN_TYPES = ()
    FUNCTION = "save_images"

    OUTPUT_NODE = True

    CATEGORY = "♾️Mixlab/Output"

    def save_images(self, images,file_path , prompt=None, extra_pnginfo=None):
        filename_prefix = os.path.basename(file_path)
        if file_path=='':
            filename_prefix="ComfyUI"
        
        filename_prefix, _ = os.path.splitext(filename_prefix)

        _, extension = os.path.splitext(file_path)

        if extension:
            # 是文件名,需要处理
            file_path=os.path.dirname(file_path)
            # filename_prefix=

            
        full_output_folder, filename, counter, subfolder, filename_prefix = folder_paths.get_save_image_path(filename_prefix, self.output_dir, images[0].shape[1], images[0].shape[0])
        
    
        if not os.path.exists(file_path):
            # 使用os.makedirs函数创建新目录
            os.makedirs(file_path)
            print("目录已创建")
        else:
            print("目录已存在")

        # 使用glob模块获取当前目录下的所有文件
        if file_path=="":
            files = glob.glob(full_output_folder + '/*')
        else:
            files = glob.glob(file_path + '/*')
        # 统计文件数量
        file_count = len(files)
        counter+=file_count
        print('统计文件数量',file_count,counter)

        results = list()
        for image in images:
            i = 255. * image.cpu().numpy()
            img = Image.fromarray(np.clip(i, 0, 255).astype(np.uint8))
            metadata = None
            if not args.disable_metadata:
                metadata = PngInfo()
                if prompt is not None:
                    metadata.add_text("prompt", json.dumps(prompt))
                if extra_pnginfo is not None:
                    for x in extra_pnginfo:
                        metadata.add_text(x, json.dumps(extra_pnginfo[x]))

            file = f"{filename}_{counter:05}_.png"
            
            if file_path=="":
                fp=os.path.join(full_output_folder, file)
                if os.path.exists(fp):
                    file = f"{filename}_{counter:05}_{generate_random_string(8)}.png"
                    fp=os.path.join(full_output_folder, file)
                img.save(fp, pnginfo=metadata, compress_level=self.compress_level)
                results.append({
                    "filename": file,
                    "subfolder": subfolder,
                    "type": self.type
                })
            
            else:

                fp=os.path.join(file_path, file)
                if os.path.exists(fp):
                    file = f"{filename}_{counter:05}_{generate_random_string(8)}.png"
                    fp=os.path.join(file_path, file)

                img.save(os.path.join(file_path, file), pnginfo=metadata, compress_level=self.compress_level)
                results.append({
                    "filename": file,
                    "subfolder": file_path,
                    "type": self.type
                })
            counter += 1

        return ()


class ImageBatchToList_:
    @classmethod
    def INPUT_TYPES(s):
        return {"required": {"image_batch": ("IMAGE",), }}

    RETURN_TYPES = ("IMAGE",)
    RETURN_NAMES = ("image_list",)
    OUTPUT_IS_LIST = (True,)
    FUNCTION = "run"

    CATEGORY = "♾️Mixlab/Image"

    def run(self, image_batch):
        images = [image_batch[i:i + 1, ...] for i in range(image_batch.shape[0])]
        return (images, )

class ImageListToBatch_:
    @classmethod
    def INPUT_TYPES(s):
        return {
            "required": {
                "images": ("IMAGE",),
            }
        }

    RETURN_TYPES = ("IMAGE",)
    FUNCTION = "run"
    INPUT_IS_LIST = True
    CATEGORY = "♾️Mixlab/Image"

    def run(self, images):
        shape = images[0].shape[1:3]
        out = []

        for i in range(len(images)):
            img = images[i].permute([0,3,1,2])
            if images[i].shape[1:3] != shape:
                transforms = T.Compose([
                    T.CenterCrop(min(img.shape[2], img.shape[3])),
                    T.Resize((shape[0], shape[1]), interpolation=T.InterpolationMode.BICUBIC),
                ])
                img = transforms(img)
            out.append(img.permute([0,2,3,1]))

        out = torch.cat(out, dim=0)

        return (out,)