forked from jags111/efficiency-nodes-comfyui
-
Notifications
You must be signed in to change notification settings - Fork 0
/
efficiency_nodes.py
4415 lines (3704 loc) · 229 KB
/
efficiency_nodes.py
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
# Efficiency Nodes - A collection of my ComfyUI custom nodes to help streamline workflows and reduce total node count.
# by Luciano Cirino (Discord: TSC#9184) - April 2023 - October 2023
# https://github.com/LucianoCirino/efficiency-nodes-comfyui
from torch import Tensor
from PIL import Image, ImageOps, ImageDraw, ImageFont
from PIL.PngImagePlugin import PngInfo
import numpy as np
import torch
import ast
from pathlib import Path
from importlib import import_module
import os
import sys
import copy
import subprocess
import json
import psutil
# Get the absolute path of various directories
my_dir = os.path.dirname(os.path.abspath(__file__))
custom_nodes_dir = os.path.abspath(os.path.join(my_dir, '..'))
comfy_dir = os.path.abspath(os.path.join(my_dir, '..', '..'))
# Construct the path to the font file
font_path = os.path.join(my_dir, 'arial.ttf')
# Append comfy_dir to sys.path & import files
sys.path.append(comfy_dir)
from nodes import LatentUpscaleBy, KSampler, KSamplerAdvanced, VAEDecode, VAEDecodeTiled, VAEEncode, VAEEncodeTiled, \
ImageScaleBy, CLIPSetLastLayer, CLIPTextEncode, ControlNetLoader, ControlNetApply, ControlNetApplyAdvanced, \
PreviewImage, MAX_RESOLUTION
from comfy_extras.nodes_upscale_model import UpscaleModelLoader, ImageUpscaleWithModel
from comfy_extras.nodes_clip_sdxl import CLIPTextEncodeSDXL, CLIPTextEncodeSDXLRefiner
import comfy.sample
import comfy.samplers
import comfy.sd
import comfy.utils
import comfy.latent_formats
sys.path.remove(comfy_dir)
# Append my_dir to sys.path & import files
sys.path.append(my_dir)
from tsc_utils import *
from .py import smZ_cfg_denoiser
from .py import smZ_rng_source
from .py import cg_mixed_seed_noise
from .py import city96_latent_upscaler
from .py import ttl_nn_latent_upscaler
from .py import bnk_tiled_samplers
from .py import bnk_adv_encode
sys.path.remove(my_dir)
# Append custom_nodes_dir to sys.path
sys.path.append(custom_nodes_dir)
# GLOBALS
REFINER_CFG_OFFSET = 0 #Refiner CFG Offset
########################################################################################################################
# Common function for encoding prompts
def encode_prompts(positive_prompt, negative_prompt, token_normalization, weight_interpretation, clip, clip_skip,
refiner_clip, refiner_clip_skip, ascore, is_sdxl, empty_latent_width, empty_latent_height,
return_type="both"):
positive_encoded = negative_encoded = refiner_positive_encoded = refiner_negative_encoded = None
# Process base encodings if needed
if return_type in ["base", "both"]:
clip = CLIPSetLastLayer().set_last_layer(clip, clip_skip)[0]
positive_encoded = bnk_adv_encode.AdvancedCLIPTextEncode().encode(clip, positive_prompt, token_normalization, weight_interpretation)[0]
negative_encoded = bnk_adv_encode.AdvancedCLIPTextEncode().encode(clip, negative_prompt, token_normalization, weight_interpretation)[0]
# Process refiner encodings if needed
if return_type in ["refiner", "both"] and is_sdxl and refiner_clip and refiner_clip_skip and ascore:
refiner_clip = CLIPSetLastLayer().set_last_layer(refiner_clip, refiner_clip_skip)[0]
refiner_positive_encoded = bnk_adv_encode.AdvancedCLIPTextEncode().encode(refiner_clip, positive_prompt, token_normalization, weight_interpretation)[0]
refiner_positive_encoded = bnk_adv_encode.AddCLIPSDXLRParams().encode(refiner_positive_encoded, empty_latent_width, empty_latent_height, ascore[0])[0]
refiner_negative_encoded = bnk_adv_encode.AdvancedCLIPTextEncode().encode(refiner_clip, negative_prompt, token_normalization, weight_interpretation)[0]
refiner_negative_encoded = bnk_adv_encode.AddCLIPSDXLRParams().encode(refiner_negative_encoded, empty_latent_width, empty_latent_height, ascore[1])[0]
# Return results based on return_type
if return_type == "base":
return positive_encoded, negative_encoded, clip
elif return_type == "refiner":
return refiner_positive_encoded, refiner_negative_encoded, refiner_clip
elif return_type == "both":
return positive_encoded, negative_encoded, clip, refiner_positive_encoded, refiner_negative_encoded, refiner_clip
########################################################################################################################
# TSC Efficient Loader
class TSC_EfficientLoader:
@classmethod
def INPUT_TYPES(cls):
return {"required": { "ckpt_name": (folder_paths.get_filename_list("checkpoints"),),
"vae_name": (["Baked VAE"] + folder_paths.get_filename_list("vae"),),
"clip_skip": ("INT", {"default": -1, "min": -24, "max": -1, "step": 1}),
"lora_name": (["None"] + folder_paths.get_filename_list("loras"),),
"lora_model_strength": ("FLOAT", {"default": 1.0, "min": -10.0, "max": 10.0, "step": 0.01}),
"lora_clip_strength": ("FLOAT", {"default": 1.0, "min": -10.0, "max": 10.0, "step": 0.01}),
"positive": ("STRING", {"default": "CLIP_POSITIVE","multiline": True}),
"negative": ("STRING", {"default": "CLIP_NEGATIVE", "multiline": True}),
"token_normalization": (["none", "mean", "length", "length+mean"],),
"weight_interpretation": (["comfy", "A1111", "compel", "comfy++", "down_weight"],),
"empty_latent_width": ("INT", {"default": 512, "min": 64, "max": MAX_RESOLUTION, "step": 64}),
"empty_latent_height": ("INT", {"default": 512, "min": 64, "max": MAX_RESOLUTION, "step": 64}),
"batch_size": ("INT", {"default": 1, "min": 1, "max": 262144})},
"optional": {"lora_stack": ("LORA_STACK", ),
"cnet_stack": ("CONTROL_NET_STACK",)},
"hidden": { "prompt": "PROMPT",
"my_unique_id": "UNIQUE_ID",},
}
RETURN_TYPES = ("MODEL", "CONDITIONING", "CONDITIONING", "LATENT", "VAE", "CLIP", "DEPENDENCIES",)
RETURN_NAMES = ("MODEL", "CONDITIONING+", "CONDITIONING-", "LATENT", "VAE", "CLIP", "DEPENDENCIES", )
FUNCTION = "efficientloader"
CATEGORY = "Efficiency Nodes/Loaders"
def efficientloader(self, ckpt_name, vae_name, clip_skip, lora_name, lora_model_strength, lora_clip_strength,
positive, negative, token_normalization, weight_interpretation, empty_latent_width,
empty_latent_height, batch_size, lora_stack=None, cnet_stack=None, refiner_name="None",
ascore=None, prompt=None, my_unique_id=None, loader_type="regular"):
# Clean globally stored objects
globals_cleanup(prompt)
# Create Empty Latent
latent = torch.zeros([batch_size, 4, empty_latent_height // 8, empty_latent_width // 8]).cpu()
# Retrieve cache numbers
vae_cache, ckpt_cache, lora_cache, refn_cache = get_cache_numbers("Efficient Loader")
if lora_name != "None" or lora_stack:
# Initialize an empty list to store LoRa parameters.
lora_params = []
# Check if lora_name is not the string "None" and if so, add its parameters.
if lora_name != "None":
lora_params.append((lora_name, lora_model_strength, lora_clip_strength))
# If lora_stack is not None or an empty list, extend lora_params with its items.
if lora_stack:
lora_params.extend(lora_stack)
# Load LoRa(s)
model, clip = load_lora(lora_params, ckpt_name, my_unique_id, cache=lora_cache, ckpt_cache=ckpt_cache, cache_overwrite=True)
if vae_name == "Baked VAE":
vae = get_bvae_by_ckpt_name(ckpt_name)
else:
model, clip, vae = load_checkpoint(ckpt_name, my_unique_id, cache=ckpt_cache, cache_overwrite=True)
lora_params = None
# Load Refiner Checkpoint if given
if refiner_name != "None":
refiner_model, refiner_clip, _ = load_checkpoint(refiner_name, my_unique_id, output_vae=False,
cache=refn_cache, cache_overwrite=True, ckpt_type="refn")
else:
refiner_model = refiner_clip = None
# Extract clip_skips
refiner_clip_skip = clip_skip[1] if loader_type == "sdxl" else None
clip_skip = clip_skip[0] if loader_type == "sdxl" else clip_skip
# Encode prompt based on loader_type
positive_encoded, negative_encoded, clip, refiner_positive_encoded, refiner_negative_encoded, refiner_clip = \
encode_prompts(positive, negative, token_normalization, weight_interpretation, clip, clip_skip,
refiner_clip, refiner_clip_skip, ascore, loader_type == "sdxl",
empty_latent_width, empty_latent_height)
# Apply ControlNet Stack if given
if cnet_stack:
controlnet_conditioning = TSC_Apply_ControlNet_Stack().apply_cnet_stack(positive_encoded, negative_encoded, cnet_stack)
positive_encoded, negative_encoded = controlnet_conditioning[0], controlnet_conditioning[1]
# Check for custom VAE
if vae_name != "Baked VAE":
vae = load_vae(vae_name, my_unique_id, cache=vae_cache, cache_overwrite=True)
# Data for XY Plot
dependencies = (vae_name, ckpt_name, clip, clip_skip, refiner_name, refiner_clip, refiner_clip_skip,
positive, negative, token_normalization, weight_interpretation, ascore,
empty_latent_width, empty_latent_height, lora_params, cnet_stack)
### Debugging
###print_loaded_objects_entries()
print_loaded_objects_entries(my_unique_id, prompt)
if loader_type == "regular":
return (model, positive_encoded, negative_encoded, {"samples":latent}, vae, clip, dependencies,)
elif loader_type == "sdxl":
return ((model, clip, positive_encoded, negative_encoded, refiner_model, refiner_clip,
refiner_positive_encoded, refiner_negative_encoded), {"samples":latent}, vae, dependencies,)
#=======================================================================================================================
# TSC Efficient Loader SDXL
class TSC_EfficientLoaderSDXL(TSC_EfficientLoader):
@classmethod
def INPUT_TYPES(cls):
return {"required": { "base_ckpt_name": (folder_paths.get_filename_list("checkpoints"),),
"base_clip_skip": ("INT", {"default": -2, "min": -24, "max": -1, "step": 1}),
"refiner_ckpt_name": (["None"] + folder_paths.get_filename_list("checkpoints"),),
"refiner_clip_skip": ("INT", {"default": -2, "min": -24, "max": -1, "step": 1}),
"positive_ascore": ("FLOAT", {"default": 6.0, "min": 0.0, "max": 1000.0, "step": 0.01}),
"negative_ascore": ("FLOAT", {"default": 2.0, "min": 0.0, "max": 1000.0, "step": 0.01}),
"vae_name": (["Baked VAE"] + folder_paths.get_filename_list("vae"),),
"positive": ("STRING", {"default": "CLIP_POSITIVE", "multiline": True}),
"negative": ("STRING", {"default": "CLIP_NEGATIVE", "multiline": True}),
"token_normalization": (["none", "mean", "length", "length+mean"],),
"weight_interpretation": (["comfy", "A1111", "compel", "comfy++", "down_weight"],),
"empty_latent_width": ("INT", {"default": 1024, "min": 64, "max": MAX_RESOLUTION, "step": 64}),
"empty_latent_height": ("INT", {"default": 1024, "min": 64, "max": MAX_RESOLUTION, "step": 64}),
"batch_size": ("INT", {"default": 1, "min": 1, "max": 64})},
"optional": {"lora_stack": ("LORA_STACK", ), "cnet_stack": ("CONTROL_NET_STACK",),},
"hidden": { "prompt": "PROMPT", "my_unique_id": "UNIQUE_ID",},
}
RETURN_TYPES = ("SDXL_TUPLE", "LATENT", "VAE", "DEPENDENCIES",)
RETURN_NAMES = ("SDXL_TUPLE", "LATENT", "VAE", "DEPENDENCIES", )
FUNCTION = "efficientloaderSDXL"
CATEGORY = "Efficiency Nodes/Loaders"
def efficientloaderSDXL(self, base_ckpt_name, base_clip_skip, refiner_ckpt_name, refiner_clip_skip, positive_ascore,
negative_ascore, vae_name, positive, negative, token_normalization, weight_interpretation,
empty_latent_width, empty_latent_height, batch_size, lora_stack=None, cnet_stack=None,
prompt=None, my_unique_id=None):
clip_skip = (base_clip_skip, refiner_clip_skip)
lora_name = "None"
lora_model_strength = lora_clip_strength = 0
return super().efficientloader(base_ckpt_name, vae_name, clip_skip, lora_name, lora_model_strength, lora_clip_strength,
positive, negative, token_normalization, weight_interpretation, empty_latent_width, empty_latent_height,
batch_size, lora_stack=lora_stack, cnet_stack=cnet_stack, refiner_name=refiner_ckpt_name,
ascore=(positive_ascore, negative_ascore), prompt=prompt, my_unique_id=my_unique_id, loader_type="sdxl")
#=======================================================================================================================
# TSC Unpack SDXL Tuple
class TSC_Unpack_SDXL_Tuple:
@classmethod
def INPUT_TYPES(cls):
return {"required": {"sdxl_tuple": ("SDXL_TUPLE",)},}
RETURN_TYPES = ("MODEL", "CLIP", "CONDITIONING","CONDITIONING", "MODEL", "CLIP", "CONDITIONING", "CONDITIONING",)
RETURN_NAMES = ("BASE_MODEL", "BASE_CLIP", "BASE_CONDITIONING+", "BASE_CONDITIONING-",
"REFINER_MODEL", "REFINER_CLIP","REFINER_CONDITIONING+","REFINER_CONDITIONING-",)
FUNCTION = "unpack_sdxl_tuple"
CATEGORY = "Efficiency Nodes/Misc"
def unpack_sdxl_tuple(self, sdxl_tuple):
return (sdxl_tuple[0], sdxl_tuple[1],sdxl_tuple[2],sdxl_tuple[3],
sdxl_tuple[4],sdxl_tuple[5],sdxl_tuple[6],sdxl_tuple[7],)
# =======================================================================================================================
# TSC Pack SDXL Tuple
class TSC_Pack_SDXL_Tuple:
@classmethod
def INPUT_TYPES(cls):
return {"required": {"base_model": ("MODEL",),
"base_clip": ("CLIP",),
"base_positive": ("CONDITIONING",),
"base_negative": ("CONDITIONING",),
"refiner_model": ("MODEL",),
"refiner_clip": ("CLIP",),
"refiner_positive": ("CONDITIONING",),
"refiner_negative": ("CONDITIONING",),},}
RETURN_TYPES = ("SDXL_TUPLE",)
RETURN_NAMES = ("SDXL_TUPLE",)
FUNCTION = "pack_sdxl_tuple"
CATEGORY = "Efficiency Nodes/Misc"
def pack_sdxl_tuple(self, base_model, base_clip, base_positive, base_negative,
refiner_model, refiner_clip, refiner_positive, refiner_negative):
return ((base_model, base_clip, base_positive, base_negative,
refiner_model, refiner_clip, refiner_positive, refiner_negative),)
########################################################################################################################
# TSC LoRA Stacker
class TSC_LoRA_Stacker:
modes = ["simple", "advanced"]
@classmethod
def INPUT_TYPES(cls):
loras = ["None"] + folder_paths.get_filename_list("loras")
inputs = {
"required": {
"input_mode": (cls.modes,),
"lora_count": ("INT", {"default": 3, "min": 0, "max": 50, "step": 1}),
}
}
for i in range(1, 50):
inputs["required"][f"lora_name_{i}"] = (loras,)
inputs["required"][f"lora_wt_{i}"] = ("FLOAT", {"default": 1.0, "min": -10.0, "max": 10.0, "step": 0.01})
inputs["required"][f"model_str_{i}"] = ("FLOAT", {"default": 1.0, "min": -10.0, "max": 10.0, "step": 0.01})
inputs["required"][f"clip_str_{i}"] = ("FLOAT", {"default": 1.0, "min": -10.0, "max": 10.0, "step": 0.01})
inputs["optional"] = {
"lora_stack": ("LORA_STACK",)
}
return inputs
RETURN_TYPES = ("LORA_STACK",)
RETURN_NAMES = ("LORA_STACK",)
FUNCTION = "lora_stacker"
CATEGORY = "Efficiency Nodes/Stackers"
def lora_stacker(self, input_mode, lora_count, lora_stack=None, **kwargs):
# Extract values from kwargs
loras = [kwargs.get(f"lora_name_{i}") for i in range(1, lora_count + 1)]
# Create a list of tuples using provided parameters, exclude tuples with lora_name as "None"
if input_mode == "simple":
weights = [kwargs.get(f"lora_wt_{i}") for i in range(1, lora_count + 1)]
loras = [(lora_name, lora_weight, lora_weight) for lora_name, lora_weight in zip(loras, weights) if
lora_name != "None"]
else:
model_strs = [kwargs.get(f"model_str_{i}") for i in range(1, lora_count + 1)]
clip_strs = [kwargs.get(f"clip_str_{i}") for i in range(1, lora_count + 1)]
loras = [(lora_name, model_str, clip_str) for lora_name, model_str, clip_str in
zip(loras, model_strs, clip_strs) if lora_name != "None"]
# If lora_stack is not None, extend the loras list with lora_stack
if lora_stack is not None:
loras.extend([l for l in lora_stack if l[0] != "None"])
return (loras,)
#=======================================================================================================================
# TSC Control Net Stacker
class TSC_Control_Net_Stacker:
@classmethod
def INPUT_TYPES(cls):
return {"required": {"control_net": ("CONTROL_NET",),
"image": ("IMAGE",),
"strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}),
"start_percent": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1.0, "step": 0.001}),
"end_percent": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.001})},
"optional": {"cnet_stack": ("CONTROL_NET_STACK",)},
}
RETURN_TYPES = ("CONTROL_NET_STACK",)
RETURN_NAMES = ("CNET_STACK",)
FUNCTION = "control_net_stacker"
CATEGORY = "Efficiency Nodes/Stackers"
def control_net_stacker(self, control_net, image, strength, start_percent, end_percent, cnet_stack=None):
# If control_net_stack is None, initialize as an empty list
cnet_stack = [] if cnet_stack is None else cnet_stack
# Extend the control_net_stack with the new tuple
cnet_stack.extend([(control_net, image, strength, start_percent, end_percent)])
return (cnet_stack,)
#=======================================================================================================================
# TSC Apply ControlNet Stack
class TSC_Apply_ControlNet_Stack:
@classmethod
def INPUT_TYPES(cls):
return {"required": {"positive": ("CONDITIONING",),
"negative": ("CONDITIONING",)},
"optional": {"cnet_stack": ("CONTROL_NET_STACK",)}
}
RETURN_TYPES = ("CONDITIONING","CONDITIONING",)
RETURN_NAMES = ("CONDITIONING+","CONDITIONING-",)
FUNCTION = "apply_cnet_stack"
CATEGORY = "Efficiency Nodes/Stackers"
def apply_cnet_stack(self, positive, negative, cnet_stack=None):
if cnet_stack is None:
return (positive, negative)
for control_net_tuple in cnet_stack:
control_net, image, strength, start_percent, end_percent = control_net_tuple
controlnet_conditioning = ControlNetApplyAdvanced().apply_controlnet(positive, negative, control_net, image,
strength, start_percent, end_percent)
positive, negative = controlnet_conditioning[0], controlnet_conditioning[1]
return (positive, negative, )
########################################################################################################################
# TSC KSampler (Efficient)
class TSC_KSampler:
empty_image = pil2tensor(Image.new('RGBA', (1, 1), (0, 0, 0, 0)))
@classmethod
def INPUT_TYPES(cls):
return {"required":
{"model": ("MODEL",),
"seed": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff}),
"steps": ("INT", {"default": 20, "min": 1, "max": 10000}),
"cfg": ("FLOAT", {"default": 7.0, "min": 0.0, "max": 100.0}),
"sampler_name": (comfy.samplers.KSampler.SAMPLERS,),
"scheduler": (comfy.samplers.KSampler.SCHEDULERS,),
"positive": ("CONDITIONING",),
"negative": ("CONDITIONING",),
"latent_image": ("LATENT",),
"denoise": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01}),
"preview_method": (["auto", "latent2rgb", "taesd", "vae_decoded_only", "none"],),
"vae_decode": (["true", "true (tiled)", "false"],),
},
"optional": { "optional_vae": ("VAE",),
"script": ("SCRIPT",),},
"hidden": {"prompt": "PROMPT", "extra_pnginfo": "EXTRA_PNGINFO", "my_unique_id": "UNIQUE_ID",},
}
RETURN_TYPES = ("MODEL", "CONDITIONING", "CONDITIONING", "LATENT", "VAE", "IMAGE", )
RETURN_NAMES = ("MODEL", "CONDITIONING+", "CONDITIONING-", "LATENT", "VAE", "IMAGE", )
OUTPUT_NODE = True
FUNCTION = "sample"
CATEGORY = "Efficiency Nodes/Sampling"
def sample(self, model, seed, steps, cfg, sampler_name, scheduler, positive, negative, latent_image,
preview_method, vae_decode, denoise=1.0, prompt=None, extra_pnginfo=None, my_unique_id=None,
optional_vae=(None,), script=None, add_noise=None, start_at_step=None, end_at_step=None,
return_with_leftover_noise=None, sampler_type="regular"):
# Rename the vae variable
vae = optional_vae
# If vae is not connected, disable vae decoding
if vae == (None,) and vae_decode != "false":
print(f"{warning('KSampler(Efficient) Warning:')} No vae input detected, proceeding as if vae_decode was false.\n")
vae_decode = "false"
#---------------------------------------------------------------------------------------------------------------
# Unpack SDXL Tuple embedded in the 'model' channel
if sampler_type == "sdxl":
sdxl_tuple = model
model, _, positive, negative, refiner_model, _, refiner_positive, refiner_negative = sdxl_tuple
else:
refiner_model = refiner_positive = refiner_negative = None
#---------------------------------------------------------------------------------------------------------------
def keys_exist_in_script(*keys):
return any(key in script for key in keys) if script else False
#---------------------------------------------------------------------------------------------------------------
def vae_decode_latent(vae, samples, vae_decode):
return VAEDecodeTiled().decode(vae,samples,320)[0] if "tiled" in vae_decode else VAEDecode().decode(vae,samples)[0]
def vae_encode_image(vae, pixels, vae_decode):
return VAEEncodeTiled().encode(vae,pixels,320)[0] if "tiled" in vae_decode else VAEEncode().encode(vae,pixels)[0]
# ---------------------------------------------------------------------------------------------------------------
def process_latent_image(model, seed, steps, cfg, sampler_name, scheduler, positive, negative, latent_image,
denoise, sampler_type, add_noise, start_at_step, end_at_step, return_with_leftover_noise,
refiner_model, refiner_positive, refiner_negative, vae, vae_decode, preview_method):
# Store originals
previous_preview_method = global_preview_method()
original_prepare_noise = comfy.sample.prepare_noise
original_KSampler = comfy.samplers.KSampler
original_model_str = str(model)
# Initialize output variables
samples = images = gifs = preview = cnet_imgs = None
try:
# Change the global preview method (temporarily)
set_preview_method(preview_method)
# ------------------------------------------------------------------------------------------------------
# Check if "noise" exists in the script before main sampling has taken place
if keys_exist_in_script("noise"):
rng_source, cfg_denoiser, add_seed_noise, m_seed, m_weight = script["noise"]
smZ_rng_source.rng_rand_source(rng_source) # this function monkey patches comfy.sample.prepare_noise
if cfg_denoiser:
comfy.samplers.KSampler = smZ_cfg_denoiser.SDKSampler
if add_seed_noise:
comfy.sample.prepare_noise = cg_mixed_seed_noise.get_mixed_noise_function(comfy.sample.prepare_noise, m_seed, m_weight)
else:
m_seed = m_weight = None
else:
rng_source = cfg_denoiser = add_seed_noise = m_seed = m_weight = None
# ------------------------------------------------------------------------------------------------------
# Check if "anim" exists in the script before main sampling has taken place
if keys_exist_in_script("anim"):
if preview_method != "none":
set_preview_method("none") # disable preview method
print(f"{warning('KSampler(Efficient) Warning:')} Live preview disabled for animatediff generations.")
motion_model, beta_schedule, context_options, frame_rate, loop_count, format, pingpong, save_image = script["anim"]
model = AnimateDiffLoaderWithContext().load_mm_and_inject_params(model, motion_model, beta_schedule, context_options)[0]
# ------------------------------------------------------------------------------------------------------
# Store run parameters as strings. Load previous stored samples if all parameters match.
latent_image_hash = tensor_to_hash(latent_image["samples"])
positive_hash = tensor_to_hash(positive[0][0])
negative_hash = tensor_to_hash(negative[0][0])
refiner_positive_hash = tensor_to_hash(refiner_positive[0][0]) if refiner_positive is not None else None
refiner_negative_hash = tensor_to_hash(refiner_negative[0][0]) if refiner_negative is not None else None
# Include motion_model, beta_schedule, and context_options as unique identifiers if they exist.
model_identifier = [original_model_str, motion_model, beta_schedule, context_options] if keys_exist_in_script("anim")\
else [original_model_str]
parameters = [model_identifier] + [seed, steps, cfg, sampler_name, scheduler, positive_hash, negative_hash,
latent_image_hash, denoise, sampler_type, add_noise, start_at_step,
end_at_step, return_with_leftover_noise, refiner_model, refiner_positive_hash,
refiner_negative_hash, rng_source, cfg_denoiser, add_seed_noise, m_seed, m_weight]
# Convert all elements in parameters to strings, except for the hash variable checks
parameters = [str(item) if not isinstance(item, type(latent_image_hash)) else item for item in parameters]
# Load previous latent if all parameters match, else returns 'None'
samples = load_ksampler_results("latent", my_unique_id, parameters)
if samples is None: # clear stored images
store_ksampler_results("image", my_unique_id, None)
store_ksampler_results("cnet_img", my_unique_id, None)
if samples is not None: # do not re-sample
images = load_ksampler_results("image", my_unique_id)
cnet_imgs = True # "True" will denote that it can be loaded provided the preprocessor matches
# Sample the latent_image(s) using the Comfy KSampler nodes
elif sampler_type == "regular":
samples = KSampler().sample(model, seed, steps, cfg, sampler_name, scheduler, positive, negative,
latent_image, denoise=denoise)[0] if denoise>0 else latent_image
elif sampler_type == "advanced":
samples = KSamplerAdvanced().sample(model, add_noise, seed, steps, cfg, sampler_name, scheduler,
positive, negative, latent_image, start_at_step, end_at_step,
return_with_leftover_noise, denoise=1.0)[0]
elif sampler_type == "sdxl":
# Disable refiner if refine_at_step is -1
if end_at_step == -1:
end_at_step = steps
# Perform base model sampling
add_noise = return_with_leftover_noise = "enable"
samples = KSamplerAdvanced().sample(model, add_noise, seed, steps, cfg, sampler_name, scheduler,
positive, negative, latent_image, start_at_step, end_at_step,
return_with_leftover_noise, denoise=1.0)[0]
# Perform refiner model sampling
if refiner_model and end_at_step < steps:
add_noise = return_with_leftover_noise = "disable"
samples = KSamplerAdvanced().sample(refiner_model, add_noise, seed, steps, cfg + REFINER_CFG_OFFSET,
sampler_name, scheduler, refiner_positive, refiner_negative,
samples, end_at_step, steps,
return_with_leftover_noise, denoise=1.0)[0]
# Cache the first pass samples in the 'last_helds' dictionary "latent" if not xyplot
if not any(keys_exist_in_script(key) for key in ["xyplot"]):
store_ksampler_results("latent", my_unique_id, samples, parameters)
# ------------------------------------------------------------------------------------------------------
# Check if "hiresfix" exists in the script after main sampling has taken place
if keys_exist_in_script("hiresfix"):
# Unpack the tuple from the script's "hiresfix" key
upscale_type, latent_upscaler, upscale_by, use_same_seed, hires_seed, hires_steps, hires_denoise,\
iterations, hires_control_net, hires_cnet_strength, preprocessor, preprocessor_imgs, \
latent_upscale_function, latent_upscale_model, pixel_upscale_model = script["hiresfix"]
# Define hires_seed
hires_seed = seed if use_same_seed else hires_seed
# Define latent_upscale_model
if latent_upscale_model is None:
latent_upscale_model = model
elif keys_exist_in_script("anim"):
latent_upscale_model = \
AnimateDiffLoaderWithContext().load_mm_and_inject_params(latent_upscale_model, motion_model,
beta_schedule, context_options)[0]
# Generate Preprocessor images and Apply Control Net
if hires_control_net is not None:
# Attempt to load previous "cnet_imgs" if previous images were loaded and preprocessor is same
if cnet_imgs is True:
cnet_imgs = load_ksampler_results("cnet_img", my_unique_id, [preprocessor])
# If cnet_imgs is None, generate new ones
if cnet_imgs is None:
if images is None:
images = vae_decode_latent(vae, samples, vae_decode)
store_ksampler_results("image", my_unique_id, images)
cnet_imgs = AIO_Preprocessor().execute(preprocessor, images)[0]
store_ksampler_results("cnet_img", my_unique_id, cnet_imgs, [preprocessor])
positive = ControlNetApply().apply_controlnet(positive, hires_control_net, cnet_imgs, hires_cnet_strength)[0]
# Iterate for the given number of iterations
if upscale_type == "latent":
for _ in range(iterations):
upscaled_latent_image = latent_upscale_function().upscale(samples, latent_upscaler, upscale_by)[0]
samples = KSampler().sample(latent_upscale_model, hires_seed, hires_steps, cfg, sampler_name, scheduler,
positive, negative, upscaled_latent_image, denoise=hires_denoise)[0]
images = None # set to None when samples is updated
elif upscale_type == "pixel":
if images is None:
images = vae_decode_latent(vae, samples, vae_decode)
store_ksampler_results("image", my_unique_id, images)
images = ImageUpscaleWithModel().upscale(pixel_upscale_model, images)[0]
images = ImageScaleBy().upscale(images, "nearest-exact", upscale_by/4)[0]
elif upscale_type == "both":
for _ in range(iterations):
if images is None:
images = vae_decode_latent(vae, samples, vae_decode)
store_ksampler_results("image", my_unique_id, images)
images = ImageUpscaleWithModel().upscale(pixel_upscale_model, images)[0]
images = ImageScaleBy().upscale(images, "nearest-exact", upscale_by/4)[0]
samples = vae_encode_image(vae, images, vae_decode)
upscaled_latent_image = latent_upscale_function().upscale(samples, latent_upscaler, 1)[0]
samples = KSampler().sample(latent_upscale_model, hires_seed, hires_steps, cfg, sampler_name, scheduler,
positive, negative, upscaled_latent_image, denoise=hires_denoise)[0]
images = None # set to None when samples is updated
# ------------------------------------------------------------------------------------------------------
# Check if "tile" exists in the script after main sampling has taken place
if keys_exist_in_script("tile"):
# Unpack the tuple from the script's "tile" key
upscale_by, tile_size, tiling_strategy, tiling_steps, tile_seed, tiled_denoise,\
tile_controlnet, strength = script["tile"]
# Decode image, store if first decode
if images is None:
images = vae_decode_latent(vae, samples, vae_decode)
if not any(keys_exist_in_script(key) for key in ["xyplot", "hiresfix"]):
store_ksampler_results("image", my_unique_id, images)
# Upscale image
upscaled_image = ImageScaleBy().upscale(images, "nearest-exact", upscale_by)[0]
upscaled_latent = vae_encode_image(vae, upscaled_image, vae_decode)
# If using Control Net, Apply Control Net using upscaled_image and loaded control_net
if tile_controlnet is not None:
positive = ControlNetApply().apply_controlnet(positive, tile_controlnet, upscaled_image, 1)[0]
# Sample latent
TSampler = bnk_tiled_samplers.TiledKSampler
samples = TSampler().sample(model, tile_seed, tile_size, tile_size, tiling_strategy, tiling_steps, cfg,
sampler_name, scheduler, positive, negative, upscaled_latent,
denoise=tiled_denoise)[0]
images = None # set to None when samples is updated
# ------------------------------------------------------------------------------------------------------
# Check if "anim" exists in the script after the main sampling has taken place
if keys_exist_in_script("anim"):
if images is None:
images = vae_decode_latent(vae, samples, vae_decode)
if not any(keys_exist_in_script(key) for key in ["xyplot", "hiresfix", "tile"]):
store_ksampler_results("image", my_unique_id, images)
gifs = AnimateDiffCombine().generate_gif(images, frame_rate, loop_count, format=format,
pingpong=pingpong, save_image=save_image, prompt=prompt, extra_pnginfo=extra_pnginfo)["ui"]["gifs"]
# ------------------------------------------------------------------------------------------------------
# Decode image if not yet decoded
if "true" in vae_decode:
if images is None:
images = vae_decode_latent(vae, samples, vae_decode)
# Store decoded image as base image of no script is detected
if all(not keys_exist_in_script(key) for key in ["xyplot", "hiresfix", "tile", "anim"]):
store_ksampler_results("image", my_unique_id, images)
# Append Control Net Images (if exist)
if cnet_imgs is not None and not True:
if preprocessor_imgs and upscale_type == "latent":
if keys_exist_in_script("xyplot"):
print(
f"{warning('HighRes-Fix Warning:')} Preprocessor images auto-disabled when XY Plotting.")
else:
# Resize cnet_imgs if necessary and stack
if images.shape[1:3] != cnet_imgs.shape[1:3]: # comparing height and width
cnet_imgs = quick_resize(cnet_imgs, images.shape)
images = torch.cat([images, cnet_imgs], dim=0)
# Define preview images
if keys_exist_in_script("anim"):
preview = {"gifs": gifs, "images": list()}
elif preview_method == "none" or (preview_method == "vae_decoded_only" and vae_decode == "false"):
preview = {"images": list()}
elif images is not None:
preview = PreviewImage().save_images(images, prompt=prompt, extra_pnginfo=extra_pnginfo)["ui"]
# Define a dummy output image
if images is None and vae_decode == "false":
images = TSC_KSampler.empty_image
finally:
# Restore global changes
set_preview_method(previous_preview_method)
comfy.samplers.KSampler = original_KSampler
comfy.sample.prepare_noise = original_prepare_noise
return samples, images, gifs, preview
# ---------------------------------------------------------------------------------------------------------------
# Clean globally stored objects of non-existant nodes
globals_cleanup(prompt)
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# If not XY Plotting
if not keys_exist_in_script("xyplot"):
# Process latent image
samples, images, gifs, preview = process_latent_image(model, seed, steps, cfg, sampler_name, scheduler,
positive, negative, latent_image, denoise, sampler_type, add_noise,
start_at_step, end_at_step, return_with_leftover_noise, refiner_model,
refiner_positive, refiner_negative, vae, vae_decode, preview_method)
if sampler_type == "sdxl":
result = (sdxl_tuple, samples, vae, images,)
else:
result = (model, positive, negative, samples, vae, images,)
if preview is None:
return {"result": result}
else:
return {"ui": preview, "result": result}
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# If XY Plot
elif keys_exist_in_script("xyplot"):
# If no vae connected, throw errors
if vae == (None,):
print(f"{error('KSampler(Efficient) Error:')} VAE input must be connected in order to use the XY Plot script.")
return {"ui": {"images": list()},
"result": (model, positive, negative, latent_image, vae, TSC_KSampler.empty_image,)}
# If vae_decode is not set to true, print message that changing it to true
if "true" not in vae_decode:
print(f"{warning('KSampler(Efficient) Warning:')} VAE decoding must be set to \'true\'"
" for the XY Plot script, proceeding as if \'true\'.\n")
#___________________________________________________________________________________________________________
# Initialize, unpack, and clean variables for the XY Plot script
vae_name = None
ckpt_name = None
clip = None
clip_skip = None
refiner_name = None
refiner_clip = None
refiner_clip_skip = None
positive_prompt = None
negative_prompt = None
ascore = None
empty_latent_width = None
empty_latent_height = None
lora_stack = None
cnet_stack = None
# Split the 'samples' tensor
samples_tensors = torch.split(latent_image['samples'], 1, dim=0)
# Check if 'noise_mask' exists and split if it does
if 'noise_mask' in latent_image:
noise_mask_tensors = torch.split(latent_image['noise_mask'], 1, dim=0)
latent_tensors = [{'samples': img, 'noise_mask': mask} for img, mask in
zip(samples_tensors, noise_mask_tensors)]
else:
latent_tensors = [{'samples': img} for img in samples_tensors]
# Set latent only to the first of the batch
latent_image = latent_tensors[0]
# Unpack script Tuple (X_type, X_value, Y_type, Y_value, grid_spacing, Y_label_orientation, dependencies)
X_type, X_value, Y_type, Y_value, grid_spacing, Y_label_orientation, cache_models, xyplot_as_output_image,\
xyplot_id, dependencies = script["xyplot"]
#_______________________________________________________________________________________________________
# The below section is used to check wether the XY_type is allowed for the Ksampler instance being used.
# If not the correct type, this section will abort the xy plot script.
samplers = {
"regular": {
"disallowed": ["AddNoise", "ReturnNoise", "StartStep", "EndStep", "RefineStep",
"Refiner", "Refiner On/Off", "AScore+", "AScore-"],
"name": "KSampler (Efficient)"
},
"advanced": {
"disallowed": ["RefineStep", "Denoise", "RefineStep", "Refiner", "Refiner On/Off",
"AScore+", "AScore-"],
"name": "KSampler Adv. (Efficient)"
},
"sdxl": {
"disallowed": ["AddNoise", "EndStep", "Denoise"],
"name": "KSampler SDXL (Eff.)"
}
}
# Define disallowed XY_types for each ksampler type
def get_ksampler_details(sampler_type):
return samplers.get(sampler_type, {"disallowed": [], "name": ""})
def suggest_ksampler(X_type, Y_type, current_sampler):
for sampler, details in samplers.items():
if sampler != current_sampler and X_type not in details["disallowed"] and Y_type not in details["disallowed"]:
return details["name"]
return "a different KSampler"
# In your main function or code segment:
details = get_ksampler_details(sampler_type)
disallowed_XY_types = details["disallowed"]
ksampler_name = details["name"]
if X_type in disallowed_XY_types or Y_type in disallowed_XY_types:
error_prefix = f"{error(f'{ksampler_name} Error:')}"
failed_type = []
if X_type in disallowed_XY_types:
failed_type.append(f"X_type: '{X_type}'")
if Y_type in disallowed_XY_types:
failed_type.append(f"Y_type: '{Y_type}'")
suggested_ksampler = suggest_ksampler(X_type, Y_type, sampler_type)
print(f"{error_prefix} Invalid value for {' and '.join(failed_type)}. "
f"Use {suggested_ksampler} for this XY Plot type."
f"\nDisallowed XY_types for this KSampler are: {', '.join(disallowed_XY_types)}.")
return {"ui": {"images": list()},
"result": (model, positive, negative, latent_image, vae, TSC_KSampler.empty_image,)}
#_______________________________________________________________________________________________________
# Unpack Effficient Loader dependencies
if dependencies is not None:
vae_name, ckpt_name, clip, clip_skip, refiner_name, refiner_clip, refiner_clip_skip,\
positive_prompt, negative_prompt, token_normalization, weight_interpretation, ascore,\
empty_latent_width, empty_latent_height, lora_stack, cnet_stack = dependencies
#_______________________________________________________________________________________________________
# Printout XY Plot values to be processed
def process_xy_for_print(value, replacement, type_):
if type_ == "Seeds++ Batch" and isinstance(value, list):
return [v + seed for v in value] # Add seed to every entry in the list
elif type_ == "Scheduler" and isinstance(value, tuple):
return value[0] # Return only the first entry of the tuple
elif type_ == "VAE" and isinstance(value, list):
# For each string in the list, extract the filename from the path
return [os.path.basename(v) for v in value]
elif (type_ == "Checkpoint" or type_ == "Refiner") and isinstance(value, list):
# For each tuple in the list, return only the first value if the second or third value is None
return [(os.path.basename(v[0]),) + v[1:] if v[1] is None or v[2] is None
else (os.path.basename(v[0]), v[1]) if v[2] is None
else (os.path.basename(v[0]),) + v[1:] for v in value]
elif type_ == "LoRA" and isinstance(value, list):
# Return only the first Tuple of each inner array
return [[(os.path.basename(v[0][0]),) + v[0][1:], "..."] if len(v) > 1
else [(os.path.basename(v[0][0]),) + v[0][1:]] for v in value]
elif type_ == "LoRA Batch" and isinstance(value, list):
# Extract the basename of the first value of the first tuple from each sublist
return [os.path.basename(v[0][0]) for v in value if v and isinstance(v[0], tuple) and v[0][0]]
elif (type_ == "LoRA Wt" or type_ == "LoRA MStr") and isinstance(value, list):
# Extract the first value of the first tuple from each sublist
return [v[0][1] for v in value if v and isinstance(v[0], tuple)]
elif type_ == "LoRA CStr" and isinstance(value, list):
# Extract the first value of the first tuple from each sublist
return [v[0][2] for v in value if v and isinstance(v[0], tuple)]
elif type_ == "ControlNetStrength" and isinstance(value, list):
# Extract the third entry of the first tuple from each inner list
return [round(inner_list[0][2], 3) for inner_list in value]
elif type_ == "ControlNetStart%" and isinstance(value, list):
# Extract the third entry of the first tuple from each inner list
return [round(inner_list[0][3], 3) for inner_list in value]
elif type_ == "ControlNetEnd%" and isinstance(value, list):
# Extract the third entry of the first tuple from each inner list
return [round(inner_list[0][4], 3) for inner_list in value]
elif isinstance(value, tuple):
return tuple(replacement if v is None else v for v in value)
else:
return replacement if value is None else value
# Determine the replacements based on X_type and Y_type
replacement_X = scheduler if X_type == 'Sampler' else clip_skip if X_type == 'Checkpoint' else None
replacement_Y = scheduler if Y_type == 'Sampler' else clip_skip if Y_type == 'Checkpoint' else None
# Process X_value and Y_value
X_value_processed = process_xy_for_print(X_value, replacement_X, X_type)
Y_value_processed = process_xy_for_print(Y_value, replacement_Y, Y_type)
print(info("-" * 40))
print(info('XY Plot Script Inputs:'))
print(info(f"(X) {X_type}:"))
for item in X_value_processed:
print(info(f" {item}"))
print(info(f"(Y) {Y_type}:"))
for item in Y_value_processed:
print(info(f" {item}"))
print(info("-" * 40))
#_______________________________________________________________________________________________________
# Perform various initializations in this section
# If not caching models, set to 1.
if cache_models == "False":
vae_cache = ckpt_cache = lora_cache = refn_cache = 1
else:
# Retrieve cache numbers
vae_cache, ckpt_cache, lora_cache, refn_cache = get_cache_numbers("XY Plot")
# Pack cache numbers in a tuple
cache = (vae_cache, ckpt_cache, lora_cache, refn_cache)
# Add seed to every entry in the list
X_value = [v + seed for v in X_value] if "Seeds++ Batch" == X_type else X_value
Y_value = [v + seed for v in Y_value] if "Seeds++ Batch" == Y_type else Y_value
# Embedd original prompts into prompt variables
positive_prompt = (positive_prompt, positive_prompt)
negative_prompt = (negative_prompt, negative_prompt)
# Set lora_stack to None if one of types are LoRA
if "LoRA" in X_type or "LoRA" in Y_type:
lora_stack = None
# Define the manipulated and static Control Net Variables with a tuple with shape (cn_1, cn_2, cn_3).
# The information in this tuple will be used by the plotter to properly plot Control Net XY input types.
cn_1, cn_2, cn_3 = None, None, None
# If X_type has "ControlNet" or both X_type and Y_type have "ControlNet"
if "ControlNet" in X_type:
cn_1, cn_2, cn_3 = X_value[0][0][2], X_value[0][0][3], X_value[0][0][4]
# If only Y_type has "ControlNet" and not X_type
elif "ControlNet" in Y_type:
cn_1, cn_2, cn_3 = Y_value[0][0][2], Y_value[0][0][3], Y_value[0][0][4]
# Additional checks for other substrings
if "ControlNetStrength" in X_type or "ControlNetStrength" in Y_type:
cn_1 = None
if "ControlNetStart%" in X_type or "ControlNetStart%" in Y_type:
cn_2 = None
if "ControlNetEnd%" in X_type or "ControlNetEnd%" in Y_type:
cn_3 = None
# Embed the information in cnet_stack
cnet_stack = (cnet_stack, (cn_1, cn_2, cn_3))
# Optimize image generation by prioritization:
priority = [
"Checkpoint",
"Refiner",
"LoRA",
"VAE",
]
conditioners = {
"Positive Prompt S/R",
"Negative Prompt S/R",
"AScore+",
"AScore-",
"Clip Skip",
"Clip Skip (Refiner)",
"ControlNetStrength",
"ControlNetStart%",
"ControlNetEnd%"
}
# Get priority values; return a high number if the type is not in priority list
x_priority = priority.index(X_type) if X_type in priority else 999
y_priority = priority.index(Y_type) if Y_type in priority else 999
# Check if both are conditioners
are_both_conditioners = X_type in conditioners and Y_type in conditioners
# Special cases
is_special_case = (
(X_type == "Refiner On/Off" and Y_type in ["RefineStep", "Steps"]) or
(X_type == "Nothing" and Y_type != "Nothing")
)
# Determine whether to flip
flip_xy = (y_priority < x_priority and not are_both_conditioners) or is_special_case
# Perform the flip if necessary
if flip_xy:
X_type, Y_type = Y_type, X_type
X_value, Y_value = Y_value, X_value
#_______________________________________________________________________________________________________
# The below code will clean from the cache any ckpt/vae/lora models it will not be reusing.
# Note: Special LoRA types will not trigger cache: "LoRA Batch", "LoRA Wt", "LoRA MStr", "LoRA CStr"
# Map the type names to the dictionaries
dict_map = {"VAE": [], "Checkpoint": [], "LoRA": [], "Refiner": []}