-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathmikey_nodes.py
5482 lines (4946 loc) · 285 KB
/
mikey_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
import datetime
from fractions import Fraction
import gc
import hashlib
import importlib.util
from itertools import product
import json
from math import ceil, pow, gcd
import os
import psutil
import random
import re
import sys
from textwrap import wrap
import html
import latent_preview
import requests
import numpy as np
from PIL import Image, ImageOps, ImageDraw, ImageFilter, ImageChops, ImageFont
from PIL.PngImagePlugin import PngInfo
import torch
import torch.nn.functional as F
from tqdm import tqdm
import folder_paths
file_path = os.path.join(folder_paths.base_path, 'comfy_extras/nodes_clip_sdxl.py')
module_name = "nodes_clip_sdxl"
spec = importlib.util.spec_from_file_location(module_name, file_path)
module = importlib.util.module_from_spec(spec)
sys.modules[module_name] = module
spec.loader.exec_module(module)
from nodes_clip_sdxl import CLIPTextEncodeSDXL, CLIPTextEncodeSDXLRefiner
file_path = os.path.join(folder_paths.base_path, 'comfy_extras/nodes_upscale_model.py')
module_name = "nodes_upscale_model"
spec = importlib.util.spec_from_file_location(module_name, file_path)
module = importlib.util.module_from_spec(spec)
sys.modules[module_name] = module
spec.loader.exec_module(module)
import comfy_extras
from nodes_upscale_model import UpscaleModelLoader, ImageUpscaleWithModel
from comfy.model_management import soft_empty_cache, free_memory, get_torch_device, current_loaded_models, load_model_gpu
from nodes import LoraLoader, ConditioningAverage, common_ksampler, ImageScale, ImageScaleBy, VAEEncode, VAEDecode
import comfy.utils
from comfy_extras.chainner_models import model_loading
from comfy_extras.nodes_custom_sampler import Noise_EmptyNoise, Noise_RandomNoise
from comfy import model_management, model_base
def calculate_file_hash(file_path):
# open the file in binary mode
with open(file_path, 'rb') as f:
# read the file in chunks to avoid loading the whole file into memory
chunk_size = 4096
hash_object = hashlib.sha256()
while True:
chunk = f.read(chunk_size)
if not chunk:
break
hash_object.update(chunk)
# return the hexadecimal representation of the hash
return hash_object.hexdigest()
def get_cached_file_hashes():
# load the cached file hashes from the JSON file
cache_file_path = os.path.join(folder_paths.base_path, 'file_hashes.json')
if os.path.exists(cache_file_path):
with open(cache_file_path, 'r') as f:
return json.load(f)
else:
return {}
def get_file_hash(file_path):
# check if the file hash is already cached
# replace \ with / in file_path
file_path = file_path.replace('\\', '/')
cached_file_hashes = get_cached_file_hashes()
file_name = os.path.basename(file_path)
if file_name in cached_file_hashes:
return cached_file_hashes[file_name]
else:
# calculate the file hash and cache it
file_hash = calculate_file_hash(file_path)[:10]
cache_file_hash(file_path, file_hash)
return file_hash
def cache_file_hash(file_path, file_hash):
# update the cached file hashes dictionary and save to the JSON file
cache_file_path = os.path.join(folder_paths.base_path, 'file_hashes.json')
cached_file_hashes = get_cached_file_hashes()
cached_file_hashes[os.path.basename(file_path)] = file_hash
with open(cache_file_path, 'w') as f:
json.dump(cached_file_hashes, f)
def find_latent_size(width: int, height: int, res: int = 1024) -> (int, int):
best_w = 0
best_h = 0
target_ratio = Fraction(width, height)
for i in range(1, 256):
for j in range(1, 256):
if Fraction(8 * i, 8 * j) > target_ratio * 0.98 and Fraction(8 * i, 8 * j) < target_ratio and 8 * i * 8 * j <= res * res:
candidates = [
(ceil(8 * i / 64) * 64, ceil(8 * j / 64) * 64),
(8 * i // 64 * 64, ceil(8 * j / 64) * 64),
(ceil(8 * i / 64) * 64, 8 * j // 64 * 64),
(8 * i // 64 * 64, 8 * j // 64 * 64),
]
for w, h in candidates:
if w * h > res * res:
continue
if w * h > best_w * best_h:
best_w, best_h = w, h
return best_w, best_h
def find_tile_dimensions(width: int, height: int, multiplier: float, res: int) -> (int, int):
new_width = width * multiplier // 8 * 8
new_height = height * multiplier // 8 * 8
width_multiples = round(new_width / res, 0)
height_multiples = round(new_height / res, 0)
tile_width = new_width / width_multiples // 1
tile_height = new_height / height_multiples // 1
return tile_width, tile_height
def find_tile_dimensions(width: int, height: int, multiplier: float, res: int) -> (int, int):
new_width = int(width * multiplier) // 8 * 8
new_height = int(height * multiplier) // 8 * 8
width_multiples = max(1, new_width // res)
height_multiples = max(1, new_height // res)
tile_width = new_width // width_multiples
tile_height = new_height // height_multiples
return int(tile_width), int(tile_height)
def read_ratios():
p = os.path.dirname(os.path.realpath(__file__))
file_path = os.path.join(p, 'ratios.json')
with open(file_path, 'r') as file:
data = json.load(file)
ratio_sizes = list(data['ratios'].keys())
ratio_dict = data['ratios']
# user_styles.json
user_styles_path = os.path.join(folder_paths.base_path, 'user_ratios.json')
# check if file exists
if os.path.isfile(user_styles_path):
# read json and update ratio_dict
with open(user_styles_path, 'r') as file:
user_data = json.load(file)
for ratio in user_data['ratios']:
ratio_dict[ratio] = user_data['ratios'][ratio]
ratio_sizes.append(ratio)
return ratio_sizes, ratio_dict
def read_ratio_presets():
p = os.path.dirname(os.path.realpath(__file__))
file_path = os.path.join(p, 'ratio_presets.json')
with open(file_path, 'r') as file:
data = json.load(file)
ratio_presets = list(data['ratio_presets'].keys())
ratio_preset_dict = data['ratio_presets']
# user_ratio_presets.json
user_ratio_presets_path = os.path.join(folder_paths.base_path, 'user_ratio_presets.json')
# check if file exists
if os.path.isfile(user_ratio_presets_path):
# read json and update ratio_dict
with open(user_ratio_presets_path, 'r') as file:
user_data = json.load(file)
for ratio in user_data['ratio_presets']:
ratio_preset_dict[ratio] = user_data['ratio_presets'][ratio]
ratio_presets.append(ratio)
# remove duplicate presets
ratio_presets = sorted(list(set(ratio_presets)))
return ratio_presets, ratio_preset_dict
def read_styles():
p = os.path.dirname(os.path.realpath(__file__))
file_path = os.path.join(p, 'styles.json')
with open(file_path, 'r') as file:
data = json.load(file)
# each style has a positive and negative key
""" start of json styles.json looks like this:
{
"styles": {
"none": {
"positive": "",
"negative": ""
},
"3d-model": {
"positive": "3d model, polygons, mesh, textures, lighting, rendering",
"negative": "2D representation, lack of depth and volume, no realistic rendering"
},
"""
styles = list(data['styles'].keys())
pos_style = {}
neg_style = {}
for style in styles:
pos_style[style] = data['styles'][style]['positive']
neg_style[style] = data['styles'][style]['negative']
# user_styles.json
user_styles_path = os.path.join(folder_paths.base_path, 'user_styles.json')
# check if file exists
if os.path.isfile(user_styles_path):
# read json and update pos_style and neg_style
with open(user_styles_path, 'r') as file:
user_data = json.load(file)
for style in user_data['styles']:
pos_style[style] = user_data['styles'][style]['positive']
neg_style[style] = user_data['styles'][style]['negative']
styles.append(style)
return styles, pos_style, neg_style
#def read_ratio_presets():
# file_path = os.path.join(folder_paths.base_path, 'user_ratio_presets.json')
# if os.path.isfile(file_path):
# with open(file_path, 'r') as file:
# data = json.load(file)
# ratio_presets = list(data['ratio_presets'].keys())
# return ratio_presets, data['ratio_presets']
# else:
# return ['none'], {'none': None}
def find_and_replace_wildcards(prompt, offset_seed, debug=False):
# wildcards use the __file_name__ syntax with optional |word_to_find
wildcard_path = os.path.join(folder_paths.base_path, 'wildcards')
wildcard_regex = r'((\d+)\$\$)?__(!|\+|-|\*)?((?:[^|_]+_)*[^|_]+)((?:\|[^|]+)*)__'
# r'(\[(\d+)\$\$)?__((?:[^|_]+_)*[^|_]+)((?:\|[^|]+)*)__\]?'
match_strings = []
random.seed(offset_seed)
offset = offset_seed
new_prompt = ''
last_end = 0
for m in re.finditer(wildcard_regex, prompt):
full_match, lines_count_str, offset_type, actual_match, words_to_find_str = m.groups()
# Append everything up to this match
new_prompt += prompt[last_end:m.start()]
# lock indicator
lock_indicator = offset_type == '!'
# increment indicator
increment_indicator = offset_type == '+'
# decrement indicator
decrement_indicator = offset_type == '-'
# random indicator
random_indicator = offset_type == '*'
#for full_match, lines_count_str, actual_match, words_to_find_str in re.findall(wildcard_regex, prompt):
words_to_find = words_to_find_str.split('|')[1:] if words_to_find_str else None
if debug:
print(f'Wildcard match: {actual_match}')
print(f'Wildcard words to find: {words_to_find}')
lines_to_insert = int(lines_count_str) if lines_count_str else 1
if debug:
print(f'Wildcard lines to insert: {lines_to_insert}')
match_parts = actual_match.split('/')
if len(match_parts) > 1:
wildcard_dir = os.path.join(*match_parts[:-1])
wildcard_file = match_parts[-1]
else:
wildcard_dir = ''
wildcard_file = match_parts[0]
search_path = os.path.join(wildcard_path, wildcard_dir)
file_path = os.path.join(search_path, wildcard_file + '.txt')
if not os.path.isfile(file_path) and wildcard_dir == '':
file_path = os.path.join(wildcard_path, wildcard_file + '.txt')
if os.path.isfile(file_path):
store_offset = None
if actual_match in match_strings:
store_offset = offset
if lock_indicator:
offset = offset_seed
elif random_indicator:
offset = random.randint(0, 1000000)
elif increment_indicator:
offset = offset_seed + 1
elif decrement_indicator:
offset = offset_seed - 1
else:
offset = random.randint(0, 1000000)
selected_lines = []
with open(file_path, 'r', encoding='utf-8') as file:
file_lines = file.readlines()
num_lines = len(file_lines)
if words_to_find:
for i in range(lines_to_insert):
start_idx = (offset + i) % num_lines
for j in range(num_lines):
line_number = (start_idx + j) % num_lines
line = file_lines[line_number].strip()
if any(re.search(r'\b' + re.escape(word) + r'\b', line, re.IGNORECASE) for word in words_to_find):
selected_lines.append(line)
break
else:
start_idx = offset % num_lines
for i in range(lines_to_insert):
line_number = (start_idx + i) % num_lines
line = file_lines[line_number].strip()
selected_lines.append(line)
if len(selected_lines) == 1:
replacement_text = selected_lines[0]
else:
replacement_text = ','.join(selected_lines)
new_prompt += replacement_text
match_strings.append(actual_match)
if store_offset is not None:
offset = store_offset
store_offset = None
offset += lines_to_insert
if debug:
print('Wildcard prompt selected: ' + replacement_text)
else:
if debug:
print(f'Wildcard file {wildcard_file}.txt not found in {search_path}')
last_end = m.end()
new_prompt += prompt[last_end:]
return new_prompt
def process_wildcard_syntax(text, seed):
# wildcard sytax is {like|this}
# select a random word from the | separated list
random.seed(seed)
wc_re = re.compile(r'{([^{}]*)}')
def repl(m):
parts = m.group(1).split('|')
return random.choice(parts)
while wc_re.search(text):
text = wc_re.sub(repl, text)
return text
def search_and_replace(text, extra_pnginfo, prompt):
if extra_pnginfo is None or prompt is None:
return text
# if %date: in text, then replace with date
#print(text)
if '%date:' in text:
for match in re.finditer(r'%date:(.*?)%', text):
date_match = match.group(1)
cursor = 0
date_pattern = ''
now = datetime.datetime.now()
pattern_map = {
'yyyy': now.strftime('%Y'),
'yy': now.strftime('%y'),
'MM': now.strftime('%m'),
'M': now.strftime('%m').lstrip('0'),
'dd': now.strftime('%d'),
'd': now.strftime('%d').lstrip('0'),
'hh': now.strftime('%H'),
'h': now.strftime('%H').lstrip('0'),
'mm': now.strftime('%M'),
'm': now.strftime('%M').lstrip('0'),
'ss': now.strftime('%S'),
's': now.strftime('%S').lstrip('0')
}
sorted_keys = sorted(pattern_map.keys(), key=len, reverse=True)
while cursor < len(date_match):
replaced = False
for key in sorted_keys:
if date_match.startswith(key, cursor):
date_pattern += pattern_map[key]
cursor += len(key)
replaced = True
break
if not replaced:
date_pattern += date_match[cursor]
cursor += 1
text = text.replace('%date:' + match.group(1) + '%', date_pattern)
# Parse JSON if they are strings
if isinstance(extra_pnginfo, str):
extra_pnginfo = json.loads(extra_pnginfo)
if isinstance(prompt, str):
prompt = json.loads(prompt)
# Map from "Node name for S&R" to id in the workflow
node_to_id_map = {}
try:
for node in extra_pnginfo['workflow']['nodes']:
node_name = node['properties'].get('Node name for S&R')
node_id = node['id']
node_to_id_map[node_name] = node_id
except:
return text
# Find all patterns in the text that need to be replaced
patterns = re.findall(r"%([^%]+)%", text)
for pattern in patterns:
# Split the pattern to get the node name and widget name
node_name, widget_name = pattern.split('.')
# Find the id for this node name
node_id = node_to_id_map.get(node_name)
if node_id is None:
print(f"No node with name {node_name} found.")
# check if user entered id instead of node name
if node_name in node_to_id_map.values():
node_id = node_name
else:
continue
# Find the value of the specified widget in prompt JSON
prompt_node = prompt.get(str(node_id))
if prompt_node is None:
print(f"No prompt data for node with id {node_id}.")
continue
widget_value = prompt_node['inputs'].get(widget_name)
if widget_value is None:
print(f"No widget with name {widget_name} found for node {node_name}.")
continue
# Replace the pattern in the text
text = text.replace(f"%{pattern}%", str(widget_value))
return text
def strip_all_syntax(text):
# replace any <lora:lora_name> with nothing
text = re.sub(r'<lora:(.*?)>', '', text)
# replace any <lora:lora_name:multiplier> with nothing
text = re.sub(r'<lora:(.*?):(.*?)>', '', text)
# replace any <style:style_name> with nothing
text = re.sub(r'<style:(.*?)>', '', text)
# replace any __wildcard_name__ with nothing
text = re.sub(r'__(.*?)__', '', text)
# replace any __wildcard_name|word__ with nothing
text = re.sub(r'__(.*?)\|(.*?)__', '', text)
# replace any [2$__wildcard__] with nothing
text = re.sub(r'\[\d+\$(.*?)\]', '', text)
# replace any [2$__wildcard|word__] with nothing
text = re.sub(r'\[\d+\$(.*?)\|(.*?)\]', '', text)
# replace double spaces with single spaces
text = text.replace(' ', ' ')
# replace double commas with single commas
text = text.replace(',,', ',')
# replace ` , ` with `, `
text = text.replace(' , ', ', ')
# replace leading and trailing spaces and commas
text = text.strip(' ,')
# clean up any < > [ ] or _ that are left over
text = text.replace('<', '').replace('>', '').replace('[', '').replace(']', '').replace('_', '')
return text
def add_metadata_to_dict(info_dict, **kwargs):
for key, value in kwargs.items():
if isinstance(value, (int, float, str)):
if key not in info_dict:
info_dict[key] = [value]
else:
info_dict[key].append(value)
def load_lora(model, clip, lora_filename, lora_multiplier, lora_clip_multiplier):
try:
#full_lora_path = folder_paths.get_full_path("loras", lora_filename)
ll = LoraLoader()
model, clip_lora = ll.load_lora(model, clip, lora_filename, lora_multiplier, lora_clip_multiplier)
print('Loading LoRA: ' + lora_filename + ' with multiplier: ' + str(lora_multiplier))
return model, clip_lora
except:
print('Warning: LoRA file ' + lora_filename + ' not found or file path is invalid. Skipping this LoRA.')
return model, clip
def extract_and_load_loras(text, model, clip):
# load loras detected in the prompt text
# The text for adding LoRA to the prompt, <lora:filename:multiplier>, is only used to enable LoRA, and is erased from prompt afterwards
# The multiplier is optional, and defaults to 1.0
# We update the model and clip, and return the new model and clip with the lora prompt stripped from the text
# If multiple lora prompts are detected we chain them together like: original clip > clip_with_lora1 > clip_with_lora2 > clip_with_lora3 > etc
lora_re = r'<lora:(.*?)(?::(.*?))?>'
# find all lora prompts
lora_prompts = re.findall(lora_re, text)
stripped_text = text
# if we found any lora prompts
if len(lora_prompts) > 0:
# loop through each lora prompt
for lora_prompt in lora_prompts:
# get the lora filename
lora_filename = lora_prompt[0]
# check for file extension in filename
if '.safetensors' not in lora_filename:
lora_filename += '.safetensors'
# get the lora multiplier
try:
lora_multiplier = float(lora_prompt[1]) if lora_prompt[1] != '' else 1.0
except:
lora_multiplier = 1.0
# apply the lora to the clip using the LoraLoader.load_lora function
# apply the lora to the clip
model, clip = load_lora(model, clip, lora_filename, lora_multiplier, lora_multiplier)
# strip the lora prompts from the text
stripped_text = re.sub(lora_re, '', stripped_text)
return model, clip, stripped_text
def process_random_syntax(text, seed):
#print('checking for random syntax')
random.seed(seed)
random_re = r'<random:(-?\d*\.?\d+):(-?\d*\.?\d+)>'
matches = re.finditer(random_re, text)
# Create a list to hold the new segments of text
new_text_list = []
last_end = 0
# Iterate through matches
for match in matches:
lower_bound, upper_bound = map(float, match.groups())
random_value = random.uniform(lower_bound, upper_bound)
random_value = round(random_value, 4)
# Append text up to the match and the generated number
new_text_list.append(text[last_end:match.start()])
new_text_list.append(str(random_value))
# Update the index of the last match end
last_end = match.end()
# Append remaining text after the last match
new_text_list.append(text[last_end:])
# Combine the list into a single string
new_text = ''.join(new_text_list)
#print(new_text)
return new_text
def read_cluts():
p = os.path.dirname(os.path.realpath(__file__))
halddir = os.path.join(p, 'HaldCLUT')
files = [os.path.join(halddir, f) for f in os.listdir(halddir) if os.path.isfile(os.path.join(halddir, f)) and f.endswith('.png')]
return files
def apply_hald_clut(hald_img, img):
hald_w, hald_h = hald_img.size
clut_size = int(round(pow(hald_w, 1/3)))
scale = (clut_size * clut_size - 1) / 255
img = np.asarray(img)
# Convert the HaldCLUT image to numpy array
hald_img_array = np.asarray(hald_img)
# If the HaldCLUT image is monochrome, duplicate its single channel to three
if len(hald_img_array.shape) == 2:
hald_img_array = np.stack([hald_img_array]*3, axis=-1)
hald_img_array = hald_img_array.reshape(clut_size ** 6, 3)
clut_r = np.rint(img[:, :, 0] * scale).astype(int)
clut_g = np.rint(img[:, :, 1] * scale).astype(int)
clut_b = np.rint(img[:, :, 2] * scale).astype(int)
filtered_image = np.zeros((img.shape))
filtered_image[:, :] = hald_img_array[clut_r + clut_size ** 2 * clut_g + clut_size ** 4 * clut_b]
filtered_image = Image.fromarray(filtered_image.astype('uint8'), 'RGB')
return filtered_image
def gamma_correction_pil(image, gamma):
# Convert PIL Image to NumPy array
img_array = np.array(image)
# Normalization [0,255] -> [0,1]
img_array = img_array / 255.0
# Apply gamma correction
img_corrected = np.power(img_array, gamma)
# Convert corrected image back to original scale [0,1] -> [0,255]
img_corrected = np.uint8(img_corrected * 255)
# Convert NumPy array back to PIL Image
corrected_image = Image.fromarray(img_corrected)
return corrected_image
# Tensor to PIL
def tensor2pil(image):
return Image.fromarray(np.clip(255. * image.cpu().numpy().squeeze(), 0, 255).astype(np.uint8))
# PIL to Tensor
def pil2tensor(image):
return torch.from_numpy(np.array(image).astype(np.float32) / 255.0).unsqueeze(0)
def tensor2numpy(image):
# Convert tensor to numpy array and transpose dimensions from (C, H, W) to (H, W, C)
return (255.0 * image.cpu().numpy().squeeze().transpose(1, 2, 0)).astype(np.uint8)
# create a wrapper function that can apply a function to multiple images in a batch
# while passing all other arguments to the function
def apply_to_batch(func):
def wrapper(self, image, *args, **kwargs):
images = []
for img in image:
images.append(func(self, img, *args, **kwargs))
batch_tensor = torch.cat(images, dim=0)
return (batch_tensor, )
return wrapper
class WildcardProcessor:
@classmethod
def INPUT_TYPES(s):
return {"required": {"prompt": ("STRING", {"multiline": True, "placeholder": "Prompt Text"}),
"seed": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff})},
"hidden": {"prompt_": "PROMPT", "extra_pnginfo": "EXTRA_PNGINFO"},}
RETURN_TYPES = ('STRING',)
FUNCTION = 'process'
CATEGORY = 'Mikey/Text'
def process(self, prompt, seed, prompt_=None, extra_pnginfo=None):
if prompt_ is None:
prompt_ = {}
if extra_pnginfo is None:
extra_pnginfo = {}
prompt = search_and_replace(prompt, extra_pnginfo, prompt_)
prompt = process_wildcard_syntax(prompt, seed)
prompt = process_random_syntax(prompt, seed)
new_prompt = find_and_replace_wildcards(prompt, seed)
# loop to pick up wildcards that are in wildcard files
if new_prompt != prompt:
for i in range(10):
prompt = new_prompt
prompt = search_and_replace(prompt, extra_pnginfo, prompt_)
prompt = process_wildcard_syntax(prompt, seed)
prompt = process_random_syntax(prompt, seed)
new_prompt = find_and_replace_wildcards(prompt, seed)
if new_prompt == prompt:
break
return (new_prompt, )
class HaldCLUT:
@classmethod
def INPUT_TYPES(s):
s.haldclut_files = read_cluts()
s.file_names = [os.path.basename(f) for f in s.haldclut_files]
return {"required": {"image": ("IMAGE",),
"hald_clut": (s.file_names,),
"gamma_correction": (['True','False'],)}}
RETURN_TYPES = ('IMAGE',)
RETURN_NAMES = ('image',)
FUNCTION = 'apply_haldclut'
CATEGORY = 'Mikey/Image'
OUTPUT_NODE = True
@apply_to_batch
def apply_haldclut(self, image, hald_clut, gamma_correction):
hald_img = Image.open(self.haldclut_files[self.file_names.index(hald_clut)])
img = tensor2pil(image)
if gamma_correction == 'True':
corrected_img = gamma_correction_pil(img, 1.0/2.2)
else:
corrected_img = img
filtered_image = apply_hald_clut(hald_img, corrected_img).convert("RGB")
#return (pil2tensor(filtered_image), )
return pil2tensor(filtered_image)
@classmethod
def IS_CHANGED(self, hald_clut):
return (np.nan,)
class EmptyLatentRatioSelector:
@classmethod
def INPUT_TYPES(s):
s.ratio_sizes, s.ratio_dict = read_ratios()
return {'required': {'ratio_selected': (s.ratio_sizes,),
"batch_size": ("INT", {"default": 1, "min": 1, "max": 64})}}
RETURN_TYPES = ('LATENT',)
FUNCTION = 'generate'
CATEGORY = 'Mikey/Latent'
def generate(self, ratio_selected, batch_size=1):
width = self.ratio_dict[ratio_selected]["width"]
height = self.ratio_dict[ratio_selected]["height"]
latent = torch.zeros([batch_size, 4, height // 8, width // 8])
return ({"samples":latent}, )
class EmptyLatentRatioCustom:
@classmethod
def INPUT_TYPES(s):
s.ratio_sizes, s.ratio_dict = read_ratios()
return {"required": { "width": ("INT", {"default": 1024, "min": 1, "max": 8192, "step": 1}),
"height": ("INT", {"default": 1024, "min": 1, "max": 8192, "step": 1}),
"batch_size": ("INT", {"default": 1, "min": 1, "max": 64})}}
RETURN_TYPES = ('LATENT',)
FUNCTION = 'generate'
CATEGORY = 'Mikey/Latent'
def generate(self, width, height, batch_size=1):
# solver
if width == 1 and height == 1 or width == height:
w, h = 1024, 1024
if f'{width}:{height}' in self.ratio_dict:
w, h = self.ratio_dict[f'{width}:{height}']
else:
w, h = find_latent_size(width, height)
latent = torch.zeros([batch_size, 4, h // 8, w // 8])
return ({"samples":latent}, )
class RatioAdvanced:
@classmethod
def INPUT_TYPES(s):
s.ratio_sizes, s.ratio_dict = read_ratios()
default_ratio = s.ratio_sizes[0]
# prepend 'custom' to ratio_sizes
s.ratio_sizes.insert(0, 'custom')
s.ratio_presets, s.ratio_config = read_ratio_presets()
if 'none' not in s.ratio_presets:
s.ratio_presets.append('none')
return {"required": { "preset": (s.ratio_presets, {"default": "none"}),
"swap_axis": (['true','false'], {"default": 'false'}),
"select_latent_ratio": (s.ratio_sizes, {'default': default_ratio}),
"custom_latent_w": ("INT", {"default": 0, "min": 0, "max": 8192, "step": 1}),
"custom_latent_h": ("INT", {"default": 0, "min": 0, "max": 8192, "step": 1}),
"select_cte_ratio": (s.ratio_sizes, {'default': default_ratio}),
"cte_w": ("INT", {"default": 0, "min": 0, "max": 8192, "step": 1}),
"cte_h": ("INT", {"default": 0, "min": 0, "max": 8192, "step": 1}),
"cte_mult": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 100.0, "step": 0.01}),
"cte_res": ("INT", {"default": 0, "min": 0, "max": 8192, "step": 1}),
"cte_fit_size": ("INT", {"default": 0, "min": 0, "max": 8192, "step": 1}),
"select_target_ratio": (s.ratio_sizes, {'default': default_ratio}),
"target_w": ("INT", {"default": 0, "min": 0, "max": 8192, "step": 1}),
"target_h": ("INT", {"default": 0, "min": 0, "max": 8192, "step": 1}),
"target_mult": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 100.0, "step": 0.01}),
"target_res": ("INT", {"default": 0, "min": 0, "max": 8192, "step": 1}),
"target_fit_size": ("INT", {"default": 0, "min": 0, "max": 8192, "step": 1}),
"crop_w": ("INT", {"default": 0, "min": 0, "max": 8192, "step": 1}),
"crop_h": ("INT", {"default": 0, "min": 0, "max": 8192, "step": 1}),
"use_preset_seed": (['true','false'], {"default": 'false'}),
"seed": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff}),
},
"hidden": {"unique_id": "UNIQUE_ID", "extra_pnginfo": "EXTRA_PNGINFO", "prompt": "PROMPT"}}
RETURN_TYPES = ('INT', 'INT', # latent
'INT', 'INT', # clip text encode
'INT', 'INT', # target
'INT', 'INT') # crop
RETURN_NAMES = ('latent_w', 'latent_h',
'cte_w', 'cte_h',
'target_w', 'target_h',
'crop_w', 'crop_h')
CATEGORY = 'Mikey/Utils'
FUNCTION = 'calculate'
def mult(self, width, height, mult):
return int(width * mult), int(height * mult)
def fit(self, width, height, fit_size):
if width > height:
return fit_size, int(height * fit_size / width)
else:
return int(width * fit_size / height), fit_size
def res(self, width, height, res):
return find_latent_size(width, height, res)
def calculate(self, preset, swap_axis, select_latent_ratio, custom_latent_w, custom_latent_h,
select_cte_ratio, cte_w, cte_h, cte_mult, cte_res, cte_fit_size,
select_target_ratio, target_w, target_h, target_mult, target_res, target_fit_size,
crop_w, crop_h, use_preset_seed, seed, unique_id=None, extra_pnginfo=None, prompt=None):
# check if use_preset_seed is true
if use_preset_seed == 'true' and len(self.ratio_presets) > 1:
# seed is a randomly generated number that can be much larger than the number of presets
# we use the seed to select a preset
offset = seed % len(self.ratio_presets - 1)
presets = [p for p in self.ratio_presets if p != 'none']
preset = presets[offset]
# check if ratio preset is selected
if preset != 'none':
latent_width = self.ratio_config[preset]['custom_latent_w']
latent_height = self.ratio_config[preset]['custom_latent_h']
cte_w = self.ratio_config[preset]['cte_w']
cte_h = self.ratio_config[preset]['cte_h']
target_w = self.ratio_config[preset]['target_w']
target_h = self.ratio_config[preset]['target_h']
crop_w = self.ratio_config[preset]['crop_w']
crop_h = self.ratio_config[preset]['crop_h']
if swap_axis == 'true':
latent_width, latent_height = latent_height, latent_width
cte_w, cte_h = cte_h, cte_w
target_w, target_h = target_h, target_w
crop_w, crop_h = crop_h, crop_w
"""
example user_ratio_presets.json
{
"ratio_presets": {
"all_1024": {
"custom_latent_w": 1024,
"custom_latent_h": 1024,
"cte_w": 1024,
"cte_h": 1024,
"target_w": 1024,
"target_h": 1024,
"crop_w": 0,
"crop_h": 0
},
}
}
"""
return (latent_width, latent_height,
cte_w, cte_h,
target_w, target_h,
crop_w, crop_h)
# if no preset is selected, check if custom latent ratio is selected
if select_latent_ratio != 'custom':
latent_width = self.ratio_dict[select_latent_ratio]["width"]
latent_height = self.ratio_dict[select_latent_ratio]["height"]
else:
latent_width = custom_latent_w
latent_height = custom_latent_h
# check if cte ratio is selected
if select_cte_ratio != 'custom':
cte_w = self.ratio_dict[select_cte_ratio]["width"]
cte_h = self.ratio_dict[select_cte_ratio]["height"]
else:
cte_w = cte_w
cte_h = cte_h
# check if cte_mult not 0
if cte_mult != 0.0:
cte_w, cte_h = self.mult(cte_w, cte_h, cte_mult)
# check if cte_res not 0
if cte_res != 0:
cte_w, cte_h = self.res(cte_w, cte_h, cte_res)
# check if cte_fit_size not 0
if cte_fit_size != 0:
cte_w, cte_h = self.fit(cte_w, cte_h, cte_fit_size)
# check if target ratio is selected
if select_target_ratio != 'custom':
target_w = self.ratio_dict[select_target_ratio]["width"]
target_h = self.ratio_dict[select_target_ratio]["height"]
else:
target_w = target_w
target_h = target_h
# check if target_mult not 0
if target_mult != 0.0:
target_w, target_h = self.mult(target_w, target_h, target_mult)
# check if target_res not 0
if target_res != 0:
target_w, target_h = self.res(target_w, target_h, target_res)
# check if target_fit_size not 0
if target_fit_size != 0:
target_w, target_h = self.fit(target_w, target_h, target_fit_size)
#prompt.get(str(unique_id))['inputs']['output_latent_w'] = str(latent_width)
#prompt.get(str(unique_id))['inputs']['output_latent_h'] = str(latent_height)
#prompt.get(str(unique_id))['inputs']['output_cte_w'] = str(cte_w)
#prompt.get(str(unique_id))['inputs']['output_cte_h'] = str(cte_h)
#prompt.get(str(unique_id))['inputs']['output_target_w'] = str(target_w)
#prompt.get(str(unique_id))['inputs']['output_target_h'] = str(target_h)
#prompt.get(str(unique_id))['inputs']['output_crop_w'] = str(crop_w)
#prompt.get(str(unique_id))['inputs']['output_crop_h'] = str(crop_h)
return (latent_width, latent_height,
cte_w, cte_h,
target_w, target_h,
crop_w, crop_h)
class PresetRatioSelector:
@classmethod
def INPUT_TYPES(s):
s.ratio_presets, s.ratio_config = read_ratio_presets()
return {"required": { "select_preset": (s.ratio_presets, {"default": "none"}),
"swap_axis": (['true','false'], {"default": 'false'}),
"use_preset_seed": (['true','false'], {"default": 'false'}),
"seed": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff})},
"hidden": {"unique_id": "UNIQUE_ID", "extra_pnginfo": "EXTRA_PNGINFO", "prompt": "PROMPT"}}
RETURN_TYPES = ('INT', 'INT', # latent
'INT', 'INT', # clip text encode
'INT', 'INT', # target
'INT', 'INT') # crop
RETURN_NAMES = ('latent_w', 'latent_h',
'cte_w', 'cte_h',
'target_w', 'target_h',
'crop_w', 'crop_h')
CATEGORY = 'Mikey/Utils'
FUNCTION = 'calculate'
def calculate(self, select_preset, swap_axis, use_preset_seed, seed, unique_id=None, extra_pnginfo=None, prompt=None):
# check if use_preset_seed is true
if use_preset_seed == 'true' and len(self.ratio_presets) > 0:
# seed is a randomly generated number that can be much larger than the number of presets
# we use the seed to select a preset
len_presets = len(self.ratio_presets)
offset = seed % (len_presets - 1)
presets = [p for p in self.ratio_presets if p != 'none']
select_preset = presets[offset]
latent_width = self.ratio_config[select_preset]['custom_latent_w']
latent_height = self.ratio_config[select_preset]['custom_latent_h']
cte_w = self.ratio_config[select_preset]['cte_w']
cte_h = self.ratio_config[select_preset]['cte_h']
target_w = self.ratio_config[select_preset]['target_w']
target_h = self.ratio_config[select_preset]['target_h']
crop_w = self.ratio_config[select_preset]['crop_w']
crop_h = self.ratio_config[select_preset]['crop_h']
if swap_axis == 'true':
latent_width, latent_height = latent_height, latent_width
cte_w, cte_h = cte_h, cte_w
target_w, target_h = target_h, target_w
crop_w, crop_h = crop_h, crop_w
#prompt.get(str(unique_id))['inputs']['output_latent_w'] = str(latent_width)
#prompt.get(str(unique_id))['inputs']['output_latent_h'] = str(latent_height)
#prompt.get(str(unique_id))['inputs']['output_cte_w'] = str(cte_w)
#prompt.get(str(unique_id))['inputs']['output_cte_h'] = str(cte_h)
#prompt.get(str(unique_id))['inputs']['output_target_w'] = str(target_w)
#prompt.get(str(unique_id))['inputs']['output_target_h'] = str(target_h)
#prompt.get(str(unique_id))['inputs']['output_crop_w'] = str(crop_w)
#prompt.get(str(unique_id))['inputs']['output_crop_h'] = str(crop_h)
return (latent_width, latent_height,
cte_w, cte_h,
target_w, target_h,
crop_w, crop_h)
class INTtoSTRING:
@classmethod
def INPUT_TYPES(s):
return {"required": {"int_": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff}),
"use_commas": (['true','false'], {"default": 'false'})}}
RETURN_TYPES = ('STRING',)
FUNCTION = 'convert'
CATEGORY = 'Mikey/Utils'
def convert(self, int_, use_commas):
if use_commas == 'true':
return (f'{int_:,}', )
else:
return (f'{int_}', )
class FLOATtoSTRING:
@classmethod
def INPUT_TYPES(s):
return {"required": {"float_": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1000000.0}),
"use_commas": (['true','false'], {"default": 'false'})}}
RETURN_TYPES = ('STRING',)
FUNCTION = 'convert'
CATEGORY = 'Mikey/Utils'
def convert(self, float_, use_commas):
if use_commas == 'true':
return (f'{float_:,}', )
else:
return (f'{float_}', )
class RangeFloat:
# using the seed value as the step in a range
# generate a list of numbers from start to end with a step value
# then select the number at the offset value
@classmethod
def INPUT_TYPES(s):
return {"required": {"start": ("FLOAT", {"default": 0, "min": 0, "step": 0.0001, "max": 0xffffffffffffffff}),
"end": ("FLOAT", {"default": 0, "min": 0, "step": 0.0001, "max": 0xffffffffffffffff}),
"step": ("FLOAT", {"default": 0, "min": 0, "step": 0.0001, "max": 0xffffffffffffffff}),
"seed": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff})}}
RETURN_TYPES = ('FLOAT','STRING',)
FUNCTION = 'generate'
CATEGORY = 'Mikey/Utils'
def generate(self, start, end, step, seed):
range_ = np.arange(start, end, step)
list_of_numbers = list(range_)
# offset
offset = seed % len(list_of_numbers)
return (list_of_numbers[offset], f'{list_of_numbers[offset]}',)
class RangeInteger:
# using the seed value as the step in a range
# generate a list of numbers from start to end with a step value
# then select the number at the offset value
@classmethod
def INPUT_TYPES(s):
return {"required": {"start": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff}),
"end": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff}),
"step": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff}),
"seed": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff})}}
RETURN_TYPES = ('INT','STRING',)
FUNCTION = 'generate'
CATEGORY = 'Mikey/Utils'
def generate(self, start, end, step, seed):
range_ = np.arange(start, end, step)
list_of_numbers = list(range_)
# offset
offset = seed % len(list_of_numbers)
return (list_of_numbers[offset], f'{list_of_numbers[offset]}',)
class ResizeImageSDXL:
crop_methods = ["disabled", "center"]
upscale_methods = ["nearest-exact", "bilinear", "area", "bicubic"]
@classmethod
def INPUT_TYPES(s):
return {"required": { "image": ("IMAGE",), "upscale_method": (s.upscale_methods,),
"crop": (s.crop_methods,)}}
RETURN_TYPES = ('IMAGE',)
FUNCTION = 'resize'
CATEGORY = 'Mikey/Image'
def upscale(self, image, upscale_method, width, height, crop):