Repository navigation
Expand file tree
/
Copy pathworkspace.py
More file actions
6445 lines (6067 loc) · 348 KB
/
Copy pathworkspace.py
File metadata and controls
6445 lines (6067 loc) · 348 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
"""RedNode Studio Workspace — the whole scattered input rig in one tabbed node.
What it replaces: the pile of LoadImage nodes, resize chains, mask inputs, source chain
links and floating slider bars that feed RedNode Studio. One node, one panel with tabs
(Subject / People / Scene / Moodboard / Masks / Dials), remembered image galleries per
tab, and every output the studio wants — both as one bundle and as flat sockets for the
Get/Set wiring style.
Storage: filenames only, exactly like LoadImage. The galleries hold names of files in
the ComfyUI input directory; uploads go through the normal /upload API, so workflows
stay small and the files survive restarts. Missing files show up as a readable error
naming the file, not a silent skip of the image you selected.
Resize: every image is scaled so its LONG EDGE hits the target (1024 or 1536, or off),
aspect preserved, dims rounded to /8 so downstream latents never complain. Small images
scale up, huge ones scale down — nothing is cropped.
Masks: painted in ComfyUI's own mask editor over the tab's selected image (the panel
opens it). The editor writes a clipspace file whose alpha carries the mask; this node
reads `1 - alpha`, the LoadImage convention. The `boost_mask_in` / `edit_mask_in`
sockets accept a wired MASK instead and always win over the painted one.
The `config` widget is plain JSON and the single source of truth; the panel above edits
it, and it is hand-editable if the UI is ever unavailable.
"""
import hashlib
from .overrides import env as _env
import random as _random
import asyncio
import json
import os
import re
import numpy as np
import torch
from PIL import Image, ImageOps
import folder_paths
import comfy.samplers
from .rednode import SETTINGS_TYPE
from . import autoprompt
from . import postprocess
from . import lora_stack as _lora
from . import sampler_dials as _dials
from .prompt_tools import SWAP_MODES, STYLE_MODES, ACT_MODES, convert_text
WORKSPACE_TYPE = "KREA2_WORKSPACE"
RIG_TYPE = "RN_RIG" # a RedNode Rig Model's record (custom_rig.py)
CUSTOM_SENTINEL = "custom (live)"
# the Latent tab's preset canvas sizes; the JS list mirrors this order
LATENT_PRESETS = [(1024, 1024), (832, 1216), (1216, 832), (896, 1152), (1152, 896),
(768, 1344), (1344, 768)]
# tabs whose caption can run through the built-in Prompt Converter. The converter
# is plain text work (gender, medium, the NSFW swaps, custom rules, the authority
# lock), so anything that produces a prompt can use one.
CONVERTER_TABS = ("i2i", "subject", "scene")
# ---------------------------------------------------------------------------
# VRAM tiers. Half these dials cost memory in ways nothing on screen explains: the
# fidelity pair builds an L x L attention bias that grows with resolution SQUARED,
# the likeness caps feed more vision tokens, and resize multiplies both. A user who
# drags three of them up has no way to know which one cost the 4 GB.
#
# So: pick a tier and the numbers are held to what that tier can take. "high" is
# free range and stays the default, because capping someone who never asked would
# be its own surprise.
VRAM_TIERS = ("low", "medium", "high")
# The shape a painted region is grown toward. Defined HERE rather than beside the
# geometry in paint_render, because paint_render imports this module and the reverse
# would be a cycle. paint_render re-exports it, so there is still one list.
REGION_SHAPES = ("auto", "square", "landscape", "portrait")
# How many times one Generate may run the same low denoise over its own result. Ten
# because past that a chain has stopped settling a shape and started eating it, and
# because a mistyped 40 is twenty minutes of sampling nobody asked for. Same reason
# REGION_SHAPES lives here: paint_render imports this module, not the other way.
PAINT_PASS_MAX = 10
VRAM_CAPS = {
"low": {
"resize": 1024,
"reference_fidelity": 2.5, "scene_fidelity": 1.5,
"likeness_vs_obedience": 768, "subject_likeness_px": 1024,
"style_detail_px": 384, "latent_scale": 1.25, "latent_batch": 2,
"moodboard_refs": 3,
},
"medium": {
"resize": 1536,
"reference_fidelity": 6.0, "scene_fidelity": 4.0,
"likeness_vs_obedience": 1536, "subject_likeness_px": 2048,
"style_detail_px": 768, "latent_scale": 1.6, "latent_batch": 4,
"moodboard_refs": 6,
},
"high": {},
}
def rerun_reasons(cfg):
"""Why this node cannot be cached between queues, in your own terms.
A node that re-runs every time re-captions every time, and from the console
that just looks like the caption cache failing. These are the switches that
cause it, so the answer is on screen instead of being guesswork.
"""
why = []
for name in IMAGE_TABS:
t = cfg["tabs"].get(name) or {}
if t.get("random") and t.get("on") and len(t.get("images") or []) > 1:
why.append(f"the {name} tab's dice is on, so it picks a different image "
"each queue")
a = t.get("auto") or {}
if a.get("on") and t.get("on") and not a.get("fixed", True):
why.append(f"the {name} tab's auto prompt is set to FRESH")
if cfg["latent"]["on"] and cfg["latent"]["random"]:
why.append("the Latent tab's dice is on")
return why
def vram_report(cfg, tabs, post_cfg):
"""Name what is actually spending VRAM this run, loudest first.
Nothing on screen tells you that fidelity 4.0 at resize 1536 costs several
times what fidelity 4.0 at 1024 does, so the console says it out loud instead
of leaving people to guess which knob emptied their card.
"""
d = cfg["dials"]
px = cfg["resize"] or 1024
heavy = []
if d.get("reference_fidelity", 1.0) != 1.0 or d.get("scene_fidelity", 1.0) != 1.0:
# the bias matrix is L x L and L grows with resolution SQUARED
scale = (px / 1024.0) ** 2
heavy.append(f"fidelity dials build an attention bias matrix "
f"(~{scale:.1f}x the 1024 cost at resize {px})")
if d.get("isolate_refs"):
heavy.append("isolate refs adds a second bias matrix")
grounding = max(int(d.get("likeness_vs_obedience", 0) or 0),
int(d.get("subject_likeness_px", 0) or 0))
if grounding > 1024:
heavy.append(f"likeness {grounding}px feeds extra vision tokens")
if int(d.get("style_detail_px", 0) or 0) > 512:
heavy.append(f"style detail {int(d['style_detail_px'])}px enlarges every ref")
mb = tabs.get("moodboard", {})
if mb.get("on") and isinstance(mb.get("sel"), list) and len(mb["sel"]) > 2:
heavy.append(f"{len(mb['sel'])} moodboard refs are encoded together")
engines = []
for name in AUTO_TABS:
a = tabs.get(name, {}).get("auto") or {}
if not (a.get("on") and tabs[name].get("on")):
continue
for eng, key in (("Ollama", "ollama"), ("WD14", "wd14"), ("JoyCaption", "joy"),
("QwenVL", "qwen")):
if a.get(key) and eng not in engines:
engines.append(eng)
if engines:
heavy.append(f"{', '.join(engines)} each load a model to caption")
post_on = sorted(postprocess.active_fx(post_cfg))
if any(n in postprocess.DEPTH_EFFECTS for n in post_on):
heavy.append("depth of field / haze load a depth estimator")
if d.get("boosts_off"):
# the master off switch holds both fidelity dials at 1.0 or below downstream;
# a pull above 1 never happens, a loosened one still builds the matrix
if all(d.get(k, 1.0) >= 1.0 for k in ("reference_fidelity", "scene_fidelity")):
heavy = [x for x in heavy if "bias matrix" not in x]
heavy.insert(0, "boosts off: no attention bias matrix is built")
else:
heavy.insert(0, "boosts off: no extra pull, but a fidelity below 1.0 still "
"builds the bias matrix to loosen it")
tier = cfg.get("vram_tier", "high")
if heavy:
print(f"[RedNode Workspace] VRAM ({tier} tier): " + "; ".join(heavy), flush=True)
else:
print(f"[RedNode Workspace] VRAM ({tier} tier): nothing expensive is on",
flush=True)
def cap_for(tier, key):
return VRAM_CAPS.get(tier, {}).get(key)
def _cap(tier, key, value, what, notes):
"""Hold `value` to the tier's ceiling, recording anything that was pulled down."""
ceiling = cap_for(tier, key)
if ceiling is None or value is None or value <= ceiling:
return value
notes.append(f"{what} {value:g} -> {ceiling:g}")
return ceiling
# the managed folder inside ComfyUI/input: panel uploads land here (per-tab subfolders),
# and images in here get caption sidecars written next to them
MANAGED_SUBFOLDER = "rednode"
def _managed(entry):
"""A panel upload: under the managed subfolder by name AND by where it resolves,
so "rednode/../x" is not one."""
if not str(entry).replace("\\", "/").startswith(MANAGED_SUBFOLDER + "/"):
return False
bare, base = _entry_base(entry)
return _inside_dir(os.path.join(base, MANAGED_SUBFOLDER), base) \
and _inside_dir(os.path.join(base, bare), os.path.join(base, MANAGED_SUBFOLDER))
# every key the Settings dict carries, at the Settings node's own defaults — the studio
# indexes some of these unconditionally, so the workspace must always send a full dict
SETTINGS_DEFAULTS = dict(
transfer="style", reference_processing="full image", style_directive=True,
hide_style_refs=True, style_detail_px=384, likeness_vs_obedience=768,
reference_fidelity=2.5, scene_fidelity=1.0, fit_mode="fit",
identity_start=0.0, identity_end=1.0, isolate_refs=False, boost_blocks="all",
scene_start=0.0, scene_end=1.0,
subject_likeness_px=0, edit_mask_feather=2, picture_labels=False,
ref_t0_modulation=False, vision_system_prompt="", attention="auto",
)
# the dials the panel surfaces (name -> clamp range); everything else stays at default.
# style_strength is NOT a settings key: it is the studio's own widget, so it rides the
# bundle at the top level instead of inside the settings dict.
DIALS = {
"style_strength": (0.0, 1.0),
"reference_fidelity": (0.0, 10.0),
"scene_fidelity": (0.0, 10.0),
"likeness_vs_obedience": (0, 2048),
"subject_likeness_px": (0, 4096),
"style_detail_px": (128, 1536),
"edit_mask_feather": (0, 32),
"identity_start": (0.0, 1.0),
"identity_end": (0.0, 1.0),
"scene_start": (0.0, 1.0),
"scene_end": (0.0, 1.0),
}
# boolean dials, surfaced as ON/OFF switches in the dial sections
BOOL_DIALS = ("hide_style_refs", "style_directive", "isolate_refs",
"picture_labels", "ref_t0_modulation", "boosts_off",
"caption_passthrough", "echo_prompts")
# choice dials: value must be one of the listed options or it is dropped
CHOICE_DIALS = {
"transfer": ["style", "subject"],
"reference_processing": ["full image", "quadrant crops (2x2)", "fine tiles (4x4)"],
"fit_mode": ["fit", "crop (legacy)"],
"boost_blocks": ["all", "early", "mid", "late"],
"attention": ["auto", "default", "pytorch"],
}
# free-text dials (the vision system prompt); passed through as-is
TEXT_DIALS = ("vision_system_prompt",)
# vision system prompts shipped with the pack. They change how the encoder READS the
# references; the names are what the Advanced tab's picker shows. User-saved prompts
# live beside them and may not reuse these names.
VISION_PROMPTS = {
"Style extract": (
"Describe the artistic style, color palette, lighting, texture and rendering "
"technique of the reference images in detail. Ignore their subjects, people and "
"composition entirely."),
"Identity lock": (
"Describe the person's face, hair, eyes and distinguishing features in precise "
"detail. Treat clothing and background as unimportant."),
"Anime to real": (
"Describe the person's identity, face, hair and clothing as a real human being. "
"Ignore the illustration style completely."),
"Real to anime": (
"Describe the person and scene as stylized anime artwork. Focus on shapes, hair "
"color and outfit rather than photographic detail."),
"Garment focus": (
"Describe the clothing and accessories in the reference images in full "
"construction detail: fabric, pattern, cut, seams and fit. The person wearing "
"them is unimportant."),
}
# CAPTION INSTRUCTIONS: what Ollama is TOLD to write about an image. Distinct from
# VISION_PROMPTS above, which change how the Krea 2 encoder READS the references.
# These stand in for autoprompt.SYSTEM_PROMPTS, which was reachable only by editing
# the source. Ollama alone reads these: the local captioners answer worse when handed
# wording they were not trained on, so they keep the mode's own.
# Each entry is BOTH halves of the Ollama call: the system prompt and the question.
# Plenty of vision models take their orders from the question and skim the system
# prompt, so a preset that set only one half would work on some models and not others.
CAPTION_INSTRUCTIONS = {
"Booru tags only": {
"system": (
"Describe the image as a flat comma-separated list of booru-style tags only. "
"No sentences, no preamble, no explanation."),
"question": "List the tags for this image."},
"One short sentence": {
"system": (
"Describe the image in a single short sentence of no more than twenty words. "
"Answer with the sentence only, no preamble."),
"question": "Describe this image in one short sentence."},
"Camera and lighting": {
"system": (
"Describe only the camera work and lighting: shot type, angle, lens character, "
"depth of field, light direction, quality and colour temperature. Do not "
"describe the subject's identity or the story. Answer with the description "
"only, no preamble."),
"question": "Describe the camera work and the lighting."},
"Clothing only": {
"system": (
"Describe only the clothing and accessories in full construction detail: "
"garment type, fabric, pattern, cut, fit and how it sits on the body. Do not "
"describe the face, the background or the lighting. Answer with the "
"description only, no preamble."),
"question": "Describe the clothing and accessories."},
"No people": {
"system": (
"Describe the setting, objects, lighting and composition. Refer to any people "
"only as 'a person' or 'people' with no description of their appearance. "
"Answer with the description only, no preamble."),
"question": "Describe the setting and the composition."},
}
def _instruction_pair(value):
"""One preset as {system, question}. Tolerates the plain string the first build of
this feature saved, so nobody's saved wordings are lost to the format change."""
if isinstance(value, str):
return {"system": value, "question": ""}
if isinstance(value, dict):
return {"system": str(value.get("system") or ""),
"question": str(value.get("question") or "")}
return {"system": "", "question": ""}
def _instructions_path(make=False):
override = _env("KREA2RN_CAPTION_INSTRUCTIONS")
if override:
return override
try:
base = os.path.join(folder_paths.get_user_directory(), "default", "rednode-krea2")
except Exception:
base = os.path.join(os.path.dirname(__file__), "user_data")
if make:
os.makedirs(base, exist_ok=True)
return os.path.join(base, "caption_instructions.json")
def load_caption_instructions():
"""Shipped instructions plus your saved ones; shipped names always win.
Every entry comes back as {system, question} whatever shape it was stored in."""
out = {}
try:
with open(_instructions_path(), encoding="utf-8") as f:
data = json.load(f)
for name, value in (data.get("prompts") or {}).items():
pair = _instruction_pair(value)
if pair["system"].strip() or pair["question"].strip():
out[str(name)] = pair
except (OSError, ValueError):
pass
out.update({k: _instruction_pair(v) for k, v in CAPTION_INSTRUCTIONS.items()})
return out
def save_caption_instruction(name, text, question=""):
name = str(name).strip()
if not name:
raise ValueError("give the instruction a name")
if name in CAPTION_INSTRUCTIONS:
raise ValueError(f"{name!r} ships with the pack and cannot be overwritten")
system = str(text or "")
question = str(question or "")
# either half alone is a usable preset: some models need only the question changed
if not system.strip() and not question.strip():
raise ValueError("type an instruction or a question first")
user = {}
try:
with open(_instructions_path(), encoding="utf-8") as f:
user = json.load(f).get("prompts") or {}
except (OSError, ValueError):
pass
user[name] = {"system": system, "question": question}
with open(_instructions_path(make=True), "w", encoding="utf-8") as f:
json.dump({"version": 2, "prompts": user}, f, indent=2, ensure_ascii=False)
return name
def delete_caption_instruction(name):
name = str(name).strip()
if name in CAPTION_INSTRUCTIONS:
raise ValueError(f"{name!r} ships with the pack and cannot be deleted")
user = {}
try:
with open(_instructions_path(), encoding="utf-8") as f:
user = json.load(f).get("prompts") or {}
except (OSError, ValueError):
pass
user.pop(name, None)
with open(_instructions_path(make=True), "w", encoding="utf-8") as f:
json.dump({"version": 1, "prompts": user}, f, indent=2, ensure_ascii=False)
def _vision_path(make=False):
override = _env("KREA2RN_VISION_PROMPTS")
if override:
return override
try:
base = os.path.join(folder_paths.get_user_directory(), "default", "rednode-krea2")
except Exception:
base = os.path.join(os.path.dirname(__file__), "user_data")
if make:
os.makedirs(base, exist_ok=True)
return os.path.join(base, "vision_prompts.json")
def load_vision_prompts():
"""Shipped prompts plus the user's saved ones; shipped names always win."""
out = {}
try:
with open(_vision_path(), encoding="utf-8") as f:
data = json.load(f)
for name, text in (data.get("prompts") or {}).items():
if isinstance(text, str) and text.strip():
out[str(name)] = text
except (OSError, ValueError):
pass
out.update(VISION_PROMPTS)
return out
def save_vision_prompt(name, text):
name = str(name).strip()
if not name:
raise ValueError("give the prompt a name")
if name in VISION_PROMPTS:
raise ValueError(f"{name!r} ships with the pack and cannot be overwritten")
if not isinstance(text, str) or not text.strip():
raise ValueError("the prompt text is empty")
user = {}
try:
with open(_vision_path(), encoding="utf-8") as f:
user = json.load(f).get("prompts") or {}
except (OSError, ValueError):
pass
user[name] = text
with open(_vision_path(make=True), "w", encoding="utf-8") as f:
json.dump({"version": 1, "prompts": user}, f, indent=2, ensure_ascii=False)
return name
def delete_vision_prompt(name):
name = str(name).strip()
if name in VISION_PROMPTS:
raise ValueError(f"{name!r} ships with the pack and cannot be deleted")
user = {}
try:
with open(_vision_path(), encoding="utf-8") as f:
user = json.load(f).get("prompts") or {}
except (OSError, ValueError):
pass
user.pop(name, None)
with open(_vision_path(make=True), "w", encoding="utf-8") as f:
json.dump({"version": 1, "prompts": user}, f, indent=2, ensure_ascii=False)
# THE WORKSPACE'S OWN STAGE TAPS: the moments it can photograph for the Stage View,
# in the order they happen. Off unless switched on (the STAGES sub-tab).
# the moments a run can photograph for the Stages strip, in the order they happen
TAP_POINTS = ("refs", "source", "editor", "reangle", "realism", "swap", "render",
"passes", "post", "final")
# the list a workflow saved before the Editor, Realism, Render and Post points existed
# carries: it meant "everything", so it still does
_OLD_TAP_ALL = ("refs", "source", "reangle", "swap", "passes", "final")
TAP_PX = (320, 512, 768, 1024, 1536, 0)
# the tab names the Run tab's log uses
RUN_TAB_NAMES = {"subject": "Subject", "scene": "Scene", "moodboard": "Moodboard",
"i2i": "Img2Img", "text_style": "Image to text Style",
"text_subject": "Image to text Subject", "text_scene": "Image to text Scene"}
# IMAGE TO TEXT, under Img2Img's Auto prompt: galleries that are only ever captioned.
# Their pictures never reach the model, so they work on any rig.
TEXT_TABS = ("text_style", "text_subject", "text_scene")
# swap_ref: the Swap page's own gallery, read only when Swap's reference is "own"
# editor_src: the Editor tab's source, what Re-angle, Realism and Swap edit
# ai: the AI tab's own gallery, for captioning a picture without turning anything on
IMAGE_TABS = ("i2i", "subject", "subject2", "subject3", "scene", "moodboard",
"swap_ref", "editor_src", "ai") + TEXT_TABS
# the tabs with an auto prompt, and the ones whose selection is a list
AUTO_TABS = ("subject", "scene", "moodboard", "i2i", "ai") + TEXT_TABS
# Inject into, stored as "follow the rig": the caption joins whichever row this
# rig renders, so switching rigs moves it with them instead of leaving it aimed
# at another rig's words. The panel writes this; prompt_row_for resolves it.
AUTO_ROW = "(auto)"
MULTI_TABS = ("moodboard",) + TEXT_TABS
def _presets_path(make=False):
override = _env("KREA2RN_WORKSPACE_PRESETS")
if override:
return override
try:
base = os.path.join(folder_paths.get_user_directory(), "default", "rednode-krea2")
except Exception:
base = os.path.join(os.path.dirname(__file__), "user_data")
if make:
os.makedirs(base, exist_ok=True)
return os.path.join(base, "workspace_presets.json")
def load_presets():
"""{preset name: full workspace config dict}. Galleries are filenames, so presets are
per-machine — which is what a working set of reference images is anyway."""
try:
with open(_presets_path(), encoding="utf-8") as f:
data = json.load(f)
out = {}
for name, cfg in (data.get("presets") or {}).items():
if isinstance(cfg, dict):
out[str(name)] = cfg
return out
except (OSError, ValueError):
return {}
def save_preset(name, config):
name = str(name).strip()
if not name:
raise ValueError("give the preset a name")
if name == CUSTOM_SENTINEL:
raise ValueError(f"{CUSTOM_SENTINEL!r} is reserved")
if not isinstance(config, dict):
raise ValueError("a workspace preset stores the whole config object")
presets = load_presets()
presets[name] = config
with open(_presets_path(make=True), "w", encoding="utf-8") as f:
json.dump({"version": 1, "presets": presets}, f, indent=2, ensure_ascii=False)
return name
def delete_preset(name):
presets = load_presets()
presets.pop(str(name), None)
with open(_presets_path(make=True), "w", encoding="utf-8") as f:
json.dump({"version": 1, "presets": presets}, f, indent=2, ensure_ascii=False)
# The clamp notice, printed once per change instead of once per parse. parse_config
# runs more than once per queue (IS_CHANGED and build both call it), so an unchanged
# ceiling used to say the same thing two or three times per run.
_LAST_HELD = None
def _announce_held(tier, held):
global _LAST_HELD
if not held:
_LAST_HELD = None # a clean parse re-arms the notice
return
msg = (f"[RedNode Workspace] {tier} VRAM tier held back: {', '.join(held)}. "
"Switch the tier in the footer to lift the ceiling.")
if msg != _LAST_HELD:
_LAST_HELD = msg
print(msg, flush=True)
# What a Moodboard picture gives its auto prompt, any mix of the three, captioned
# one read at a time and joined in this order
MOOD_READS = ("style", "subject", "scene_action")
# the Frame slots an auto prompt can join, and where each Moodboard read goes unless
# told otherwise
INJECT_SLOTS = ("style", "subject", "surroundings", "light_and_colour", "prompt")
MOOD_SLOT_DEFAULTS = {"style": "style", "subject": "subject", "scene_action": "surroundings"}
def mood_reads(meta, default="style"):
"""A Moodboard picture's reads; a picture never set takes the tab's mode."""
r = meta.get("reads") if isinstance(meta, dict) else None
if isinstance(r, list):
return [m for m in MOOD_READS if m in r]
return [default if default in MOOD_READS else "style"]
def _normalise_auto(auto_in, default_mode):
"""Return the shared per-image auto-prompt contract."""
auto_in = auto_in if isinstance(auto_in, dict) else {}
mode = str(auto_in.get("mode") or default_mode)
if mode not in autoprompt.SYSTEM_PROMPTS:
mode = default_mode
return {
"on": bool(auto_in.get("on")),
"ollama": bool(auto_in.get("ollama", True)),
"wd14": bool(auto_in.get("wd14", True)),
"mode": mode,
"combine": "blend" if auto_in.get("combine") == "blend" else "append",
"joy": bool(auto_in.get("joy")),
"qwen": bool(auto_in.get("qwen")),
"clipgen": bool(auto_in.get("clipgen")),
"florence": bool(auto_in.get("florence")),
"length": max(0, min(300, int(auto_in.get("length", 0))))
if isinstance(auto_in.get("length"), (int, float)) else 0,
# fixed (default): the same image reuses the cached prompt. Unfixed
# re-runs the LLM every queue for fresh wording each run.
"fixed": bool(auto_in.get("fixed", True)),
# the Subject tab's: rewrite the prompt row with the named people's captions
"rewrite": bool(auto_in.get("rewrite")),
# Injection: this tab's caption lands in a named Prompts-tab row, into one
# Frame slot, automatically at queue time. Empty = the caption only rides
# its own output socket, exactly as before.
"inject_row": str(auto_in.get("inject_row") or ""),
# before or after the words already typed in that slot
"inject_pos": "before" if auto_in.get("inject_pos") == "before" else "after",
"inject_slot": (str(auto_in.get("inject_slot"))
if auto_in.get("inject_slot") in INJECT_SLOTS
else "subject"),
# the Moodboard's: each read joins its own Frame slot
"inject_slots": {
m: (str((auto_in.get("inject_slots") or {}).get(m))
if isinstance(auto_in.get("inject_slots"), dict)
and (auto_in.get("inject_slots") or {}).get(m) in INJECT_SLOTS
else MOOD_SLOT_DEFAULTS[m])
for m in MOOD_READS},
}
def _file_gb(folders, name):
"""A model file's size in GB, looked up in the first folder that has it."""
if not name:
return 0.0
try:
import folder_paths
except Exception:
return 0.0
for f in folders:
try:
p = folder_paths.get_full_path(f, name)
except Exception:
p = None
if p and os.path.isfile(p):
return os.path.getsize(p) / 1024 ** 3
return 0.0
def _vosr2_gb(bundle):
"""A VOSR 2.0 bundle's size in GB. It is a FOLDER (DiT + Qwen VAE + DINOv2),
not a single file, so _file_gb cannot see it. Falls back to the measured
size of the one published bundle when the folder is not on disk yet, since
the pass would download it on first run rather than fail."""
try:
import folder_paths
root = os.path.join(folder_paths.models_dir, "vosr2", bundle or "VOSR2")
if os.path.isdir(root):
total = 0
for dirpath, dirnames, names in os.walk(root):
if ".cache" in dirpath:
continue
for n in names:
try:
total += os.path.getsize(os.path.join(dirpath, n))
except OSError:
pass
if total:
return total / 1024 ** 3
except Exception:
pass
return 6.5
# THE PASS KINDS THAT LOAD NO RIG: their own loaders do the loading, so the
# rig on the card is not their cost. Both upscalers, and the estimate and the
# run must agree on the set (refine_pipeline.UPSCALERS is the run's copy).
UPSCALE_KINDS = ("upscale", "vosr2")
# rough working memory for a diffusion transformer at batch 1, per megapixel sampled
WORK_GB_PER_MP = 1.8
# the Qwen edit model (Swap, Re-angle) per megapixel of each picture it reads
EDIT_WORK_GB_PER_MP = 3.0
# the widgets a loader names its file in, per socket of a RedNode Rig Model node
RIG_FILE_KEYS = {
"model": ("unet_name", "ckpt_name"),
"clip": ("clip_name", "clip_name1", "clip_name2", "clip_name3", "ckpt_name"),
"vae": ("vae_name", "ckpt_name"),
}
def _add_rig_file(rec, key, value):
if key == "ckpt_name":
rec["checkpoint"] = value
elif key == "unet_name":
rec.setdefault("unet", value)
elif key == "vae_name":
rec.setdefault("vae", value)
elif value not in rec.setdefault("clips", []):
rec["clips"].append(value)
def graph_rig_files(prompt):
"""{rig name: {unet, checkpoint, clips, vae}} for "Your own nodes" rigs: the
files named by the loaders wired into each RedNode Rig Model node. The Models
tab holds no file names for such a rig, so its size was invisible."""
out = {}
if not isinstance(prompt, dict):
return out
for n in prompt.values():
if not isinstance(n, dict) or n.get("class_type") != "RedNodeRigModel":
continue
ins = n.get("inputs") or {}
rig = (ins.get("rig").strip() if isinstance(ins.get("rig"), str) else "") or "My rig"
rec = out.setdefault(rig, {})
for sock, keys in RIG_FILE_KEYS.items():
queue, seen = [ins.get(sock)], set()
while queue and len(seen) < 40:
link = queue.pop(0)
if not (isinstance(link, list) and len(link) == 2):
continue
nid = str(link[0])
up = prompt.get(nid)
if nid in seen or not isinstance(up, dict):
continue
seen.add(nid)
uin = up.get("inputs") or {}
hits = [(k, uin[k]) for k in keys if isinstance(uin.get(k), str) and uin[k]]
if hits:
for k, v in hits:
_add_rig_file(rec, k, v)
continue
queue.extend(v for v in uin.values() if isinstance(v, list))
return out
def _edit_stage(cfg, render_px, render_batch, i2i_run):
"""(name, parts, total GB, working GB) for the Qwen edit engine when Swap or
Re-angle will run, else None. It loads after or before the render, so the
run's peak is the larger of the two stages, not their sum."""
it = cfg["tabs"]["i2i"]
sw = it.get("swap") or {}
ra = it.get("reangle") or {}
src_px = float(cfg["resize"] or 1024) ** 2 * 0.75
jobs = []
# a stage on the render runs whatever the pass mode; a source stage needs the
# pass (i2i_run already says no under Prompt only)
if ra.get("on"):
if ra.get("target") == "render":
jobs.append(("Re-angle", ra, render_px, render_batch, 1))
elif i2i_run:
jobs.append(("Re-angle", ra, src_px, 1, 1))
if sw.get("on"):
if sw.get("target") == "render":
jobs.append(("Swap", sw, render_px, render_batch, 2))
elif i2i_run:
jobs.append(("Swap", sw, src_px, 1, 2))
if not jobs:
return None
best = None
for name, sc, px, batch, pics in jobs:
parts = []
for label, folders, key in (
("Edit model", ("diffusion_models", "unet", "unet_gguf"), "unet"),
("Edit text encoder", ("text_encoders", "clip"), "clip"),
("Edit VAE", ("vae",), "vae")):
g = _file_gb(folders, sc.get(key))
if g:
parts.append(["%s (%s)" % (label, name), round(g, 1)])
work = EDIT_WORK_GB_PER_MP * (px / 1e6) * pics * batch
parts.append(["Edit working memory (%s, %.1f MP, %d pictures%s)"
% (name, px / 1e6, pics, ", batch of %d" % batch if batch > 1 else ""),
round(work, 1)])
total = sum(g for _n, g in parts)
if best is None or total > best[2]:
best = (name, parts, total, work)
return best
def vae_images(t):
"""A decode as IMAGE [N, H, W, C]. A video VAE (Krea 2's Wan) hands back
[batch, frames, H, W, C]; taking [0] kept the first picture of a batch."""
if t.ndim > 4:
t = t.reshape((-1,) + tuple(t.shape[-3:]))
# an RGBA VAE (Qwen Image 2.1) decodes four channels; every stage after the
# decode blends and saves RGB, so the alpha stops here
if t.ndim == 4 and t.shape[-1] > 3:
t = t[..., :3]
return t
def estimate_vram(cfg, rig_files=None):
"""{"peak": GB, "need": GB, "parts": [[name, GB], ...], "work": GB,
"stages": [[name, GB]]} for the Workspace's own run, from the model files it
will load and the size it works at. "peak" is everything resident at once;
"need" is what cannot leave the card while a stage samples (vram_hold.decide). Rough on purpose: it decides whether Auto holds, and it is shown so
the number is not a mystery. `rig_files` names the files of "Your own nodes"
rigs (graph_rig_files). None when the Workspace does not render (external
sampler, no rig)."""
rig_files = rig_files if isinstance(rig_files, dict) else {}
M = cfg["models"]
rigs = M.get("rigs") or []
if not rigs or M.get("sampler_mode") != "internal":
return None
active = rigs[min(M.get("active", 0), len(rigs) - 1)]
tabs = cfg["tabs"]
it = tabs["i2i"]
i2i_run = it["on"] and not it["prompt_only"] and (it["images"] or it["canvas"] != "gallery")
run = it if i2i_run else cfg["latent"]
names = [active["name"]] + [n for n in (run.get("pass_rig") or []) if n] \
if run.get("rig_custom") else [active["name"]]
used = [r for r in rigs if r["name"] in names] or [active]
def files(r):
# a rig of your own nodes names its files in the workflow, not on the tab
if r.get("kind") == "node":
got = rig_files.get(str(r.get("node") or r.get("name") or "").strip()) or {}
return {"unet": got.get("unet") or r.get("unet"),
"checkpoint": got.get("checkpoint") or r.get("checkpoint"),
"clips": got.get("clips") or ([r["clip"]] if r.get("clip") else []),
"vae": got.get("vae") or r.get("vae")}
return {"unet": r.get("unet"), "checkpoint": r.get("checkpoint"),
"clips": [r["clip"]] if r.get("clip") else [], "vae": r.get("vae")}
def model_gb(r):
f = files(r)
return (_file_gb(("diffusion_models", "unet", "unet_gguf"), f["unet"])
or _file_gb(("checkpoints",), f["checkpoint"]))
parts = []
mg = max((model_gb(r), r["name"]) for r in used)
if mg[0]:
parts.append(["Model (%s)" % mg[1], round(mg[0], 1)])
af = files(active)
te = sum(_file_gb(("text_encoders", "clip", "clip_gguf"), c) for c in af["clips"])
if te:
parts.append(["Text encoder", round(te, 1)])
vae = _file_gb(("vae",), af["vae"])
if vae:
parts.append(["VAE", round(vae, 1)])
# the size it works at: the Latent tab's canvas, or the resize for a source
if i2i_run:
edge = cfg["resize"] or 1024
px = edge * edge * 0.75
else:
px = cfg["latent"]["w"] * cfg["latent"]["h"]
scales = [float(x) for x in (run.get("pass_scale") or []) if x] \
if run.get("scale_custom") else [float(run.get("scale") or 1.0)]
px *= max([1.0] + scales) ** 2
batch = max(1, int(cfg["latent"].get("batch") or 1)) if not i2i_run else 1
krea2 = active.get("clip_type") == "krea2"
nrefs = 0
if krea2:
nrefs = sum(1 for n in ("subject", "scene")
if tabs[n]["on"] and tabs[n]["images"]
and not (n == "scene" and tabs[n].get("words_only")))
nrefs += len(tabs["subject"].get("extra_sel") or [])
work = WORK_GB_PER_MP * (px / 1e6) * batch * (1 + 0.5 * nrefs)
parts.append(["Working memory (%.1f MP%s%s)"
% (px / 1e6, ", batch of %d" % batch if batch > 1 else "",
", %d refs" % nrefs if nrefs else ""), round(work, 1)])
d = cfg["dials"]
boosted = krea2 and nrefs and cfg.get("use_dials") and any(
abs(float(d.get(k, 1.0)) - 1.0) > 1e-6 for k in ("reference_fidelity", "scene_fidelity"))
if boosted:
tokens = px / 256 * (1 + nrefs)
parts.append(["Fidelity boost matrix", round(tokens * tokens * 4 / 1024 ** 3, 1)])
render = round(sum(g for _n, g in parts), 1)
render_work = sum(g for n, g in parts if "Working memory" in n or "boost matrix" in n)
def need_of(stage_parts, total):
# WHAT CANNOT LEAVE THE CARD while the stage samples. The text encoder has
# done its work by then, SAM3 has found its target and the upscale model has
# grown the frame: ComfyUI drops all three by itself when the card fills, so
# they are in "peak" (everything resident) and not in "need". A pass on the
# rig already on the card carries that rig's text encoder inside one part.
drop = sum(g for n, g in stage_parts
if str(n).startswith(("Text encoder", "Edit text encoder", "SAM3",
"Upscale model")))
if any(str(n).startswith("Rig on the card") for n, _g in stage_parts):
drop += te
return round(max(0.0, total - drop), 1)
out = {"peak": render, "parts": parts, "work": round(render_work, 1),
"need": need_of(parts, render), "stages": [["Render", render]]}
def rig_cost(name):
# (model, text encoder, VAE) in GB for a rig named on a Detailer pass
r = next((x for x in rigs if x.get("name") == name), None)
if not r:
return (0.0, 0.0, 0.0)
f = files(r)
return (model_gb(r),
sum(_file_gb(("text_encoders", "clip", "clip_gguf"), c) for c in f["clips"]),
_file_gb(("vae",), f["vae"]))
# the stages after the render, each its own peak: the edit engine for a
# Swap or Re-angle, and the Detailer's passes with their own loads
later = [_edit_stage(cfg, px, batch, i2i_run),
_detailer_stage(cfg, (mg[0] or 0.0) + te + vae, px, rig_cost)]
for st in later:
if not st:
continue
name, eparts, etotal, ework = st
out["parts"] = out["parts"] + eparts
out["stages"].append([name, round(etotal, 1)])
out["peak"] = round(max(out["peak"], etotal), 1)
out["work"] = round(max(out["work"], ework), 1)
out["need"] = round(max(out["need"], need_of(eparts, etotal)), 1)
return out
def _detailer_stage(cfg, base_gb, render_px, rig_cost=None):
"""(name, parts, total GB, working GB) for the Detailer's passes when the
Workspace runs them, else None. Each pass is costed on its own and the
heaviest wins, since they run one after another. A pass keeps the rig's
model, text encoder and VAE on the card (base_gb) unless it frees VRAM
first; on top of that a detailer pass loads the SAM3 checkpoint, a tiled
pass its upscale model, and a SeedVR2 pass its DiT and VAE plus working
memory at the size it writes, which is where a 4K pass becomes the run's
real peak. A pass on ANOTHER rig loads that rig's files as well, on top of
the main rig still on the card, which is how two models end up resident at
once; rig_cost(name) gives (model, text encoder, VAE) in GB for a rig."""
if not cfg.get("detailer_on"):
return None
raw = cfg.get("detailer") if isinstance(cfg.get("detailer"), dict) else {}
stages = [s for s in (raw.get("stages") or []) if isinstance(s, dict)
and s.get("on", True)
and s.get("type") in ("sampler", "detailer", "upscale", "usdu", "vosr2",
"realism")]
# a mask detailer on Re-render loads the conversion's files, not a rig: it
# costs what a Re-render pass costs
stages = [dict(s, type="realism") if (s.get("type") == "detailer"
and s.get("engine") == "rerender") else s
for s in stages]
if not stages:
return None
from .refine_pipeline import UPSCALE_SIZES
best = None
for i, s in enumerate(stages):
kind = s.get("type")
label = {"sampler": "Sampler pass", "detailer": "Detailer pass",
"upscale": "SeedVR2 pass", "usdu": "Tiled upscale",
"vosr2": "VOSR2 pass", "realism": "Re-render pass"}[kind]
parts = []
other = str(s.get("rig") or "").strip()
active_name = str((cfg["models"].get("rigs") or [{}])[min(cfg["models"].get("active", 0),
max(0, len(cfg["models"].get("rigs") or []) - 1))].get("name") or "")
if other and other != active_name and rig_cost and kind not in UPSCALE_KINDS:
# A PASS ON ANOTHER RIG NEEDS THAT RIG, NOT BOTH. ComfyUI evicts the
# main model when this one wants the room, so the two are never
# summed; counting them together read tens of GB over anything the
# chart ever showed.
om, ot, ov = rig_cost(other)
if om:
parts.append(["Model (%s, %s %d)" % (other, label, i + 1), round(om, 1)])
if ot:
parts.append(["Text encoder (%s, %s %d)" % (other, label, i + 1), round(ot, 1)])
if ov:
parts.append(["VAE (%s, %s %d)" % (other, label, i + 1), round(ov, 1)])
elif kind not in UPSCALE_KINDS and not s.get("free_vram"):
parts.append(["Rig on the card (%s %d)" % (label, i + 1), round(base_gb, 1)])
if kind == "detailer":
g = _file_gb(("sam3",), str(s.get("sam_model") or "sam3.pt"))
if g:
parts.append(["SAM3 (%s %d)" % (label, i + 1), round(g, 1)])
if kind == "usdu":
g = _file_gb(("upscale_models",), str(s.get("usdu_model") or ""))
if g:
parts.append(["Upscale model (%s %d)" % (label, i + 1), round(g, 1)])
if kind == "upscale":
g = _file_gb(("seedvr2",), str(s.get("dit_model") or ""))
if g:
# blocks swapped to the CPU are not on the card: by default all
# 36 are, leaving roughly a tenth of the file resident
try:
swapped = max(0, min(36, int(s.get("blocks_to_swap", 36))))
except (TypeError, ValueError):
swapped = 36
g = g * max(0.1, (36 - swapped) / 36.0)
parts.append(["SeedVR2 model on the card (%s %d)" % (label, i + 1), round(g, 1)])
g = _file_gb(("seedvr2",), str(s.get("vae_model") or ""))
if g:
parts.append(["SeedVR2 VAE (%s %d)" % (label, i + 1), round(g, 1)])
if kind == "vosr2":
# the whole bundle goes to the card: no block swapping to discount,
# and force_full_load=True in the pack's loader means all of it
g = _vosr2_gb(str(s.get("vosr2_model") or ""))
if g:
parts.append(["VOSR2 bundle (%s %d)" % (label, i + 1), round(g, 1)])
# the size the pass works at: SeedVR2 writes its target size; a tiled
# pass one tile at a time; a sampler or detailer pass its crop or the
# picture as it arrives, grown by the pass's scale
if kind == "upscale":
px = float(UPSCALE_SIZES.get(str(s.get("size") or "1080p"), UPSCALE_SIZES["1080p"]))
if s.get("tiled", True) is not False:
# tiled encode and decode: a tile at a time, never the frame
try:
tile = max(64, min(4096, int(s.get("tile", 1024))))
except (TypeError, ValueError):
tile = 1024
px = min(px, float(tile * tile))
elif kind == "vosr2":
# VOSR2 tiles, which is why its measured peak barely moves between
# x2 and x4. A tile of 0 means no tiling, and then the cost follows
# the output, which is not knowable from the config; 1080p stands
# in for it so the estimate is not silently optimistic.
try:
tile = max(0, min(4096, int(s.get("vosr2_tile", 512))))
except (TypeError, ValueError):
tile = 512
px = float(tile * tile) if tile else float(UPSCALE_SIZES["1080p"])