-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnodes.py
More file actions
859 lines (727 loc) · 34.4 KB
/
Copy pathnodes.py
File metadata and controls
859 lines (727 loc) · 34.4 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
import json
import torch
import os
import math
import comfy.utils
import folder_paths
from PIL import Image, ImageOps
import numpy as np
# --------------------------------------------------------------------------
# Node 1: Abhash: Load Ingredients
# --------------------------------------------------------------------------
class AbhashIngredientsLoader:
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"ingredients_data": ("STRING", {"default": "[]", "multiline": False}),
"prompt": ("STRING", {"default": "", "multiline": True}),
}
}
RETURN_TYPES = tuple(["IMAGE"] * 10 + ["STRING"])
RETURN_NAMES = tuple([f"image_{i+1}" for i in range(10)] + ["prompt"])
FUNCTION = "load_ingredients"
CATEGORY = "Abhash"
DESCRIPTION = "Isang node para mag-load ng multiple images at videos ng sabay-sabay."
def load_ingredients(self, ingredients_data, prompt, **kwargs):
try:
items = json.loads(ingredients_data)
except Exception:
items = []
images = []
for item in items:
if not isinstance(item, dict) or "filename" not in item:
continue
filename = item["filename"]
subfolder = item.get("subfolder", "")
image_path = folder_paths.get_annotated_filepath(filename)
if not image_path:
if subfolder:
image_path = os.path.join(folder_paths.get_input_directory(), subfolder, filename)
else:
image_path = os.path.join(folder_paths.get_input_directory(), filename)
if not os.path.exists(image_path):
print(f"[AbhashIngredientsLoader] Missing file: {image_path}")
continue
try:
img = Image.open(image_path)
img = ImageOps.exif_transpose(img)
img = img.convert("RGB")
img = np.array(img).astype(np.float32) / 255.0
img = torch.from_numpy(img)[None,]
images.append(img)
except Exception as e:
print(f"[AbhashIngredientsLoader] Error loading {image_path}: {e}")
# Pad outputs to 10
empty_image = torch.zeros((1, 64, 64, 3))
outputs = []
for i in range(10):
if i < len(images):
outputs.append(images[i])
else:
outputs.append(empty_image)
outputs.append(prompt)
return tuple(outputs)
# --------------------------------------------------------------------------
# Node 2: Abhash: Combine Ingredients
# --------------------------------------------------------------------------
class AbhashCombineIngredients:
@classmethod
def INPUT_TYPES(cls):
optional = {}
for i in range(1, 11):
optional[f"image_{i}"] = ("IMAGE",)
return {
"required": {},
"optional": optional
}
RETURN_TYPES = tuple(["IMAGE"] * 10)
RETURN_NAMES = tuple([f"image_{i+1}" for i in range(10)])
FUNCTION = "combine"
CATEGORY = "Abhash"
DESCRIPTION = "Isang utility para pagdikitin ang mga IMAGE outputs kung kailangan."
def combine(self, **kwargs):
outputs = []
for i in range(1, 11):
img = kwargs.get(f"image_{i}")
if img is not None and torch.max(img) > 0.0:
outputs.append(img)
else:
outputs.append(torch.zeros((1, 64, 64, 3)))
return tuple(outputs)
# --------------------------------------------------------------------------
# Node 3: Abhash: Flux Reference Encode
# --------------------------------------------------------------------------
class AbhashFluxReferenceEncode:
@classmethod
def INPUT_TYPES(cls):
optional = {}
for i in range(1, 11):
optional[f"image_{i}"] = ("IMAGE",)
return {
"required": {
"conditioning": ("CONDITIONING", ),
"vae": ("VAE", ),
"active_slots": ("INT", {"default": 1, "min": 1, "max": 10, "step": 1}),
},
"optional": optional
}
RETURN_TYPES = ("CONDITIONING",)
RETURN_NAMES = ("CONDITIONING",)
FUNCTION = "apply"
CATEGORY = "Abhash"
DESCRIPTION = "Isang bypass node na awtomatikong mag-vae-encode at append sa ReferenceLatent."
def apply(self, conditioning, vae, active_slots, **kwargs):
images = []
for i in range(1, active_slots + 1):
img = kwargs.get(f"image_{i}")
if img is not None and torch.max(img) > 0.0:
images.append(img)
if not images:
return (conditioning,)
out_cond = []
for t in conditioning:
if not isinstance(t, list) and not isinstance(t, tuple):
out_cond.append(t)
continue
if len(t) < 2 or not isinstance(t[1], dict):
out_cond.append(t)
continue
out_cond.append([t[0], t[1].copy()])
for img in images:
latent = {"samples": vae.encode(img[:,:,:,:3])}
for n in out_cond:
if "reference_latents" in n[1]:
n[1]["reference_latents"] = n[1]["reference_latents"] + [latent["samples"]]
else:
n[1]["reference_latents"] = [latent["samples"]]
return (out_cond,)
# --------------------------------------------------------------------------
# Node 4: Abhash: Apply Ingredients (Flux / Image to Image)
# --------------------------------------------------------------------------
class AbhashApplyIngredients:
@classmethod
def INPUT_TYPES(cls):
optional = {}
for i in range(1, 11):
optional[f"image_{i}"] = ("IMAGE",)
return {
"required": {
"conditioning": ("CONDITIONING",),
"vae": ("VAE",),
"active_slots": ("INT", {"default": 1, "min": 1, "max": 10, "step": 1}),
"megapixels": ("FLOAT", {"default": 1.0, "min": 0.1, "max": 10.0, "step": 0.1}),
},
"optional": optional,
}
RETURN_TYPES = ("CONDITIONING",)
RETURN_NAMES = ("CONDITIONING",)
FUNCTION = "apply"
CATEGORY = "Abhash"
DESCRIPTION = (
"Isang node para mabypass ang Group 1-10 para sa Flux Image to Image. Pinagsamang Scale To Total Pixels, "
"VAE Encode, at ReferenceLatent sa iisang node."
)
def apply(self, conditioning, vae, active_slots, megapixels, **kwargs):
images = []
for i in range(1, active_slots + 1):
img = kwargs.get(f"image_{i}")
if img is not None and torch.max(img) > 0.0:
images.append(img)
if not images:
return (conditioning,)
first_img = images[0]
samples = first_img.movedim(-1, 1)
total = int(megapixels * 1024 * 1024)
scale_by = math.sqrt(total / (samples.shape[2] * samples.shape[3]))
target_width = round(samples.shape[3] * scale_by)
target_height = round(samples.shape[2] * scale_by)
resolution_steps = 64
target_width = max(resolution_steps, round(target_width / resolution_steps) * resolution_steps)
target_height = max(resolution_steps, round(target_height / resolution_steps) * resolution_steps)
out_cond = []
for t in conditioning:
if not isinstance(t, list) and not isinstance(t, tuple):
out_cond.append(t)
continue
if len(t) < 2 or not isinstance(t[1], dict):
out_cond.append(t)
continue
out_cond.append([t[0], t[1].copy()])
for img in images:
samples = img.movedim(-1, 1)
scaled_samples = comfy.utils.common_upscale(samples, target_width, target_height, "lanczos", "center")
scaled_img = scaled_samples.movedim(1, -1)
latent = {"samples": vae.encode(scaled_img[:,:,:,:3])}
for n in out_cond:
if "reference_latents" in n[1]:
n[1]["reference_latents"] = n[1]["reference_latents"] + [latent["samples"]]
else:
n[1]["reference_latents"] = [latent["samples"]]
return (out_cond,)
# --------------------------------------------------------------------------
# Node 5: Abhash: Apply Ingredients (LTX Video 2.3)
# --------------------------------------------------------------------------
class AbhashApplyIngredientsLTX:
@classmethod
def INPUT_TYPES(cls):
optional = {}
for i in range(1, 11):
optional[f"image_{i}"] = ("IMAGE",)
return {
"required": {
"active_slots": ("INT", {"default": 1, "min": 1, "max": 10, "step": 1}),
"megapixels": ("FLOAT", {"default": 1.0, "min": 0.1, "max": 10.0, "step": 0.1}),
},
"optional": optional,
}
RETURN_TYPES = ("IMAGE",)
RETURN_NAMES = ("IMAGE_BATCH",)
FUNCTION = "apply"
CATEGORY = "Abhash"
DESCRIPTION = (
"Isang node para mabypass ang mga groups at diretsong mag-supply ng Video Batch Images "
"para sa LTX Video 2.3 workflows. Nag-s-scale to total pixels, crop sa /32, at nagba-batch ng images."
)
def apply(self, active_slots, megapixels, **kwargs):
images = []
for i in range(1, active_slots + 1):
img = kwargs.get(f"image_{i}")
if img is not None and torch.max(img) > 0.0:
images.append(img)
if not images:
return (torch.zeros((1, 64, 64, 3)),)
first_img = images[0]
samples = first_img.movedim(-1, 1)
total = int(megapixels * 1024 * 1024)
scale_by = math.sqrt(total / (samples.shape[2] * samples.shape[3]))
target_width = round(samples.shape[3] * scale_by)
target_height = round(samples.shape[2] * scale_by)
resolution_steps = 32
target_width = max(resolution_steps, round(target_width / resolution_steps) * resolution_steps)
target_height = max(resolution_steps, round(target_height / resolution_steps) * resolution_steps)
processed_images = []
for img in images:
samples = img.movedim(-1, 1)
scaled_samples = comfy.utils.common_upscale(samples, target_width, target_height, "lanczos", "center")
scaled_img = scaled_samples.movedim(1, -1)
processed_images.append(scaled_img)
batched_images = torch.cat(processed_images, dim=0)
return (batched_images,)
# --------------------------------------------------------------------------
# Node 6: ab-node (Load 6 References)
# --------------------------------------------------------------------------
class AbMultiReferenceLoader:
@classmethod
def INPUT_TYPES(cls):
input_dir = folder_paths.get_input_directory()
files = []
if os.path.exists(input_dir):
files = [f for f in os.listdir(input_dir) if os.path.isfile(os.path.join(input_dir, f))]
file_list = ["None"] + sorted(files)
return {
"required": {
"image_1_name": (file_list, {"default": "None", "image_upload": True}),
"image_2_name": (file_list, {"default": "None", "image_upload": True}),
"image_3_name": (file_list, {"default": "None", "image_upload": True}),
"image_4_name": (file_list, {"default": "None", "image_upload": True}),
"image_5_name": (file_list, {"default": "None", "image_upload": True}),
"image_6_name": (file_list, {"default": "None", "image_upload": True}),
},
"optional": {
"image_1": ("IMAGE",),
"image_2": ("IMAGE",),
"image_3": ("IMAGE",),
"image_4": ("IMAGE",),
"image_5": ("IMAGE",),
"image_6": ("IMAGE",),
}
}
RETURN_TYPES = ("IMAGE", "IMAGE", "IMAGE", "IMAGE", "IMAGE", "IMAGE", "IMAGE", "INT")
RETURN_NAMES = ("image_1", "image_2", "image_3", "image_4", "image_5", "image_6", "image_batch", "active_count")
FUNCTION = "load_images"
CATEGORY = "Abhash"
DESCRIPTION = "Isang custom 'ab-node' para mag-load ng hanggang anim (6) na reference images. Maaaring mag-upload directly o mag-connect ng external LoadImage nodes."
def load_images(self, image_1_name, image_2_name, image_3_name, image_4_name, image_5_name, image_6_name,
image_1=None, image_2=None, image_3=None, image_4=None, image_5=None, image_6=None):
input_images = [image_1, image_2, image_3, image_4, image_5, image_6]
filenames = [image_1_name, image_2_name, image_3_name, image_4_name, image_5_name, image_6_name]
loaded_images = []
outputs = []
empty_image = torch.zeros((1, 64, 64, 3))
for i in range(6):
if input_images[i] is not None and torch.max(input_images[i]) > 0.0:
outputs.append(input_images[i])
loaded_images.append(input_images[i])
continue
filename = filenames[i]
if filename == "None" or not filename:
outputs.append(empty_image)
continue
image_path = folder_paths.get_annotated_filepath(filename)
if not image_path:
image_path = os.path.join(folder_paths.get_input_directory(), filename)
if not os.path.exists(image_path):
outputs.append(empty_image)
continue
try:
img = Image.open(image_path)
img = ImageOps.exif_transpose(img)
img = img.convert("RGB")
img = np.array(img).astype(np.float32) / 255.0
img = torch.from_numpy(img)[None,]
outputs.append(img)
loaded_images.append(img)
except Exception:
outputs.append(empty_image)
if loaded_images:
ref_shape = loaded_images[0].shape
ref_h, ref_w = ref_shape[1], ref_shape[2]
resized_images = []
for img in loaded_images:
if img.shape[1] != ref_h or img.shape[2] != ref_w:
samples = img.movedim(-1, 1)
scaled_samples = comfy.utils.common_upscale(samples, ref_w, ref_h, "lanczos", "center")
scaled_img = scaled_samples.movedim(1, -1)
resized_images.append(scaled_img)
else:
resized_images.append(img)
image_batch = torch.cat(resized_images, dim=0)
else:
image_batch = empty_image
active_count = len(loaded_images)
return (outputs[0], outputs[1], outputs[2], outputs[3], outputs[4], outputs[5], image_batch, active_count)
# --------------------------------------------------------------------------
# Node 7: ab-prompt-splitter (Scene Splitter)
# --------------------------------------------------------------------------
class AbPromptSplitter:
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"full_script": ("STRING", {"default": "SCENE: 1\nScene 1 prompt here...\n\nSCENE: 2\nScene 2 prompt here...", "multiline": True}),
},
"optional": {
"global_prefix": ("STRING", {"default": "", "multiline": True}),
"global_suffix": ("STRING", {"default": "", "multiline": True}),
}
}
RETURN_TYPES = ("STRING", "STRING", "STRING", "STRING", "STRING", "STRING")
RETURN_NAMES = ("scene_1", "scene_2", "scene_3", "scene_4", "scene_5", "scene_6")
FUNCTION = "split_prompt"
CATEGORY = "Abhash"
DESCRIPTION = "Hinihiwalay ang isang mahabang script sa anim (6) na scenes gamit ang marker na 'SCENE: 1' hanggang 'SCENE: 6'."
def split_prompt(self, full_script, global_prefix="", global_suffix=""):
import re
# Split by "SCENE: <number>" (case insensitive)
# We find all positions of "SCENE: \d"
markers = list(re.finditer(r'(?i)SCENE:\s*(\d+)', full_script))
scenes_content = [""] * 6
if markers:
for i in range(len(markers)):
start = markers[i].end()
end = markers[i+1].start() if i+1 < len(markers) else len(full_script)
scene_num = int(markers[i].group(1))
content = full_script[start:end].strip()
# If scene number is between 1 and 6, assign it
if 1 <= scene_num <= 6:
scenes_content[scene_num - 1] = content
else:
# Fallback: if no markers found, just split by lines
lines = [l.strip() for l in full_script.split("\n") if l.strip()]
for i in range(min(len(lines), 6)):
scenes_content[i] = lines[i]
# Fill empty scenes with the last non-empty one
last_valid = "photo"
for i in range(6):
if scenes_content[i]:
last_valid = scenes_content[i]
else:
scenes_content[i] = last_valid
final_outputs = []
for content in scenes_content:
full = []
if global_prefix.strip(): full.append(global_prefix.strip())
full.append(content)
if global_suffix.strip(): full.append(global_suffix.strip())
final_outputs.append(", ".join(full))
return tuple(final_outputs)
# --------------------------------------------------------------------------
# Node 8: Abhash: Scene Sequence Loader
# --------------------------------------------------------------------------
class AbhashSceneSequenceLoader:
"""
Loads scenes from a JSON file and distributes prompt fields as
parallel lists so ComfyUI iterates the whole pipeline once per
scene automatically within a single Queue Prompt run.
"""
@classmethod
def INPUT_TYPES(cls):
input_dir = folder_paths.get_input_directory()
try:
files = [f for f in os.listdir(input_dir) if f.lower().endswith(".json")]
except FileNotFoundError:
files = []
return {
"required": {
"scene_file": (files if files else ["scenes.json"], {}),
"width": ("INT", {"default": 1024, "min": 64, "max": 4096, "step": 8}),
"height": ("INT", {"default": 1024, "min": 64, "max": 4096, "step": 8}),
},
"optional": {
"override_path": ("STRING", {"default": "", "multiline": False}),
},
}
RETURN_TYPES = ("STRING", "STRING", "STRING", "INT", "INT", "INT")
RETURN_NAMES = (
"positive_prompt",
"negative_prompt",
"filename_prefix",
"scene_number",
"width",
"height",
)
OUTPUT_IS_LIST = (True, True, True, True, True, True)
FUNCTION = "load_scenes"
CATEGORY = "Abhash"
DESCRIPTION = "Nag-lo-load ng scene-by-scene prompts mula sa JSON file at awtomatikong ipinapamahagi sa buong workflow bilang list."
def load_scenes(self, scene_file, width, height, override_path=""):
path = override_path.strip() if override_path.strip() else os.path.join(
folder_paths.get_input_directory(), scene_file
)
with open(path, "r", encoding="utf-8") as f:
data = json.load(f)
scenes = data.get("scenes", [])
if not scenes:
raise ValueError(f"No 'scenes' array found in {path}")
positives, negatives, prefixes, numbers, widths, heights = [], [], [], [], [], []
for i, scene in enumerate(scenes, start=1):
scene_id = scene.get("id", i)
positives.append(scene["prompt"])
negatives.append(scene.get("negative_prompt", ""))
prefixes.append(f"scene_{int(scene_id):03d}")
numbers.append(int(scene_id))
widths.append(int(scene.get("width", width)))
heights.append(int(scene.get("height", height)))
return (positives, negatives, prefixes, numbers, widths, heights)
# --------------------------------------------------------------------------
# Node 9: Abhash: Auto Split Scenes
# --------------------------------------------------------------------------
class AbhashAutoSplitScenes:
"""
6 manually-editable scene boxes by default. If you wire a combined
script into the 'script' connector, it overrides all 6 boxes by
auto-splitting the text using 'SCENE 1:' ... 'SCENE 6:' markers
(case-insensitive, colon optional, order-insensitive).
"""
@classmethod
def INPUT_TYPES(cls):
required = {}
for i in range(1, 7):
required[f"scene{i}"] = ("STRING", {"default": "", "multiline": True})
return {
"required": required,
"optional": {
"script": ("STRING", {"default": "", "multiline": True, "forceInput": True}),
},
}
RETURN_TYPES = ("STRING", "STRING", "STRING", "STRING", "STRING", "STRING")
RETURN_NAMES = ("scene1", "scene2", "scene3", "scene4", "scene5", "scene6")
FUNCTION = "auto_split"
CATEGORY = "Abhash"
DESCRIPTION = (
"6 editable scene boxes. Kapag naka-connect ang 'script' input, "
"awtomatikong hinahati ang naka-wire na text gamit ang 'SCENE 1:' "
"hanggang 'SCENE 6:' markers, ino-override ang manual na laman ng boxes."
)
def auto_split(self, scene1, scene2, scene3, scene4, scene5, scene6, script=""):
manual = [scene1, scene2, scene3, scene4, scene5, scene6]
if not script or not script.strip():
return tuple(manual)
import re
markers = list(re.finditer(r'(?i)SCENE\s*:?\s*(\d+)\s*:?', script))
scenes_content = [""] * 6
if markers:
for i in range(len(markers)):
start = markers[i].end()
end = markers[i + 1].start() if i + 1 < len(markers) else len(script)
scene_num = int(markers[i].group(1))
content = script[start:end].strip()
if 1 <= scene_num <= 6:
scenes_content[scene_num - 1] = content
else:
# Fallback kung walang "SCENE N" markers: hatiin sa blank lines
chunks = [c.strip() for c in re.split(r'\n\s*\n', script) if c.strip()]
for i in range(min(len(chunks), 6)):
scenes_content[i] = chunks[i]
# Fill empty slots with the last valid scene (avoid blank panels)
last_valid = manual[0] if manual[0] else "photo"
for i in range(6):
if scenes_content[i]:
last_valid = scenes_content[i]
else:
scenes_content[i] = last_valid
return tuple(scenes_content)
# --------------------------------------------------------------------------
# Node 10: Abhash: Storyboard Splitter
# --------------------------------------------------------------------------
class AbhashStoryboardSplitter:
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"ingredients_data": ("STRING", {"default": "[]", "multiline": False}),
"script": ("STRING", {"default": "SCENE 1: Same person from @1, walking calmly along a narrow dirt forest trail...\n\nSCENE 2: Same person from @2, walking deeper...", "multiline": True}),
},
}
RETURN_TYPES = ("STRING", "IMAGE", "STRING", "IMAGE", "STRING", "IMAGE", "STRING", "IMAGE", "STRING", "IMAGE", "STRING", "IMAGE")
RETURN_NAMES = ("scene1_prompt", "scene1_image", "scene2_prompt", "scene2_image", "scene3_prompt", "scene3_image", "scene4_prompt", "scene4_image", "scene5_prompt", "scene5_image", "scene6_prompt", "scene6_image")
FUNCTION = "split_storyboard"
CATEGORY = "Abhash"
DESCRIPTION = "Pinagsamang node: naglo-load ng images mula sa JSON data, nag-a-auto-split ng scenes mula sa script, at nagtutugma ng reference images gamit ang '@' tag."
def split_storyboard(self, ingredients_data, script):
import re
print(f"[StoryboardSplitter] Raw ingredients_data: {ingredients_data}")
# 1. Load images from JSON data
try:
items = json.loads(ingredients_data)
print(f"[StoryboardSplitter] Parsed items: {items}")
except Exception as e:
print(f"[StoryboardSplitter] Error parsing ingredients_data: {e}")
items = []
loaded_images = {}
empty_image = torch.zeros((1, 64, 64, 3))
for i, item in enumerate(items[:6]):
if not isinstance(item, dict) or "filename" not in item:
continue
filename = item["filename"]
subfolder = item.get("subfolder", "abhash")
# Subukan muna ang annotated filepath, kung wala, construct path
image_path = folder_paths.get_annotated_filepath(filename)
if not image_path:
image_path = os.path.join(folder_paths.get_input_directory(), subfolder, filename)
print(f"[StoryboardSplitter] Trying to load: {image_path}")
if os.path.exists(image_path):
try:
img = Image.open(image_path)
img = ImageOps.exif_transpose(img)
img = img.convert("RGB")
img = np.array(img).astype(np.float32) / 255.0
img = torch.from_numpy(img)[None,]
loaded_images[i + 1] = img
print(f"[StoryboardSplitter] Successfully loaded image {i+1}")
except Exception as e:
print(f"[StoryboardSplitter] Error loading image {i+1}: {e}")
else:
print(f"[StoryboardSplitter] File not found: {image_path}")
# 2. Split scenes
scenes_content = [""] * 6
if script and script.strip():
# I-adjust ang regex para mas swak sa @image_N o @N
markers = list(re.finditer(r'(?i)SCENE\s*:?\s*(\d+)\s*:?', script))
if markers:
for i in range(len(markers)):
start = markers[i].end()
end = markers[i + 1].start() if i + 1 < len(markers) else len(script)
scene_num = int(markers[i].group(1))
content = script[start:end].strip()
if 1 <= scene_num <= 6:
scenes_content[scene_num - 1] = content
else:
chunks = [c.strip() for c in re.split(r'\n\s*\n', script) if c.strip()]
for i in range(min(len(chunks), 6)):
scenes_content[i] = chunks[i]
# Fill empty slots
last_valid = "photo"
for i in range(6):
if scenes_content[i]:
last_valid = scenes_content[i]
else:
scenes_content[i] = last_valid
# 3. Parse tags and prepare outputs
final_data = []
print(f"[StoryboardSplitter] Loaded images keys: {list(loaded_images.keys())}")
for i in range(6):
scene_text = scenes_content[i]
# Hanapin ANG LAHAT ng tags: @image_N o @N (suporta na sa maramihang
# reference images sa isang scene, hal. @image_1 + @image_2 + @image_3)
raw_matches = re.findall(r'@(?:image_)?(\d+)', scene_text)
ref_indices = [int(m) for m in raw_matches]
print(f"[StoryboardSplitter] Scene {i+1} prompt: '{scene_text[:30]}...' -> Detected ref_indices: {ref_indices}")
# Clean prompt (tanggalin lahat ng @tags mula sa text)
cleaned_text = re.sub(r'@(?:image_)?\d+', '', scene_text).strip(' ,')
# I-collect lahat ng valid/existing na images na tinukoy sa scene na ito,
# sunod-sunod ayon sa pagkalagay nila sa text, walang duplicate
seen = []
mapped_list = []
for idx in ref_indices:
if idx in loaded_images and idx not in seen:
mapped_list.append(loaded_images[idx])
seen.append(idx)
if not mapped_list:
mapped_list = [loaded_images.get(1, empty_image)]
print(f"[StoryboardSplitter] Scene {i+1} fell back to image_1")
else:
print(f"[StoryboardSplitter] Scene {i+1} mapped to images: {seen}")
# I-resize lahat sa parehong laki (base sa unang image sa listahan),
# tapos i-batch (torch.cat) para maipasa lahat bilang isang IMAGE output
ref_shape = mapped_list[0].shape
ref_h, ref_w = ref_shape[1], ref_shape[2]
resized_list = []
for img in mapped_list:
if img.shape[1] != ref_h or img.shape[2] != ref_w:
samples = img.movedim(-1, 1)
scaled_samples = comfy.utils.common_upscale(samples, ref_w, ref_h, "lanczos", "center")
resized_list.append(scaled_samples.movedim(1, -1))
else:
resized_list.append(img)
mapped_img = torch.cat(resized_list, dim=0)
final_data.extend([cleaned_text, mapped_img])
return tuple(final_data)
# --------------------------------------------------------------------------
# Node 11: Abhash: Storyboard Combine
# --------------------------------------------------------------------------
class AbhashStoryboardCombine:
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"image_1": ("IMAGE",),
"image_2": ("IMAGE",),
"image_3": ("IMAGE",),
"image_4": ("IMAGE",),
"image_5": ("IMAGE",),
"image_6": ("IMAGE",),
}
}
RETURN_TYPES = ("IMAGE", "IMAGE", "IMAGE", "IMAGE", "IMAGE", "IMAGE")
RETURN_NAMES = ("image_1", "image_2", "image_3", "image_4", "image_5", "image_6")
FUNCTION = "combine"
CATEGORY = "Abhash"
DESCRIPTION = "Utility para i-re-batch/i-standardize ang 6 na images."
def combine(self, image_1, image_2, image_3, image_4, image_5, image_6):
return (image_1, image_2, image_3, image_4, image_5, image_6)
# --------------------------------------------------------------------------
# Node 12: Abhash: Storyboard Reference Encode
# --------------------------------------------------------------------------
class AbhashStoryboardReferenceEncode:
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"vae": ("VAE",),
"cond_1": ("CONDITIONING",),
"image_1": ("IMAGE",),
"cond_2": ("CONDITIONING",),
"image_2": ("IMAGE",),
"cond_3": ("CONDITIONING",),
"image_3": ("IMAGE",),
"cond_4": ("CONDITIONING",),
"image_4": ("IMAGE",),
"cond_5": ("CONDITIONING",),
"image_5": ("IMAGE",),
"cond_6": ("CONDITIONING",),
"image_6": ("IMAGE",),
}
}
RETURN_TYPES = ("CONDITIONING", "CONDITIONING", "CONDITIONING", "CONDITIONING", "CONDITIONING", "CONDITIONING")
RETURN_NAMES = ("c_cond_1", "c_cond_2", "c_cond_3", "c_cond_4", "c_cond_5", "c_cond_6")
FUNCTION = "apply"
CATEGORY = "Abhash"
DESCRIPTION = "Pinagsamang node para i-encode ang 6 na images at i-apply sa 6 na conditionings nang sabay-sabay."
def apply(self, vae, cond_1, image_1, cond_2, image_2, cond_3, image_3, cond_4, image_4, cond_5, image_5, cond_6, image_6):
def encode_scene(cond, img):
out_cond = []
for t in cond:
if not isinstance(t, list) or len(t) < 2 or not isinstance(t[1], dict):
out_cond.append(t)
continue
out_cond.append([t[0], t[1].copy()])
# 'img' ay maaaring isang BATCH ng maraming reference images para
# sa scene na ito (galing sa AbhashStoryboardSplitter kung marami
# ang @image_N tags). I-encode isa-isa at i-stack lahat bilang
# reference_latents para masunod LAHAT ng reference, hindi lang isa.
batch_size = img.shape[0]
latents = []
for b in range(batch_size):
frame = img[b:b+1, :, :, :3]
latents.append(vae.encode(frame))
for n in out_cond:
n[1]["reference_latents"] = latents
return out_cond
return (
encode_scene(cond_1, image_1),
encode_scene(cond_2, image_2),
encode_scene(cond_3, image_3),
encode_scene(cond_4, image_4),
encode_scene(cond_5, image_5),
encode_scene(cond_6, image_6),
)
NODE_CLASS_MAPPINGS = {
"AbhashLoadIngredients": AbhashIngredientsLoader,
"AbhashCombineIngredients": AbhashCombineIngredients,
"AbhashFluxReferenceEncode": AbhashFluxReferenceEncode,
"AbhashApplyIngredients": AbhashApplyIngredients,
"AbhashApplyIngredientsLTX": AbhashApplyIngredientsLTX,
"ab-node": AbMultiReferenceLoader,
"ab-prompt-splitter": AbPromptSplitter,
"AbhashSceneSequenceLoader": AbhashSceneSequenceLoader,
"AbhashAutoSplitScenes": AbhashAutoSplitScenes,
"AbhashStoryboardSplitter": AbhashStoryboardSplitter,
"AbhashStoryboardCombine": AbhashStoryboardCombine,
"AbhashStoryboardReferenceEncode": AbhashStoryboardReferenceEncode,
}
NODE_DISPLAY_NAME_MAPPINGS = {
"AbhashLoadIngredients": "Abhash: Load Ingredients",
"AbhashCombineIngredients": "Abhash: Combine Ingredients",
"AbhashFluxReferenceEncode": "Abhash: Flux Reference Encode",
"AbhashApplyIngredients": "Abhash: Apply Ingredients (Flux / Image to Image)",
"AbhashApplyIngredientsLTX": "Abhash: Apply Ingredients (LTX Video 2.3)",
"ab-node": "ab-node (Load 5 References)",
"ab-prompt-splitter": "ab-prompt-splitter (Scene Splitter)",
"AbhashSceneSequenceLoader": "Abhash: Scene Sequence Loader",
"AbhashAutoSplitScenes": "Abhash: Auto Split Scenes",
"AbhashStoryboardSplitter": "Abhash: Storyboard Splitter",
"AbhashStoryboardCombine": "Abhash: Storyboard Combine",
"AbhashStoryboardReferenceEncode": "Abhash: Storyboard Reference Encode",
}