-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path__init__.py
More file actions
3176 lines (2736 loc) · 118 KB
/
__init__.py
File metadata and controls
3176 lines (2736 loc) · 118 KB
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 sys
import os
import json
import re
import random
from PIL import Image, ImageOps, ImageDraw, ImageFilter, ImageFont, ImageSequence
from typing import Union, List, Tuple
import torch
import numpy as np
import scipy
import hashlib
import pilgram
import cv2
import logging
import math
from tqdm import tqdm
from typing_extensions import override
import comfy
from comfy_extras.nodes_logic import SwitchNode, SoftSwitchNode
from comfy_api.latest import ComfyExtension, io
from comfy import model_management
import nodes
import node_helpers
import folder_paths
from nodes import MAX_RESOLUTION
from unifiedefficientloader import UnifiedSafetensorsLoader
from . import system_messages
from . import instruct_prompts
from . import bonus_prompts
from . import edit_target_prompts
from . import edit_op_prompts
from . import camera_shot_prompts
RAM_THRESHOLD = 32 * 1024 * 1024 * 1024 # 16 GB
RAM_FREE_THRESHOLD = 8 * 1024 * 1024 * 1024 # 8 GB
try:
from unifiedefficientloader import UnifiedSafetensorsLoader
_unifiedefficientloader_available = True
except ImportError:
_unifiedefficientloader_available = False
def model_detection_error_hint(path, state_dict):
filename = os.path.basename(path)
if 'lora' in filename.lower():
return "\nHINT: This seems to be a Lora file and Lora files should be put in the lora folder and loaded with a lora loader node.."
return ""
def load_diffusion_model(unet_path, model_options={}, disable_dynamic=False):
total_ram = comfy.model_management.get_total_memory(comfy.model_management.torch.device("cpu"))
free_ram = comfy.model_management.get_free_memory(comfy.model_management.torch.device("cpu"))
if total_ram < RAM_THRESHOLD or free_ram < RAM_FREE_THRESHOLD or not _unifiedefficientloader_available:
sd, metadata = comfy.utils.load_torch_file(unet_path, return_metadata=True)
logging.warning("Total and free system RAM is low, falling back to ComfyUI default model loading")
model = comfy.sd.load_diffusion_model_state_dict(sd, model_options=model_options, metadata=metadata, disable_dynamic=disable_dynamic)
if model is None:
logging.error("ERROR UNSUPPORTED DIFFUSION MODEL {}".format(unet_path))
raise RuntimeError("ERROR: Could not detect model type of: {}\n{}".format(unet_path, model_detection_error_hint(unet_path, sd)))
model.cached_patcher_init = (load_diffusion_model, (unet_path, model_options))
else:
with UnifiedSafetensorsLoader(unet_path, low_memory=True) as loader:
metadata = loader._read_header()
sd = loader.load_all()
model = comfy.sd.load_diffusion_model_state_dict(sd, model_options=model_options, metadata=metadata, disable_dynamic=disable_dynamic)
if model is None:
logging.error("ERROR UNSUPPORTED DIFFUSION MODEL {}".format(unet_path))
raise RuntimeError("ERROR: Could not detect model type of: {}\n{}".format(unet_path, model_detection_error_hint(unet_path, sd)))
model.cached_patcher_init = (load_diffusion_model, (unet_path, model_options))
return model
def round_to_nearest(n, m):
return int((n + (m / 2)) // m) * m
# Tensor to PIL
def simpletensor2pil(image):
return Image.fromarray(
np.clip(255.0 * image.cpu().numpy().squeeze(), 0, 255).astype(np.uint8)
)
# PIL to Tensor
def simplepil2tensor(image):
return torch.from_numpy(np.array(image).astype(np.float32) / 255.0).unsqueeze(0)
def pil2tensor(image: Union[Image.Image, List[Image.Image]]) -> torch.Tensor:
if isinstance(image, list):
return torch.cat([pil2tensor(img) for img in image], dim=0)
return torch.from_numpy(np.array(image).astype(np.float32) / 255.0).unsqueeze(0)
def tensor2pil(image: torch.Tensor) -> List[Image.Image]:
batch_count = image.size(0) if len(image.shape) > 3 else 1
if batch_count > 1:
out = []
for i in range(batch_count):
out.extend(tensor2pil(image[i]))
return out
return [
Image.fromarray(
np.clip(255.0 * image.cpu().numpy().squeeze(), 0, 255).astype(np.uint8)
)
]
def pad_text_with_joiners(text: str) -> str:
"""
Pad each character in the text with word joiner unicode characters.
Parameters:
text (str): Input string to pad
Returns:
str: String with word joiners between each character and at start/end
"""
if not text:
return ""
padding_char = "\u2060"
# Build the pattern using an f-string to correctly embed the unicode char.
pattern = f"([^{padding_char}])(?=[^{padding_char}])"
replacement = r"\1" + padding_char
joined_text = re.sub(pattern, replacement, text)
return padding_char + joined_text + padding_char
def ideographic_joined_crlf(text: str) -> str:
"""
Pad each character in the text with word joiner unicode characters.
Parameters:
text (str): Input string to pad
Returns:
str: String with word joiners between each character and at start/end
"""
if not text:
return ""
ideographic_pad = "\u2060\u3000\u2060"
carriage_linefeed = "\u000D\u000A"
pattern = r"\s"
replacement = f"{ideographic_pad}{carriage_linefeed}{ideographic_pad}"
replaced_text = re.sub(pattern, replacement, text)
return carriage_linefeed + ideographic_pad + replaced_text + ideographic_pad + carriage_linefeed
def ideographic_joined_linepad(text: str) -> str:
"""
Pad each character in the text with word joiner unicode characters.
Parameters:
text (str): Input string to pad
Returns:
str: String with word joiners between each character and at start/end
"""
if not text:
return ""
ideographic_pad = "\u2060\u3000\u2060"
carriage_linefeed = "\u000D\u000A"
pattern = r"^(.*)$"
replacement = ideographic_pad + r"\1" + ideographic_pad + carriage_linefeed
replaced_text = re.sub(pattern, replacement, text)
return carriage_linefeed + ideographic_pad + replaced_text
def ideographic_joined_sentence(text: str) -> str:
"""
Pad each character in the text with word joiner unicode characters.
Parameters:
text (str): Input string to pad
Returns:
str: String with word joiners between each character and at start/end
"""
if not text:
return ""
ideographic_pad = "\u2060\u3000\u2060"
carriage_linefeed = "\u000D\u000A"
pattern = r"([^\w\s,]|\.\s)(\w+.+?\.)"
replacement = r"\1" + carriage_linefeed + ideographic_pad + r"\2" + ideographic_pad + carriage_linefeed
replaced_text = re.sub(pattern, replacement, text)
return replaced_text
def to_bold_fraktur(text: str) -> str:
"""
Convert all ASCII letters in a string to their Unicode mathematical
bold fraktur counterparts.
Parameters:
text (str): Input string to convert
Returns:
str: String with letters converted to bold fraktur
"""
result = []
# Bold fraktur uppercase starts at U+1D56C (𝕬)
# Bold fraktur lowercase starts at U+1D586 (𝖆)
BOLD_FRAKTUR_UPPER_START = 0x1D56C
BOLD_FRAKTUR_LOWER_START = 0x1D586
for char in text:
if "A" <= char <= "Z":
offset = ord(char) - ord("A")
result.append(chr(BOLD_FRAKTUR_UPPER_START + offset))
elif "a" <= char <= "z":
offset = ord(char) - ord("a")
result.append(chr(BOLD_FRAKTUR_LOWER_START + offset))
else:
result.append(char)
return "".join(result)
def frakturpad(text: str) -> str:
"""
Convert ASCII letters to bold fraktur and pad with word joiners.
First converts A-Z and a-z to their bold fraktur equivalents,
then pads the result with word joiner characters (U+2060).
"""
fraktur_text = to_bold_fraktur(text)
return pad_text_with_joiners(fraktur_text)
def from_bold_fraktur(text: str) -> str:
"""
Convert all Unicode mathematical bold fraktur letters in a string
back to their ASCII counterparts.
Parameters:
text (str): Input string containing bold fraktur characters
Returns:
str: String with bold fraktur letters converted back to ASCII
"""
result = []
# Bold fraktur uppercase starts at U+1D56C (𝕬)
# Bold fraktur lowercase starts at U+1D586 (𝖆)
BOLD_FRAKTUR_UPPER_START = 0x1D56C
BOLD_FRAKTUR_UPPER_END = BOLD_FRAKTUR_UPPER_START + 25 # Z
BOLD_FRAKTUR_LOWER_START = 0x1D586
BOLD_FRAKTUR_LOWER_END = BOLD_FRAKTUR_LOWER_START + 25 # z
for char in text:
code_point = ord(char)
if BOLD_FRAKTUR_UPPER_START <= code_point <= BOLD_FRAKTUR_UPPER_END:
offset = code_point - BOLD_FRAKTUR_UPPER_START
result.append(chr(ord("A") + offset))
elif BOLD_FRAKTUR_LOWER_START <= code_point <= BOLD_FRAKTUR_LOWER_END:
offset = code_point - BOLD_FRAKTUR_LOWER_START
result.append(chr(ord("a") + offset))
else:
result.append(char)
return "".join(result)
def remove_joiners(text: str) -> str:
"""
Remove all word joiner unicode characters (U+2060) from the text.
Parameters:
text (str): Input string potentially containing word joiners
Returns:
str: String with all word joiner characters removed
"""
padding_char = "\u2060"
return text.replace(padding_char, "")
def unfrakturpad(text: str) -> str:
"""
Inverse of frakturpad: remove word joiners and convert bold fraktur back to ASCII.
First removes word joiner characters (U+2060), then converts bold fraktur
letters back to their A-Z and a-z equivalents.
"""
text_without_joiners = remove_joiners(text)
return from_bold_fraktur(text_without_joiners)
def _hex_to_rgb(hex_str: str, default=(255, 255, 255)):
hex_str = hex_str.lstrip('#')
try:
if len(hex_str) == 6:
return tuple(int(hex_str[i:i+2], 16) for i in (0, 2, 4))
elif len(hex_str) == 8:
return tuple(int(hex_str[i:i+2], 16) for i in (0, 2, 4, 6))
except ValueError:
pass
return default
def _diag(H: int, W: int) -> float:
return math.sqrt(H * H + W * W)
def _pct_to_px(pct: float, diag: float) -> int:
return max(0, round(abs(pct) * diag / 100.0))
def _blur_kernel_for_diag(diag: float) -> tuple:
k = max(3, int(round(diag / 724.0 * 3)))
if k % 2 == 0: k += 1
return (k, k)
def _rgb_to_lab(rgb: np.ndarray) -> np.ndarray:
lin = np.where(rgb <= 0.04045,
rgb / 12.92,
((rgb + 0.055) / 1.055) ** 2.4)
M = np.array([[0.4124564, 0.3575761, 0.1804375],[0.2126729, 0.7151522, 0.0721750],[0.0193339, 0.1191920, 0.9503041],
], dtype=np.float32)
xyz = lin @ M.T / np.array([0.95047, 1.00000, 1.08883], dtype=np.float32)
def f(t):
return np.where(t > (6/29)**3,
t ** (1/3),
t / (3 * (6/29)**2) + 4/29)
fx, fy, fz = f(xyz[..., 0]), f(xyz[..., 1]), f(xyz[..., 2])
return np.stack([116*fy - 16, 500*(fx - fy), 200*(fy - fz)], axis=-1).astype(np.float32)
def _dis_flow(gray_a: np.ndarray, gray_b: np.ndarray, preset: int) -> np.ndarray:
return cv2.DISOpticalFlow_create(preset).calc(gray_a, gray_b, None)
def _warp(image: np.ndarray, flow: np.ndarray) -> np.ndarray:
H, W = flow.shape[:2]
yy, xx = np.mgrid[0:H, 0:W].astype(np.float32)
map_x = (xx + flow[..., 0]).astype(np.float32)
map_y = (yy + flow[..., 1]).astype(np.float32)
return cv2.remap(image, map_x, map_y, cv2.INTER_LINEAR, cv2.BORDER_REFLECT)
def _occlusion_mask(flow_fwd: np.ndarray, flow_bwd: np.ndarray, threshold: float) -> np.ndarray:
H, W = flow_fwd.shape[:2]
yy, xx = np.mgrid[0:H, 0:W].astype(np.float32)
bwd_x = cv2.remap(flow_bwd[..., 0], xx + flow_fwd[..., 0], yy + flow_fwd[..., 1],
cv2.INTER_LINEAR, cv2.BORDER_CONSTANT, 0)
bwd_y = cv2.remap(flow_bwd[..., 1], xx + flow_fwd[..., 0], yy + flow_fwd[..., 1],
cv2.INTER_LINEAR, cv2.BORDER_CONSTANT, 0)
err = np.sqrt((flow_fwd[..., 0] + bwd_x)**2 + (flow_fwd[..., 1] + bwd_y)**2)
return (err > threshold).astype(np.float32)
def _grow_mask(mask: np.ndarray, grow_px: int) -> np.ndarray:
if grow_px == 0: return mask
radius = abs(grow_px)
k = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (radius * 2 + 1, radius * 2 + 1))
op = cv2.MORPH_DILATE if grow_px > 0 else cv2.MORPH_ERODE
return cv2.morphologyEx(mask.astype(np.uint8), op, k).astype(np.float32)
def _auto_delta_e_threshold(delta_e: np.ndarray) -> float:
p75 = float(np.percentile(delta_e, 75))
p90 = float(np.percentile(delta_e, 90))
spread = p90 - p75
threshold = p75 + max(spread * 0.4, 3.0) if spread > 5.0 else p75 + max(spread * 0.6, 4.0)
return float(np.clip(threshold, 4.0, 60.0))
def _auto_occlusion_threshold(flow_fwd: np.ndarray, flow_bwd: np.ndarray) -> float:
H, W = flow_fwd.shape[:2]
yy, xx = np.mgrid[0:H, 0:W].astype(np.float32)
bwd_x = cv2.remap(flow_bwd[..., 0], xx + flow_fwd[..., 0], yy + flow_fwd[..., 1],
cv2.INTER_LINEAR, cv2.BORDER_CONSTANT, 0)
bwd_y = cv2.remap(flow_bwd[..., 1], xx + flow_fwd[..., 0], yy + flow_fwd[..., 1],
cv2.INTER_LINEAR, cv2.BORDER_CONSTANT, 0)
err = np.sqrt((flow_fwd[..., 0] + bwd_x)**2 + (flow_fwd[..., 1] + bwd_y)**2)
p85 = float(np.percentile(err, 85))
p95 = float(np.percentile(err, 95))
threshold = p95 + max((p95 - p85) * 0.5, 0.5)
return float(np.clip(threshold, 1.0, 15.0))
def _match_histogram(source: np.ndarray, template: np.ndarray) -> np.ndarray:
"""
Adjust the pixel values of a source image such that its histogram
matches that of a target template image.
Both source and template should be 2D numpy arrays (a single channel).
"""
oldshape = source.shape
source_flat = source.ravel()
template_flat = template.ravel()
# get the set of unique pixel values and their corresponding indices and counts
s_values, bin_idx, s_counts = np.unique(source_flat, return_inverse=True, return_counts=True)
t_values, t_counts = np.unique(template_flat, return_counts=True)
# take the cumsum of the counts and normalize by the number of pixels to
# get the empirical cumulative distribution functions for the source and
# template images (maps pixel value --> quantile)
s_quantiles = np.cumsum(s_counts).astype(np.float64)
s_quantiles /= s_quantiles[-1]
t_quantiles = np.cumsum(t_counts).astype(np.float64)
t_quantiles /= t_quantiles[-1]
# interpolate linearly to find the pixel values in the template image
# that correspond most closely to the quantiles in the source image
interp_t_values = np.interp(s_quantiles, t_quantiles, t_values)
return interp_t_values[bin_idx].reshape(oldshape)
def _match_image_properties(
original_tensor: torch.Tensor,
generated_tensor: torch.Tensor,
overall_weight: float,
color_weight: float,
lighting_weight: float,
texture_preservation: float,
mask_tensor: torch.Tensor = None,
) -> torch.Tensor:
batch_size = generated_tensor.size(0)
out_tensors = []
orig_batch = original_tensor.size(0)
mask_batch = mask_tensor.size(0) if mask_tensor is not None else 0
for i in range(batch_size):
orig_i = i if i < orig_batch else 0
orig_np = np.clip(255.0 * original_tensor[orig_i].cpu().numpy().squeeze(), 0, 255).astype(np.uint8)
gen_np = np.clip(255.0 * generated_tensor[i].cpu().numpy().squeeze(), 0, 255).astype(np.uint8)
mask_np = None
if mask_tensor is not None:
mask_i = i if i < mask_batch else 0
# Extract mask, it might be (H, W) or (1, H, W) or (C, H, W)
# Typically comfy masks are (H, W)
m_t = mask_tensor[mask_i].cpu().numpy()
if m_t.ndim > 2:
m_t = m_t.squeeze()
if m_t.shape != gen_np.shape[:2]:
m_t = cv2.resize(m_t, (gen_np.shape[1], gen_np.shape[0]), interpolation=cv2.INTER_LINEAR)
mask_np = m_t[:, :, np.newaxis] # (H, W, 1)
orig_lab = cv2.cvtColor(orig_np, cv2.COLOR_RGB2LAB)
gen_lab = cv2.cvtColor(gen_np, cv2.COLOR_RGB2LAB)
out_lab = np.copy(gen_lab).astype(np.float32)
gen_lab_f = gen_lab.astype(np.float32)
# Detail extraction using Bilateral Filter to preserve edges
# We extract details from the generated image to add them back later
if texture_preservation > 0.0:
# Apply bilateral filter to the L channel to get the "base" lighting without textures
gen_l_base = cv2.bilateralFilter(gen_lab_f[:, :, 0], d=9, sigmaColor=75, sigmaSpace=75)
# The difference is our high-frequency texture/edge detail
gen_l_detail = gen_lab_f[:, :, 0] - gen_l_base
# Apply bilateral filter to the original image L channel as well before matching
orig_l_base = cv2.bilateralFilter(orig_lab[:, :, 0].astype(np.float32), d=9, sigmaColor=75, sigmaSpace=75)
# Match the base (textureless) lighting histograms
l_trans_base = _match_histogram(gen_l_base, orig_l_base)
# Add the generated image's original texture back onto the matched base
l_trans = l_trans_base + (gen_l_detail * texture_preservation)
else:
# Standard matching if texture preservation is 0
l_trans = _match_histogram(gen_lab[:, :, 0], orig_lab[:, :, 0])
l_weight = lighting_weight * overall_weight
out_lab[:, :, 0] = gen_lab_f[:, :, 0] * (1.0 - l_weight) + l_trans * l_weight
# 2. Color (A and B channels)
# If color_weight > 0, we match the A and B histograms
a_trans = _match_histogram(gen_lab[:, :, 1], orig_lab[:, :, 1])
b_trans = _match_histogram(gen_lab[:, :, 2], orig_lab[:, :, 2])
c_weight = color_weight * overall_weight
out_lab[:, :, 1] = gen_lab_f[:, :, 1] * (1.0 - c_weight) + a_trans * c_weight
out_lab[:, :, 2] = gen_lab_f[:, :, 2] * (1.0 - c_weight) + b_trans * c_weight
# Apply soft masking if provided
if mask_np is not None:
out_lab = gen_lab_f * (1.0 - mask_np) + out_lab * mask_np
out_lab = np.clip(out_lab, 0, 255).astype(np.uint8)
res_rgb = cv2.cvtColor(out_lab, cv2.COLOR_LAB2RGB)
out_tensor = torch.from_numpy(res_rgb.astype(np.float32) / 255.0).unsqueeze(0)
out_tensors.append(out_tensor)
return torch.cat(out_tensors, dim=0)
def _composite(original_np: np.ndarray,
generated_np: np.ndarray,
delta_e_threshold: float,
flow_preset: int,
occlusion_threshold: float,
grow_px: int,
close_radius: int,
min_region_px: int,
feather_px: float) -> tuple:
H, W = original_np.shape[:2]
diag = _diag(H, W)
orig_u8 = (np.clip(original_np, 0, 1) * 255).astype(np.uint8)
gen_u8 = (np.clip(generated_np, 0, 1) * 255).astype(np.uint8)
gray_orig = cv2.cvtColor(orig_u8, cv2.COLOR_RGB2GRAY)
gray_gen = cv2.cvtColor(gen_u8, cv2.COLOR_RGB2GRAY)
flow_fwd = _dis_flow(gray_orig, gray_gen, flow_preset)
flow_bwd = _dis_flow(gray_gen, gray_orig, flow_preset)
warped_gen_dense = _warp(generated_np.astype(np.float32), flow_fwd)
blur_kernel = _blur_kernel_for_diag(diag)
orig_blur = cv2.GaussianBlur(original_np, blur_kernel, 0)
wgen_blur = cv2.GaussianBlur(warped_gen_dense, blur_kernel, 0)
orig_lab = _rgb_to_lab(orig_blur.reshape(-1, 3)).reshape(H, W, 3)
wgen_lab = _rgb_to_lab(wgen_blur.reshape(-1, 3)).reshape(H, W, 3)
lab_diff = orig_lab - wgen_lab
lab_diff[..., 0] *= 0.7
delta_e = np.sqrt((lab_diff**2).sum(axis=2))
sk = max(_blur_kernel_for_diag(diag)[0], 5)
if sk % 2 == 0: sk += 1
delta_e_smooth = cv2.GaussianBlur(delta_e, (sk, sk), 0)
auto_report = {}
if delta_e_threshold < 0:
delta_e_threshold = _auto_delta_e_threshold(delta_e_smooth)
auto_report["auto_delta_e"] = delta_e_threshold
if occlusion_threshold < 0:
occlusion_threshold = _auto_occlusion_threshold(flow_fwd, flow_bwd)
auto_report["auto_occlusion"] = occlusion_threshold
occluded = _occlusion_mask(flow_fwd, flow_bwd, occlusion_threshold)
changed = np.maximum((delta_e_smooth > delta_e_threshold).astype(np.float32), occluded)
if grow_px != 0:
changed = _grow_mask(changed, grow_px)
if close_radius > 0:
k = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (close_radius * 2 + 1, close_radius * 2 + 1))
changed = cv2.morphologyEx(changed.astype(np.uint8), cv2.MORPH_CLOSE, k).astype(np.float32)
if min_region_px > 0:
n, labeled, stats_cc, _ = cv2.connectedComponentsWithStats((changed > 0.5).astype(np.uint8), connectivity=8)
for i in range(1, n):
if stats_cc[i, cv2.CC_STAT_AREA] < min_region_px:
changed[labeled == i] = 0
sharp_mask = changed.copy()
if feather_px > 0:
inv_mask = (sharp_mask < 0.5).astype(np.uint8)
if inv_mask.min() == 0:
dist = cv2.distanceTransform(inv_mask, cv2.DIST_L2, 5)
fade_dist = feather_px * 3.0
t = np.clip(1.0 - (dist / fade_dist), 0.0, 1.0)
composite_mask = (t * t * (3.0 - 2.0 * t)).astype(np.float32)
else:
composite_mask = sharp_mask
else:
composite_mask = sharp_mask
y_grid, x_grid = np.mgrid[0:H:10, 0:W:10]
pts_orig = np.stack([x_grid, y_grid], axis=-1).reshape(-1, 2).astype(np.float32)
flow_sub = flow_fwd[0:H:10, 0:W:10].reshape(-1, 2)
mask_sub = sharp_mask[0:H:10, 0:W:10].reshape(-1)
bg_idx = mask_sub < 0.1
M = None
if bg_idx.sum() > 10:
src_pts = pts_orig[bg_idx]
dst_pts = src_pts + flow_sub[bg_idx]
M, _ = cv2.estimateAffinePartial2D(src_pts, dst_pts, method=cv2.RANSAC)
if M is not None:
final_aligned_gen = cv2.warpAffine(
generated_np.astype(np.float32),
M.astype(np.float64),
(W, H),
flags=cv2.INTER_LINEAR | cv2.WARP_INVERSE_MAP,
borderMode=cv2.BORDER_REFLECT
)
else:
final_aligned_gen = generated_np
m3 = composite_mask[..., np.newaxis]
result = np.clip(original_np * (1.0 - m3) + final_aligned_gen * m3, 0, 1)
flow_mag = np.sqrt((flow_fwd**2).sum(axis=2))
n_changed = int((sharp_mask > 0.5).sum())
stats = {
"changed_pct": 100 * n_changed / (H * W),
"occluded_px": int(occluded.sum()),
"flow_mean_px": float(flow_mag.mean()),
"flow_p99_px": float(np.percentile(flow_mag, 99)),
"median_de": float(np.median(delta_e)),
"resolution": f"{W}x{H}",
"diagonal_px": round(diag),
}
stats.update(auto_report)
return result, composite_mask, stats
class LlamaTokenizerOptions(io.ComfyNode):
@classmethod
def define_schema(cls) -> io.Schema:
return io.Schema(
node_id="LlTokenizerOptions",
category="_for_testing/conditioning",
inputs=[
io.Clip.Input("clip"),
io.Int.Input("min_padding", default=0, min=0, max=10000, step=1),
io.Int.Input("min_length", default=0, min=0, max=10000, step=1),
],
outputs=[io.Clip.Output()],
is_experimental=True,
)
@classmethod
def execute(cls, clip, min_padding, min_length) -> io.NodeOutput:
clip = clip.clone()
for llama_type in ["qwen3_4b", "qwen3_8b", "qwen25_7b", "mistral3_24b"]:
clip.set_tokenizer_option("{}_min_padding".format(llama_type), min_padding)
clip.set_tokenizer_option("{}_min_length".format(llama_type), min_length)
return io.NodeOutput(clip)
class SamplingParameters(io.ComfyNode):
@classmethod
def define_schema(cls) -> io.Schema:
return io.Schema(
node_id="SamplingParameters",
category="advanced",
inputs=[
io.Int.Input(
id="width", default=1024, min=16, max=nodes.MAX_RESOLUTION, step=16
),
io.Int.Input(
id="height", default=1024, min=16, max=nodes.MAX_RESOLUTION, step=16
),
io.Int.Input(id="batch_size", default=1, min=1, max=4096),
io.Float.Input(
id="scale_by",
default=1.0,
min=0.0,
max=10.0,
step=0.01,
tooltip="How much to upscale initial resolution by for the upscaled one.",
),
io.Int.Input(
id="multiple",
default=16,
min=4,
max=128,
step=4,
tooltip="Nearest multiple of the result to set the upscaled resolution to.",
),
io.Int.Input(
id="steps",
default=26,
min=1,
max=10000,
step=1,
tooltip="How many steps to run the sampling for.",
),
io.Float.Input(
id="cfg",
default=3.5,
min=-100.0,
max=100.0,
step=0.01,
tooltip="The amount of influence your prompot will have on the final image.",
),
io.Int.Input(
id="seed",
min=-sys.maxsize,
max=sys.maxsize,
control_after_generate=True,
),
],
outputs=[
io.Int.Output(display_name="width"),
io.Int.Output(display_name="height"),
io.Int.Output(display_name="batch_size"),
io.Int.Output(display_name="upscaled_width"),
io.Int.Output(display_name="upscaled_height"),
io.Int.Output(display_name="steps"),
io.Float.Output(display_name="cfg"),
io.Int.Output(display_name="seed"),
io.Int.Output(display_name="tile_width"),
io.Int.Output(display_name="tile_height"),
io.Int.Output(display_name="tile_padding"),
],
)
@classmethod
def execute(
cls,
*,
width: int,
height: int,
batch_size: int = 1,
scale_by: float,
multiple: int,
steps: int,
cfg: float,
seed: int,
) -> io.NodeOutput:
upscaled_width = round_to_nearest(int(width * scale_by), int(multiple))
upscaled_height = round_to_nearest(int(height * scale_by), int(multiple))
if scale_by > 2.0:
tile_width = round_to_nearest(
int((upscaled_width - (width / scale_by)) / scale_by), int(multiple)
)
tile_height = round_to_nearest(
int((upscaled_height - (height / scale_by)) / scale_by), int(multiple)
)
tile_padding = round_to_nearest(
int(max(width, height) - max(tile_width, tile_height)), int(multiple)
)
else:
tile_width = round_to_nearest(int(upscaled_width * 0.5), int(multiple))
tile_height = round_to_nearest(int(upscaled_height * 0.5), int(multiple))
tile_padding = round_to_nearest(
int(max(width, height) - max(tile_width, tile_height)), int(multiple)
)
width = round_to_nearest(int(width), int(multiple))
height = round_to_nearest(int(height), int(multiple))
return io.NodeOutput(
width,
height,
batch_size,
upscaled_width,
upscaled_height,
steps,
cfg,
seed,
tile_width,
tile_height,
tile_padding,
)
class AdjustedResolutionParameters(io.ComfyNode):
@classmethod
def define_schema(cls) -> io.Schema:
return io.Schema(
node_id="AdjustedResolutionParameters",
category="utils",
inputs=[
io.Int.Input(
id="width", default=1024, min=16, max=nodes.MAX_RESOLUTION, step=16
),
io.Int.Input(
id="height", default=1024, min=16, max=nodes.MAX_RESOLUTION, step=16
),
io.Int.Input(id="batch_size", default=1, min=1, max=4096),
io.Float.Input(
id="scale_by",
default=1.0,
min=0.0,
max=10.0,
step=0.01,
tooltip="How much to upscale initial resolution by for the upscaled one.",
),
io.Int.Input(
id="multiple",
default=16,
min=4,
max=128,
step=4,
tooltip="Nearest multiple of the result to set the upscaled resolution to.",
),
],
outputs=[
io.Int.Output(display_name="adjusted_width"),
io.Int.Output(display_name="adjusted_height"),
io.Int.Output(display_name="upscaled_width"),
io.Int.Output(display_name="upscaled_height"),
],
)
@classmethod
def execute(cls, width: int, height: int, batch_size: int, scale_by: float, multiple: int) -> io.NodeOutput:
adjusted_width = round_to_nearest(width, multiple)
adjusted_height = round_to_nearest(height, multiple)
upscaled_width = round_to_nearest(width * scale_by, multiple)
upscaled_height = round_to_nearest(height * scale_by, multiple)
return io.NodeOutput(
adjusted_width,
adjusted_height,
upscaled_width,
upscaled_height,
)
class GetJsonKeyValue(io.ComfyNode):
@classmethod
def define_schema(cls) -> io.Schema:
return io.Schema(
node_id="GetJsonKeyValue",
category="advanced/utils",
inputs=[
io.String.Input(
"json_path",
default="./input/JSON_KeyValueStore.json",
multiline=False,
tooltip="Path to a .json file with simple top level structure with key and value. See example in custom node folder.",
),
io.Combo.Input(
"key_id_method",
options=["custom", "random_rotate", "increment_rotate"],
),
io.Int.Input(
"rotation_interval",
default=0,
tooltip="how many steps to jump when doing rotate.",
),
io.String.Input(
"key_id",
default="placeholder",
multiline=False,
tooltip="Put name of key in the .json here if using custom in key_id_method.",
),
],
outputs=[io.String.Output(display_name="key_value")],
)
@classmethod
def execute(
cls, json_path, key_id_method, rotation_interval, key_id="placeholder"
) -> io.NodeOutput:
"""
Loads API keys from a JSON file (top-level dictionary)
and selects one based on the specified method.
Args:
json_path (str): Path to the JSON file. Expected format:
{"key_id_1": "api_key_value_1", "key_id_2": "api_key_value_2", ...}
key_id_method (str): Method to select the key ('custom', 'random_rotate', 'increment_rotate').
rotation_interval (int): Used as index for 'increment_rotate'.
key_id (str, optional): ID (key name) of the key to select if key_id_method is 'custom'. Defaults to "placeholder".
Returns:
str: The selected API key string.
Raises: ValueError or RuntimeError if unable to find or select a key.
"""
api_keys_data = None
absolute_json_path = os.path.abspath(json_path)
try:
with open(absolute_json_path, "r") as f:
api_keys_data = json.load(f)
except FileNotFoundError:
raise ValueError(
f"RotateKeyAPI Error: JSON file not found at {absolute_json_path}"
)
except json.JSONDecodeError:
raise ValueError(
f"RotateKeyAPI Error: Could not decode JSON from {absolute_json_path}. Check file format."
)
except Exception as e:
raise RuntimeError(
f"RotateKeyAPI Error: Unexpected error reading file {absolute_json_path}: {e}"
)
if not isinstance(api_keys_data, dict):
raise ValueError(
f"RotateKeyAPI Error: JSON content is not a dictionary in {absolute_json_path}. Expected format: {{'key_id': 'api_key', ...}}"
)
if not api_keys_data:
raise ValueError(
f"RotateKeyAPI Error: The JSON dictionary in {absolute_json_path} is empty."
)
selected_key_value = None
if key_id_method == "custom":
if key_id == "placeholder":
print(
"RotateKeyAPI Warning: 'custom' method selected but 'key_id' is still the default 'placeholder'. Ensure this is intended or provide a valid key ID."
)
selected_key_value = api_keys_data.get(key_id)
if selected_key_value is None:
raise ValueError(
f"RotateKeyAPI Error: Custom key ID '{key_id}' not found in the JSON dictionary keys."
)
elif key_id_method == "random_rotate":
api_keys_list = list(api_keys_data.values())
selected_key_value = random.choice(api_keys_list)
elif key_id_method == "increment_rotate":
api_keys_list = list(api_keys_data.values())
index = rotation_interval % len(api_keys_list)
try:
selected_key_value = api_keys_list[index]
except IndexError:
raise IndexError(
f"RotateKeyAPI Error: Calculated index {index} (from interval {rotation_interval}) is out of bounds for list of size {len(api_keys_list)}."
)
except Exception as e:
raise RuntimeError(
f"RotateKeyAPI Error: Unexpected error accessing item at index {index}: {e}"
)
if not isinstance(selected_key_value, str) or not selected_key_value:
raise ValueError(
f"RotateKeyAPI Error: Retrieved value for selected key is not a valid string. Value: {selected_key_value}"
)
print(
f"RotateKeyAPI: Successfully retrieved API key using method '{key_id_method}'."
)
return io.NodeOutput(selected_key_value)
class Image_Color_Noise(io.ComfyNode):
@classmethod
def define_schema(cls) -> io.Schema:
return io.Schema(
node_id="Image_Color_Noise",
category="utils",
inputs=[
io.Int.Input("width", default=512, max=4096, min=64, step=1),
io.Int.Input("height", default=512, max=4096, min=64, step=1),
io.Float.Input("frequency", default=0.5, max=100.0, min=0.0, step=0.01),
io.Float.Input(
"attenuation", default=0.5, max=100.0, min=0.0, step=0.01
),
io.Combo.Input(
"noise_type",
options=["grey", "white", "red", "pink", "green", "blue", "mix"],
),
io.Int.Input("seed", default=0, min=0, max=0xFFFFFFFFFFFFFFFF),
],
outputs=[
io.Image.Output(display_name="noise_image"),
],
)
@classmethod
def execute(cls, width, height, frequency, attenuation, noise_type, seed):
generator = torch.Generator()
generator.manual_seed(seed)
noise_image = cls.generate_power_noise(
width, height, frequency, attenuation, noise_type, generator
)
return io.NodeOutput(pil2tensor(noise_image))
@classmethod
def generate_power_noise(
cls, width, height, frequency, attenuation, noise_type, generator
):
def normalize_array(arr):
return (255 * (arr - np.min(arr)) / (np.max(arr) - np.min(arr))).astype(
np.uint8
)
def white_noise(w, h, gen):
return torch.rand(h, w, generator=gen).numpy()
def grey_noise_texture(w, h, att, gen):
return torch.normal(mean=0, std=att, size=(h, w), generator=gen).numpy()
def fourier_noise(w, h, att, power_modifier, gen):
noise = grey_noise_texture(w, h, att, gen)
fy = np.fft.fftfreq(h)[:, np.newaxis]
fx = np.fft.fftfreq(w)
f = np.sqrt(fx**2 + fy**2)
f[0, 0] = 1.0
power_spectrum = f**power_modifier
fft_noise = np.fft.fft2(noise)
fft_modified = fft_noise * power_spectrum
inv_fft = np.fft.ifft2(fft_modified)
return np.real(inv_fft)
noise_array = np.zeros((height, width, 3), dtype=np.uint8)
zeros_channel = np.zeros((height, width), dtype=np.uint8)