forked from LucianoCirino/efficiency-nodes-comfyui
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathefficiency_nodes.py
2464 lines (2051 loc) · 121 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
from comfy.sd import ModelPatcher, CLIP, VAE
from nodes import common_ksampler, CLIPSetLastLayer
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
import os
import sys
import subprocess
import json
import folder_paths
import psutil
# Get the absolute path of the parent directory of the current script
my_dir = os.path.dirname(os.path.abspath(__file__))
# Add the My directory path to the sys.path list
sys.path.append(my_dir)
# Construct the absolute path to the ComfyUI directory
comfy_dir = os.path.abspath(os.path.join(my_dir, '..', '..'))
# Add the ComfyUI directory path to the sys.path list
sys.path.append(comfy_dir)
# Construct the path to the font file
font_path = os.path.join(my_dir, 'arial.ttf')
# Import functions from ComfyUI
import comfy.samplers
import comfy.sd
import comfy.utils
# Import my util functions
from tsc_utils import *
MAX_RESOLUTION=8192
########################################################################################################################
# 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": "Positive","multiline": True}),
"negative": ("STRING", {"default": "Negative", "multiline": True}),
"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": 64})},
"optional": {"lora_stack": ("LORA_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, empty_latent_width, empty_latent_height, batch_size, lora_stack=None,
prompt=None, my_unique_id=None):
model: ModelPatcher | None = None
clip: CLIP | None = None
vae: VAE | None = None
# Create Empty Latent
latent = torch.zeros([batch_size, 4, empty_latent_height // 8, empty_latent_width // 8]).cpu()
# Clean globally stored objects
globals_cleanup(prompt)
# Retrieve cache numbers
vae_cache, ckpt_cache, lora_cache = get_cache_numbers("Efficient Loader")
if lora_name != "None":
lora_params = [(lora_name, lora_model_strength, lora_clip_strength)]
if lora_stack is not None:
lora_params.extend(lora_stack)
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
# Check for custom VAE
if vae_name != "Baked VAE":
vae = load_vae(vae_name, my_unique_id, cache=vae_cache, cache_overwrite=True)
# Debugging
###print_loaded_objects_entries()
# CLIP skip
if not clip:
raise Exception("No CLIP found")
clip = clip.clone()
clip.clip_layer(clip_skip)
# Data for XY Plot
dependencies = (vae_name, ckpt_name, clip, clip_skip, positive, negative, lora_params)
return (model, [[clip.encode(positive), {}]], [[clip.encode(negative), {}]], {"samples":latent}, vae, clip, dependencies, )
########################################################################################################################
# TSC LoRA Stacker
class TSC_LoRA_Stacker:
loras = ["None"] + folder_paths.get_filename_list("loras")
@classmethod
def INPUT_TYPES(cls):
return {"required": {
"lora_name_1": (cls.loras,),
"lora_wt_1": ("FLOAT", {"default": 1.0, "min": -10.0, "max": 10.0, "step": 0.01}),
"lora_name_2": (cls.loras,),
"lora_wt_2": ("FLOAT", {"default": 1.0, "min": -10.0, "max": 10.0, "step": 0.01}),
"lora_name_3": (cls.loras,),
"lora_wt_3": ("FLOAT", {"default": 1.0, "min": -10.0, "max": 10.0, "step": 0.01})},
"optional": {"lora_stack": ("LORA_STACK",)},
}
RETURN_TYPES = ("LORA_STACK",)
RETURN_NAMES = ("LORA_STACK",)
FUNCTION = "lora_stacker"
CATEGORY = "Efficiency Nodes/Misc"
def lora_stacker(self, lora_name_1, lora_wt_1, lora_name_2, lora_wt_2, lora_name_3, lora_wt_3, lora_stack=None):
# Create a list of tuples using provided parameters, exclude tuples with lora_name as "None"
loras = [(lora_name, lora_wt, lora_wt) for lora_name, lora_wt, lora_wt in
[(lora_name_1, lora_wt_1, lora_wt_1),
(lora_name_2, lora_wt_2, lora_wt_2),
(lora_name_3, lora_wt_3, lora_wt_3)]
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 LoRA Stacker Advanced
class TSC_LoRA_Stacker_Adv:
loras = ["None"] + folder_paths.get_filename_list("loras")
@classmethod
def INPUT_TYPES(cls):
return {"required": {
"lora_name_1": (cls.loras,),
"model_str_1": ("FLOAT", {"default": 1.0, "min": -10.0, "max": 10.0, "step": 0.01}),
"clip_str_1": ("FLOAT", {"default": 1.0, "min": -10.0, "max": 10.0, "step": 0.01}),
"lora_name_2": (cls.loras,),
"model_str_2": ("FLOAT", {"default": 1.0, "min": -10.0, "max": 10.0, "step": 0.01}),
"clip_str_2": ("FLOAT", {"default": 1.0, "min": -10.0, "max": 10.0, "step": 0.01}),
"lora_name_3": (cls.loras,),
"model_str_3": ("FLOAT", {"default": 1.0, "min": -10.0, "max": 10.0, "step": 0.01}),
"clip_str_3": ("FLOAT", {"default": 1.0, "min": -10.0, "max": 10.0, "step": 0.01})},
"optional": {"lora_stack": ("LORA_STACK",)},
}
RETURN_TYPES = ("LORA_STACK",)
RETURN_NAMES = ("LORA_STACK",)
FUNCTION = "lora_stacker"
CATEGORY = "Efficiency Nodes/Misc"
def lora_stacker(self, lora_name_1, model_str_1, clip_str_1, lora_name_2, model_str_2, clip_str_2,
lora_name_3, model_str_3, clip_str_3, lora_stack=None):
# Create a list of tuples using provided parameters, exclude tuples with lora_name as "None"
loras = [(lora_name, model_str, clip_str) for lora_name, model_str, clip_str in
[(lora_name_1, model_str_1, clip_str_1),
(lora_name_2, model_str_2, clip_str_2),
(lora_name_3, model_str_3, clip_str_3)]
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 KSampler (Efficient)
class TSC_KSampler:
empty_image = pil2tensor(Image.new('RGBA', (1, 1), (0, 0, 0, 0)))
def __init__(self):
self.output_dir = os.path.join(comfy_dir, 'temp')
self.type = "temp"
@classmethod
def INPUT_TYPES(cls):
return {"required":
{"sampler_state": (["Sample", "Hold", "Script"], ),
"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_image": (["Disabled", "Enabled", "Output Only"],),
},
"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, sampler_state, model, seed, steps, cfg, sampler_name, scheduler, positive, negative,
latent_image, preview_image, denoise=1.0, prompt=None, extra_pnginfo=None, my_unique_id=None,
optional_vae=(None,), script=None):
# Extract node_settings from json
def get_settings():
# Get the directory path of the current file
my_dir = os.path.dirname(os.path.abspath(__file__))
# Construct the file path for node_settings.json
settings_file = os.path.join(my_dir, 'node_settings.json')
# Load the settings from the JSON file
with open(settings_file, 'r') as file:
node_settings = json.load(file)
# Retrieve the settings
kse_vae_tiled = node_settings.get("KSampler (Efficient)", {}).get('vae_tiled', False)
xy_vae_tiled = node_settings.get("XY Plot", {}).get('vae_tiled', False)
return kse_vae_tiled, xy_vae_tiled
kse_vae_tiled, xy_vae_tiled = get_settings()
# Functions for previewing images in Ksampler
def map_filename(filename):
prefix_len = len(os.path.basename(filename_prefix))
prefix = filename[:prefix_len + 1]
try:
digits = int(filename[prefix_len + 1:].split('_')[0])
except:
digits = 0
return (digits, prefix)
def compute_vars(input):
input = input.replace("%width%", str(images[0].shape[1]))
input = input.replace("%height%", str(images[0].shape[0]))
return input
def preview_images(images, filename_prefix):
filename_prefix = compute_vars(filename_prefix)
subfolder = os.path.dirname(os.path.normpath(filename_prefix))
filename = os.path.basename(os.path.normpath(filename_prefix))
full_output_folder = os.path.join(self.output_dir, subfolder)
try:
counter = max(filter(lambda a: a[1][:-1] == filename and a[1][-1] == "_",
map(map_filename, os.listdir(full_output_folder))))[0] + 1
except ValueError:
counter = 1
except FileNotFoundError:
os.makedirs(full_output_folder, exist_ok=True)
counter = 1
if not os.path.exists(self.output_dir):
os.makedirs(self.output_dir)
results = list()
for image in images:
i = 255. * image.cpu().numpy()
img = Image.fromarray(np.clip(i, 0, 255).astype(np.uint8))
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=4)
results.append({
"filename": file,
"subfolder": subfolder,
"type": self.type
});
counter += 1
return results
def get_value_by_id(key: str, my_unique_id):
global last_helds
for value, id_ in last_helds[key]:
if id_ == my_unique_id:
return value
return None
def update_value_by_id(key: str, my_unique_id, new_value):
global last_helds
for i, (value, id_) in enumerate(last_helds[key]):
if id_ == my_unique_id:
last_helds[key][i] = (new_value, id_)
return True
last_helds[key].append((new_value, my_unique_id))
return True
# Clean globally stored objects of non-existant nodes
globals_cleanup(prompt)
# Convert ID string to an integer
my_unique_id = int(my_unique_id)
# Vae input check
vae = optional_vae
if vae == (None,):
print('\033[33mKSampler(Efficient) Warning:\033[0m No vae input detected, preview and output image disabled.\n')
preview_image = "Disabled"
# Init last_results
if get_value_by_id("results", my_unique_id) is None:
last_results = list()
else:
last_results = get_value_by_id("results", my_unique_id)
# Init last_latent
if get_value_by_id("latent", my_unique_id) is None:
last_latent = latent_image
else:
last_latent = {"samples": None}
last_latent["samples"] = get_value_by_id("latent", my_unique_id)
# Init last_images
if get_value_by_id("images", my_unique_id) == None:
last_images = TSC_KSampler.empty_image
else:
last_images = get_value_by_id("images", my_unique_id)
# Initialize latent
latent: Tensor|None = None
# Define filename_prefix
filename_prefix = "KSeff_{:02d}".format(my_unique_id)
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# Check the current sampler state
if sampler_state == "Sample":
# Sample using the common KSampler function and store the samples
samples = common_ksampler(model, seed, steps, cfg, sampler_name, scheduler, positive, negative,
latent_image, denoise=denoise)
# Extract the latent samples from the returned samples dictionary
latent = samples[0]["samples"]
# Store the latent samples in the 'last_helds' dictionary with a unique ID
update_value_by_id("latent", my_unique_id, latent)
# If not in preview mode, return the results in the specified format
if preview_image == "Disabled":
# Enable vae decode on next Hold
update_value_by_id("vae_decode", my_unique_id, True)
return {"ui": {"images": list()},
"result": (model, positive, negative, {"samples": latent}, vae, TSC_KSampler.empty_image,)}
else:
# Decode images and store
if kse_vae_tiled == False:
images = vae.decode(latent).cpu()
else:
images = vae.decode_tiled(latent).cpu()
update_value_by_id("images", my_unique_id, images)
# Disable vae decode on next Hold
update_value_by_id("vae_decode", my_unique_id, False)
# Generate image results and store
results = preview_images(images, filename_prefix)
update_value_by_id("results", my_unique_id, results)
# Determine what the 'images' value should be
images_value = list() if preview_image == "Output Only" else results
# Output image results to ui and node outputs
return {"ui": {"images": images_value},
"result": (model, positive, negative, {"samples": latent}, vae, images,)}
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# If the sampler state is "Hold"
elif sampler_state == "Hold":
# If not in preview mode, return the results in the specified format
if preview_image == "Disabled":
return {"ui": {"images": list()},
"result": (model, positive, negative, last_latent, vae, TSC_KSampler.empty_image,)}
else:
latent = last_latent["samples"]
if get_value_by_id("vae_decode", my_unique_id) == True:
# Decode images and store
if kse_vae_tiled == False:
images = vae.decode(latent).cpu()
else:
images = vae.decode_tiled(latent).cpu()
update_value_by_id("images", my_unique_id, images)
# Disable vae decode on next Hold
update_value_by_id("vae_decode", my_unique_id, False)
# Generate image results and store
results = preview_images(images, filename_prefix)
update_value_by_id("results", my_unique_id, results)
else:
images = last_images
results = last_results
# Determine what the 'images' value should be
images_value = list() if preview_image == "Output Only" else results
# Output image results to ui and node outputs
return {"ui": {"images": images_value},
"result": (model, positive, negative, {"samples": latent}, vae, images,)}
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
elif sampler_state == "Script":
# Store name of connected node to script input
script_node_name, script_node_id = extract_node_info(prompt, my_unique_id, 'script')
# If no valid script input connected, error out
if script == None or script == (None,) or script_node_name!="XY Plot":
if script_node_name!="XY Plot":
print('\033[31mKSampler(Efficient) Error:\033[0m No valid script input detected')
return {"ui": {"images": list()},
"result": (model, positive, negative, last_latent, vae, last_images,)}
# If no vae connected, throw errors
if vae == (None,):
print('\033[31mKSampler(Efficient) Error:\033[0m VAE must be connected to use Script mode.')
return {"ui": {"images": list()},
"result": (model, positive, negative, last_latent, vae, last_images,)}
# If preview_image set to disabled, run script anyways with message
if preview_image == "Disabled":
print('\033[33mKSampler(Efficient) Warning:\033[0m The preview image cannot be disabled when running'
' the XY Plot script, proceeding as if it was enabled.\n')
# Extract the 'samples' tensor and split it into individual image tensors
image_tensors = torch.split(latent_image['samples'], 1, dim=0)
# Get the shape of the first image tensor
shape = image_tensors[0].shape
# Extract the original height and width
latent_height, latent_width = shape[2] * 8, shape[3] * 8
# Set latent only to the first latent of batch
latent_image = {'samples': image_tensors[0]}
#___________________________________________________________________________________________________________
# Initialize, unpack, and clean variables for the XY Plot script
if script_node_name == "XY Plot":
# Initialize variables
vae_name = None
ckpt_name = None
clip = None
lora_params = None
positive_prompt = None
negative_prompt = None
clip_skip = None
# 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,\
flip_xy, dependencies = script
# Unpack Effficient Loader dependencies
if dependencies is not None:
vae_name, ckpt_name, clip, clip_skip, positive_prompt, negative_prompt, lora_params = dependencies
# Helper function to process printout values
def process_xy_for_print(value, replacement, type_):
if isinstance(value, tuple) and type_ == "Scheduler":
return value[0] # Return only the first entry of the tuple
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(v, replacement_X, X_type) for v in X_value]
Y_value_processed = [process_xy_for_print(v, replacement_Y, Y_type) for v in Y_value]
# Print XY Plot Inputs
print("-" * 40)
print("XY Plot Script Inputs:")
print(f"(X) {X_type}: {X_value_processed}")
print(f"(Y) {Y_type}: {Y_value_processed}")
print("-" * 40)
# If not caching models, set to 1.
if cache_models == "False":
vae_cache = ckpt_cache = lora_cache = 1
else:
# Retrieve cache numbers
vae_cache, ckpt_cache, lora_cache = get_cache_numbers("XY Plot")
# Pack cache numbers in a tuple
cache = (vae_cache, ckpt_cache, lora_cache)
# Embedd original prompts into prompt variables
positive_prompt = (positive_prompt, positive_prompt)
negative_prompt = (negative_prompt, negative_prompt)
#_______________________________________________________________________________________________________
#The below code will clean from the cache any ckpt/vae/lora models it will not be reusing.
# Map the type names to the dictionaries
dict_map = {"VAE": [], "Checkpoint": [], "LoRA": []}
# Create a list of tuples with types and values
type_value_pairs = [(X_type, X_value), (Y_type, Y_value)]
# Iterate over type-value pairs
for t, v in type_value_pairs:
if t in dict_map:
# Flatten the list of lists of tuples if the type is "LoRA"
if t == "LoRA":
dict_map[t] = [item for sublist in v for item in sublist]
else:
dict_map[t] = v
ckpt_dict = [t[0] for t in dict_map.get("Checkpoint", [])] if dict_map.get("Checkpoint", []) else []
lora_dict = [[t,] for t in dict_map.get("LoRA", [])] if dict_map.get("LoRA", []) else []
# If both ckpt_dict and lora_dict are not empty, manipulate lora_dict as described
if ckpt_dict and lora_dict:
lora_dict = [(lora_params, ckpt) for ckpt in ckpt_dict for lora_params in lora_dict]
# If lora_dict is not empty and ckpt_dict is empty, insert ckpt_name into each tuple in lora_dict
elif lora_dict:
lora_dict = [(lora_params, ckpt_name) for lora_params in lora_dict]
vae_dict = dict_map.get("VAE", [])
# prioritize Caching Checkpoints over LoRAs but not both.
if X_type == "LoRA":
ckpt_dict = []
if X_type == "Checkpoint":
lora_dict = []
# Print dict_arrays for debugging
###print(f"vae_dict={vae_dict}\nckpt_dict={ckpt_dict}\nlora_dict={lora_dict}")
# Clean values that won't be reused
clear_cache_by_exception(script_node_id, vae_dict=vae_dict, ckpt_dict=ckpt_dict, lora_dict=lora_dict)
# Print loaded_objects for debugging
###print_loaded_objects_entries()
#_______________________________________________________________________________________________________
# Function that changes appropiate variables for next processed generations (also generates XY_labels)
def define_variable(var_type, var, seed, steps, cfg, sampler_name, scheduler, denoise, vae_name, ckpt_name,
clip_skip, positive_prompt, negative_prompt, lora_params, var_label, num_label):
# Define default max label size limit
max_label_len = 36
# If var_type is "Seeds++ Batch", update var and seed, and generate labels
if var_type == "Seeds++ Batch":
text = f"Seed: {seed}"
# If var_type is "Steps", update steps and generate labels
elif var_type == "Steps":
steps = var
text = f"steps: {steps}"
# If var_type is "CFG Scale", update cfg and generate labels
elif var_type == "CFG Scale":
cfg = var
text = f"CFG: {round(cfg,2)}"
# If var_type is "Sampler", update sampler_name, scheduler, and generate labels
elif var_type == "Sampler":
sampler_name = var[0]
if var[1] == "":
text = f"{sampler_name}"
else:
if var[1] != None:
scheduler = (var[1], scheduler[1])
else:
scheduler = (scheduler[1], scheduler[1])
text = f"{sampler_name} ({scheduler[0]})"
text = text.replace("ancestral", "a").replace("uniform", "u").replace("exponential","exp")
# If var_type is "Scheduler", update scheduler and generate labels
elif var_type == "Scheduler":
if len(var) == 2:
scheduler = (var[0], scheduler[1])
text = f"{sampler_name} ({scheduler[0]})"
else:
scheduler = (var, scheduler[1])
text = f"{scheduler[0]}"
text = text.replace("ancestral", "a").replace("uniform", "u").replace("exponential","exp")
# If var_type is "Denoise", update denoise and generate labels
elif var_type == "Denoise":
denoise = var
text = f"denoise: {round(denoise, 2)}"
# If var_type is "VAE", update vae_name and generate labels
elif var_type == "VAE":
vae_name = var
vae_filename = os.path.splitext(os.path.basename(vae_name))[0]
text = f"VAE: {vae_filename}"
# If var_type is "Positive Prompt S/R", update positive_prompt and generate labels
elif var_type == "Positive Prompt S/R":
search_txt, replace_txt = var
if replace_txt != None:
positive_prompt = (positive_prompt[1].replace(search_txt, replace_txt, 1), positive_prompt[1])
else:
positive_prompt = (positive_prompt[1], positive_prompt[1])
replace_txt = search_txt
text = f"{replace_txt}"
# If var_type is "Negative Prompt S/R", update negative_prompt and generate labels
elif var_type == "Negative Prompt S/R":
search_txt, replace_txt = var
if replace_txt:
negative_prompt = (negative_prompt[1].replace(search_txt, replace_txt, 1), negative_prompt[1])
else:
negative_prompt = (negative_prompt[1], negative_prompt[1])
replace_txt = search_txt
text = f"(-) {replace_txt}"
# If var_type is "Checkpoint", update model and clip (if needed) and generate labels
elif var_type == "Checkpoint":
ckpt_name = var[0]
if var[1] == None:
clip_skip = (clip_skip[1],clip_skip[1])
else:
clip_skip = (var[1],clip_skip[1])
ckpt_filename = os.path.splitext(os.path.basename(ckpt_name))[0]
text = f"{ckpt_filename}"
elif var_type == "Clip Skip":
clip_skip = (var, clip_skip[1])
text = f"Clip Skip ({clip_skip[0]})"
elif var_type == "LoRA":
lora_params = var
max_label_len = 30 + (12 * (len(lora_params)-1))
if len(lora_params) == 1:
lora_name, lora_model_wt, lora_clip_wt = lora_params[0]
lora_filename = os.path.splitext(os.path.basename(lora_name))[0]
lora_model_wt = format(float(lora_model_wt), ".2f").rstrip('0').rstrip('.')
lora_clip_wt = format(float(lora_clip_wt), ".2f").rstrip('0').rstrip('.')
lora_filename = lora_filename[:max_label_len - len(f"LoRA: ({lora_model_wt})")]
if lora_model_wt == lora_clip_wt:
text = f"LoRA: {lora_filename}({lora_model_wt})"
else:
text = f"LoRA: {lora_filename}({lora_model_wt},{lora_clip_wt})"
elif len(lora_params) > 1:
lora_filenames = [os.path.splitext(os.path.basename(lora_name))[0] for lora_name, _, _ in lora_params]
lora_details = [(format(float(lora_model_wt), ".2f").rstrip('0').rstrip('.'),
format(float(lora_clip_wt), ".2f").rstrip('0').rstrip('.')) for _, lora_model_wt, lora_clip_wt in lora_params]
non_name_length = sum(len(f"({lora_details[i][0]},{lora_details[i][1]})") + 2 for i in range(len(lora_params)))
available_space = max_label_len - non_name_length
max_name_length = available_space // len(lora_params)
lora_filenames = [filename[:max_name_length] for filename in lora_filenames]
text_elements = [f"{lora_filename}({lora_details[i][0]})" if lora_details[i][0] == lora_details[i][1] else f"{lora_filename}({lora_details[i][0]},{lora_details[i][1]})" for i, lora_filename in enumerate(lora_filenames)]
text = " ".join(text_elements)
def truncate_texts(texts, num_label, max_label_len):
truncate_length = max(min(max(len(text) for text in texts), max_label_len), 24)
return [text if len(text) <= truncate_length else text[:truncate_length] + "..." for text in
texts]
# Add the generated text to var_label if it's not full
if len(var_label) < num_label:
var_label.append(text)
# If var_type VAE , truncate entries in the var_label list when it's full
if len(var_label) == num_label and (var_type == "VAE" or var_type == "Checkpoint" or var_type == "LoRA"):
var_label = truncate_texts(var_label, num_label, max_label_len)
# Return the modified variables
return steps, cfg, sampler_name, scheduler, denoise, vae_name, ckpt_name, clip_skip, \
positive_prompt, negative_prompt, lora_params, var_label
# _______________________________________________________________________________________________________
# The function below is used to smartly load Checkpoint/LoRA/VAE models between generations.
def define_model(model, clip, positive, negative, positive_prompt, negative_prompt, clip_skip, vae,
vae_name, ckpt_name, lora_params, index, types, script_node_id, cache):
# Encode prompt and apply clip_skip. Return new conditioning.
def encode_prompt(positive_prompt, negative_prompt, clip, clip_skip):
clip = CLIPSetLastLayer().set_last_layer(clip, clip_skip)[0]
return [[clip.encode(positive_prompt), {}]], [[clip.encode(negative_prompt), {}]]
# Variable to track wether to encode prompt or not
encode = False
# Unpack types tuple
X_type, Y_type = types
# Note: Index is held at 0 when Y_type == "Nothing"
# Load VAE if required
if (X_type == "VAE" and index == 0) or Y_type == "VAE":
vae = load_vae(vae_name, script_node_id, cache=cache[0])
# Load Checkpoint if required. If Y_type is LoRA, required models will be loaded by load_lora func.
if (X_type == "Checkpoint" and index == 0 and Y_type != "LoRA"):
if lora_params is None:
model, clip, _ = load_checkpoint(ckpt_name, script_node_id, output_vae=False, cache=cache[1])
else: # Load Efficient Loader LoRA
model, clip = load_lora(lora_params, ckpt_name, script_node_id,
cache=None, ckpt_cache=cache[1])
encode = True
# Load LoRA if required
elif (X_type == "LoRA" and index == 0):
# Don't cache Checkpoints
model, clip = load_lora(lora_params, ckpt_name, script_node_id, cache=cache[2])
encode = True
elif Y_type == "LoRA": # X_type must be Checkpoint, so cache those as defined
model, clip = load_lora(lora_params, ckpt_name, script_node_id,
cache=None, ckpt_cache=cache[1])
encode = True
# Encode Prompt if required
prompt_types = ["Positive Prompt S/R", "Negative Prompt S/R", "Clip Skip"]
if (X_type in prompt_types and index == 0) or Y_type in prompt_types:
encode = True
# Encode prompt if needed
if encode == True:
positive, negative = encode_prompt(positive_prompt[0], negative_prompt[0], clip, clip_skip)
return model, positive, negative, vae
# ______________________________________________________________________________________________________
# The below function is used to generate the results based on all the processed variables
def process_values(model, seed, steps, cfg, sampler_name, scheduler, positive, negative, latent_image,
denoise, vae, latent_list=[], image_tensor_list=[], image_pil_list=[]):
# Sample
samples = common_ksampler(model, seed, steps, cfg, sampler_name, scheduler, positive, negative,
latent_image, denoise=denoise)
# Decode images and store
latent = samples[0]["samples"]
# Add the latent tensor to the tensors list
latent_list.append(latent)
# Decode the latent tensor
if xy_vae_tiled == False:
image = vae.decode(latent).cpu()
else:
image = vae.decode_tiled(latent).cpu()
# Add the resulting image tensor to image_tensor_list
image_tensor_list.append(image)
# Convert the image from tensor to PIL Image and add it to the image_pil_list
image_pil_list.append(tensor2pil(image))
# Return the touched variables
return latent_list, image_tensor_list, image_pil_list
# ______________________________________________________________________________________________________
# The below section is the heart of the XY Plot image generation
# Initiate Plot label text variables X/Y_label
X_label = []
Y_label = []
# Seed_updated for "Seeds++ Batch" incremental seeds
seed_updated = seed
# Store the KSamplers original scheduler inside the same scheduler variable
scheduler = (scheduler, scheduler)
# Store the Eff Loaders original clip_skip inside the same clip_skip variable
clip_skip = (clip_skip, clip_skip)
# Store types in a Tuple for easy function passing
types = (X_type, Y_type)
# Fill Plot Rows (X)
for X_index, X in enumerate(X_value):
# Seed control based on loop index during Batch
if X_type == "Seeds++ Batch":
# Update seed based on the inner loop index
seed_updated = seed + X_index
# Define X parameters and generate labels
steps, cfg, sampler_name, scheduler, denoise, vae_name, ckpt_name, clip_skip, positive_prompt, negative_prompt, \
lora_params, X_label = \
define_variable(X_type, X, seed_updated, steps, cfg, sampler_name, scheduler, denoise, vae_name, ckpt_name,
clip_skip, positive_prompt, negative_prompt, lora_params, X_label, len(X_value))
if X_type != "Nothing" and Y_type == "Nothing":
# Models & Conditionings
model, positive, negative , vae = \
define_model(model, clip, positive, negative, positive_prompt, negative_prompt, clip_skip[0], vae,
vae_name, ckpt_name, lora_params, 0, types, script_node_id, cache)
# Generate Results
latent_list, image_tensor_list, image_pil_list = \
process_values(model, seed_updated, steps, cfg, sampler_name, scheduler[0],
positive, negative, latent_image, denoise, vae)
elif X_type != "Nothing" and Y_type != "Nothing":
# Seed control based on loop index during Batch
for Y_index, Y in enumerate(Y_value):
if Y_type == "Seeds++ Batch":
# Update seed based on the inner loop index
seed_updated = seed + Y_index
# Define Y parameters and generate labels
steps, cfg, sampler_name, scheduler, denoise, vae_name, ckpt_name, clip_skip, positive_prompt, negative_prompt, lora_params, Y_label = \
define_variable(Y_type, Y, seed_updated, steps, cfg, sampler_name, scheduler, denoise, vae_name, ckpt_name,
clip_skip, positive_prompt, negative_prompt, lora_params, Y_label, len(Y_value))
# Models & Conditionings
model, positive, negative, vae = \
define_model(model, clip, positive, negative, positive_prompt, negative_prompt, clip_skip[0], vae,
vae_name, ckpt_name, lora_params, Y_index, types, script_node_id, cache)
# Generate Results
latent_list, image_tensor_list, image_pil_list = \
process_values(model, seed_updated, steps, cfg, sampler_name, scheduler[0],
positive, negative, latent_image, denoise, vae)
# Clean up cache
if cache_models == "False":
clear_cache_by_exception(script_node_id, vae_dict=[], ckpt_dict=[], lora_dict=[])
#
else:
# Prioritrize Caching Checkpoints over LoRAs.
if X_type == "LoRA":
clear_cache_by_exception(script_node_id, ckpt_dict=[])
elif X_type == "Checkpoint":
clear_cache_by_exception(script_node_id, lora_dict=[])
# ______________________________________________________________________________________________________
def print_plot_variables(X_type, Y_type, X_value, Y_value, seed, ckpt_name, lora_params,
vae_name, clip_skip, steps, cfg, sampler_name, scheduler, denoise,
num_rows, num_cols, latent_height, latent_width):
print("-" * 40) # Print an empty line followed by a separator line
print("\033[32mXY Plot Results:\033[0m")
def get_vae_name(X_type, Y_type, X_value, Y_value, vae_name):
if X_type == "VAE":
vae_name = ", ".join(map(lambda x: os.path.splitext(os.path.basename(str(x)))[0], X_value))
elif Y_type == "VAE":
vae_name = ", ".join(map(lambda y: os.path.splitext(os.path.basename(str(y)))[0], Y_value))
else:
vae_name = os.path.splitext(os.path.basename(str(vae_name)))[0]
return vae_name
def get_clip_skip(X_type, Y_type, X_value, Y_value, clip_skip):
if X_type == "Clip Skip":
clip_skip = ", ".join(map(str, X_value))
elif Y_type == "Clip Skip":
clip_skip = ", ".join(map(str, Y_value))
else:
clip_skip = clip_skip[1]
return clip_skip
def get_checkpoint_name(ckpt_type, ckpt_values, clip_skip_type, clip_skip_values, ckpt_name, clip_skip):
if ckpt_type == "Checkpoint":
if clip_skip_type == "Clip Skip":
ckpt_name = ", ".join([os.path.splitext(os.path.basename(str(ckpt[0])))[0] for ckpt in ckpt_values])
else:
ckpt_name = ", ".join([f"{os.path.splitext(os.path.basename(str(ckpt[0])))[0]}({str(ckpt[1]) if ckpt[1] is not None else str(clip_skip_values)})"
for ckpt in ckpt_values])
clip_skip = "_"
else:
ckpt_name = os.path.splitext(os.path.basename(str(ckpt_name)))[0]
return ckpt_name, clip_skip
def get_lora_name(X_type, Y_type, X_value, Y_value, lora_params=None):
if X_type != "LoRA" and Y_type != "LoRA":
if lora_params:
return f"[{', '.join([f'{os.path.splitext(os.path.basename(name))[0]}({round(model_wt, 3)},{round(clip_wt, 3)})' for name, model_wt, clip_wt in lora_params])}]"
else:
return None
else:
return get_lora_sublist_name(X_type,
X_value) if X_type == "LoRA" else get_lora_sublist_name(Y_type, Y_value) if Y_type == "LoRA" else None
def get_lora_sublist_name(lora_type, lora_value):
return ", ".join([
f"[{', '.join([f'{os.path.splitext(os.path.basename(str(x[0])))[0]}({round(x[1], 3)},{round(x[2], 3)})' for x in sublist])}]"
for sublist in lora_value])
# use these functions:
ckpt_type, clip_skip_type = (X_type, Y_type) if X_type in ["Checkpoint", "Clip Skip"] else (Y_type, X_type)
ckpt_values, clip_skip_values = (X_value, Y_value) if X_type in ["Checkpoint", "Clip Skip"] else (Y_value, X_value)
clip_skip = get_clip_skip(X_type, Y_type, X_value, Y_value, clip_skip)
ckpt_name, clip_skip = get_checkpoint_name(ckpt_type, ckpt_values, clip_skip_type, clip_skip_values, ckpt_name, clip_skip)
vae_name = get_vae_name(X_type, Y_type, X_value, Y_value, vae_name)
lora_name = get_lora_name(X_type, Y_type, X_value, Y_value, lora_params)
seed_list = [seed + x for x in X_value] if X_type == "Seeds++ Batch" else\
[seed + y for y in Y_value] if Y_type == "Seeds++ Batch" else [seed]
seed = ", ".join(map(str, seed_list))
steps = ", ".join(map(str, X_value)) if X_type == "Steps" else ", ".join(
map(str, Y_value)) if Y_type == "Steps" else steps
cfg = ", ".join(map(str, X_value)) if X_type == "CFG Scale" else ", ".join(
map(str, Y_value)) if Y_type == "CFG Scale" else cfg
if X_type == "Sampler":
if Y_type == "Scheduler":
sampler_name = ", ".join([f"{x[0]}" for x in X_value])
scheduler = ", ".join([f"{y}" for y in Y_value])
else:
sampler_name = ", ".join(
[f"{x[0]}({x[1] if x[1] != '' and x[1] is not None else scheduler[1]})" for x in X_value])
scheduler = "_"
elif Y_type == "Sampler":
if X_type == "Scheduler":
sampler_name = ", ".join([f"{y[0]}" for y in Y_value])
scheduler = ", ".join([f"{x}" for x in X_value])
else:
sampler_name = ", ".join(
[f"{y[0]}({y[1] if y[1] != '' and y[1] is not None else scheduler[1]})" for y in Y_value])
scheduler = "_"
else:
scheduler = ", ".join([str(x[0]) if isinstance(x, tuple) else str(x) for x in X_value]) if X_type == "Scheduler" else \
", ".join([str(y[0]) if isinstance(y, tuple) else str(y) for y in Y_value]) if Y_type == "Scheduler" else scheduler[0]
denoise = ", ".join(map(str, X_value)) if X_type == "Denoise" else ", ".join(
map(str, Y_value)) if Y_type == "Denoise" else denoise
# Printouts
print(f"img_count: {len(X_value)*len(Y_value)}")
print(f"img_dims: {latent_height} x {latent_width}")
print(f"plot_dim: {num_cols} x {num_rows}")
if clip_skip == "_":
print(f"ckpt(clipskip): {ckpt_name if ckpt_name is not None else ''}")
else:
print(f"ckpt: {ckpt_name if ckpt_name is not None else ''}")
print(f"clip_skip: {clip_skip if clip_skip is not None else ''}")
if lora_name:
print(f"lora(mod,clip): {lora_name if lora_name is not None else ''}")
print(f"vae: {vae_name if vae_name is not None else ''}")
print(f"seed: {seed}")
print(f"steps: {steps}")
print(f"cfg: {cfg}")
if scheduler == "_":
print(f"sampler(schr): {sampler_name}")
else:
print(f"sampler: {sampler_name}")
print(f"scheduler: {scheduler}")
print(f"denoise: {denoise}")
if X_type == "Positive Prompt S/R" or Y_type == "Positive Prompt S/R":
positive_prompt = ", ".join([str(x[0]) if i == 0 else str(x[1]) for i, x in enumerate(
X_value)]) if X_type == "Positive Prompt S/R" else ", ".join(