diff --git a/calliope-backend/scripts/audit_reference_conversion.py b/calliope-backend/scripts/audit_reference_conversion.py index b7b5f182..34cb5882 100644 --- a/calliope-backend/scripts/audit_reference_conversion.py +++ b/calliope-backend/scripts/audit_reference_conversion.py @@ -21,6 +21,7 @@ except ModuleNotFoundError: from calliope.comfyui.companions import load_companions from calliope.comfyui.delivery_scope import exclusion_for +from calliope.comfyui.h3_core_reference import CORE_PROFILE from calliope.comfyui.serialization_reference import ( ASR_PROFILE, AUX_PROFILE, @@ -307,6 +308,7 @@ REFERENCE_PROFILES = ( *SCAIL_LOAD_PROFILES, GRID_PROFILE, H3_PROFILE, + CORE_PROFILE, ) @@ -601,6 +603,89 @@ def h3_field_evidence(source, prompt): return fields +def core_field_evidence(source): + """Node diagnostics only, including rejected layouts; never a partial prompt.""" + from calliope.comfyui.h3_core_reference import LAYOUTS, saved_values, serialize_node + + evidence = [] + links = { + e[0]: (i, e) + for i, e in enumerate(source.get("links", [])) + if isinstance(e, list) and len(e) == 6 + } + for i, node in enumerate(source.get("nodes", [])): + ct = node.get("type") + if ct not in LAYOUTS: + continue + fields, reasons = [], [] + try: + saved = saved_values(node) + except (ValueError, TypeError, KeyError, AttributeError) as exc: + saved = {} + reasons.append(str(exc)) + for name, value in saved.items(): + wi = LAYOUTS[ct].index(name) + fields.append( + { + "field": name, + "value": value, + "json_type": type(value).__name__, + "source_value_pointer": f"/nodes/{i}/widgets_values/{wi}", + "named_pointer": f"/nodes/{i}/widgets_values_named/{name}" + if name in (node.get("widgets_values_named") or {}) + else None, + } + ) + try: + serialize_node(node) + layout_accepted = True + except (ValueError, TypeError, KeyError, AttributeError) as exc: + layout_accepted = False + if str(exc) not in reasons: + reasons.append(str(exc)) + physical = [] + for si, socket in enumerate(node.get("inputs", [])): + entry = links.get(socket.get("link")) + if entry: + li, edge = entry + physical.append( + { + "input": socket.get("name"), + "socket_pointer": f"/nodes/{i}/inputs/{si}", + "link_pointer": f"/links/{li}", + "endpoint": [str(edge[1]), edge[2]], + "declared_type": edge[5], + "source_endpoint_only": True, + "upstream_type_in_public_profile": any( + n.get("id") == edge[1] and n.get("type") in LAYOUTS + for n in source.get("nodes", []) + ), + } + ) + evidence.append( + { + "node_id": str(node.get("id")), + "type": ct, + "pointer": f"/nodes/{i}", + "layout_accepted": layout_accepted, + "saved_fields": fields, + "physical_input_evidence": physical, + "reasons": reasons, + "outputs_pointer": f"/nodes/{i}/outputs", + "outputs": node.get("outputs", []), + "workflow_only_control": { + "pointer": f"/nodes/{i}/widgets_values/1", + "value": "fixed", + } + if ct == "RandomNoise" and saved + else None, + "contract_manifest": "h3-core-reference/sources.json", + "not_a_submittable_node_or_partial_prompt": True, + } + ) + return evidence + + def profile_attempt(source, profile): expected = { **STRUCTURE_PROFILES, @@ -608,6 +693,7 @@ def profile_attempt(source, profile): CASE04_PROFILE: "1.53.6", GRID_PROFILE: "1.41.20", H3_PROFILE: "1.53.10", + CORE_PROFILE: "1.53.10", **VHS_PROFILES, **SETGET_PROFILES, **VIDEOINFO_PROFILES, @@ -788,6 +874,23 @@ def profile_attempt(source, profile): if profile in VHS_PROFILES else "crop-split-reference/verified-facts.json" ) + if profile == CORE_PROFILE: + assumptions.update( + { + "reference_sources": [ + "h3-core-reference/sources.json", + "h3-reference/sources.json", + ], + "core_version": "0.33.0", + "core_commit": "2f35f4a08176d993cded35dac3332be4f7287f41", + "source_core_provider_version": "unknown_unless_explicitly_declared", + "reference_provider": "comfy-core", + "restoration_policy": "positional_when_named_absent_else_exact_typed_agreement", + "expressions": "opaque_strings_never_evaluated", + "primitive_float_bound": "conservative_32_64_bit_sys_maxsize_intersection", + "random_seed_bound": "core_uint64_intersect_JS_safe_integer", + } + ) if profile == H3_PROFILE: assumptions["h3_contract"] = "h3-reference/sources.json" assumptions["reference_sources"] = ["h3-reference/sources.json"] @@ -821,6 +924,8 @@ def profile_attempt(source, profile): and expected == "1.48.6" ): assumptions["missing_frontend_policy"] = "requires_explicit_1.48.6" + if profile == CORE_PROFILE: + assumptions["missing_frontend_policy"] = "explicit_1.53.10_reference_assumption" assumptions["missing_node_declarations"] = [ n["pointer"] for n in node_inventory( @@ -844,6 +949,7 @@ def profile_attempt(source, profile): PROFILE, AUX_PROFILE, PRIMITIVE_PROFILE, + CORE_PROFILE, *MEDIA_PROFILES, SEPARATION_PROFILE, *CROP_SPLIT_PROFILES, @@ -874,6 +980,11 @@ def profile_attempt(source, profile): else "serializer_or_structure_rejected", "issues": result.issues, "unresolved_boundaries": result.unresolved_boundaries, + **( + {"supported_node_evidence": core_field_evidence(source)} + if profile == CORE_PROFILE + else {} + ), **( {"virtual_resolutions": result.virtual_resolutions} if profile in (*SETGET_PROFILES, *VIDEOINFO_PROFILES, *SCAIL_LOAD_PROFILES) @@ -890,6 +1001,11 @@ def profile_attempt(source, profile): or "restored_saved_state_before_queue_hooks", "candidate_sha256": canonical_sha(result.prompt), "candidate_prompt": result.prompt, + **( + {"supported_node_evidence": core_field_evidence(source)} + if profile == CORE_PROFILE + else {} + ), **( {"virtual_resolutions": result.virtual_resolutions} if profile in (*SETGET_PROFILES, *VIDEOINFO_PROFILES, *SCAIL_LOAD_PROFILES) @@ -1016,7 +1132,9 @@ def audit_library(repo: Path, profiles=REFERENCE_PROFILES, *, baseline_profiles= } if baseline_profiles is None: excluded_profiles = ( - (H3_PROFILE,) + (CORE_PROFILE,) + if CORE_PROFILE in profiles + else (H3_PROFILE,) if H3_PROFILE in profiles else (GRID_PROFILE,) if GRID_PROFILE in profiles diff --git a/calliope-backend/src/calliope/comfyui/h3_core_reference.py b/calliope-backend/src/calliope/comfyui/h3_core_reference.py new file mode 100644 index 00000000..efc8deeb --- /dev/null +++ b/calliope-backend/src/calliope/comfyui/h3_core_reference.py @@ -0,0 +1,246 @@ +"""Six core0.33.0 saved-state contracts, under explicit frontend1.53.10 assumptions. + +Sources: docs/hel-892/h3-core-reference/sources.json. Never imports upstream, +evaluates expressions, computes dimensions or inspects a target installation. +""" + +from __future__ import annotations + +import math +from copy import deepcopy +from string import ascii_lowercase + +CORE_PROFILE = "comfy-frontend-1.53.10-core-0.33.0-h3-first-group-reference" +CORE_COMMIT = "2f35f4a08176d993cded35dac3332be4f7287f41" +LAYOUTS = { + "PrimitiveStringMultiline": ("value",), + "ResolutionSelector": ("aspect_ratio", "megapixels", "multiple"), + "ComfyMathExpression": ("expression",), + "PrimitiveFloat": ("value",), + "RandomNoise": ("noise_seed", "control_after_generate"), + "BasicScheduler": ("scheduler", "steps", "denoise"), +} +RATIOS = ( + "1:1 (Square)", + "2:3 (Portrait Photo)", + "3:2 (Photo)", + "3:4 (Portrait Standard)", + "4:3 (Standard)", + "9:16 (Portrait Widescreen)", + "16:9 (Widescreen)", + "21:9 (Ultrawide)", +) +SCHEDULERS = ( + "simple", + "sgm_uniform", + "karras", + "exponential", + "ddim_uniform", + "beta", + "normal", + "linear_quadratic", + "kl_optimal", +) +NUMERIC_UNION = "FLOAT,INT,BOOLEAN" +OVERRIDES = ( + "ue_properties", + "widget_ue_connectable", + "input_ue_unconnectable", + "ue_links", + "links_added_by_ue", + "widgets", + "serializeValue", + "comfyDynamic", + "serialize_widgets", + "fallbackWidgetsValuesNames", + "comfyClass", + "onNodeCreated", + "onConnectInput", + "onConnectionsChange", + "onInputAdded", + "onConfigure", + "onSerialize", + "getInputLink", + "resolveInput", + "resolveOutput", + "onExecute", + "isVirtualNode", + "applyToGraph", + "beforeQueued", + "afterQueued", +) + + +def definitions(): + """Public schemas only; no injected test helpers in this class set.""" + + def spec(required, outputs, optional=None): + return { + "input": { + "required": {k: [v] for k, v in required.items()}, + "optional": {k: [v] for k, v in (optional or {}).items()}, + }, + "output": outputs, + } + + return { + "PrimitiveStringMultiline": spec({"value": "STRING"}, ["STRING"]), + "ResolutionSelector": spec( + {"aspect_ratio": "COMBO", "megapixels": "FLOAT", "multiple": "INT"}, + ["INT", "INT"], + ), + "ComfyMathExpression": spec( + {"expression": "STRING", "values.a": NUMERIC_UNION}, + ["FLOAT", "INT", "BOOLEAN"], + {f"values.{c}": NUMERIC_UNION for c in ascii_lowercase[1:]}, + ), + "PrimitiveFloat": spec({"value": "FLOAT"}, ["FLOAT"]), + "RandomNoise": spec({"noise_seed": "INT"}, ["NOISE"]), + "BasicScheduler": spec( + {"model": "MODEL", "scheduler": "COMBO", "steps": "INT", "denoise": "FLOAT"}, + ["SIGMAS"], + ), + } + + +def check_overrides(container): + if any(k in container for k in OVERRIDES): + raise ValueError("第一组不解释UE或未知控件/恢复/执行覆盖") + + +def saved_values(node): + """Decode only proved widget order; no graph/slot validity claim here.""" + ct, props = node.get("type"), node.get("properties") or {} + if ct not in LAYOUTS: + raise ValueError("第一组只覆盖六类core节点") + for k, expected in (("cnr_id", "comfy-core"), ("ver", "0.33.0")): + if k in props and props[k] != expected: + raise ValueError("第一组提供方/core版本声明冲突;缺失仅为显式参考假设") + if "aux_id" in props: + raise ValueError("第一组不解释其它来源身份") + if type(node.get("mode", 0)) is not int or node.get("mode", 0) != 0: + raise ValueError("第一组仅正常mode=0") + check_overrides(node) + check_overrides(props) + layout, values = LAYOUTS[ct], node.get("widgets_values") + if not isinstance(values, list) or len(values) != len(layout): + raise ValueError("第一组控件保存数组缺项/多项") + if "widgets_values_named" in node: + named = node["widgets_values_named"] + if not isinstance(named, dict) or set(named) != set(layout): + raise ValueError("第一组具名保存缺项/多项") + if any(type(named[k]) is not type(v) or named[k] != v for k, v in zip(layout, values)): + raise ValueError("第一组具名/位置恢复冲突") + result = dict(zip(layout, values)) + + def number(name, kind, lo, hi): + value = result[name] + # Conservative typed intersection: never coerce bool, text or FLOAT into INT. + valid_type = type(value) is int if kind == "INT" else type(value) in (int, float) + if not valid_type or not lo <= value <= hi or not math.isfinite(value): + raise ValueError(f"第一组{name}数值类型/范围不符") + + if ct in ("PrimitiveStringMultiline", "ComfyMathExpression"): + if type(values[0]) is not str: + raise ValueError("第一组文本必须是原样字符串") + elif ct == "ResolutionSelector": + if result["aspect_ratio"] not in RATIOS: + raise ValueError("第一组aspect_ratio枚举不符") + number("megapixels", "FLOAT", 0.1, 16.0) + number("multiple", "INT", 8, 128) + elif ct == "PrimitiveFloat": + # Core uses platform-dependent sys.maxsize. Accept only the conservative + # 32/64-bit intersection; do not claim the target platform was observed. + number("value", "FLOAT", -(2**31 - 1), 2**31 - 1) + elif ct == "RandomNoise": + # JS Number cannot safely retain arbitrary 64-bit integers. Intersect + # core's uint64 bound with exact saved/restored numeric representation. + number("noise_seed", "INT", 0, 2**53 - 1) + if result.pop("control_after_generate") != "fixed": + raise ValueError("第一组seed只接受fixed;排队变值控制未证明") + elif ct == "BasicScheduler": + if result["scheduler"] not in SCHEDULERS: + raise ValueError("第一组scheduler枚举不符") + number("steps", "INT", 1, 10000) + number("denoise", "FLOAT", 0.0, 1.0) + return result + + +def serialize_node(node): + result = saved_values(node) + ct, spec = node["type"], definitions()[node["type"]] + outputs = node.get("outputs", []) + if [s.get("type") for s in outputs] != spec["output"]: + raise ValueError("第一组输出槽数量/类型不符") + expected_names = { + "PrimitiveStringMultiline": ["STRING"], + "ResolutionSelector": ["width", "height"], + "ComfyMathExpression": ["FLOAT", "INT", "BOOL"], + "PrimitiveFloat": ["FLOAT"], + "RandomNoise": ["NOISE"], + "BasicScheduler": ["SIGMAS"], + }[ct] + if [s.get("name") for s in outputs] != expected_names or any( + "slot_index" in s and (type(s["slot_index"]) is not int or s["slot_index"] != i) + for i, s in enumerate(outputs) + ): + raise ValueError("第一组输出槽名字/slot_index不符") + sockets = node.get("inputs", []) + names = [s.get("name") for s in sockets] + if len(names) != len(set(names)): + raise ValueError("第一组重复输入槽") + declared = {**spec["input"]["required"], **spec["input"]["optional"]} + for s in sockets: + name = s.get("name") + if name not in declared or s.get("type") != declared[name][0]: + raise ValueError("第一组输入槽/类型或动态布局未证明") + if "widget" in s and s["widget"] != {"name": name}: + raise ValueError("第一组控件输入绑定不符") + if "slot_index" in s: + raise ValueError("第一组输入槽额外slot_index未证明") + if ct == "ComfyMathExpression": + dynamic = [n for n in names if n != "expression"] + if not 2 <= len(dynamic) <= 26 or dynamic != [ + f"values.{c}" for c in ascii_lowercase[: len(dynamic)] + ]: + raise ValueError("第一组算式需已构造values.a/b连续动态槽;不恢复旧values占位") + return result + + +def validate_structure(source): + """Reuse direct root invariants without mutating absent source identity. + + Only the proved numeric MultiType autogrow slots may specialize a link type. + No unknown node obtains a schema through this validation. + """ + from .structure_reference import validate_grid_structure + + declared = (source.get("extra") or {}).get("frontendVersion") + if declared is not None and declared != "1.53.10": + raise ValueError("第一组前端声明冲突;缺失仅显式采用1.53.10参考") + for container in (source, source.get("extra") or {}): + check_overrides(container) + for node in source["nodes"]: + check_overrides(node) + check_overrides(node.get("properties") or {}) + if node.get("type") == "Reroute": + raise ValueError("第一组不扩展虚拟节点") + graph = deepcopy(source) + graph.setdefault("extra", {})["frontendVersion"] = "1.53.10" + nodes = {n["id"]: n for n in graph["nodes"]} + for edge in graph.get("links", []): + if not isinstance(edge, list) or len(edge) != 6: + continue # Shared validator gives the precise structural rejection. + target = nodes.get(edge[3], {}) + slot = edge[4] + if type(slot) is not int or not 0 <= slot < len(target.get("inputs", [])): + continue + socket = target["inputs"][slot] + if ( + target.get("type") == "ComfyMathExpression" + and socket.get("name") in {f"values.{c}" for c in ascii_lowercase} + and socket.get("type") == NUMERIC_UNION + and edge[5] in NUMERIC_UNION.split(",") + ): + socket["type"] = edge[5] + validate_grid_structure(graph, frontend="1.53.10") diff --git a/calliope-backend/src/calliope/comfyui/serialization_reference.py b/calliope-backend/src/calliope/comfyui/serialization_reference.py index 862eab55..e0e9d370 100644 --- a/calliope-backend/src/calliope/comfyui/serialization_reference.py +++ b/calliope-backend/src/calliope/comfyui/serialization_reference.py @@ -14,6 +14,7 @@ import json import math from typing import Any +from .h3_core_reference import CORE_PROFILE from .structure_reference import ( GRID_PROFILE, H3_PROFILE, @@ -488,6 +489,10 @@ def reference_definitions(profile: str = PROFILE) -> dict[str, Any]: "output": outputs, } + if profile == CORE_PROFILE: + from .h3_core_reference import definitions + + return definitions() if profile == H3_PROFILE: return h3_definitions() if profile == GRID_PROFILE: @@ -574,6 +579,10 @@ def reference_definitions(profile: str = PROFILE) -> dict[str, Any]: def serialize_reference_widgets(node: dict[str, Any], profile: str = PROFILE) -> dict[str, Any]: """Apply only the pinned identity serializers; reject any extra/missing value.""" + if profile == CORE_PROFILE: + from .h3_core_reference import serialize_node + + return serialize_node(node) if profile == H3_PROFILE: return serialize_h3_node(node) if profile == GRID_PROFILE: diff --git a/calliope-backend/src/calliope/comfyui/ui2api.py b/calliope-backend/src/calliope/comfyui/ui2api.py index 4993c950..c16c208a 100644 --- a/calliope-backend/src/calliope/comfyui/ui2api.py +++ b/calliope-backend/src/calliope/comfyui/ui2api.py @@ -13,6 +13,7 @@ from __future__ import annotations from dataclasses import dataclass, field from typing import Any +from .h3_core_reference import CORE_PROFILE from .serialization_reference import ( ASR_PROFILE, AUX_PROFILE, @@ -77,6 +78,7 @@ def convert_reference(source: Any, profile: str = PROFILE) -> Conversion: PROFILE, GRID_PROFILE, H3_PROFILE, + CORE_PROFILE, ASR_PROFILE, *MEDIA_PROFILES, SEPARATION_PROFILE, @@ -101,6 +103,10 @@ def convert_reference(source: Any, profile: str = PROFILE) -> Conversion: True, ) try: + if profile == CORE_PROFILE: + from .h3_core_reference import validate_structure + + validate_structure(source) if profile == GRID_PROFILE: validate_grid_structure(source) if profile == H3_PROFILE: @@ -233,12 +239,13 @@ def convert_reference(source: Any, profile: str = PROFILE) -> Conversion: result.diagnostic_graph = source except (ValueError, TypeError, KeyError, AttributeError, IndexError) as exc: issue = {"code": "invalid_reference_contract", "message": str(exc)} - if profile in (GRID_PROFILE, H3_PROFILE): + if profile in (GRID_PROFILE, H3_PROFILE, CORE_PROFILE): issue["pointer"] = "/" return Conversion(None, [issue], True) result.reference_only = True if profile in ( H3_PROFILE, + CORE_PROFILE, GRID_PROFILE, ASR_PROFILE, *MEDIA_PROFILES, @@ -257,7 +264,7 @@ def _convert( def fail(code: str, message: str, node_id: Any = "") -> None: issue = {"code": code, "message": message, "node_id": str(node_id)} - if reference and reference_profile in (GRID_PROFILE, H3_PROFILE): + if reference and reference_profile in (GRID_PROFILE, H3_PROFILE, CORE_PROFILE): issue["pointer"] = next( ( f"/nodes/{i}" @@ -318,6 +325,7 @@ def _convert( CASE04_PROFILE: "1.53.6", GRID_PROFILE: "1.41.20", H3_PROFILE: "1.53.10", + CORE_PROFILE: "1.53.10", **VHS_PROFILES, **SETGET_PROFILES, **VIDEOINFO_PROFILES, @@ -464,12 +472,24 @@ def _convert( expected = declared[name][0] if declared[name] else None actual = outputs[link[2]] # Custom unions/wildcards need frontend evidence; do not guess coercions. - if expected != actual and not ( - reference - and reference_profile in (PREVIEW_PROFILE, CASE04_PROFILE, ASR_PROFILE, H3_PROFILE) - and ct == "PreviewAny" - and name == "source" - and expected == "*" + if ( + expected != actual + and not ( + reference + and reference_profile == CORE_PROFILE + and ct == "ComfyMathExpression" + and name.startswith("values.") + and actual in ("FLOAT", "INT", "BOOLEAN") + and expected == "FLOAT,INT,BOOLEAN" + ) + and not ( + reference + and reference_profile + in (PREVIEW_PROFILE, CASE04_PROFILE, ASR_PROFILE, H3_PROFILE) + and ct == "PreviewAny" + and name == "source" + and expected == "*" + ) ): fail( "link_type_unverified", diff --git a/calliope-backend/tests/test_audio_separation_reference.py b/calliope-backend/tests/test_audio_separation_reference.py index ee8b49c8..97fdc3d7 100644 --- a/calliope-backend/tests/test_audio_separation_reference.py +++ b/calliope-backend/tests/test_audio_separation_reference.py @@ -361,7 +361,7 @@ def test_library_actual_delta_keeps_every_old_attempt_and_all_six_golden_compari previous = json.loads((REPO / "docs/hel-892/media-evidence/library.json").read_bytes()) profiles = tuple( p - for p in audit.REFERENCE_PROFILES + for p in audit.REFERENCE_PROFILES[:26] if p not in ( *audit.CROP_SPLIT_PROFILES, diff --git a/calliope-backend/tests/test_crop_split_reference.py b/calliope-backend/tests/test_crop_split_reference.py index e2a97150..90716e40 100644 --- a/calliope-backend/tests/test_crop_split_reference.py +++ b/calliope-backend/tests/test_crop_split_reference.py @@ -353,7 +353,7 @@ def test_two_disjoint_instances_preserve_nodes_links_and_values(profile): def test_all_old_fourteen_profiles_attempts_gaps_and_six_differences_unchanged(): historical_profiles = tuple( p - for p in audit.REFERENCE_PROFILES + for p in audit.REFERENCE_PROFILES[:26] if p not in ( *VHS_PROFILES, diff --git a/calliope-backend/tests/test_grid_reference.py b/calliope-backend/tests/test_grid_reference.py index 319af041..36b549e8 100644 --- a/calliope-backend/tests/test_grid_reference.py +++ b/calliope-backend/tests/test_grid_reference.py @@ -339,7 +339,9 @@ def test_fixed_sources_and_original_profile_cohorts_remain_identical(): profiles = tuple(old["profiles"]) assert ( len(profiles) == 24 - and tuple(p for p in audit.REFERENCE_PROFILES if p not in (GRID_PROFILE, audit.H3_PROFILE)) + and tuple( + p for p in audit.REFERENCE_PROFILES[:26] if p not in (GRID_PROFILE, audit.H3_PROFILE) + ) == profiles ) current = audit.audit_library(REPO, (*profiles, GRID_PROFILE), baseline_profiles=profiles) diff --git a/calliope-backend/tests/test_h3_core_reference.py b/calliope-backend/tests/test_h3_core_reference.py new file mode 100644 index 00000000..a44414da --- /dev/null +++ b/calliope-backend/tests/test_h3_core_reference.py @@ -0,0 +1,449 @@ +"""Synthetic contract tests are distinct from the three unchanged real closed graphs.""" + +import copy +import json +from pathlib import Path + +import pytest +from scripts import audit_reference_conversion as audit +from scripts.verify_frontend_sources import verify + +from calliope.comfyui.h3_core_reference import ( + CORE_PROFILE, + LAYOUTS, + NUMERIC_UNION, + definitions, + saved_values, + serialize_node, +) +from calliope.comfyui.ui2api import convert, convert_reference + +REPO = Path(__file__).resolve().parents[2] +PATH = next((REPO / "example_ComfyUI_workflows").rglob("minimax-h3文生视频无审核版.json")) + + +def real(): + return json.loads(PATH.read_bytes()) + + +def node(nid): + return copy.deepcopy(next(n for n in real()["nodes"] if n["id"] == nid)) + + +def single(nid): + n = node(nid) + for s in n["outputs"]: + s["links"] = None + for s in n["inputs"]: + s["link"] = None + return {"nodes": [n], "links": [], "extra": {}} + + +def closed(g): + old = copy.deepcopy(g) + r = convert_reference(g, CORE_PROFILE) + assert r.prompt is None and r.issues and r.reference_only and g == old + assert all(i.get("pointer") is not None for i in r.issues) + a = audit.profile_attempt(g, CORE_PROFILE) + assert a["status"] in ("rejected", "not_applicable") and "candidate_prompt" not in a + + +def synthetic_math(): + g = single(133) + n = node(132) + # Construct the fixed frontend shape as a TEST fixture, never alter source bytes. + n["inputs"] = [ + {"name": "values.a", "type": NUMERIC_UNION, "link": 1}, + {"name": "values.b", "type": NUMERIC_UNION, "link": None}, + ] + for s in n["outputs"]: + s["links"] = None + g["nodes"][0]["outputs"][0]["links"] = [1] + g["nodes"].append(n) + g["links"] = [[1, 133, 0, 132, 0, "FLOAT"]] + return g + + +def test_real_main_seven_instances_five_layouts_and_two_explicit_dynamic_rejections(): + g = real() + assert len(g["nodes"]) == 21 and len(g["links"]) == 24 + selected = [n for n in g["nodes"] if n["type"] in LAYOUTS] + assert len(selected) == 7 and len(definitions()) == 6 + assert sum(len(saved_values(n)) for n in selected) == 11 + for n in selected: + if n["type"] == "ComfyMathExpression": + with pytest.raises(ValueError, match="动态布局"): + serialize_node(n) + else: + assert serialize_node(n) == saved_values(n) + closed(g) + a = audit.profile_attempt(g, CORE_PROFILE) + assert a["status"] == "rejected" + evidence = a["supported_node_evidence"] + assert len(evidence) == 7 and sum(e["layout_accepted"] for e in evidence) == 5 + assert sum(len(e["saved_fields"]) for e in evidence) == 11 + assert all(e["not_a_submittable_node_or_partial_prompt"] for e in evidence) + assert all(e["reasons"] for e in evidence if not e["layout_accepted"]) + assert a["assumptions"]["source_frontend_declaration"] is None + assert a["assumptions"]["source_core_provider_version"].startswith("unknown") + assert a["assumptions"]["core_version"] == "0.33.0" + assert convert(g).prompt is None + + +@pytest.mark.parametrize("nid", [1, 115, 133, 129]) +def test_supported_saved_state_instances_under_explicit_missing_identity_assumption(nid): + g = single(nid) + before = copy.deepcopy(g) + r = convert_reference(g, CORE_PROFILE) + assert r.prompt is not None and r.reference_only and g == before + assert r.prompt[str(nid)]["inputs"] == serialize_node(g["nodes"][0]) + assert r.serialization_stage == "restored_saved_state_before_queue_hooks" + for n in g["nodes"]: + n["properties"].update(cnr_id="comfy-core", ver="0.33.0") + g["extra"]["frontendVersion"] = "1.53.10" + assert convert_reference(g, CORE_PROFILE).prompt == r.prompt + + +@pytest.mark.parametrize("nid", [1, 115, 133, 129, 124, 132]) +@pytest.mark.parametrize( + "mutation", ["provider", "version", "aux", "mode", "ue", "hook", "short", "long"] +) +def test_identity_mode_layout_unknown_coverage_never_yields_partial_prompt(nid, mutation): + g = single(nid) + n = g["nodes"][0] + if mutation == "provider": + n["properties"]["cnr_id"] = "other" + elif mutation == "version": + n["properties"]["ver"] = "0.30.0" + elif mutation == "aux": + n["properties"]["aux_id"] = "comfy-core" + elif mutation == "mode": + n["mode"] = True + elif mutation == "ue": + n["properties"]["ue_properties"] = {} + elif mutation == "hook": + n["onConfigure"] = "unknown" + elif mutation == "short": + n["widgets_values"].pop() + else: + n["widgets_values"].append("extra") + with pytest.raises(ValueError): + serialize_node(n) + closed(g) + + +@pytest.mark.parametrize( + "nid,index,value", + [ + (1, 0, None), + (1, 0, []), + (115, 0, "16:9"), + (115, 1, True), + (115, 1, 0.09), + (115, 1, 16.1), + (115, 1, "0.7"), + (115, 2, 32.0), + (115, 2, 7), + (115, 2, 129), + (133, 0, True), + (133, 0, "10"), + (133, 0, float("inf")), + (133, 0, float("nan")), + (133, 0, 10**500), + (129, 0, True), + (129, 0, 42.0), + (129, 0, -1), + (129, 0, 2**53), + (129, 0, 2**64), + (129, 1, "randomize"), + (129, 1, "increment"), + (129, 1, "decrement"), + (129, 1, None), + (124, 0, "unknown"), + (124, 1, 4.0), + (124, 1, True), + (124, 1, 0), + (124, 1, 10001), + (124, 2, -0.01), + (124, 2, 1.01), + (124, 2, True), + (124, 2, "1.0"), + ], +) +def test_types_enums_boundaries_seed_and_nonfixed_controls(nid, index, value): + n = node(nid) + n["widgets_values"][index] = value + with pytest.raises(ValueError): + saved_values(n) + + +@pytest.mark.parametrize( + "nid,index,value", + [ + (1, 0, "opaque\ntext\u0000原样"), + (115, 1, 0.1), + (115, 1, 16.0), + (115, 2, 8), + (115, 2, 128), + (129, 0, 0), + (129, 0, 2**53 - 1), + (133, 0, -100.5), + (124, 0, "kl_optimal"), + (124, 1, 1), + (124, 1, 10000), + (124, 2, 0.0), + (124, 2, 1.0), + ], +) +def test_proved_values_propagate_without_coercion_or_calculation(nid, index, value): + n = node(nid) + n["widgets_values"][index] = value + field = LAYOUTS[n["type"]][index] + v = saved_values(n)[field] + assert v == value and type(v) is type(value) + + +@pytest.mark.parametrize("nid", [1, 115, 133, 129, 124, 132]) +@pytest.mark.parametrize("mutation", ["missing", "extra", "conflict", "typed-conflict"]) +def test_optional_named_save_must_be_complete_and_agree(nid, mutation): + n = node(nid) + layout = LAYOUTS[n["type"]] + n["widgets_values_named"] = dict(zip(layout, n["widgets_values"])) + if mutation == "missing": + n["widgets_values_named"].pop(layout[0]) + elif mutation == "extra": + n["widgets_values_named"]["extra"] = 0 + elif mutation == "typed-conflict": + n["widgets_values_named"][layout[0]] = True + else: + n["widgets_values_named"][layout[0]] = "conflict" + with pytest.raises(ValueError): + saved_values(n) + + +def test_synthetic_math_expression_is_opaque_physical_union_edge_and_instance_switch(): + g = synthetic_math() + original_expression = g["nodes"][1]["widgets_values"][0] + r = convert_reference(g, CORE_PROFILE) + assert r.prompt is not None, r.issues + assert r.prompt["132"]["inputs"] == { + "expression": original_expression, + "values.a": ["133", 0], + } + g["nodes"][1]["widgets_values"][0] = "__import__('never_called') / 0 + unknown" + g["nodes"][0]["id"] = 990 + g["links"][0][1] = 990 + r = convert_reference(g, CORE_PROFILE) + assert r.prompt is not None, r.issues + assert r.prompt["132"]["inputs"]["values.a"] == ["990", 0] + assert r.prompt["132"]["inputs"]["expression"] == g["nodes"][1]["widgets_values"][0] + + +def test_synthetic_physical_widget_input_overrides_saved_value(): + g = single(133) + n = copy.deepcopy(g["nodes"][0]) + n["id"] = 991 + n["inputs"] = [{"name": "value", "type": "FLOAT", "link": 1, "widget": {"name": "value"}}] + n["widgets_values"] = [99.0] + g["nodes"][0]["outputs"][0]["links"] = [1] + g["nodes"].append(n) + g["links"] = [[1, 133, 0, 991, 0, "FLOAT"]] + r = convert_reference(g, CORE_PROFILE) + assert r.prompt is not None, r.issues + assert r.prompt["991"]["inputs"]["value"] == ["133", 0] + + +@pytest.mark.parametrize( + "mutation", + [ + "frontend", + "ue", + "renderer", + "subgraph", + "missing-end", + "wrong-slot", + "wrong-type", + "duplicate-link", + "reverse-input", + "reverse-output", + "duplicate-input", + "cycle", + "wrong-output-name", + "wrong-slot-index", + "unknown-class", + "math-placeholder", + ], +) +def test_synthetic_graph_structure_is_strict(mutation): + g = synthetic_math() + a, b = g["nodes"] + if mutation == "frontend": + g["extra"]["frontendVersion"] = "1.53.6" + elif mutation == "ue": + g["extra"]["ue_properties"] = {} + elif mutation == "renderer": + g["extra"]["workflowRendererVersion"] = "Vue" + elif mutation == "subgraph": + g["definitions"] = {"subgraphs": [{"id": "unknown"}]} + elif mutation == "missing-end": + g["links"][0][1] = 999 + elif mutation == "wrong-slot": + g["links"][0][2] = 1 + elif mutation == "wrong-type": + g["links"][0][5] = "INT" + elif mutation == "duplicate-link": + g["links"].append(g["links"][0]) + elif mutation == "reverse-input": + b["inputs"][0]["link"] = 9 + elif mutation == "reverse-output": + a["outputs"][0]["links"] = [] + elif mutation == "duplicate-input": + b["inputs"].append(copy.deepcopy(b["inputs"][0])) + elif mutation == "cycle": + a["inputs"] = [{"name": "value", "type": "FLOAT", "link": 2}] + b["outputs"][0]["links"] = [2] + g["links"].append([2, 132, 0, 133, 0, "FLOAT"]) + elif mutation == "wrong-output-name": + b["outputs"][1]["name"] = "FLOAT" + elif mutation == "wrong-slot-index": + b["outputs"][0]["slot_index"] = True + elif mutation == "unknown-class": + a["type"] = "TestOnlyHelperNotRegistered" + else: + b["inputs"].append({"name": "values", "type": "COMFY_AUTOGROW_V3", "link": None}) + closed(g) + + +def test_three_unchanged_uncensored_graphs_remain_closed(): + paths = sorted(PATH.parent.glob("*.json")) + assert len(paths) == 3 + for path in paths: + g = json.loads(path.read_bytes()) + closed(g) + a = audit.profile_attempt(g, CORE_PROFILE) + assert a["status"] == "rejected" + + +def test_pinned_sources_without_importing_upstream(): + r = verify(REPO / "docs/hel-892/h3-core-reference") + assert not r["upstream_code_executed"] and len(r["sources_verified"]) >= 9 + + +def test_all_old_26_profiles_attempts_gaps_hashes_and_six_companions_frozen(): + old = json.loads((REPO / "docs/hel-892/h3-evidence/library.json").read_bytes()) + profiles = tuple(old["profiles"]) + assert len(profiles) == 26 and profiles == audit.REFERENCE_PROFILES[:26] + before = audit.audit_library(REPO, profiles) + now = audit.audit_library(REPO, baseline_profiles=profiles) + assert old["gap_groups"] == before["gap_groups"] + for a, b, c in zip(old["cases"], before["cases"], now["cases"]): + assert a["attempts"] == b["attempts"] == c["attempts"][:26] + assert a["candidate_hashes"] == c["candidate_hashes"] + assert a.get("comparisons") == b.get("comparisons") == c.get("comparisons") + assert now["coverage_delta"]["new_complete_paths"] == [] + assert len(now["coverage_delta"]["current_complete_paths"]) == 9 + assert sum(r["status"] == "blocked" for r in now["cases"]) == 136 + six = audit.audit(REPO, "case04-batch-reference") + assert six == json.loads( + (REPO / "docs/hel-892/media-evidence/protected-six-cases.json").read_bytes() + ) + + +@pytest.mark.parametrize( + "key", + [ + "serialize_widgets", + "fallbackWidgetsValuesNames", + "comfyClass", + "onNodeCreated", + "onConnectInput", + "onConnectionsChange", + "onInputAdded", + ], +) +def test_unknown_frontend_construction_overrides_are_not_ignored(key): + g = single(133) + g["nodes"][0][key] = False + closed(g) + + +def test_float_platform_limit_is_symbolic_and_only_conservative_intersection_accepted(): + n = node(133) + for value in (-(2**31 - 1), 2**31 - 1): + n["widgets_values"] = [value] + assert saved_values(n)["value"] == value + for value in (-(2**31), 2**31): + n["widgets_values"] = [value] + with pytest.raises(ValueError): + saved_values(n) + + +def test_official_schema_ids_registration_enums_and_widget_order_by_static_ast_only(): + import ast + + from calliope.comfyui.h3_core_reference import RATIOS, SCHEDULERS + + root = REPO / "docs/hel-892/h3-core-reference" + expected = { + "nodes_primitive.py": { + "StringMultiline": ("PrimitiveStringMultiline", ["value"]), + "Float": ("PrimitiveFloat", ["value"]), + }, + "nodes_resolution.py": { + "ResolutionSelector": ( + "ResolutionSelector", + ["aspect_ratio", "megapixels", "multiple"], + ), + }, + "nodes_math.py": { + "MathExpressionNode": ("ComfyMathExpression", ["expression", "values"]), + }, + "nodes_custom_sampler.py": { + "RandomNoise": ("RandomNoise", ["noise_seed"]), + "BasicScheduler": ("BasicScheduler", ["model", "scheduler", "steps", "denoise"]), + }, + } + for filename, classes in expected.items(): + tree = ast.parse((root / ("core__comfy_extras__" + filename)).read_text()) + registered = { + n.id + for fn in ast.walk(tree) + if isinstance(fn, ast.AsyncFunctionDef) and fn.name == "get_node_list" + for ret in fn.body + if isinstance(ret, ast.Return) and isinstance(ret.value, ast.List) + for n in ret.value.elts + if isinstance(n, ast.Name) + } + for name, (node_id, fields) in classes.items(): + assert name in registered + cls = next(n for n in tree.body if isinstance(n, ast.ClassDef) and n.name == name) + fn = next( + n for n in cls.body if isinstance(n, ast.FunctionDef) and n.name == "define_schema" + ) + schema = next( + c + for c in ast.walk(fn) + if isinstance(c, ast.Call) + and isinstance(c.func, ast.Attribute) + and c.func.attr == "Schema" + ) + kw = {k.arg: k.value for k in schema.keywords} + assert ast.literal_eval(kw["node_id"]) == node_id + actual = [] + for c in kw["inputs"].elts: + ident = c.args[0] if c.args else next(k.value for k in c.keywords if k.arg == "id") + actual.append(ast.literal_eval(ident)) + assert actual == fields + tree = ast.parse((root / "core__comfy_extras__nodes_resolution.py").read_text()) + ratios = next(n for n in tree.body if isinstance(n, ast.ClassDef) and n.name == "AspectRatio") + assert ( + tuple(ast.literal_eval(n.value) for n in ratios.body if isinstance(n, ast.Assign)) == RATIOS + ) + tree = ast.parse((root / "core__comfy__samplers.py").read_text()) + registry = next( + n + for n in tree.body + if isinstance(n, ast.Assign) + and any(isinstance(t, ast.Name) and t.id == "SCHEDULER_HANDLERS" for t in n.targets) + ) + assert tuple(ast.literal_eval(k) for k in registry.value.keys) == SCHEDULERS diff --git a/calliope-backend/tests/test_h3_reference.py b/calliope-backend/tests/test_h3_reference.py index ac681f86..d68126aa 100644 --- a/calliope-backend/tests/test_h3_reference.py +++ b/calliope-backend/tests/test_h3_reference.py @@ -312,7 +312,7 @@ def test_fixed_sources_are_cached_not_imported_and_include_registration(): def test_full_library_old_25_attempts_gaps_eight_hashes_and_six_pairs_frozen(): old = json.loads((REPO / "docs/hel-892/grid-evidence/library.json").read_bytes()) baseline = tuple(old["profiles"]) - assert len(baseline) == 25 and baseline == audit.REFERENCE_PROFILES[:-1] + assert len(baseline) == 25 and baseline == audit.REFERENCE_PROFILES[:25] before = audit.audit_library(REPO, baseline) now = audit.audit_library(REPO, baseline_profiles=baseline) assert old["gap_groups"] == before["gap_groups"] diff --git a/calliope-backend/tests/test_scail_load_reference.py b/calliope-backend/tests/test_scail_load_reference.py index 349bc426..d89c3fee 100644 --- a/calliope-backend/tests/test_scail_load_reference.py +++ b/calliope-backend/tests/test_scail_load_reference.py @@ -244,7 +244,11 @@ def test_exact_historical_emission_is_not_user_provenance(): assert serialize_scail_load_node(loader())["custom_width"] == 0 assert ( len( - [p for p in audit.REFERENCE_PROFILES if p not in (audit.GRID_PROFILE, audit.H3_PROFILE)] + [ + p + for p in audit.REFERENCE_PROFILES[:26] + if p not in (audit.GRID_PROFILE, audit.H3_PROFILE) + ] ) == 24 ) diff --git a/calliope-backend/tests/test_setget_reference.py b/calliope-backend/tests/test_setget_reference.py index 65bff837..41754ade 100644 --- a/calliope-backend/tests/test_setget_reference.py +++ b/calliope-backend/tests/test_setget_reference.py @@ -334,7 +334,7 @@ def test_wrong_frontend_missing_policy_and_profile_inventory(): len( [ p - for p in audit.REFERENCE_PROFILES + for p in audit.REFERENCE_PROFILES[:26] if p not in ( *audit.VIDEOINFO_PROFILES, @@ -421,7 +421,7 @@ def test_historical_18_profiles_attempts_gaps_and_six_comparisons_unchanged(): old = json.loads((REPO / "docs/hel-892/vhs-evidence/library.json").read_bytes()) baseline = tuple( p - for p in audit.REFERENCE_PROFILES + for p in audit.REFERENCE_PROFILES[:26] if p not in ( *SETGET_PROFILES, @@ -433,7 +433,7 @@ def test_historical_18_profiles_attempts_gaps_and_six_comparisons_unchanged(): ) now = audit.audit_library( REPO, - tuple(p for p in audit.REFERENCE_PROFILES if p != audit.H3_PROFILE), + tuple(p for p in audit.REFERENCE_PROFILES[:26] if p != audit.H3_PROFILE), baseline_profiles=baseline, ) actual_old = audit.audit_library(REPO, baseline) diff --git a/calliope-backend/tests/test_vhs_reference.py b/calliope-backend/tests/test_vhs_reference.py index 3c09f1be..05c4b7c0 100644 --- a/calliope-backend/tests/test_vhs_reference.py +++ b/calliope-backend/tests/test_vhs_reference.py @@ -288,7 +288,7 @@ def test_old_sixteen_attempts_gaps_candidates_and_six_comparisons_protected(): # Freeze this batch's 18-profile history; Set/Get has separate current protection. historical_profiles = tuple( p - for p in audit.REFERENCE_PROFILES + for p in audit.REFERENCE_PROFILES[:26] if p not in ( *audit.SETGET_PROFILES, diff --git a/calliope-backend/tests/test_videoinfo_reference.py b/calliope-backend/tests/test_videoinfo_reference.py index 90703458..fd09f6ca 100644 --- a/calliope-backend/tests/test_videoinfo_reference.py +++ b/calliope-backend/tests/test_videoinfo_reference.py @@ -279,7 +279,7 @@ def test_real_entities_strict_source_schema_and_old_profiles_stay_frozen(): len( [ p - for p in audit.REFERENCE_PROFILES + for p in audit.REFERENCE_PROFILES[:26] if p not in (*audit.SCAIL_LOAD_PROFILES, audit.GRID_PROFILE, audit.H3_PROFILE) ] ) diff --git a/docs/hel-892/h3-core-evidence/recompute.py b/docs/hel-892/h3-core-evidence/recompute.py new file mode 100644 index 00000000..d986d92c --- /dev/null +++ b/docs/hel-892/h3-core-evidence/recompute.py @@ -0,0 +1,469 @@ +"""Recompute H3 core first-group reference evidence and protections without services or upstream execution.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import sqlite3 +import subprocess +import sys +import tarfile +import zipfile +from collections import Counter +from pathlib import Path + +BASE = "8e832b8e0e14db85932f4d830be2d2929b9e62a1" + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--repo", type=Path, required=True) + parser.add_argument("--db", type=Path, required=True) + parser.add_argument("--documents", type=Path, required=True) + args = parser.parse_args() + repo = args.repo.resolve() + sys.path.insert(0, str(repo / "calliope-backend")) + from calliope.comfyui.h3_core_reference import CORE_PROFILE + from scripts import audit_reference_conversion as audit + from scripts.audit_library_documents import audit as audit_docs + from scripts.verify_frontend_sources import verify + + out = repo / "docs/hel-892/h3-core-evidence" + + def write(name, value): + (out / name).write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n") + + old = json.loads((repo / "docs/hel-892/h3-evidence/library.json").read_bytes()) + profiles = tuple(old["profiles"]) + assert len(profiles) == 26 + assert profiles == tuple(p for p in audit.REFERENCE_PROFILES if p != CORE_PROFILE) + before = audit.audit_library(repo, profiles) + now = audit.audit_library(repo, baseline_profiles=profiles) + write("library.json", now) + for a, b, c in zip(old["cases"], before["cases"], now["cases"]): + assert a["source_path"] == b["source_path"] == c["source_path"] + assert a["attempts"] == b["attempts"] == c["attempts"][:26] + assert a.get("comparisons") == b.get("comparisons") == c.get("comparisons") + if a["candidate_hashes"]: + assert a["candidate_hashes"] == c["candidate_hashes"] + assert old["gap_groups"] == before["gap_groups"] + six = audit.audit(repo, "case04-batch-reference") + assert six == json.loads( + (repo / "docs/hel-892/media-evidence/protected-six-cases.json").read_bytes() + ) + write( + "previous-protection.json", + { + "baseline_profiles": profiles, + "old_attempts_identical": True, + "old_gaps_identical": True, + "six_companion_differences_identical": True, + "old_candidate_hashes_identical": True, + }, + ) + + def groups(report): + return { + tuple( + g[k] + for k in ("type", "provider", "version", "profile", "code", "rule_gap") + ): Counter( + (o["source_path"], o["node_pointer"], o["node_id"]) + for o in g["occurrences"] + ) + for g in report["gap_groups"] + } + + def stats(report): + gs = groups(report) + return { + "groups": len(gs), + "raw_occurrences": sum(sum(c.values()) for c in gs.values()), + "unique_occurrences_per_group": sum(len(c) for c in gs.values()), + "unique_nodes": len({o for c in gs.values() for o in c}), + "unique_paths": len({o[0] for c in gs.values() for o in c}), + } + + def diffrows(a, b): + return [ + { + "key": list(k), + "occurrences": [ + { + "source_path": o[0], + "node_pointer": o[1], + "node_id": o[2], + "count": n, + } + for o, n in sorted((v - b.get(k, Counter())).items(), key=str) + ], + } + for k, v in sorted(a.items(), key=str) + if v - b.get(k, Counter()) + ] + + def unavailable(report): + return sorted( + r["source_path"] + for r in report["cases"] + if all(a["status"] == "not_applicable" for a in r["attempts"]) + ) + + removed_unavailable = sorted(set(unavailable(before)) - set(unavailable(now))) + added_unavailable = sorted(set(unavailable(now)) - set(unavailable(before))) + ga, gb = groups(before), groups(now) + added, removed = diffrows(gb, ga), diffrows(ga, gb) + write( + "coverage-delta.json", + { + "baseline_profiles": profiles, + "baseline": stats(before), + "current": stats(now), + "key_fields": [ + "type", + "provider", + "version", + "profile", + "code", + "rule_gap", + ], + "occurrence_key": ["source_path", "node_pointer", "node_id"], + "added_groups": added, + "removed_groups": removed, + "added_occurrences": sum( + o["count"] for g in added for o in g["occurrences"] + ), + "removed_occurrences": sum( + o["count"] for g in removed for o in g["occurrences"] + ), + "new_complete_paths": now["coverage_delta"]["new_complete_paths"], + "complete_paths": now["coverage_delta"]["current_complete_paths"], + "closed_paths": [ + r["source_path"] for r in now["cases"] if r["status"] == "blocked" + ], + "unavailable_frontend_before": unavailable(before), + "unavailable_frontend_after": unavailable(now), + "removed_unavailable_frontend_paths": removed_unavailable, + "added_unavailable_frontend_paths": added_unavailable, + "unavailable_frontend_change_reason": "new explicit missing-identity 1.53.10/core0.33.0 assumption; applicability is not source provenance or conversion success", + "attempt_counts": dict( + Counter(a["status"] for r in now["cases"] for a in r["attempts"]) + ), + "conflicts": sum(r["status"] == "candidate_conflict" for r in now["cases"]), + }, + ) + + from calliope.comfyui.ui2api import convert_reference + + targets = sorted( + (repo / "example_ComfyUI_workflows/4-视频生成/uncensored").glob("*.json") + ) + assert len(targets) == 3 + actual_rows = [] + for target in targets: + source = json.loads(target.read_bytes()) + actual = convert_reference(source, CORE_PROFILE) + assert actual.prompt is None and actual.issues + row = next( + r + for r in now["cases"] + if r["source_path"] == target.relative_to(repo).as_posix() + ) + assert row["comparison_status"] == "comparison_unavailable" + attempt = next(a for a in row["attempts"] if a["profile"] == CORE_PROFILE) + assert attempt["status"] == "rejected" and "candidate_prompt" not in attempt + actual_rows.append( + { + "source_path": row["source_path"], + "source_sha256": row["source_sha256"], + "profile": CORE_PROFILE, + "prompt": None, + "comparison_status": row["comparison_status"], + "execution_verified": False, + "original_bytes_modified": False, + "attempt": attempt, + } + ) + write("actual-three-graphs.json", actual_rows) + main = next( + r + for r in actual_rows + if r["source_path"].endswith("minimax-h3文生视频无审核版.json") + ) + evidence = main["attempt"]["supported_node_evidence"] + assert len(evidence) == 7 and sum(e["layout_accepted"] for e in evidence) == 5 + assert sum(len(e["saved_fields"]) for e in evidence) == 11 + main_source = json.loads((repo / main["source_path"]).read_bytes()) + + def pointer(doc, text): + for key in text.strip("/").split("/"): + doc = doc[int(key)] if isinstance(doc, list) else doc[key] + return doc + + for r in actual_rows: + doc = json.loads((repo / r["source_path"]).read_bytes()) + for e in r["attempt"]["supported_node_evidence"]: + for f in e["saved_fields"]: + value = pointer(doc, f["source_value_pointer"]) + assert type(value).__name__ == f["json_type"] and value == f["value"] + for edge in e["physical_input_evidence"]: + original = pointer(doc, edge["link_pointer"]) + assert edge["endpoint"] == [str(original[1]), original[2]] + write( + "main-node-evidence.json", + { + "source_path": main["source_path"], + "source_sha256": main["source_sha256"], + "source_entities": len(main_source["nodes"]), + "source_edges": len(main_source["links"]), + "profile": CORE_PROFILE, + "prompt": None, + "complete_candidates_added": 0, + "comparison_status": "comparison_unavailable", + "saved_fields_only": 11, + "layout_accepted_instances": 5, + "layout_rejected_instances": 2, + "supported_node_evidence": evidence, + "remaining_classes": sorted( + { + n["type"] + for n in main_source["nodes"] + if n["type"] not in {e["type"] for e in evidence} + } + ), + "remaining_instance_count": len(main_source["nodes"]) - len(evidence), + "issues": main["attempt"]["issues"], + "no_partial_prompt": True, + "execution_verified": False, + }, + ) + inventory = evidence + attempts = [ + { + "source_path": r["source_path"], + "source_sha256": r["source_sha256"], + "declared_frontend": r["frontend_version"], + "attempt": r["attempts"][-1], + } + for r in now["cases"] + ] + assert all(r["attempt"]["profile"] == CORE_PROFILE for r in attempts) + write( + "profile-disposition.json", + { + "profile": CORE_PROFILE, + "counts": dict(Counter(r["attempt"]["status"] for r in attempts)), + "cases": attempts, + "proven_source_identity": False, + "complete_candidates_added": 0, + }, + ) + + dirs = [ + "serialization-evidence", + "structure-reference", + "controlnet-reference", + "promoted-reference", + "case04-reference", + "media-reference", + "separation-reference", + "crop-split-reference", + "vhs-reference", + "setget-reference", + "videoinfo-reference", + "scail-load-reference", + "grid-reference", + "h3-reference", + "h3-core-reference", + ] + entries = [] + counts = [] + for name in dirs: + directory = repo / "docs/hel-892" / name + verify(directory) + rows = json.loads((directory / "sources.json").read_bytes())["sources"] + for entry in rows: + lines = (directory / entry["local_file"]).read_text().splitlines() + locations = entry.get("rule_locations", {}) + for lo, hi in ( + locations.values() if isinstance(locations, dict) else locations + ): + assert 1 <= lo <= hi <= len(lines) + counts.append( + { + "manifest": name, + "entries": len(rows), + "unique_ids": len({r["id"] for r in rows}), + } + ) + entries.extend(rows) + write( + "cached-sources-check.json", + { + "manifests": counts, + "entries": len(entries), + "unique_ids_summed_per_manifest": sum(c["unique_ids"] for c in counts), + "global_distinct_id_strings": len({r["id"] for r in entries}), + "unique_url_and_hash": len({(r["raw_url"], r["sha256"]) for r in entries}), + "note": "ID counts are strings; URL+SHA256 is separately deduplicated; repeated frontend originals retained", + }, + ) + + originals = json.loads( + (repo / "docs/hel-892/media-evidence/original-bytes.json").read_bytes() + )["files"] + for row in originals: + raw = (repo / row["path"]).read_bytes() + assert raw == subprocess.check_output( + ["git", "show", f"{BASE}:{row['path']}"], cwd=repo + ) + assert len(originals) == 163 + write( + "original-bytes.json", + {"base": BASE, "count": 163, "all_unchanged": True, "files": originals}, + ) + production = json.loads( + (repo / "docs/hel-892/setget-evidence/production-protection.json").read_bytes() + )["files"] + for row in production: + raw = (repo / row["path"]).read_bytes() + assert raw == subprocess.check_output( + ["git", "show", f"{BASE}:{row['path']}"], cwd=repo + ) + assert hashlib.sha256(raw).hexdigest() == row["sha256"] + write("production-protection.json", {"base": BASE, "files": production}) + db = sqlite3.connect(args.db) + db.row_factory = sqlite3.Row + rows = db.execute( + "SELECT * FROM workflows WHERE source_repo_path IS NOT NULL" + ).fetchall() + assert len(rows) == 155 + assert Counter(r["import_state"] for r in rows) == { + "pending_check": 16, + "needs_conversion": 139, + } + assert not any( + r["is_enabled"] or r["doc_completed_at"] or r["exec_verified_at"] for r in rows + ) + issues = Counter(i["code"] for r in rows for i in json.loads(r["import_issues"])) + companion_values = sum( + p.get("value_origin") == "supplied_api_companion" + for r in rows + for p in json.loads(r["doc_json"])["params"] + ) + assert ( + companion_values == 294 + and issues["companion_unverified"] == 6 + and issues["environment_unchecked"] == 16 + ) + write( + "isolation.json", + { + "states": dict(Counter(r["import_state"] for r in rows)), + "count": 155, + "enabled_or_completed_or_executed": 0, + "issue_counts": dict(issues), + "companion_named_values": companion_values, + "reference_candidates_written_to_db": False, + "user_whole_row_protection": "executed affected tests", + }, + ) + from calliope.comfyui.companions import load_companions + from calliope.comfyui.library import import_library + + # A separate in-memory copy proves the complete user row is preserved; + # the fresh catalogue under audit is never mutated by this protection check. + protected = sqlite3.connect(":memory:") + db.backup(protected) + protected.row_factory = sqlite3.Row + wid = rows[0]["id"] + protected.execute( + "UPDATE workflows SET description='用户整行保护测试' WHERE id=?", (wid,) + ) + protected.commit() + snapshot = dict( + protected.execute("SELECT * FROM workflows WHERE id=?", (wid,)).fetchone() + ) + rerun = import_library( + protected, + repo / "example_ComfyUI_workflows", + source_commit=BASE, + companions=load_companions(repo / "docs/hel-892/supplied-api/manifest.json"), + ) + assert rerun["counts"] == {"conflict": 1, "skipped": 154, "user_excluded": 1} + assert ( + dict(protected.execute("SELECT * FROM workflows WHERE id=?", (wid,)).fetchone()) + == snapshot + ) + write( + "user-row-protection.json", + { + "isolated_in_memory_copy": True, + "counts": rerun["counts"], + "all_columns_identical": True, + "column_count": len(snapshot), + "fresh_catalogue_mutated": False, + }, + ) + protected.close() + db.close() + report = audit_docs(repo, args.documents.resolve()) + summary = {k: v for k, v in report.items() if k != "files"} + assert ( + summary["named_values_preserved"] == 1217 + and summary["unnamed_widget_nodes"] == 3660 + ) + assert summary["full_documents_completed"] == 0 and summary["real_executions"] == 0 + write("document-audit-summary.json", summary) + packages = [] + with ( + zipfile.ZipFile(next((repo / "calliope-backend/dist").glob("*.whl"))) as wh, + tarfile.open(next((repo / "calliope-backend/dist").glob("*.tar.gz"))) as sd, + ): + for name in [ + "h3_core_reference.py", + "structure_reference.py", + "serialization_reference.py", + "ui2api.py", + "protocol_references.json", + "source_reviews.json", + "delivery_scope.py", + "delivery_scope.json", + ]: + p = f"calliope-backend/src/calliope/comfyui/{name}" + raw = (repo / p).read_bytes() + assert wh.read(f"calliope/comfyui/{name}") == raw + member = next( + n for n in sd.getnames() if n.endswith(f"/src/calliope/comfyui/{name}") + ) + assert sd.extractfile(member).read() == raw + packages.append( + { + "path": p, + "sha256": hashlib.sha256(raw).hexdigest(), + "wheel_matches": True, + "sdist_matches": True, + } + ) + write("package-check.json", packages) + print( + json.dumps( + { + "ui": now["ui_total"], + "attempts": Counter( + a["status"] for r in now["cases"] for a in r["attempts"] + ), + "complete": len(now["coverage_delta"]["current_complete_paths"]), + "new_complete": now["coverage_delta"]["new_complete_paths"], + "inventory_nodes": len(inventory), + "inventory_paths": 1, + "gap_stats": stats(now), + }, + ensure_ascii=False, + ) + ) + + +if __name__ == "__main__": + main() diff --git a/docs/hel-892/h3-core-reference/core-tag.json b/docs/hel-892/h3-core-reference/core-tag.json new file mode 100644 index 00000000..8af2bc62 --- /dev/null +++ b/docs/hel-892/h3-core-reference/core-tag.json @@ -0,0 +1 @@ +{"ref":"refs/tags/v0.33.0","node_id":"REF_kwDOIygeJrFyZWZzL3RhZ3MvdjAuMzMuMA","url":"https://api.github.com/repos/Comfy-Org/ComfyUI/git/refs/tags/v0.33.0","object":{"sha":"2f35f4a08176d993cded35dac3332be4f7287f41","type":"commit","url":"https://api.github.com/repos/Comfy-Org/ComfyUI/git/commits/2f35f4a08176d993cded35dac3332be4f7287f41"}} \ No newline at end of file diff --git a/docs/hel-892/h3-core-reference/core__LICENSE b/docs/hel-892/h3-core-reference/core__LICENSE new file mode 100644 index 00000000..f288702d --- /dev/null +++ b/docs/hel-892/h3-core-reference/core__LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/docs/hel-892/h3-core-reference/core__comfy__samplers.py b/docs/hel-892/h3-core-reference/core__comfy__samplers.py new file mode 100644 index 00000000..1d6a4e10 --- /dev/null +++ b/docs/hel-892/h3-core-reference/core__comfy__samplers.py @@ -0,0 +1,1463 @@ +from __future__ import annotations + +import comfy.model_management +from .k_diffusion import sampling as k_diffusion_sampling +from .extra_samplers import uni_pc +from typing import TYPE_CHECKING, Callable, NamedTuple, Any +if TYPE_CHECKING: + from comfy.model_patcher import ModelPatcher + from comfy.model_base import BaseModel + from comfy.controlnet import ControlBase +import torch +from functools import partial +import collections +import math +import logging +import comfy.sampler_helpers +import comfy.model_patcher +import comfy.patcher_extension +import comfy.hooks +import comfy.context_windows +import comfy.multigpu +import comfy.utils +from comfy.internal_logging import detail +import scipy.stats +import numpy + + +def add_area_dims(area, num_dims): + while (len(area) // 2) < num_dims: + area = [2147483648] + area[:len(area) // 2] + [0] + area[len(area) // 2:] + return area + +def get_area_and_mult(conds, x_in, timestep_in): + dims = tuple(x_in.shape[2:]) + area = None + strength = 1.0 + + if 'timestep_start' in conds: + timestep_start = conds['timestep_start'] + if timestep_in[0] > timestep_start: + return None + if 'timestep_end' in conds: + timestep_end = conds['timestep_end'] + if timestep_in[0] < timestep_end: + return None + if 'area' in conds: + area = list(conds['area']) + area = add_area_dims(area, len(dims)) + if (len(area) // 2) > len(dims): + area = area[:len(dims)] + area[len(area) // 2:(len(area) // 2) + len(dims)] + + if 'strength' in conds: + strength = conds['strength'] + + input_x = x_in + if area is not None: + for i in range(len(dims)): + area[i] = min(input_x.shape[i + 2] - area[len(dims) + i], area[i]) + input_x = input_x.narrow(i + 2, area[len(dims) + i], area[i]) + + if 'mask' in conds: + # Scale the mask to the size of the input + # The mask should have been resized as we began the sampling process + mask_strength = 1.0 + if "mask_strength" in conds: + mask_strength = conds["mask_strength"] + mask = conds['mask'] + # assert (mask.shape[1:] == x_in.shape[2:]) + + mask = mask[:input_x.shape[0]] + if area is not None: + for i in range(len(dims)): + mask = mask.narrow(i + 1, area[len(dims) + i], area[i]) + + mask = mask * mask_strength + mask = mask.unsqueeze(1).repeat((input_x.shape[0] // mask.shape[0], input_x.shape[1]) + (1, ) * (mask.ndim - 1)) + else: + mask = torch.ones_like(input_x) + mult = mask * strength + + if 'mask' not in conds and area is not None: + fuzz = 8 + for i in range(len(dims)): + rr = min(fuzz, mult.shape[2 + i] // 4) + if area[len(dims) + i] != 0: + for t in range(rr): + m = mult.narrow(i + 2, t, 1) + m *= ((1.0 / rr) * (t + 1)) + if (area[i] + area[len(dims) + i]) < x_in.shape[i + 2]: + for t in range(rr): + m = mult.narrow(i + 2, area[i] - 1 - t, 1) + m *= ((1.0 / rr) * (t + 1)) + + conditioning = {} + model_conds = conds["model_conds"] + for c in model_conds: + conditioning[c] = model_conds[c].process_cond(batch_size=x_in.shape[0], area=area) + + hooks = conds.get('hooks', None) + control = conds.get('control', None) + + patches = None + if 'gligen' in conds: + gligen = conds['gligen'] + patches = {} + gligen_type = gligen[0] + gligen_model = gligen[1] + if gligen_type == "position": + gligen_patch = gligen_model.model.set_position(input_x.shape, gligen[2], input_x.device) + else: + gligen_patch = gligen_model.model.set_empty(input_x.shape, input_x.device) + + patches['middle_patch'] = [gligen_patch] + + cond_obj = collections.namedtuple('cond_obj', ['input_x', 'mult', 'conditioning', 'area', 'control', 'patches', 'uuid', 'hooks']) + return cond_obj(input_x, mult, conditioning, area, control, patches, conds['uuid'], hooks) + +def cond_equal_size(c1, c2): + if c1 is c2: + return True + if c1.keys() != c2.keys(): + return False + for k in c1: + if not c1[k].can_concat(c2[k]): + return False + return True + +def can_concat_cond(c1, c2): + if c1.input_x.shape != c2.input_x.shape: + return False + + def objects_concatable(obj1, obj2): + if (obj1 is None) != (obj2 is None): + return False + if obj1 is not None: + if obj1 is not obj2: + return False + return True + + if not objects_concatable(c1.control, c2.control): + return False + + if not objects_concatable(c1.patches, c2.patches): + return False + + return cond_equal_size(c1.conditioning, c2.conditioning) + +def cond_cat(c_list, device=None): + temp = {} + for x in c_list: + for k in x: + cur = temp.get(k, []) + cur.append(x[k]) + temp[k] = cur + + out = {} + for k in temp: + conds = temp[k] + out[k] = conds[0].concat(conds[1:]) + if device is not None and hasattr(out[k], 'to'): + out[k] = out[k].to(device) + + return out + +def finalize_default_conds(model: 'BaseModel', hooked_to_run: dict[comfy.hooks.HookGroup,list[tuple[tuple,int]]], default_conds: list[list[dict]], x_in, timestep, model_options): + # need to figure out remaining unmasked area for conds + default_mults = [] + for _ in default_conds: + default_mults.append(torch.ones_like(x_in)) + # look through each finalized cond in hooked_to_run for 'mult' and subtract it from each cond + for lora_hooks, to_run in hooked_to_run.items(): + for cond_obj, i in to_run: + # if no default_cond for cond_type, do nothing + if len(default_conds[i]) == 0: + continue + area: list[int] = cond_obj.area + if area is not None: + curr_default_mult: torch.Tensor = default_mults[i] + dims = len(area) // 2 + for i in range(dims): + curr_default_mult = curr_default_mult.narrow(i + 2, area[i + dims], area[i]) + curr_default_mult -= cond_obj.mult + else: + default_mults[i] -= cond_obj.mult + # for each default_mult, ReLU to make negatives=0, and then check for any nonzeros + for i, mult in enumerate(default_mults): + # if no default_cond for cond type, do nothing + if len(default_conds[i]) == 0: + continue + torch.nn.functional.relu(mult, inplace=True) + # if mult is all zeros, then don't add default_cond + if torch.max(mult) == 0.0: + continue + + cond = default_conds[i] + for x in cond: + # do get_area_and_mult to get all the expected values + p = get_area_and_mult(x, x_in, timestep) + if p is None: + continue + # replace p's mult with calculated mult + p = p._replace(mult=mult) + if p.hooks is not None: + model.current_patcher.prepare_hook_patches_current_keyframe(timestep, p.hooks, model_options) + hooked_to_run.setdefault(p.hooks, list()) + hooked_to_run[p.hooks] += [(p, i)] + +def calc_cond_batch(model: BaseModel, conds: list[list[dict]], x_in: torch.Tensor, timestep, model_options: dict[str]): + handler: comfy.context_windows.ContextHandlerABC = model_options.get("context_handler", None) + if handler is None or not handler.should_use_context(model, conds, x_in, timestep, model_options): + return _calc_cond_batch_outer(model, conds, x_in, timestep, model_options) + return handler.execute(_calc_cond_batch_outer, model, conds, x_in, timestep, model_options) + +def _calc_cond_batch_outer(model: BaseModel, conds: list[list[dict]], x_in: torch.Tensor, timestep, model_options): + executor = comfy.patcher_extension.WrapperExecutor.new_executor( + _calc_cond_batch, + comfy.patcher_extension.get_all_wrappers(comfy.patcher_extension.WrappersMP.CALC_COND_BATCH, model_options, is_model_options=True) + ) + return executor.execute(model, conds, x_in, timestep, model_options) + +def _calc_cond_batch(model: BaseModel, conds: list[list[dict]], x_in: torch.Tensor, timestep: torch.Tensor, model_options: dict[str]): + # NOTE: keep in sync with _calc_cond_batch_multigpu below. Shared logic + # (hooked_to_run accumulation, memory-fit batching, per-chunk output + # aggregation) is duplicated there with per-device scheduling layered on top. + if 'multigpu_clones' in model_options: + return _calc_cond_batch_multigpu(model, conds, x_in, timestep, model_options) + out_conds = [] + out_counts = [] + # separate conds by matching hooks + hooked_to_run: dict[comfy.hooks.HookGroup,list[tuple[tuple,int]]] = {} + default_conds = [] + has_default_conds = False + + for i in range(len(conds)): + out_conds.append(torch.zeros_like(x_in)) + out_counts.append(torch.ones_like(x_in) * 1e-37) + + cond = conds[i] + default_c = [] + if cond is not None: + for x in cond: + if 'default' in x: + default_c.append(x) + has_default_conds = True + continue + p = get_area_and_mult(x, x_in, timestep) + if p is None: + continue + if p.hooks is not None: + model.current_patcher.prepare_hook_patches_current_keyframe(timestep, p.hooks, model_options) + hooked_to_run.setdefault(p.hooks, list()) + hooked_to_run[p.hooks] += [(p, i)] + default_conds.append(default_c) + + if has_default_conds: + finalize_default_conds(model, hooked_to_run, default_conds, x_in, timestep, model_options) + + model.current_patcher.prepare_state(timestep, model_options) + + # run every hooked_to_run separately + for hooks, to_run in hooked_to_run.items(): + while len(to_run) > 0: + first = to_run[0] + first_shape = first[0][0].shape + to_batch_temp = [] + for x in range(len(to_run)): + if can_concat_cond(to_run[x][0], first[0]): + to_batch_temp += [x] + + to_batch_temp.reverse() + to_batch = to_batch_temp[:1] + + free_memory = model.current_patcher.get_free_memory(x_in.device) + for i in range(1, len(to_batch_temp) + 1): + batch_amount = to_batch_temp[:len(to_batch_temp)//i] + input_shape = [len(batch_amount) * first_shape[0]] + list(first_shape)[1:] + cond_shapes = collections.defaultdict(list) + for tt in batch_amount: + for k, v in to_run[tt][0].conditioning.items(): + cond_shapes[k].append(v.size()) + + if model.memory_required(input_shape, cond_shapes=cond_shapes) * 1.5 < free_memory: + to_batch = batch_amount + break + + input_x = [] + mult = [] + c = [] + cond_or_uncond = [] + uuids = [] + area = [] + control = None + patches = None + for x in to_batch: + o = to_run.pop(x) + p = o[0] + input_x.append(p.input_x) + mult.append(p.mult) + c.append(p.conditioning) + area.append(p.area) + cond_or_uncond.append(o[1]) + uuids.append(p.uuid) + control = p.control + patches = p.patches + + batch_chunks = len(cond_or_uncond) + input_x = torch.cat(input_x) + c = cond_cat(c) + timestep_ = torch.cat([timestep] * batch_chunks) + + transformer_options = model.current_patcher.apply_hooks(hooks=hooks) + if 'transformer_options' in model_options: + transformer_options = comfy.patcher_extension.merge_nested_dicts(transformer_options, + model_options['transformer_options'], + copy_dict1=False) + + if patches is not None: + transformer_options["patches"] = comfy.patcher_extension.merge_nested_dicts( + transformer_options.get("patches", {}), + patches + ) + + transformer_options["cond_or_uncond"] = cond_or_uncond[:] + transformer_options["uuids"] = uuids[:] + transformer_options["sigmas"] = timestep + + c['transformer_options'] = transformer_options + + if control is not None: + c['control'] = control.get_control(input_x, timestep_, c, len(cond_or_uncond), transformer_options) + + if 'model_function_wrapper' in model_options: + output = model_options['model_function_wrapper'](model.apply_model, {"input": input_x, "timestep": timestep_, "c": c, "cond_or_uncond": cond_or_uncond}).chunk(batch_chunks) + else: + output = model.apply_model(input_x, timestep_, **c).chunk(batch_chunks) + + for o in range(batch_chunks): + cond_index = cond_or_uncond[o] + a = area[o] + if a is None: + out_conds[cond_index] += output[o] * mult[o] + out_counts[cond_index] += mult[o] + else: + out_c = out_conds[cond_index] + out_cts = out_counts[cond_index] + dims = len(a) // 2 + for i in range(dims): + out_c = out_c.narrow(i + 2, a[i + dims], a[i]) + out_cts = out_cts.narrow(i + 2, a[i + dims], a[i]) + out_c += output[o] * mult[o] + out_cts += mult[o] + + for i in range(len(out_conds)): + out_conds[i] /= out_counts[i] + + return out_conds + +def _calc_cond_batch_multigpu(model: BaseModel, conds: list[list[dict]], x_in: torch.Tensor, timestep: torch.Tensor, model_options: dict[str]): + # NOTE: keep in sync with _calc_cond_batch above. Same conds-by-hooks + # accumulation, memory-fit batching, and output aggregation, but adds a + # per-device scheduler, per-device patcher/control lookup, tensor .to(device) + # placement, and MultiGPUThreadPool dispatch around the inner loop. + out_conds = [] + out_counts = [] + # separate conds by matching hooks + hooked_to_run: dict[comfy.hooks.HookGroup,list[tuple[tuple,int]]] = {} + default_conds = [] + has_default_conds = False + + output_device = x_in.device + + for i in range(len(conds)): + out_conds.append(torch.zeros_like(x_in)) + out_counts.append(torch.ones_like(x_in) * 1e-37) + + cond = conds[i] + default_c = [] + if cond is not None: + for x in cond: + if 'default' in x: + default_c.append(x) + has_default_conds = True + continue + p = get_area_and_mult(x, x_in, timestep) + if p is None: + continue + if p.hooks is not None: + model.current_patcher.prepare_hook_patches_current_keyframe(timestep, p.hooks, model_options) + hooked_to_run.setdefault(p.hooks, list()) + hooked_to_run[p.hooks] += [(p, i)] + default_conds.append(default_c) + + if has_default_conds: + finalize_default_conds(model, hooked_to_run, default_conds, x_in, timestep, model_options) + + model.current_patcher.prepare_state(timestep, model_options) + + devices = list(model_options['multigpu_clones'].keys()) + device_batched_hooked_to_run: dict[torch.device, list[tuple[comfy.hooks.HookGroup, tuple]]] = {} + # Track conds currently scheduled per device; single source of truth for capacity checks. + device_load: dict[torch.device, int] = {d: 0 for d in devices} + + total_conds = sum(len(to_run) for to_run in hooked_to_run.values()) + conds_per_device = max(1, math.ceil(total_conds / len(devices))) + + def next_available_device(start: int) -> tuple[int, torch.device]: + """Return (index, device) for the next device with remaining capacity, starting at `start`. + + Scans at most len(devices) positions, so this always terminates. Raises if no device + has remaining capacity, which would indicate a bug in conds_per_device accounting. + """ + for offset in range(len(devices)): + i = (start + offset) % len(devices) + if device_load[devices[i]] < conds_per_device: + return i, devices[i] + raise RuntimeError( + f"MultiGPU scheduler: all {len(devices)} devices at capacity " + f"({conds_per_device}) but conds remain to schedule" + ) + + # run every hooked_to_run separately + index_device = 0 + for hooks, to_run in hooked_to_run.items(): + while len(to_run) > 0: + index_device, current_device = next_available_device(index_device) + remaining_capacity = conds_per_device - device_load[current_device] + + first = to_run[0] + first_shape = first[0][0].shape + # collect candidate indices that can be concatenated with `first`, up to remaining capacity + to_batch_temp = [] + for x in range(len(to_run)): + if can_concat_cond(to_run[x][0], first[0]) and len(to_batch_temp) < remaining_capacity: + to_batch_temp += [x] + + to_batch_temp.reverse() + to_batch = to_batch_temp[:1] + + free_memory = comfy.model_management.get_free_memory(current_device) + for i in range(1, len(to_batch_temp) + 1): + batch_amount = to_batch_temp[:len(to_batch_temp)//i] + input_shape = [len(batch_amount) * first_shape[0]] + list(first_shape)[1:] + cond_shapes = collections.defaultdict(list) + for tt in batch_amount: + for k, v in to_run[tt][0].conditioning.items(): + cond_shapes[k].append(v.size()) + if model.memory_required(input_shape, cond_shapes=cond_shapes) * 1.5 < free_memory: + to_batch = batch_amount + break + + conds_to_batch = [to_run.pop(x) for x in to_batch] + device_load[current_device] += len(conds_to_batch) + device_batched_hooked_to_run.setdefault(current_device, []).append((hooks, conds_to_batch)) + + if device_load[current_device] >= conds_per_device: + index_device += 1 + + class thread_result(NamedTuple): + output: Any + mult: Any + area: Any + batch_chunks: int + cond_or_uncond: Any + error: Exception = None + + def _handle_batch(device: torch.device, batch_tuple: tuple[comfy.hooks.HookGroup, tuple], results: list[thread_result]): + try: + comfy.model_management.set_torch_device(device) + model_current: BaseModel = model_options["multigpu_clones"][device].model + # run every hooked_to_run separately + with torch.no_grad(): + for hooks, to_batch in batch_tuple: + input_x = [] + mult = [] + c = [] + cond_or_uncond = [] + uuids = [] + area = [] + control: ControlBase = None + patches = None + for x in to_batch: + o = x + p = o[0] + input_x.append(p.input_x) + mult.append(p.mult) + c.append(p.conditioning) + area.append(p.area) + cond_or_uncond.append(o[1]) + uuids.append(p.uuid) + control = p.control + patches = p.patches + + batch_chunks = len(cond_or_uncond) + input_x = torch.cat(input_x).to(device) + c = cond_cat(c, device=device) + timestep_ = torch.cat([timestep.to(device)] * batch_chunks) + + transformer_options = model_current.current_patcher.apply_hooks(hooks=hooks) + if 'transformer_options' in model_options: + transformer_options = comfy.patcher_extension.merge_nested_dicts(transformer_options, + model_options['transformer_options'], + copy_dict1=False) + + if patches is not None: + transformer_options["patches"] = comfy.patcher_extension.merge_nested_dicts( + transformer_options.get("patches", {}), + patches + ) + + transformer_options["cond_or_uncond"] = cond_or_uncond[:] + transformer_options["uuids"] = uuids[:] + transformer_options["sigmas"] = timestep.to(device) + transformer_options["sample_sigmas"] = transformer_options["sample_sigmas"].to(device) + transformer_options["multigpu_thread_device"] = device + + cast_transformer_options(transformer_options, device=device) + c['transformer_options'] = transformer_options + + if control is not None: + device_control = control.get_instance_for_device(device) + c['control'] = device_control.get_control(input_x, timestep_, c, len(cond_or_uncond), transformer_options) + + if 'model_function_wrapper' in model_options: + output = model_options['model_function_wrapper'](model_current.apply_model, {"input": input_x, "timestep": timestep_, "c": c, "cond_or_uncond": cond_or_uncond}).to(output_device).chunk(batch_chunks) + else: + output = model_current.apply_model(input_x, timestep_, **c).to(output_device).chunk(batch_chunks) + # TODO: non-NVIDIA support -- the `.to(output_device)` copies + # above are async on CUDA, so the main thread's aggregation + # could race with in-flight transfers. CUDA-only QA has not + # surfaced this in practice, but before extending multigpu + # beyond NVIDIA add a `torch.cuda.synchronize(output_device)` + # here (guarded by `output_device.type == "cuda"`). + results.append(thread_result(output, mult, area, batch_chunks, cond_or_uncond)) + except Exception as e: + results.append(thread_result(None, None, None, None, None, error=e)) + raise + + + def _handle_batch_pooled(device, batch_tuple): + worker_results = [] + _handle_batch(device, batch_tuple, worker_results) + return worker_results + + results: list[thread_result] = [] + thread_pool: comfy.multigpu.MultiGPUThreadPool = model_options.get("multigpu_thread_pool") + + # Submit all GPU work to pool threads + pool_devices = [] + for device, batch_tuple in device_batched_hooked_to_run.items(): + if thread_pool is not None: + thread_pool.submit(device, _handle_batch_pooled, device, batch_tuple) + pool_devices.append(device) + else: + # Fallback: no pool, run everything on main thread + _handle_batch(device, batch_tuple, results) + + # Collect results from pool workers + for device in pool_devices: + worker_results, error = thread_pool.get_result(device) + if error is not None: + raise error + results.extend(worker_results) + + for output, mult, area, batch_chunks, cond_or_uncond, error in results: + if error is not None: + raise error + for o in range(batch_chunks): + cond_index = cond_or_uncond[o] + a = area[o] + if a is None: + out_conds[cond_index] += output[o] * mult[o] + out_counts[cond_index] += mult[o] + else: + out_c = out_conds[cond_index] + out_cts = out_counts[cond_index] + dims = len(a) // 2 + for i in range(dims): + out_c = out_c.narrow(i + 2, a[i + dims], a[i]) + out_cts = out_cts.narrow(i + 2, a[i + dims], a[i]) + out_c += output[o] * mult[o] + out_cts += mult[o] + + for i in range(len(out_conds)): + out_conds[i] /= out_counts[i] + + return out_conds + +def calc_cond_uncond_batch(model, cond, uncond, x_in, timestep, model_options): #TODO: remove + logging.warning("WARNING: The comfy.samplers.calc_cond_uncond_batch function is deprecated please use the calc_cond_batch one instead.") + return tuple(calc_cond_batch(model, [cond, uncond], x_in, timestep, model_options)) + +def cfg_function(model, cond_pred, uncond_pred, cond_scale, x, timestep, model_options={}, cond=None, uncond=None): + if "sampler_cfg_function" in model_options: + args = {"cond": x - cond_pred, "uncond": x - uncond_pred, "cond_scale": cond_scale, "timestep": timestep, "input": x, "sigma": timestep, + "cond_denoised": cond_pred, "uncond_denoised": uncond_pred, "model": model, "model_options": model_options, "input_cond": cond, "input_uncond": uncond} + cfg_result = x - model_options["sampler_cfg_function"](args) + else: + cfg_result = uncond_pred + (cond_pred - uncond_pred) * cond_scale + + for fn in model_options.get("sampler_post_cfg_function", []): + args = {"denoised": cfg_result, "cond": cond, "uncond": uncond, "cond_scale": cond_scale, "model": model, "uncond_denoised": uncond_pred, "cond_denoised": cond_pred, + "sigma": timestep, "model_options": model_options, "input": x} + cfg_result = fn(args) + + return cfg_result + +#The main sampling function shared by all the samplers +#Returns denoised +def sampling_function(model, x, timestep, uncond, cond, cond_scale, model_options={}, seed=None): + if math.isclose(cond_scale, 1.0) and model_options.get("disable_cfg1_optimization", False) == False: + uncond_ = None + else: + uncond_ = uncond + + conds = [cond, uncond_] + if "sampler_calc_cond_batch_function" in model_options: + args = {"conds": conds, "input": x, "sigma": timestep, "model": model, "model_options": model_options} + out = model_options["sampler_calc_cond_batch_function"](args) + else: + out = calc_cond_batch(model, conds, x, timestep, model_options) + + for fn in model_options.get("sampler_pre_cfg_function", []): + args = {"conds":conds, "conds_out": out, "cond_scale": cond_scale, "timestep": timestep, + "input": x, "sigma": timestep, "model": model, "model_options": model_options} + out = fn(args) + + return cfg_function(model, out[0], out[1], cond_scale, x, timestep, model_options=model_options, cond=cond, uncond=uncond_) + + +class KSamplerX0Inpaint: + def __init__(self, model, sigmas): + self.inner_model = model + self.sigmas = sigmas + def __call__(self, x, sigma, denoise_mask, model_options={}, seed=None): + if denoise_mask is not None: + if "denoise_mask_function" in model_options: + denoise_mask = model_options["denoise_mask_function"](sigma, denoise_mask, extra_options={"model": self.inner_model, "sigmas": self.sigmas}) + latent_mask = 1. - denoise_mask + x = x * denoise_mask + self.inner_model.inner_model.scale_latent_inpaint(x=x, sigma=sigma, noise=self.noise, latent_image=self.latent_image) * latent_mask + out = self.inner_model(x, sigma, model_options=model_options, seed=seed) + if denoise_mask is not None: + out = out * denoise_mask + self.latent_image * latent_mask + return out + +def simple_scheduler(model_sampling, steps): + s = model_sampling + sigs = [] + ss = len(s.sigmas) / steps + for x in range(steps): + sigs += [float(s.sigmas[-(1 + int(x * ss))])] + sigs += [0.0] + return torch.FloatTensor(sigs) + +def ddim_scheduler(model_sampling, steps): + s = model_sampling + sigs = [] + x = 1 + if math.isclose(float(s.sigmas[x]), 0, abs_tol=0.00001): + steps += 1 + sigs = [] + else: + sigs = [0.0] + + ss = max(len(s.sigmas) // steps, 1) + while x < len(s.sigmas): + sigs += [float(s.sigmas[x])] + x += ss + sigs = sigs[::-1] + return torch.FloatTensor(sigs) + +def normal_scheduler(model_sampling, steps, sgm=False, floor=False): + s = model_sampling + start = s.timestep(s.sigma_max) + end = s.timestep(s.sigma_min) + + append_zero = True + if sgm: + timesteps = torch.linspace(start, end, steps + 1)[:-1] + else: + if math.isclose(float(s.sigma(end)), 0, abs_tol=0.00001): + steps += 1 + append_zero = False + timesteps = torch.linspace(start, end, steps) + + sigs = [] + for x in range(len(timesteps)): + ts = timesteps[x] + sigs.append(float(s.sigma(ts))) + + if append_zero: + sigs += [0.0] + + return torch.FloatTensor(sigs) + +# Implemented based on: https://arxiv.org/abs/2407.12173 +def beta_scheduler(model_sampling, steps, alpha=0.6, beta=0.6): + total_timesteps = (len(model_sampling.sigmas) - 1) + ts = 1 - numpy.linspace(0, 1, steps, endpoint=False) + ts = numpy.rint(scipy.stats.beta.ppf(ts, alpha, beta) * total_timesteps) + + sigs = [] + last_t = -1 + for t in ts: + if t != last_t: + sigs += [float(model_sampling.sigmas[int(t)])] + last_t = t + sigs += [0.0] + return torch.FloatTensor(sigs) + +# from: https://github.com/genmoai/models/blob/main/src/mochi_preview/infer.py#L41 +def linear_quadratic_schedule(model_sampling, steps, threshold_noise=0.025, linear_steps=None): + if steps == 1: + sigma_schedule = [1.0, 0.0] + else: + if linear_steps is None: + linear_steps = steps // 2 + linear_sigma_schedule = [i * threshold_noise / linear_steps for i in range(linear_steps)] + threshold_noise_step_diff = linear_steps - threshold_noise * steps + quadratic_steps = steps - linear_steps + quadratic_coef = threshold_noise_step_diff / (linear_steps * quadratic_steps ** 2) + linear_coef = threshold_noise / linear_steps - 2 * threshold_noise_step_diff / (quadratic_steps ** 2) + const = quadratic_coef * (linear_steps ** 2) + quadratic_sigma_schedule = [ + quadratic_coef * (i ** 2) + linear_coef * i + const + for i in range(linear_steps, steps) + ] + sigma_schedule = linear_sigma_schedule + quadratic_sigma_schedule + [1.0] + sigma_schedule = [1.0 - x for x in sigma_schedule] + return torch.FloatTensor(sigma_schedule) * model_sampling.sigma_max.cpu() + +# Referenced from https://github.com/AUTOMATIC1111/stable-diffusion-webui/pull/15608 +def kl_optimal_scheduler(n: int, sigma_min: float, sigma_max: float) -> torch.Tensor: + adj_idxs = torch.arange(n, dtype=torch.float).div_(n - 1) + sigmas = adj_idxs.new_zeros(n + 1) + sigmas[:-1] = (adj_idxs * math.atan(sigma_min) + (1 - adj_idxs) * math.atan(sigma_max)).tan_() + return sigmas + +def get_mask_aabb(masks): + if masks.numel() == 0: + return torch.zeros((0, 4), device=masks.device, dtype=torch.int) + + b = masks.shape[0] + + bounding_boxes = torch.zeros((b, 4), device=masks.device, dtype=torch.int) + is_empty = torch.zeros((b), device=masks.device, dtype=torch.bool) + for i in range(b): + mask = masks[i] + if mask.numel() == 0: + continue + if torch.max(mask != 0) == False: + is_empty[i] = True + continue + y, x = torch.where(mask) + bounding_boxes[i, 0] = torch.min(x) + bounding_boxes[i, 1] = torch.min(y) + bounding_boxes[i, 2] = torch.max(x) + bounding_boxes[i, 3] = torch.max(y) + + return bounding_boxes, is_empty + +def resolve_areas_and_cond_masks_multidim(conditions, dims, device): + # We need to decide on an area outside the sampling loop in order to properly generate opposite areas of equal sizes. + # While we're doing this, we can also resolve the mask device and scaling for performance reasons + for i in range(len(conditions)): + c = conditions[i] + if 'area' in c: + area = c['area'] + if area[0] == "percentage": + modified = c.copy() + a = area[1:] + a_len = len(a) // 2 + area = () + for d in range(len(dims)): + area += (max(1, round(a[d] * dims[d])),) + for d in range(len(dims)): + area += (round(a[d + a_len] * dims[d]),) + + modified['area'] = area + c = modified + conditions[i] = c + + if 'mask' in c: + mask = c['mask'] + mask = mask.to(device=device) + modified = c.copy() + if len(mask.shape) == len(dims): + mask = mask.unsqueeze(0) + if mask.shape[1:] != dims: + if mask.ndim < 4: + mask = comfy.utils.common_upscale(mask.unsqueeze(1), dims[-1], dims[-2], 'bilinear', 'none').squeeze(1) + else: + mask = comfy.utils.common_upscale(mask, dims[-1], dims[-2], 'bilinear', 'none') + + if modified.get("set_area_to_bounds", False): #TODO: handle dim != 2 + bounds = torch.max(torch.abs(mask),dim=0).values.unsqueeze(0) + boxes, is_empty = get_mask_aabb(bounds) + if is_empty[0]: + # Use the minimum possible size for efficiency reasons. (Since the mask is all-0, this becomes a noop anyway) + modified['area'] = (8, 8, 0, 0) + else: + box = boxes[0] + H, W, Y, X = (box[3] - box[1] + 1, box[2] - box[0] + 1, box[1], box[0]) + H = max(8, H) + W = max(8, W) + area = (int(H), int(W), int(Y), int(X)) + modified['area'] = area + + modified['mask'] = mask + conditions[i] = modified + +def resolve_areas_and_cond_masks(conditions, h, w, device): + logging.warning("WARNING: The comfy.samplers.resolve_areas_and_cond_masks function is deprecated please use the resolve_areas_and_cond_masks_multidim one instead.") + return resolve_areas_and_cond_masks_multidim(conditions, [h, w], device) + +def create_cond_with_same_area_if_none(conds, c): + if 'area' not in c: + return + + def area_inside(a, area_cmp): + a = add_area_dims(a, len(area_cmp) // 2) + area_cmp = add_area_dims(area_cmp, len(a) // 2) + + a_l = len(a) // 2 + area_cmp_l = len(area_cmp) // 2 + for i in range(min(a_l, area_cmp_l)): + if a[a_l + i] < area_cmp[area_cmp_l + i]: + return False + for i in range(min(a_l, area_cmp_l)): + if (a[i] + a[a_l + i]) > (area_cmp[i] + area_cmp[area_cmp_l + i]): + return False + return True + + c_area = c['area'] + smallest = None + for x in conds: + if 'area' in x: + a = x['area'] + if area_inside(c_area, a): + if smallest is None: + smallest = x + elif 'area' not in smallest: + smallest = x + else: + if math.prod(smallest['area'][:len(smallest['area']) // 2]) > math.prod(a[:len(a) // 2]): + smallest = x + else: + if smallest is None: + smallest = x + if smallest is None: + return + if 'area' in smallest: + if smallest['area'] == c_area: + return + + out = c.copy() + out['model_conds'] = smallest['model_conds'].copy() #TODO: which fields should be copied? + conds += [out] + +def calculate_start_end_timesteps(model, conds): + s = model.model_sampling + for t in range(len(conds)): + x = conds[t] + + timestep_start = None + timestep_end = None + # handle clip hook schedule, if needed + if 'clip_start_percent' in x: + timestep_start = s.percent_to_sigma(max(x['clip_start_percent'], x.get('start_percent', 0.0))) + timestep_end = s.percent_to_sigma(min(x['clip_end_percent'], x.get('end_percent', 1.0))) + else: + if 'start_percent' in x: + timestep_start = s.percent_to_sigma(x['start_percent']) + if 'end_percent' in x: + timestep_end = s.percent_to_sigma(x['end_percent']) + + if (timestep_start is not None) or (timestep_end is not None): + n = x.copy() + if (timestep_start is not None): + n['timestep_start'] = timestep_start + if (timestep_end is not None): + n['timestep_end'] = timestep_end + conds[t] = n + +def pre_run_control(model, conds): + s = model.model_sampling + # Per-device model lookup so multigpu control clones get the matching + # diffusion_model (e.g. QwenFunControlNet stashes it into extra_args). + device_models: dict = {} + patcher = getattr(model, "current_patcher", None) + if patcher is not None: + for p in patcher.get_additional_models_with_key("multigpu"): + device_models[p.load_device] = p.model + for t in range(len(conds)): + x = conds[t] + + percent_to_timestep_function = lambda a: s.percent_to_sigma(a) + if 'control' in x: + x['control'].pre_run(model, percent_to_timestep_function) + for device, device_cnet in x['control'].multigpu_clones.items(): + device_cnet.pre_run(device_models.get(device, model), percent_to_timestep_function) + +def apply_empty_x_to_equal_area(conds, uncond, name, uncond_fill_func): + cond_cnets = [] + cond_other = [] + uncond_cnets = [] + uncond_other = [] + for t in range(len(conds)): + x = conds[t] + if 'area' not in x: + if name in x and x[name] is not None: + cond_cnets.append(x[name]) + else: + cond_other.append((x, t)) + for t in range(len(uncond)): + x = uncond[t] + if 'area' not in x: + if name in x and x[name] is not None: + uncond_cnets.append(x[name]) + else: + uncond_other.append((x, t)) + + if len(uncond_cnets) > 0: + return + + for x in range(len(cond_cnets)): + temp = uncond_other[x % len(uncond_other)] + o = temp[0] + if name in o and o[name] is not None: + n = o.copy() + n[name] = uncond_fill_func(cond_cnets, x) + uncond += [n] + else: + n = o.copy() + n[name] = uncond_fill_func(cond_cnets, x) + uncond[temp[1]] = n + +def encode_model_conds(model_function, conds, noise, device, prompt_type, **kwargs): + for t in range(len(conds)): + x = conds[t] + params = x.copy() + params["device"] = device + params["noise"] = noise + default_width = None + if len(noise.shape) >= 4: #TODO: 8 multiple should be set by the model + default_width = noise.shape[3] * 8 + params["width"] = params.get("width", default_width) + params["height"] = params.get("height", noise.shape[2] * 8) + params["prompt_type"] = params.get("prompt_type", prompt_type) + for k in kwargs: + if k not in params: + params[k] = kwargs[k] + + out = model_function(**params) + x = x.copy() + model_conds = x['model_conds'].copy() + for k in out: + model_conds[k] = out[k] + x['model_conds'] = model_conds + conds[t] = x + return conds + +class Sampler: + def sample(self): + pass + + def max_denoise(self, model_wrap, sigmas): + max_sigma = float(model_wrap.inner_model.model_sampling.sigma_max) + sigma = float(sigmas[0]) + return math.isclose(max_sigma, sigma, rel_tol=1e-05) or sigma > max_sigma + +KSAMPLER_NAMES = ["euler", "euler_cfg_pp", "euler_ancestral", "euler_ancestral_cfg_pp", "heun", "heunpp2", "exp_heun_2_x0", "exp_heun_2_x0_sde", "dpm_2", "dpm_2_ancestral", + "lms", "dpm_fast", "dpm_adaptive", "dpmpp_2s_ancestral", "dpmpp_2s_ancestral_cfg_pp", "dpmpp_sde", "dpmpp_sde_gpu", + "dpmpp_2m", "dpmpp_2m_cfg_pp", "dpmpp_2m_sde", "dpmpp_2m_sde_gpu", "dpmpp_2m_sde_heun", "dpmpp_2m_sde_heun_gpu", "dpmpp_3m_sde", "dpmpp_3m_sde_gpu", "ddpm", "lcm", + "ipndm", "ipndm_v", "deis", "res_multistep", "res_multistep_cfg_pp", "res_multistep_ancestral", "res_multistep_ancestral_cfg_pp", + "gradient_estimation", "gradient_estimation_cfg_pp", "er_sde", "seeds_2", "seeds_3", "sa_solver", "sa_solver_pece"] + +class KSAMPLER(Sampler): + def __init__(self, sampler_function, extra_options={}, inpaint_options={}): + self.sampler_function = sampler_function + self.extra_options = extra_options + self.inpaint_options = inpaint_options + + def sample(self, model_wrap, sigmas, extra_args, callback, noise, latent_image=None, denoise_mask=None, disable_pbar=False): + extra_args["denoise_mask"] = denoise_mask + model_k = KSamplerX0Inpaint(model_wrap, sigmas) + model_k.latent_image = latent_image + if self.inpaint_options.get("random", False): #TODO: Should this be the default? + generator = torch.manual_seed(extra_args.get("seed", 41) + 1) + model_k.noise = torch.randn(noise.shape, generator=generator, device="cpu").to(noise.dtype).to(noise.device) + else: + model_k.noise = noise + + noise = model_wrap.inner_model.model_sampling.noise_scaling(sigmas[0], noise, latent_image, self.max_denoise(model_wrap, sigmas)) + + total_steps = len(sigmas) - 1 + first_step = True + def k_callback(x): + nonlocal first_step + if first_step: + detail("First sampler step: model=%s sampler=%s step=%s total_steps=%s cfg=%s seed=%s sigma=%s sigma_hat=%s latent_shape=%s denoised_shape=%s", model_wrap.model_patcher.model.__class__.__name__, getattr(self.sampler_function, "__name__", "unknown"), x["i"], total_steps, model_wrap.cfg, extra_args.get("seed"), x.get("sigma"), x.get("sigma_hat"), tuple(x["x"].shape), tuple(x["denoised"].shape)) + first_step = False + if callback is not None: + callback(x["i"], x["denoised"], x["x"], total_steps) + + samples = self.sampler_function(model_k, noise, sigmas, extra_args=extra_args, callback=k_callback, disable=disable_pbar, **self.extra_options) + samples = model_wrap.inner_model.model_sampling.inverse_noise_scaling(sigmas[-1], samples) + return samples + + +def ksampler(sampler_name, extra_options={}, inpaint_options={}): + if sampler_name == "dpm_fast": + def dpm_fast_function(model, noise, sigmas, extra_args, callback, disable): + if len(sigmas) <= 1: + return noise + + sigma_min = sigmas[-1] + if sigma_min == 0: + sigma_min = sigmas[-2] + total_steps = len(sigmas) - 1 + return k_diffusion_sampling.sample_dpm_fast(model, noise, sigma_min, sigmas[0], total_steps, extra_args=extra_args, callback=callback, disable=disable) + sampler_function = dpm_fast_function + elif sampler_name == "dpm_adaptive": + def dpm_adaptive_function(model, noise, sigmas, extra_args, callback, disable, **extra_options): + if len(sigmas) <= 1: + return noise + + sigma_min = sigmas[-1] + if sigma_min == 0: + sigma_min = sigmas[-2] + return k_diffusion_sampling.sample_dpm_adaptive(model, noise, sigma_min, sigmas[0], extra_args=extra_args, callback=callback, disable=disable, **extra_options) + sampler_function = dpm_adaptive_function + else: + sampler_function = getattr(k_diffusion_sampling, "sample_{}".format(sampler_name)) + + return KSAMPLER(sampler_function, extra_options, inpaint_options) + + +def process_conds(model, noise, conds, device, latent_image=None, denoise_mask=None, seed=None, latent_shapes=None): + for k in conds: + conds[k] = conds[k][:] + resolve_areas_and_cond_masks_multidim(conds[k], noise.shape[2:], device) + + for k in conds: + calculate_start_end_timesteps(model, conds[k]) + + if hasattr(model, 'extra_conds'): + for k in conds: + conds[k] = encode_model_conds(model.extra_conds, conds[k], noise, device, k, latent_image=latent_image, denoise_mask=denoise_mask, seed=seed, latent_shapes=latent_shapes) + + #make sure each cond area has an opposite one with the same area + for k in conds: + for c in conds[k]: + for kk in conds: + if k != kk: + create_cond_with_same_area_if_none(conds[kk], c) + + for k in conds: + for c in conds[k]: + if 'hooks' in c: + for hook in c['hooks'].hooks: + hook.initialize_timesteps(model) + + for k in conds: + pre_run_control(model, conds[k]) + + if "positive" in conds: + positive = conds["positive"] + for k in conds: + if k != "positive": + apply_empty_x_to_equal_area(list(filter(lambda c: c.get('control_apply_to_uncond', False) == True, positive)), conds[k], 'control', lambda cond_cnets, x: cond_cnets[x]) + apply_empty_x_to_equal_area(positive, conds[k], 'gligen', lambda cond_cnets, x: cond_cnets[x]) + + return conds + + +def preprocess_conds_hooks(conds: dict[str, list[dict[str]]]): + # determine which ControlNets have extra_hooks that should be combined with normal hooks + hook_replacement: dict[tuple[ControlBase, comfy.hooks.HookGroup], list[dict]] = {} + for k in conds: + for kk in conds[k]: + if 'control' in kk: + control: 'ControlBase' = kk['control'] + extra_hooks = control.get_extra_hooks() + if len(extra_hooks) > 0: + hooks: comfy.hooks.HookGroup = kk.get('hooks', None) + to_replace = hook_replacement.setdefault((control, hooks), []) + to_replace.append(kk) + # if nothing to replace, do nothing + if len(hook_replacement) == 0: + return + + # for optimal sampling performance, common ControlNets + hook combos should have identical hooks + # on the cond dicts + for key, conds_to_modify in hook_replacement.items(): + control = key[0] + hooks = key[1] + hooks = comfy.hooks.HookGroup.combine_all_hooks(control.get_extra_hooks() + [hooks]) + # if combined hooks are not None, set as new hooks for all relevant conds + if hooks is not None: + for cond in conds_to_modify: + cond['hooks'] = hooks + +def filter_registered_hooks_on_conds(conds: dict[str, list[dict[str]]], model_options: dict[str]): + '''Modify 'hooks' on conds so that only hooks that were registered remain. Properly accounts for + HookGroups that have the same reference.''' + registered: comfy.hooks.HookGroup = model_options.get('registered_hooks', None) + # if None were registered, make sure all hooks are cleaned from conds + if registered is None: + for k in conds: + for kk in conds[k]: + kk.pop('hooks', None) + return + # find conds that contain hooks to be replaced - group by common HookGroup refs + hook_replacement: dict[comfy.hooks.HookGroup, list[dict]] = {} + for k in conds: + for kk in conds[k]: + hooks: comfy.hooks.HookGroup = kk.get('hooks', None) + if hooks is not None: + if not hooks.is_subset_of(registered): + to_replace = hook_replacement.setdefault(hooks, []) + to_replace.append(kk) + # for each hook to replace, create a new proper HookGroup and assign to all common conds + for hooks, conds_to_modify in hook_replacement.items(): + new_hooks = hooks.new_with_common_hooks(registered) + if len(new_hooks) == 0: + new_hooks = None + for kk in conds_to_modify: + kk['hooks'] = new_hooks + + +def get_total_hook_groups_in_conds(conds: dict[str, list[dict[str]]]): + hooks_set = set() + for k in conds: + for kk in conds[k]: + hooks_set.add(kk.get('hooks', None)) + return len(hooks_set) + + +def cast_to_load_options(model_options: dict[str], device=None, dtype=None): + ''' + If any patches from hooks, wrappers, or callbacks have .to to be called, call it. + ''' + if model_options is None: + return + to_load_options = model_options.get("to_load_options", None) + if to_load_options is None: + return + cast_transformer_options(to_load_options, device, dtype) + +def cast_transformer_options(transformer_options: dict[str], device=None, dtype=None): + casts = [] + if device is not None: + casts.append(device) + if dtype is not None: + casts.append(dtype) + # if nothing to apply, do nothing + if len(casts) == 0: + return + # try to call .to on patches + if "patches" in transformer_options: + patches = transformer_options["patches"] + for name in patches: + patch_list = patches[name] + for i in range(len(patch_list)): + if hasattr(patch_list[i], "to"): + for cast in casts: + patch_list[i] = patch_list[i].to(cast) + if "patches_replace" in transformer_options: + patches = transformer_options["patches_replace"] + for name in patches: + patch_list = patches[name] + for k in patch_list: + if hasattr(patch_list[k], "to"): + for cast in casts: + patch_list[k] = patch_list[k].to(cast) + # try to call .to on any wrappers/callbacks + wrappers_and_callbacks = ["wrappers", "callbacks"] + for wc_name in wrappers_and_callbacks: + if wc_name in transformer_options: + wc: dict[str, list] = transformer_options[wc_name] + for wc_dict in wc.values(): + for wc_list in wc_dict.values(): + for i in range(len(wc_list)): + if hasattr(wc_list[i], "to"): + for cast in casts: + wc_list[i] = wc_list[i].to(cast) + +class CFGGuider: + def __init__(self, model_patcher: ModelPatcher): + self.model_patcher = model_patcher + self.model_options = model_patcher.model_options + self.original_conds = {} + self.cfg = 1.0 + + def set_conds(self, positive, negative): + self.inner_set_conds({"positive": positive, "negative": negative}) + + def set_cfg(self, cfg): + self.cfg = cfg + + def inner_set_conds(self, conds): + for k in conds: + if self.model_patcher.is_dynamic() and comfy.sampler_helpers.cond_has_hooks(conds[k]): + self.model_patcher = self.model_patcher.get_non_dynamic_delegate() + self.original_conds[k] = comfy.sampler_helpers.convert_cond(conds[k]) + + def __call__(self, *args, **kwargs): + return self.outer_predict_noise(*args, **kwargs) + + def outer_predict_noise(self, x, timestep, model_options={}, seed=None): + return comfy.patcher_extension.WrapperExecutor.new_class_executor( + self.predict_noise, + self, + comfy.patcher_extension.get_all_wrappers(comfy.patcher_extension.WrappersMP.PREDICT_NOISE, self.model_options, is_model_options=True) + ).execute(x, timestep, model_options, seed) + + def predict_noise(self, x, timestep, model_options={}, seed=None): + return sampling_function(self.inner_model, x, timestep, self.conds.get("negative", None), self.conds.get("positive", None), self.cfg, model_options=model_options, seed=seed) + + def inner_sample(self, noise, latent_image, device, sampler, sigmas, denoise_mask, callback, disable_pbar, seed, latent_shapes=None): + self.inner_model.latent_shapes = latent_shapes + + if latent_image is not None and torch.count_nonzero(latent_image) > 0: #Don't shift the empty latent image. + latent_image = self.inner_model.process_latent_in(latent_image) + + self.conds = process_conds(self.inner_model, noise, self.conds, device, latent_image, denoise_mask, seed, latent_shapes=latent_shapes) + + extra_model_options = comfy.model_patcher.create_model_options_clone(self.model_options) + extra_model_options.setdefault("transformer_options", {})["sample_sigmas"] = sigmas + extra_args = {"model_options": extra_model_options, "seed": seed} + + executor = comfy.patcher_extension.WrapperExecutor.new_class_executor( + sampler.sample, + sampler, + comfy.patcher_extension.get_all_wrappers(comfy.patcher_extension.WrappersMP.SAMPLER_SAMPLE, extra_args["model_options"], is_model_options=True) + ) + samples = executor.execute(self, sigmas, extra_args, callback, noise, latent_image, denoise_mask, disable_pbar) + return self.inner_model.process_latent_out(samples.to(torch.float32)) + + def outer_sample(self, noise, latent_image, sampler, sigmas, denoise_mask=None, callback=None, disable_pbar=False, seed=None, latent_shapes=None): + self.inner_model, self.conds, self.loaded_models = comfy.sampler_helpers.prepare_sampling(self.model_patcher, noise.shape, self.conds, self.model_options) + device = self.model_patcher.load_device + + multigpu_patchers = comfy.sampler_helpers.prepare_model_patcher_multigpu_clones(self.model_patcher, self.loaded_models, self.model_options) + + # Create persistent thread pool for all GPU devices (main + extras) + if multigpu_patchers: + extra_devices = [p.load_device for p in multigpu_patchers] + all_devices = [device] + extra_devices + self.model_options["multigpu_thread_pool"] = comfy.multigpu.MultiGPUThreadPool(all_devices) + + with comfy.model_management.cuda_device_context(device): + try: + noise = noise.to(device=device, dtype=torch.float32) + latent_image = latent_image.to(device=device, dtype=torch.float32) + sigmas = sigmas.to(device) + cast_to_load_options(self.model_options, device=device, dtype=self.model_patcher.model_dtype()) + + self.model_patcher.pre_run() + for multigpu_patcher in multigpu_patchers: + multigpu_patcher.pre_run() + output = self.inner_sample(noise, latent_image, device, sampler, sigmas, denoise_mask, callback, disable_pbar, seed, latent_shapes=latent_shapes) + finally: + thread_pool = self.model_options.pop("multigpu_thread_pool", None) + if thread_pool is not None: + thread_pool.shutdown() + self.model_patcher.cleanup() + for multigpu_patcher in multigpu_patchers: + multigpu_patcher.cleanup() + + comfy.sampler_helpers.cleanup_models(self.conds, self.loaded_models) + del self.inner_model + del self.loaded_models + return output + + def sample(self, noise, latent_image, sampler, sigmas, denoise_mask=None, callback=None, disable_pbar=False, seed=None): + if sigmas.shape[-1] == 0: + return latent_image + + if latent_image.is_nested: + sampler_shapes = [tuple(x.shape) for x in latent_image.unbind()] + latent_image, latent_shapes = comfy.utils.pack_latents(latent_image.unbind()) + noise, _ = comfy.utils.pack_latents(noise.unbind()) + else: + latent_shapes = [latent_image.shape] + sampler_shapes = [tuple(latent_image.shape)] + detail("Sampler: model=%s latent_shapes=%s", self.model_patcher.model.__class__.__name__, sampler_shapes) + + if len(latent_shapes) > 1 and callback is not None: + # samplers run on the flat pack, hand callbacks (previews, x0 output) the nested view + packed_callback = callback + def callback(step, x0, x, total_steps): + x0 = comfy.nested_tensor.NestedTensor(comfy.utils.unpack_latents(x0, latent_shapes)) + x = comfy.nested_tensor.NestedTensor(comfy.utils.unpack_latents(x, latent_shapes)) + return packed_callback(step, x0, x, total_steps) + + if denoise_mask is not None: + if denoise_mask.is_nested: + denoise_masks = denoise_mask.unbind() + denoise_masks = denoise_masks[:len(latent_shapes)] + else: + denoise_masks = [denoise_mask] + + for i in range(len(denoise_masks), len(latent_shapes)): + denoise_masks.append(torch.ones(latent_shapes[i])) + + for i in range(len(denoise_masks)): + denoise_masks[i] = comfy.sampler_helpers.prepare_mask(denoise_masks[i], latent_shapes[i], self.model_patcher.load_device) + + if len(denoise_masks) > 1: + denoise_mask, _ = comfy.utils.pack_latents(denoise_masks) + else: + denoise_mask = denoise_masks[0] + denoise_mask = denoise_mask.float() + + self.conds = {} + for k in self.original_conds: + self.conds[k] = list(map(lambda a: a.copy(), self.original_conds[k])) + preprocess_conds_hooks(self.conds) + + try: + orig_model_options = self.model_options + self.model_options = comfy.model_patcher.create_model_options_clone(self.model_options) + # if one hook type (or just None), then don't bother caching weights for hooks (will never change after first step) + orig_hook_mode = self.model_patcher.hook_mode + if get_total_hook_groups_in_conds(self.conds) <= 1: + self.model_patcher.hook_mode = comfy.hooks.EnumHookMode.MinVram + comfy.sampler_helpers.prepare_model_patcher(self.model_patcher, self.conds, self.model_options) + filter_registered_hooks_on_conds(self.conds, self.model_options) + executor = comfy.patcher_extension.WrapperExecutor.new_class_executor( + self.outer_sample, + self, + comfy.patcher_extension.get_all_wrappers(comfy.patcher_extension.WrappersMP.OUTER_SAMPLE, self.model_options, is_model_options=True) + ) + output = executor.execute(noise, latent_image, sampler, sigmas, denoise_mask, callback, disable_pbar, seed, latent_shapes=latent_shapes) + finally: + cast_to_load_options(self.model_options, device=self.model_patcher.offload_device) + self.model_options = orig_model_options + self.model_patcher.hook_mode = orig_hook_mode + self.model_patcher.restore_hook_patches() + + del self.conds + + if len(latent_shapes) > 1: + output = comfy.nested_tensor.NestedTensor(comfy.utils.unpack_latents(output, latent_shapes)) + return output + + +def sample(model, noise, positive, negative, cfg, device, sampler, sigmas, model_options={}, latent_image=None, denoise_mask=None, callback=None, disable_pbar=False, seed=None): + cfg_guider = CFGGuider(model) + cfg_guider.set_conds(positive, negative) + cfg_guider.set_cfg(cfg) + return cfg_guider.sample(noise, latent_image, sampler, sigmas, denoise_mask, callback, disable_pbar, seed) + + +SAMPLER_NAMES = KSAMPLER_NAMES + ["ddim", "uni_pc", "uni_pc_bh2"] + +class SchedulerHandler(NamedTuple): + handler: Callable[..., torch.Tensor] + # Boolean indicates whether to call the handler like: + # scheduler_function(model_sampling, steps) or + # scheduler_function(n, sigma_min: float, sigma_max: float) + use_ms: bool = True + +SCHEDULER_HANDLERS = { + "simple": SchedulerHandler(simple_scheduler), + "sgm_uniform": SchedulerHandler(partial(normal_scheduler, sgm=True)), + "karras": SchedulerHandler(k_diffusion_sampling.get_sigmas_karras, use_ms=False), + "exponential": SchedulerHandler(k_diffusion_sampling.get_sigmas_exponential, use_ms=False), + "ddim_uniform": SchedulerHandler(ddim_scheduler), + "beta": SchedulerHandler(beta_scheduler), + "normal": SchedulerHandler(normal_scheduler), + "linear_quadratic": SchedulerHandler(linear_quadratic_schedule), + "kl_optimal": SchedulerHandler(kl_optimal_scheduler, use_ms=False), +} +SCHEDULER_NAMES = list(SCHEDULER_HANDLERS) + +def calculate_sigmas(model_sampling: object, scheduler_name: str, steps: int) -> torch.Tensor: + handler = SCHEDULER_HANDLERS.get(scheduler_name) + if handler is None: + err = f"error invalid scheduler {scheduler_name}" + logging.error(err) + raise ValueError(err) + if handler.use_ms: + return handler.handler(model_sampling, steps) + return handler.handler(n=steps, sigma_min=float(model_sampling.sigma_min), sigma_max=float(model_sampling.sigma_max)) + +def sampler_object(name): + if name == "uni_pc": + sampler = KSAMPLER(uni_pc.sample_unipc) + elif name == "uni_pc_bh2": + sampler = KSAMPLER(uni_pc.sample_unipc_bh2) + elif name == "ddim": + sampler = ksampler("euler", inpaint_options={"random": True}) + else: + sampler = ksampler(name) + return sampler + +class KSampler: + SCHEDULERS = SCHEDULER_NAMES + SAMPLERS = SAMPLER_NAMES + DISCARD_PENULTIMATE_SIGMA_SAMPLERS = set(('dpm_2', 'dpm_2_ancestral', 'uni_pc', 'uni_pc_bh2')) + + def __init__(self, model, steps, device, sampler=None, scheduler=None, denoise=None, model_options={}): + self.model = model + self.device = device + if scheduler not in self.SCHEDULERS: + scheduler = self.SCHEDULERS[0] + if sampler not in self.SAMPLERS: + sampler = self.SAMPLERS[0] + self.scheduler = scheduler + self.sampler = sampler + self.set_steps(steps, denoise) + self.denoise = denoise + self.model_options = model_options + + def calculate_sigmas(self, steps): + sigmas = None + + discard_penultimate_sigma = False + if self.sampler in self.DISCARD_PENULTIMATE_SIGMA_SAMPLERS: + steps += 1 + discard_penultimate_sigma = True + + sigmas = calculate_sigmas(self.model.get_model_object("model_sampling"), self.scheduler, steps) + + if discard_penultimate_sigma: + sigmas = torch.cat([sigmas[:-2], sigmas[-1:]]) + return sigmas + + def set_steps(self, steps, denoise=None): + self.steps = steps + if denoise is None or denoise > 0.9999: + self.sigmas = self.calculate_sigmas(steps).to(self.device) + else: + if denoise <= 0.0: + self.sigmas = torch.FloatTensor([]) + else: + new_steps = int(steps/denoise) + sigmas = self.calculate_sigmas(new_steps).to(self.device) + self.sigmas = sigmas[-(steps + 1):] + + def sample(self, noise, positive, negative, cfg, latent_image=None, start_step=None, last_step=None, force_full_denoise=False, denoise_mask=None, sigmas=None, callback=None, disable_pbar=False, seed=None): + if sigmas is None: + sigmas = self.sigmas + + if last_step is not None and last_step < (len(sigmas) - 1): + sigmas = sigmas[:last_step + 1] + if force_full_denoise: + sigmas[-1] = 0 + + if start_step is not None: + if start_step < (len(sigmas) - 1): + sigmas = sigmas[start_step:] + else: + if latent_image is not None: + return latent_image + else: + return torch.zeros_like(noise) + + sampler = sampler_object(self.sampler) + + return sample(self.model, noise, positive, negative, cfg, self.device, sampler, sigmas, self.model_options, latent_image=latent_image, denoise_mask=denoise_mask, callback=callback, disable_pbar=disable_pbar, seed=seed) diff --git a/docs/hel-892/h3-core-reference/core__comfy_api__latest___io.py b/docs/hel-892/h3-core-reference/core__comfy_api__latest___io.py new file mode 100644 index 00000000..6d9e08f4 --- /dev/null +++ b/docs/hel-892/h3-core-reference/core__comfy_api__latest___io.py @@ -0,0 +1,2497 @@ +from __future__ import annotations + +import copy +import inspect +from abc import ABC, abstractmethod +from collections import Counter +from collections.abc import Iterable +from dataclasses import asdict, dataclass, field +from enum import Enum +from typing import Any, Callable, Literal, TypedDict, TypeVar, TYPE_CHECKING +from typing_extensions import NotRequired, final + +# used for type hinting +import torch + +if TYPE_CHECKING: + from spandrel import ImageModelDescriptor + from comfy.clip_vision import ClipVisionModel + from comfy.clip_vision import Output as ClipVisionOutput_ + from comfy.bg_removal_model import BackgroundRemovalModel + from comfy.controlnet import ControlNet + from comfy.hooks import HookGroup, HookKeyframeGroup + from comfy.model_patcher import ModelPatcher + from comfy.samplers import CFGGuider, Sampler + from comfy.sd import CLIP, VAE + from comfy.sd import StyleModel as StyleModel_ + from comfy_api.input import VideoInput, CurveInput as CurveInput_ +from comfy_api.internal import (_ComfyNodeInternal, _NodeOutputInternal, classproperty, copy_class, first_real_override, is_class, + prune_dict, shallow_clone_class) +from comfy_execution.graph_utils import ExecutionBlocker +from ._util import MESH, VOXEL, SPLAT, SVG as _SVG, File3D + + +class FolderType(str, Enum): + input = "input" + output = "output" + temp = "temp" + + +class UploadType(str, Enum): + image = "image_upload" + audio = "audio_upload" + video = "video_upload" + model = "file_upload" + + +class RemoteOptions: + def __init__(self, route: str, refresh_button: bool, control_after_refresh: Literal["first", "last"]="first", + timeout: int=None, max_retries: int=None, refresh: int=None): + self.route = route + """The route to the remote source.""" + self.refresh_button = refresh_button + """Specifies whether to show a refresh button in the UI below the widget.""" + self.control_after_refresh = control_after_refresh + """Specifies the control after the refresh button is clicked. If "first", the first item will be automatically selected, and so on.""" + self.timeout = timeout + """The maximum amount of time to wait for a response from the remote source in milliseconds.""" + self.max_retries = max_retries + """The maximum number of retries before aborting the request.""" + self.refresh = refresh + """The TTL of the remote input's value in milliseconds. Specifies the interval at which the remote input's value is refreshed.""" + + def as_dict(self): + return prune_dict({ + "route": self.route, + "refresh_button": self.refresh_button, + "control_after_refresh": self.control_after_refresh, + "timeout": self.timeout, + "max_retries": self.max_retries, + "refresh": self.refresh, + }) + + +class NumberDisplay(str, Enum): + number = "number" + slider = "slider" + gradient_slider = "gradientslider" + + +class ControlAfterGenerate(str, Enum): + fixed = "fixed" + increment = "increment" + decrement = "decrement" + randomize = "randomize" + +class _ComfyType(ABC): + Type = Any + io_type: str = None + +# NOTE: this is a workaround to make the decorator return the correct type +T = TypeVar("T", bound=type) +def comfytype(io_type: str, **kwargs): + ''' + Decorator to mark nested classes as ComfyType; io_type will be bound to the class. + + A ComfyType may have the following attributes: + - Type = + - class Input(Input): ... + - class Output(Output): ... + ''' + def decorator(cls: T) -> T: + if isinstance(cls, _ComfyType) or issubclass(cls, _ComfyType): + # clone Input and Output classes to avoid modifying the original class + new_cls = cls + if hasattr(new_cls, "Input"): + new_cls.Input = copy_class(new_cls.Input) + if hasattr(new_cls, "Output"): + new_cls.Output = copy_class(new_cls.Output) + else: + # copy class attributes except for special ones that shouldn't be in type() + cls_dict = { + k: v for k, v in cls.__dict__.items() + if k not in ('__dict__', '__weakref__', '__module__', '__doc__') + } + # new class + new_cls: ComfyTypeIO = type( + cls.__name__, + (cls, ComfyTypeIO), + cls_dict + ) + # metadata preservation + new_cls.__module__ = cls.__module__ + new_cls.__doc__ = cls.__doc__ + # assign ComfyType attributes, if needed + new_cls.io_type = io_type + if hasattr(new_cls, "Input") and new_cls.Input is not None: + new_cls.Input.Parent = new_cls + if hasattr(new_cls, "Output") and new_cls.Output is not None: + new_cls.Output.Parent = new_cls + return new_cls + return decorator + +def Custom(io_type: str) -> type[ComfyTypeIO]: + '''Create a ComfyType for a custom io_type.''' + @comfytype(io_type=io_type) + class CustomComfyType(ComfyTypeIO): + ... + return CustomComfyType + +class _IO_V3: + ''' + Base class for V3 Inputs and Outputs. + ''' + Parent: _ComfyType = None + + def __init__(self): + pass + + def validate(self): + pass + + @property + def io_type(self): + return self.Parent.io_type + + @property + def Type(self): + return self.Parent.Type + +class Input(_IO_V3): + ''' + Base class for a V3 Input. + ''' + def __init__(self, id: str, display_name: str=None, optional=False, tooltip: str=None, lazy: bool=None, extra_dict=None, raw_link: bool=None, advanced: bool=None): + super().__init__() + self.id = id + self.display_name = display_name + self.optional = optional + self.tooltip = tooltip + self.lazy = lazy + self.extra_dict = extra_dict if extra_dict is not None else {} + self.rawLink = raw_link + self.advanced = advanced + + def as_dict(self): + return prune_dict({ + "display_name": self.display_name, + "optional": self.optional, + "tooltip": self.tooltip, + "lazy": self.lazy, + "rawLink": self.rawLink, + "advanced": self.advanced, + }) | prune_dict(self.extra_dict) + + def get_io_type(self): + return self.io_type + + def get_all(self) -> list[Input]: + return [self] + +class WidgetInput(Input): + ''' + Base class for a V3 Input with widget. + ''' + def __init__(self, id: str, display_name: str=None, optional=False, tooltip: str=None, lazy: bool=None, + default: Any=None, + socketless: bool=None, widget_type: str=None, force_input: bool=None, extra_dict=None, raw_link: bool=None, advanced: bool=None): + super().__init__(id, display_name, optional, tooltip, lazy, extra_dict, raw_link, advanced) + self.default = default + self.socketless = socketless + self.widget_type = widget_type + self.force_input = force_input + + def as_dict(self): + return super().as_dict() | prune_dict({ + "default": self.default, + "socketless": self.socketless, + "widgetType": self.widget_type, + "forceInput": self.force_input, + }) + + def get_io_type(self): + return self.widget_type if self.widget_type is not None else super().get_io_type() + + +class Output(_IO_V3): + def __init__(self, id: str=None, display_name: str=None, tooltip: str=None, + is_output_list=False): + self.id = id + self.display_name = display_name if display_name else id + self.tooltip = tooltip + self.is_output_list = is_output_list + + def as_dict(self): + display_name = self.display_name if self.display_name else self.id + return prune_dict({ + "display_name": display_name, + "tooltip": self.tooltip, + "is_output_list": self.is_output_list, + }) + + def get_io_type(self): + return self.io_type + + +class ComfyTypeI(_ComfyType): + '''ComfyType subclass that only has a default Input class - intended for types that only have Inputs.''' + class Input(Input): + ... + +class ComfyTypeIO(ComfyTypeI): + '''ComfyType subclass that has default Input and Output classes; useful for types with both Inputs and Outputs.''' + class Output(Output): + ... + + +@comfytype(io_type="BOOLEAN") +class Boolean(ComfyTypeIO): + Type = bool + + class Input(WidgetInput): + '''Boolean input.''' + def __init__(self, id: str, display_name: str=None, optional=False, tooltip: str=None, lazy: bool=None, + default: bool=None, label_on: str=None, label_off: str=None, + socketless: bool=None, force_input: bool=None, extra_dict=None, raw_link: bool=None, advanced: bool=None): + super().__init__(id, display_name, optional, tooltip, lazy, default, socketless, None, force_input, extra_dict, raw_link, advanced) + self.label_on = label_on + self.label_off = label_off + self.default: bool + + def as_dict(self): + return super().as_dict() | prune_dict({ + "label_on": self.label_on, + "label_off": self.label_off, + }) + +@comfytype(io_type="INT") +class Int(ComfyTypeIO): + Type = int + + class Input(WidgetInput): + '''Integer input.''' + def __init__(self, id: str, display_name: str=None, optional=False, tooltip: str=None, lazy: bool=None, + default: int=None, min: int=None, max: int=None, step: int=None, control_after_generate: bool | ControlAfterGenerate=None, + display_mode: NumberDisplay=None, socketless: bool=None, force_input: bool=None, extra_dict=None, raw_link: bool=None, advanced: bool=None): + super().__init__(id, display_name, optional, tooltip, lazy, default, socketless, None, force_input, extra_dict, raw_link, advanced) + self.min = min + self.max = max + self.step = step + self.control_after_generate = control_after_generate + self.display_mode = display_mode + self.default: int + + def as_dict(self): + return super().as_dict() | prune_dict({ + "min": self.min, + "max": self.max, + "step": self.step, + "control_after_generate": self.control_after_generate, + "display": self.display_mode.value if self.display_mode else None, + }) + +@comfytype(io_type="FLOAT") +class Float(ComfyTypeIO): + Type = float + + class Input(WidgetInput): + '''Float input.''' + def __init__(self, id: str, display_name: str=None, optional=False, tooltip: str=None, lazy: bool=None, + default: float=None, min: float=None, max: float=None, step: float=None, round: float=None, + display_mode: NumberDisplay=None, gradient_stops: list[dict]=None, + socketless: bool=None, force_input: bool=None, extra_dict=None, raw_link: bool=None, advanced: bool=None): + super().__init__(id, display_name, optional, tooltip, lazy, default, socketless, None, force_input, extra_dict, raw_link, advanced) + self.min = min + self.max = max + self.step = step + self.round = round + self.display_mode = display_mode + self.gradient_stops = gradient_stops + self.default: float + + def as_dict(self): + return super().as_dict() | prune_dict({ + "min": self.min, + "max": self.max, + "step": self.step, + "round": self.round, + "display": self.display_mode, + "gradient_stops": self.gradient_stops, + }) + +@comfytype(io_type="STRING") +class String(ComfyTypeIO): + Type = str + + class Input(WidgetInput): + '''String input.''' + def __init__(self, id: str, display_name: str=None, optional=False, tooltip: str=None, lazy: bool=None, + multiline=False, placeholder: str=None, default: str=None, dynamic_prompts: bool=None, + socketless: bool=None, force_input: bool=None, extra_dict=None, raw_link: bool=None, advanced: bool=None): + super().__init__(id, display_name, optional, tooltip, lazy, default, socketless, None, force_input, extra_dict, raw_link, advanced) + self.multiline = multiline + self.placeholder = placeholder + self.dynamic_prompts = dynamic_prompts + self.default: str + + def as_dict(self): + return super().as_dict() | prune_dict({ + "multiline": self.multiline, + "placeholder": self.placeholder, + "dynamicPrompts": self.dynamic_prompts, + }) + +@comfytype(io_type="COMBO") +class Combo(ComfyTypeIO): + Type = str + class Input(WidgetInput): + """Combo input (dropdown).""" + Type = str + def __init__( + self, + id: str, + options: list[str] | list[int] | type[Enum] = None, + display_name: str=None, + optional=False, + tooltip: str=None, + lazy: bool=None, + default: str | int | Enum = None, + control_after_generate: bool | ControlAfterGenerate=None, + upload: UploadType=None, + image_folder: FolderType=None, + remote: RemoteOptions=None, + socketless: bool=None, + extra_dict=None, + raw_link: bool=None, + advanced: bool=None, + ): + if isinstance(options, type) and issubclass(options, Enum): + options = [v.value for v in options] + if isinstance(default, Enum): + default = default.value + super().__init__(id, display_name, optional, tooltip, lazy, default, socketless, None, None, extra_dict, raw_link, advanced) + self.multiselect = False + self.options = options + self.control_after_generate = control_after_generate + self.upload = upload + self.image_folder = image_folder + self.remote = remote + self.default: str + + def as_dict(self): + return super().as_dict() | prune_dict({ + "multiselect": self.multiselect, + "options": self.options, + "control_after_generate": self.control_after_generate, + **({self.upload.value: True} if self.upload is not None else {}), + "image_folder": self.image_folder.value if self.image_folder else None, + "remote": self.remote.as_dict() if self.remote else None, + }) + + class Output(Output): + def __init__(self, id: str=None, display_name: str=None, options: list[str]=None, tooltip: str=None, is_output_list=False): + super().__init__(id, display_name, tooltip, is_output_list) + self.options = options if options is not None else [] + +@comfytype(io_type="COMBO") +class MultiCombo(ComfyTypeI): + '''Multiselect Combo input (dropdown for selecting potentially more than one value).''' + Type = list[str] + class Input(Combo.Input): + def __init__(self, id: str, options: list[str], display_name: str=None, optional=False, tooltip: str=None, lazy: bool=None, + default: list[str]=None, placeholder: str=None, chip: bool=None, control_after_generate: bool | ControlAfterGenerate=None, + socketless: bool=None, extra_dict=None, raw_link: bool=None, advanced: bool=None): + super().__init__(id, options, display_name, optional, tooltip, lazy, default, control_after_generate, socketless=socketless, extra_dict=extra_dict, raw_link=raw_link, advanced=advanced) + self.multiselect = True + self.placeholder = placeholder + self.chip = chip + self.default: list[str] + + def as_dict(self): + # Frontend expects `multi_select` to be an object config (not a boolean). + # Keep top-level `multiselect` from Combo.Input for backwards compatibility. + return super().as_dict() | prune_dict({ + "multi_select": prune_dict({ + "placeholder": self.placeholder, + "chip": self.chip, + }), + }) + +@comfytype(io_type="IMAGE") +class Image(ComfyTypeIO): + Type = torch.Tensor + + +@comfytype(io_type="WAN_CAMERA_EMBEDDING") +class WanCameraEmbedding(ComfyTypeIO): + Type = torch.Tensor + + +@comfytype(io_type="WEBCAM") +class Webcam(ComfyTypeIO): + Type = str + + class Input(WidgetInput): + """Webcam input.""" + Type = str + def __init__( + self, id: str, display_name: str=None, optional=False, + tooltip: str=None, lazy: bool=None, default: str=None, socketless: bool=None, extra_dict=None, raw_link: bool=None, advanced: bool=None + ): + super().__init__(id, display_name, optional, tooltip, lazy, default, socketless, None, None, extra_dict, raw_link, advanced) + + +@comfytype(io_type="MASK") +class Mask(ComfyTypeIO): + Type = torch.Tensor + +@comfytype(io_type="LATENT") +class Latent(ComfyTypeIO): + '''Latents are stored as a dictionary.''' + class LatentDict(TypedDict): + samples: torch.Tensor + '''Latent tensors.''' + noise_mask: NotRequired[torch.Tensor] + batch_index: NotRequired[list[int]] + type: NotRequired[str] + '''Only needed if dealing with these types: audio, hunyuan3dv2''' + Type = LatentDict + +@comfytype(io_type="CONDITIONING") +class Conditioning(ComfyTypeIO): + class PooledDict(TypedDict): + pooled_output: torch.Tensor + '''Pooled output from CLIP.''' + control: NotRequired[ControlNet] + '''ControlNet to apply to conditioning.''' + control_apply_to_uncond: NotRequired[bool] + '''Whether to apply ControlNet to matching negative conditioning at sample time, if applicable.''' + cross_attn_controlnet: NotRequired[torch.Tensor] + '''CrossAttn from CLIP to use for controlnet only.''' + pooled_output_controlnet: NotRequired[torch.Tensor] + '''Pooled output from CLIP to use for controlnet only.''' + gligen: NotRequired[tuple[str, Gligen, list[tuple[torch.Tensor, int, ...]]]] + '''GLIGEN to apply to conditioning.''' + area: NotRequired[tuple[int, ...] | tuple[str, float, ...]] + '''Set area of conditioning. First half of values apply to dimensions, the second half apply to coordinates. + By default, the dimensions are based on total pixel amount, but the first value can be set to "percentage" to use a percentage of the image size instead. + + (1024, 1024, 0, 0) would apply conditioning to the top-left 1024x1024 pixels. + + ("percentage", 0.5, 0.5, 0, 0) would apply conditioning to the top-left 50% of the image.''' # TODO: verify its actually top-left + strength: NotRequired[float] + '''Strength of conditioning. Default strength is 1.0.''' + mask: NotRequired[torch.Tensor] + '''Mask to apply conditioning to.''' + mask_strength: NotRequired[float] + '''Strength of conditioning mask. Default strength is 1.0.''' + set_area_to_bounds: NotRequired[bool] + '''Whether conditioning mask should determine bounds of area - if set to false, latents are sampled at full resolution and result is applied in mask.''' + concat_latent_image: NotRequired[torch.Tensor] + '''Used for inpainting and specific models.''' + concat_mask: NotRequired[torch.Tensor] + '''Used for inpainting and specific models.''' + concat_image: NotRequired[torch.Tensor] + '''Used by SD_4XUpscale_Conditioning.''' + noise_augmentation: NotRequired[float] + '''Used by SD_4XUpscale_Conditioning.''' + hooks: NotRequired[HookGroup] + '''Applies hooks to conditioning.''' + default: NotRequired[bool] + '''Whether to this conditioning is 'default'; default conditioning gets applied to any areas of the image that have no masks/areas applied, assuming at least one area/mask is present during sampling.''' + start_percent: NotRequired[float] + '''Determines relative step to begin applying conditioning, expressed as a float between 0.0 and 1.0.''' + end_percent: NotRequired[float] + '''Determines relative step to end applying conditioning, expressed as a float between 0.0 and 1.0.''' + clip_start_percent: NotRequired[float] + '''Internal variable for conditioning scheduling - start of application, expressed as a float between 0.0 and 1.0.''' + clip_end_percent: NotRequired[float] + '''Internal variable for conditioning scheduling - end of application, expressed as a float between 0.0 and 1.0.''' + attention_mask: NotRequired[torch.Tensor] + '''Masks text conditioning; used by StyleModel among others.''' + attention_mask_img_shape: NotRequired[tuple[int, ...]] + '''Masks text conditioning; used by StyleModel among others.''' + unclip_conditioning: NotRequired[list[dict]] + '''Used by unCLIP.''' + conditioning_lyrics: NotRequired[torch.Tensor] + '''Used by AceT5Model.''' + seconds_start: NotRequired[float] + '''Used by StableAudio.''' + seconds_total: NotRequired[float] + '''Used by StableAudio.''' + lyrics_strength: NotRequired[float] + '''Used by AceStepAudio.''' + width: NotRequired[int] + '''Used by certain models (e.g. CLIPTextEncodeSDXL/Refiner, PixArtAlpha).''' + height: NotRequired[int] + '''Used by certain models (e.g. CLIPTextEncodeSDXL/Refiner, PixArtAlpha).''' + aesthetic_score: NotRequired[float] + '''Used by CLIPTextEncodeSDXL/Refiner.''' + crop_w: NotRequired[int] + '''Used by CLIPTextEncodeSDXL.''' + crop_h: NotRequired[int] + '''Used by CLIPTextEncodeSDXL.''' + target_width: NotRequired[int] + '''Used by CLIPTextEncodeSDXL.''' + target_height: NotRequired[int] + '''Used by CLIPTextEncodeSDXL.''' + reference_latents: NotRequired[list[torch.Tensor]] + '''Used by ReferenceLatent.''' + guidance: NotRequired[float] + '''Used by Flux-like models with guidance embed.''' + guiding_frame_index: NotRequired[int] + '''Used by Hunyuan ImageToVideo.''' + ref_latent: NotRequired[torch.Tensor] + '''Used by Hunyuan ImageToVideo.''' + keyframe_idxs: NotRequired[list[int]] + '''Used by LTXV.''' + frame_rate: NotRequired[float] + '''Used by LTXV.''' + stable_cascade_prior: NotRequired[torch.Tensor] + '''Used by StableCascade.''' + elevation: NotRequired[list[float]] + '''Used by SV3D.''' + azimuth: NotRequired[list[float]] + '''Used by SV3D.''' + motion_bucket_id: NotRequired[int] + '''Used by SVD-like models.''' + fps: NotRequired[int] + '''Used by SVD-like models.''' + augmentation_level: NotRequired[float] + '''Used by SVD-like models.''' + clip_vision_output: NotRequired[ClipVisionOutput_] + '''Used by WAN-like models.''' + vace_frames: NotRequired[torch.Tensor] + '''Used by WAN VACE.''' + vace_mask: NotRequired[torch.Tensor] + '''Used by WAN VACE.''' + vace_strength: NotRequired[float] + '''Used by WAN VACE.''' + camera_conditions: NotRequired[Any] # TODO: assign proper type once defined + '''Used by WAN Camera.''' + time_dim_concat: NotRequired[torch.Tensor] + '''Used by WAN Phantom Subject.''' + time_dim_replace: NotRequired[torch.Tensor] + '''Used by Kandinsky5 I2V.''' + + CondList = list[tuple[torch.Tensor, PooledDict]] + Type = CondList + +@comfytype(io_type="SAMPLER") +class Sampler(ComfyTypeIO): + if TYPE_CHECKING: + Type = Sampler + +@comfytype(io_type="SIGMAS") +class Sigmas(ComfyTypeIO): + Type = torch.Tensor + +@comfytype(io_type="NOISE") +class Noise(ComfyTypeIO): + Type = torch.Tensor + +@comfytype(io_type="GUIDER") +class Guider(ComfyTypeIO): + if TYPE_CHECKING: + Type = CFGGuider + +@comfytype(io_type="CLIP") +class Clip(ComfyTypeIO): + if TYPE_CHECKING: + Type = CLIP + +@comfytype(io_type="CONTROL_NET") +class ControlNet(ComfyTypeIO): + if TYPE_CHECKING: + Type = ControlNet + +@comfytype(io_type="VAE") +class Vae(ComfyTypeIO): + if TYPE_CHECKING: + Type = VAE + +@comfytype(io_type="MODEL") +class Model(ComfyTypeIO): + if TYPE_CHECKING: + Type = ModelPatcher + +@comfytype(io_type="BACKGROUND_REMOVAL") +class BackgroundRemoval(ComfyTypeIO): + if TYPE_CHECKING: + Type = BackgroundRemovalModel + +@comfytype(io_type="CLIP_VISION") +class ClipVision(ComfyTypeIO): + if TYPE_CHECKING: + Type = ClipVisionModel + +@comfytype(io_type="CLIP_VISION_OUTPUT") +class ClipVisionOutput(ComfyTypeIO): + if TYPE_CHECKING: + Type = ClipVisionOutput_ + +@comfytype(io_type="STYLE_MODEL") +class StyleModel(ComfyTypeIO): + if TYPE_CHECKING: + Type = StyleModel_ + +@comfytype(io_type="GLIGEN") +class Gligen(ComfyTypeIO): + '''ModelPatcher that wraps around a 'Gligen' model.''' + if TYPE_CHECKING: + Type = ModelPatcher + +@comfytype(io_type="UPSCALE_MODEL") +class UpscaleModel(ComfyTypeIO): + if TYPE_CHECKING: + Type = ImageModelDescriptor + +@comfytype(io_type="LATENT_UPSCALE_MODEL") +class LatentUpscaleModel(ComfyTypeIO): + Type = Any + +@comfytype(io_type="AUDIO") +class Audio(ComfyTypeIO): + class AudioDict(TypedDict): + waveform: torch.Tensor + sampler_rate: int + Type = AudioDict + +@comfytype(io_type="VIDEO") +class Video(ComfyTypeIO): + if TYPE_CHECKING: + Type = VideoInput + +@comfytype(io_type="SVG") +class SVG(ComfyTypeIO): + Type = _SVG + +@comfytype(io_type="LORA_MODEL") +class LoraModel(ComfyTypeIO): + Type = dict[str, torch.Tensor] + +@comfytype(io_type="LOSS_MAP") +class LossMap(ComfyTypeIO): + class LossMapDict(TypedDict): + loss: list[torch.Tensor] + Type = LossMapDict + +@comfytype(io_type="VOXEL") +class Voxel(ComfyTypeIO): + Type = VOXEL + +@comfytype(io_type="MESH") +class Mesh(ComfyTypeIO): + Type = MESH + +@comfytype(io_type="SPLAT") +class Splat(ComfyTypeIO): + Type = SPLAT + + +@comfytype(io_type="FILE_3D") +class File3DAny(ComfyTypeIO): + """General 3D file type - accepts any supported 3D format.""" + Type = File3D + + +@comfytype(io_type="FILE_3D_GLB") +class File3DGLB(ComfyTypeIO): + """GLB format 3D file - binary glTF, best for web and cross-platform.""" + Type = File3D + + +@comfytype(io_type="FILE_3D_GLTF") +class File3DGLTF(ComfyTypeIO): + """GLTF format 3D file - JSON-based glTF with external resources.""" + Type = File3D + + +@comfytype(io_type="FILE_3D_FBX") +class File3DFBX(ComfyTypeIO): + """FBX format 3D file - best for game engines and animation.""" + Type = File3D + + +@comfytype(io_type="FILE_3D_OBJ") +class File3DOBJ(ComfyTypeIO): + """OBJ format 3D file - simple geometry format.""" + Type = File3D + + +@comfytype(io_type="FILE_3D_STL") +class File3DSTL(ComfyTypeIO): + """STL format 3D file - best for 3D printing.""" + Type = File3D + + +@comfytype(io_type="FILE_3D_USDZ") +class File3DUSDZ(ComfyTypeIO): + """USDZ format 3D file - Apple AR format.""" + Type = File3D + + +@comfytype(io_type="FILE_3D_PLY") +class File3DPLY(ComfyTypeIO): + """PLY format 3D file - point cloud or Gaussian splat.""" + Type = File3D + + +@comfytype(io_type="FILE_3D_SPLAT") +class File3DSPLAT(ComfyTypeIO): + """SPLAT format 3D file - 3D Gaussian splat.""" + Type = File3D + + +@comfytype(io_type="FILE_3D_SPZ") +class File3DSPZ(ComfyTypeIO): + """SPZ format 3D file - compressed 3D Gaussian splat.""" + Type = File3D + + +@comfytype(io_type="FILE_3D_KSPLAT") +class File3DKSPLAT(ComfyTypeIO): + """KSPLAT format 3D file - 3D Gaussian splat.""" + Type = File3D + + +@comfytype(io_type="FILE_3D_SPLAT_ANY") +class File3DSplatAny(ComfyTypeIO): + """General 3D Gaussian splat file type - accepts any supported splat container (.ply / .spz / .splat / .ksplat).""" + Type = File3D + + +@comfytype(io_type="FILE_3D_POINT_CLOUD_ANY") +class File3DPointCloudAny(ComfyTypeIO): + """General point cloud file type - accepts any supported point cloud container (currently .ply).""" + Type = File3D + + +@comfytype(io_type="HOOKS") +class Hooks(ComfyTypeIO): + if TYPE_CHECKING: + Type = HookGroup + +@comfytype(io_type="HOOK_KEYFRAMES") +class HookKeyframes(ComfyTypeIO): + if TYPE_CHECKING: + Type = HookKeyframeGroup + +@comfytype(io_type="TIMESTEPS_RANGE") +class TimestepsRange(ComfyTypeIO): + '''Range defined by start and endpoint, between 0.0 and 1.0.''' + Type = tuple[int, int] + +@comfytype(io_type="LATENT_OPERATION") +class LatentOperation(ComfyTypeIO): + Type = Callable[[torch.Tensor], torch.Tensor] + +@comfytype(io_type="FLOW_CONTROL") +class FlowControl(ComfyTypeIO): + # NOTE: only used in testing_nodes right now + Type = tuple[str, Any] + +@comfytype(io_type="ACCUMULATION") +class Accumulation(ComfyTypeIO): + # NOTE: only used in testing_nodes right now + class AccumulationDict(TypedDict): + accum: list[Any] + Type = AccumulationDict + + +@comfytype(io_type="LOAD3D_CAMERA") +class Load3DCamera(ComfyTypeIO): + class CameraInfo(TypedDict): + # Coordinate system: right-handed, Y-up, camera looks down -Z + position: dict[str, float | int] # scene units + target: dict[str, float | int] # scene units; OrbitControls focus point + zoom: float | int # dimensionless, 1 = 100% + cameraType: str # 'perspective' | 'orthographic' + quaternion: NotRequired[dict[str, float | int]] # normalized, dimensionless; camera world rotation + fov: NotRequired[float | int] # degrees, vertical FOV (perspective only) + aspect: NotRequired[float | int] # width / height (perspective only) + near: NotRequired[float | int] # scene units + far: NotRequired[float | int] # scene units + frustum: NotRequired[dict[str, float | int]] # orthographic only: {left, right, top, bottom} in scene units + + Type = CameraInfo + + +@comfytype(io_type="LOAD3D_MODEL_INFO") +class Load3DModelInfo(ComfyTypeIO): + class Model3DTransform(TypedDict): + # Coordinate system: right-handed, Y-up, world space + position: dict[str, float | int] # scene units + quaternion: dict[str, float | int] # normalized, dimensionless; world rotation + scale: dict[str, float | int] # dimensionless multiplier + + Type = list[Model3DTransform] + + +@comfytype(io_type="LOAD_3D") +class Load3D(ComfyTypeIO): + """3D models are stored as a dictionary.""" + class Model3DDict(TypedDict): + image: str + mask: str + normal: str + camera_info: Load3DCamera.CameraInfo + recording: NotRequired[str] + model_3d_info: NotRequired[list[Load3DModelInfo.Model3DTransform]] + + Type = Model3DDict + + +@comfytype(io_type="LOAD_3D_ANIMATION") +class Load3DAnimation(Load3D): + ... + + +@comfytype(io_type="LAYERS") +class Layers(ComfyTypeIO): + BlendMode = Literal[ + "normal", "multiply", "screen", "overlay", "darken", "lighten", + "color-dodge", "color-burn", "hard-light", "soft-light", "difference", + "exclusion", "linear-dodge", "linear-burn", "vivid-light", "pin-light", + "linear-light", "hard-mix", "subtract", "divide", "grain-extract", + "grain-merge", "hue", "saturation", "color", "luminosity", + ] + + class LayerItem(TypedDict): + image: torch.Tensor + type: Literal["raster"] + x: NotRequired[int] + y: NotRequired[int] + mask: NotRequired[torch.Tensor] + z_index: int + name: NotRequired[str] + opacity: NotRequired[float] + blend_mode: NotRequired["Layers.BlendMode"] + visible: NotRequired[bool] + flip_h: NotRequired[bool] + flip_v: NotRequired[bool] + rotation: NotRequired[float] + w: NotRequired[int] + h: NotRequired[int] + + class Document(TypedDict): + version: int + canvas: NotRequired[tuple[int, int]] + layers: list["Layers.LayerItem"] + + Type = Document + + +@comfytype(io_type="COMPOSITOR") +class Compositor(ComfyTypeIO): + class LayerState(TypedDict): + version: NotRequired[int] + canvas: dict + background: NotRequired[dict] + inputs: NotRequired[list[str]] + order: NotRequired[list[int]] + layers: list[dict] + + Type = LayerState + + class Input(WidgetInput): + def __init__(self, id: str, display_name: str=None, optional=False, tooltip: str=None, + socketless: bool=True, default: dict=None, advanced: bool=None): + super().__init__(id, display_name, optional, tooltip, None, default, socketless, None, None, None, None, advanced) + if default is None: + self.default = {} + + +@comfytype(io_type="PHOTOMAKER") +class Photomaker(ComfyTypeIO): + Type = Any + + +@comfytype(io_type="POINT") +class Point(ComfyTypeIO): + Type = Any # NOTE: I couldn't find any references in core code to POINT io_type. Does this exist? + +@comfytype(io_type="FACE_ANALYSIS") +class FaceAnalysis(ComfyTypeIO): + Type = Any # NOTE: I couldn't find any references in core code to POINT io_type. Does this exist? + +@comfytype(io_type="BBOX") +class BBOX(ComfyTypeIO): + Type = Any # NOTE: I couldn't find any references in core code to POINT io_type. Does this exist? + +@comfytype(io_type="SEGS") +class SEGS(ComfyTypeIO): + Type = Any # NOTE: I couldn't find any references in core code to POINT io_type. Does this exist? + +@comfytype(io_type="*") +class AnyType(ComfyTypeIO): + Type = Any + +@comfytype(io_type="MODEL_PATCH") +class ModelPatch(ComfyTypeIO): + Type = Any + +@comfytype(io_type="AUDIO_ENCODER") +class AudioEncoder(ComfyTypeIO): + Type = Any + +@comfytype(io_type="AUDIO_ENCODER_OUTPUT") +class AudioEncoderOutput(ComfyTypeIO): + Type = Any + +@comfytype(io_type="TRACKS") +class Tracks(ComfyTypeIO): + class TrackDict(TypedDict): + track_path: torch.Tensor + track_visibility: torch.Tensor + Type = TrackDict + +@comfytype(io_type="DICT") +class Dict(ComfyTypeIO): + Type = dict + +@comfytype(io_type="ARRAY") +class Array(ComfyTypeIO): + Type = list + +@comfytype(io_type="COMFY_MULTITYPED_V3") +class MultiType: + Type = Any + class Input(Input): + ''' + Input that permits more than one input type; if `id` is an instance of `ComfyType.Input`, then that input will be used to create a widget (if applicable) with overridden values. + ''' + def __init__(self, id: str | Input, types: list[type[_ComfyType] | _ComfyType], display_name: str=None, optional=False, tooltip: str=None, lazy: bool=None, extra_dict=None, raw_link: bool=None, advanced: bool=None): + # if id is an Input, then use that Input with overridden values + self.input_override = None + if isinstance(id, Input): + self.input_override = copy.copy(id) + optional = id.optional if id.optional is True else optional + tooltip = id.tooltip if id.tooltip is not None else tooltip + display_name = id.display_name if id.display_name is not None else display_name + lazy = id.lazy if id.lazy is not None else lazy + id = id.id + # if is a widget input, make sure widget_type is set appropriately + if isinstance(self.input_override, WidgetInput): + self.input_override.widget_type = self.input_override.get_io_type() + super().__init__(id, display_name, optional, tooltip, lazy, extra_dict, raw_link, advanced) + self._io_types = types + + @property + def io_types(self) -> list[type[Input]]: + ''' + Returns list of Input class types permitted. + ''' + io_types = [] + for x in self._io_types: + if not is_class(x): + io_types.append(type(x)) + else: + io_types.append(x) + return io_types + + def get_io_type(self): + # ensure types are unique and order is preserved + str_types = [x.io_type for x in self.io_types] + if self.input_override is not None: + str_types.insert(0, self.input_override.get_io_type()) + return ",".join(list(dict.fromkeys(str_types))) + + def as_dict(self): + if self.input_override is not None: + return self.input_override.as_dict() | super().as_dict() + else: + return super().as_dict() + +@comfytype(io_type="COMFY_MATCHTYPE_V3") +class MatchType(ComfyTypeIO): + class Template: + def __init__(self, template_id: str, allowed_types: _ComfyType | list[_ComfyType] = AnyType): + self.template_id = template_id + # account for syntactic sugar + if not isinstance(allowed_types, Iterable): + allowed_types = [allowed_types] + for t in allowed_types: + if not isinstance(t, type): + if not isinstance(t, _ComfyType): + raise ValueError(f"Allowed types must be a ComfyType or a list of ComfyTypes, got {t.__class__.__name__}") + else: + if not issubclass(t, _ComfyType): + raise ValueError(f"Allowed types must be a ComfyType or a list of ComfyTypes, got {t.__name__}") + self.allowed_types = allowed_types + + def as_dict(self): + return { + "template_id": self.template_id, + "allowed_types": ",".join([t.io_type for t in self.allowed_types]), + } + + class Input(Input): + def __init__(self, id: str, template: MatchType.Template, + display_name: str=None, optional=False, tooltip: str=None, lazy: bool=None, extra_dict=None, raw_link: bool=None, advanced: bool=None): + super().__init__(id, display_name, optional, tooltip, lazy, extra_dict, raw_link, advanced) + self.template = template + + def as_dict(self): + return super().as_dict() | prune_dict({ + "template": self.template.as_dict(), + }) + + class Output(Output): + def __init__(self, template: MatchType.Template, id: str=None, display_name: str=None, tooltip: str=None, + is_output_list=False): + if not id and not display_name: + display_name = "MATCHTYPE" + super().__init__(id, display_name, tooltip, is_output_list) + self.template = template + + def as_dict(self): + return super().as_dict() | prune_dict({ + "template": self.template.as_dict(), + }) + +class DynamicInput(Input, ABC): + ''' + Abstract class for dynamic input registration. + ''' + pass + + +class DynamicOutput(Output, ABC): + ''' + Abstract class for dynamic output registration. + ''' + pass + + +def handle_prefix(prefix_list: list[str] | None, id: str | None = None) -> list[str]: + if prefix_list is None: + prefix_list = [] + if id is not None: + prefix_list = prefix_list + [id] + return prefix_list + +def finalize_prefix(prefix_list: list[str] | None, id: str | None = None) -> str: + assert not (prefix_list is None and id is None) + if prefix_list is None: + return id + elif id is not None: + prefix_list = prefix_list + [id] + return ".".join(prefix_list) + +@comfytype(io_type="COMFY_AUTOGROW_V3") +class Autogrow(ComfyTypeI): + Type = dict[str, Any] + _MaxNames = 100 # NOTE: max 100 names for sanity + + class _AutogrowTemplate: + def __init__(self, input: Input): + # dynamic inputs are not allowed as the template input + assert(not isinstance(input, DynamicInput)) + self.input = copy.copy(input) + if isinstance(self.input, WidgetInput): + self.input.force_input = True + self.names: list[str] = [] + self.cached_inputs = {} + + def _create_input(self, input: Input, name: str): + new_input = copy.copy(self.input) + new_input.id = name + return new_input + + def _create_cached_inputs(self): + for name in self.names: + self.cached_inputs[name] = self._create_input(self.input, name) + + def get_all(self) -> list[Input]: + return list(self.cached_inputs.values()) + + def as_dict(self): + return prune_dict({ + "input": create_input_dict_v1([self.input]), + }) + + def validate(self): + self.input.validate() + + class TemplatePrefix(_AutogrowTemplate): + def __init__(self, input: Input, prefix: str, min: int=1, max: int=10): + super().__init__(input) + self.prefix = prefix + assert(min >= 0) + assert(max >= 1) + assert(max <= Autogrow._MaxNames) + self.min = min + self.max = max + self.names = [f"{self.prefix}{i}" for i in range(self.max)] + self._create_cached_inputs() + + def as_dict(self): + return super().as_dict() | prune_dict({ + "prefix": self.prefix, + "min": self.min, + "max": self.max, + }) + + class TemplateNames(_AutogrowTemplate): + def __init__(self, input: Input, names: list[str], min: int=1): + super().__init__(input) + self.names = names[:Autogrow._MaxNames] + assert(min >= 0) + self.min = min + self._create_cached_inputs() + + def as_dict(self): + return super().as_dict() | prune_dict({ + "names": self.names, + "min": self.min, + }) + + class Input(DynamicInput): + def __init__(self, id: str, template: Autogrow.TemplatePrefix | Autogrow.TemplateNames, + display_name: str=None, optional=False, tooltip: str=None, lazy: bool=None, extra_dict=None): + super().__init__(id, display_name, optional, tooltip, lazy, extra_dict) + self.template = template + + def as_dict(self): + return super().as_dict() | prune_dict({ + "template": self.template.as_dict(), + }) + + def get_all(self) -> list[Input]: + return [self] + self.template.get_all() + + def validate(self): + self.template.validate() + + @staticmethod + def _expand_schema_for_dynamic(out_dict: dict[str, Any], live_inputs: dict[str, Any], value: tuple[str, dict[str, Any]], input_type: str, curr_prefix: list[str] | None): + # NOTE: purposely do not include self in out_dict; instead use only the template inputs + # need to figure out names based on template type + is_names = ("names" in value[1]["template"]) + is_prefix = ("prefix" in value[1]["template"]) + input = value[1]["template"]["input"] + if is_names: + min = value[1]["template"]["min"] + names = value[1]["template"]["names"] + max = len(names) + elif is_prefix: + prefix = value[1]["template"]["prefix"] + min = value[1]["template"]["min"] + max = value[1]["template"]["max"] + names = [f"{prefix}{i}" for i in range(max)] + # need to create a new input based on the contents of input + template_input = None + template_required = True + for _input_type, dict_input in input.items(): + # for now, get just the first value from dict_input; if not required, min can be ignored + if len(dict_input) == 0: + continue + template_input = list(dict_input.values())[0] + template_required = _input_type == "required" + break + if template_input is None: + raise Exception("template_input could not be determined from required or optional; this should never happen.") + new_dict = {} + new_dict_added_to = False + # first, add possible inputs into out_dict + for i, name in enumerate(names): + expected_id = finalize_prefix(curr_prefix, name) + # required + if i < min and template_required: + out_dict["required"][expected_id] = template_input + type_dict = new_dict.setdefault("required", {}) + # optional + else: + out_dict["optional"][expected_id] = template_input + type_dict = new_dict.setdefault("optional", {}) + if expected_id in live_inputs: + # NOTE: prefix gets added in parse_class_inputs + type_dict[name] = template_input + new_dict_added_to = True + # account for the edge case that all inputs are optional and no values are received + if not new_dict_added_to: + finalized_prefix = finalize_prefix(curr_prefix) + out_dict["dynamic_paths"][finalized_prefix] = finalized_prefix + out_dict["dynamic_paths_default_value"][finalized_prefix] = DynamicPathsDefaultValue.EMPTY_DICT + parse_class_inputs(out_dict, live_inputs, new_dict, curr_prefix) + +@comfytype(io_type="COMFY_DYNAMICCOMBO_V3") +class DynamicCombo(ComfyTypeI): + Type = dict[str, Any] + + class Option: + def __init__(self, key: str, inputs: list[Input]): + self.key = key + self.inputs = inputs + + def as_dict(self): + return { + "key": self.key, + "inputs": create_input_dict_v1(self.inputs), + } + + class Input(DynamicInput): + def __init__(self, id: str, options: list[DynamicCombo.Option], + display_name: str=None, optional=False, tooltip: str=None, lazy: bool=None, extra_dict=None): + super().__init__(id, display_name, optional, tooltip, lazy, extra_dict) + self.options = options + + def get_all(self) -> list[Input]: + return [self] + [input for option in self.options for input in option.inputs] + + def as_dict(self): + return super().as_dict() | prune_dict({ + "options": [o.as_dict() for o in self.options], + }) + + def validate(self): + # make sure all nested inputs are validated + for option in self.options: + for input in option.inputs: + input.validate() + + @staticmethod + def _expand_schema_for_dynamic(out_dict: dict[str, Any], live_inputs: dict[str, Any], value: tuple[str, dict[str, Any]], input_type: str, curr_prefix: list[str] | None): + finalized_id = finalize_prefix(curr_prefix) + if finalized_id in live_inputs: + key = live_inputs[finalized_id] + selected_option = None + # get options from dict + options: list[dict[str, str | dict[str, Any]]] = value[1]["options"] + for option in options: + if option["key"] == key: + selected_option = option + break + if selected_option is not None: + parse_class_inputs(out_dict, live_inputs, selected_option["inputs"], curr_prefix) + # add self to inputs + out_dict[input_type][finalized_id] = value + out_dict["dynamic_paths"][finalized_id] = finalize_prefix(curr_prefix, curr_prefix[-1]) + +@comfytype(io_type="COMFY_DYNAMICSLOT_V3") +class DynamicSlot(ComfyTypeI): + Type = dict[str, Any] + + class Input(DynamicInput): + def __init__(self, slot: Input, inputs: list[Input], + display_name: str=None, tooltip: str=None, lazy: bool=None, extra_dict=None): + assert(not isinstance(slot, DynamicInput)) + self.slot = copy.copy(slot) + self.slot.display_name = slot.display_name if slot.display_name is not None else display_name + optional = True + self.slot.tooltip = slot.tooltip if slot.tooltip is not None else tooltip + self.slot.lazy = slot.lazy if slot.lazy is not None else lazy + self.slot.extra_dict = slot.extra_dict if slot.extra_dict is not None else extra_dict + super().__init__(slot.id, self.slot.display_name, optional, self.slot.tooltip, self.slot.lazy, self.slot.extra_dict) + self.inputs = inputs + self.force_input = None + # force widget inputs to have no widgets, otherwise this would be awkward + if isinstance(self.slot, WidgetInput): + self.force_input = True + self.slot.force_input = True + + def get_all(self) -> list[Input]: + return [self.slot] + self.inputs + + def as_dict(self): + return super().as_dict() | prune_dict({ + "slotType": str(self.slot.get_io_type()), + "inputs": create_input_dict_v1(self.inputs), + "forceInput": self.force_input, + }) + + def validate(self): + self.slot.validate() + for input in self.inputs: + input.validate() + + @staticmethod + def _expand_schema_for_dynamic(out_dict: dict[str, Any], live_inputs: dict[str, Any], value: tuple[str, dict[str, Any]], input_type: str, curr_prefix: list[str] | None): + finalized_id = finalize_prefix(curr_prefix) + if finalized_id in live_inputs: + inputs = value[1]["inputs"] + parse_class_inputs(out_dict, live_inputs, inputs, curr_prefix) + # add self to inputs + out_dict[input_type][finalized_id] = value + out_dict["dynamic_paths"][finalized_id] = finalize_prefix(curr_prefix, curr_prefix[-1]) + +@comfytype(io_type="IMAGECOMPARE") +class ImageCompare(ComfyTypeI): + Type = dict + + class Input(WidgetInput): + def __init__(self, id: str, display_name: str=None, optional=False, tooltip: str=None, + socketless: bool=True, advanced: bool=None): + super().__init__(id, display_name, optional, tooltip, None, None, socketless, None, None, None, None, advanced) + + def as_dict(self): + return super().as_dict() + + +@comfytype(io_type="COLOR") +class Color(ComfyTypeIO): + Type = str + + class Input(WidgetInput): + def __init__(self, id: str, display_name: str=None, optional=False, tooltip: str=None, + socketless: bool=True, advanced: bool=None, default: str="#ffffff"): + super().__init__(id, display_name, optional, tooltip, None, default, socketless, None, None, None, None, advanced) + self.default: str + + def as_dict(self): + return super().as_dict() + + +@comfytype(io_type="COLORS") +class Colors(ComfyTypeIO): + Type = list[Color.Type] + + class Input(WidgetInput): + def __init__(self, id: str, display_name: str=None, optional=False, tooltip: str=None, + socketless: bool=True, default: list[str]=None, advanced: bool=None): + super().__init__(id, display_name, optional, tooltip, None, default, socketless, None, None, None, None, advanced) + if default is None: + self.default = [] + + +@comfytype(io_type="BOUNDING_BOX") +class BoundingBox(ComfyTypeIO): + class BoundingBoxDict(TypedDict): + x: int + y: int + width: int + height: int + Type = BoundingBoxDict + + class Input(WidgetInput): + def __init__(self, id: str, display_name: str=None, optional=False, tooltip: str=None, + socketless: bool=True, default: dict=None, component: str=None, force_input: bool=None): + super().__init__(id, display_name, optional, tooltip, None, default, socketless) + self.component = component + self.force_input = force_input + if default is None: + self.default = {"x": 0, "y": 0, "width": 512, "height": 512} + + def as_dict(self): + d = super().as_dict() + if self.component: + d["component"] = self.component + if self.force_input is not None: + d["forceInput"] = self.force_input + return d + + +@comfytype(io_type="CURVE") +class Curve(ComfyTypeIO): + from comfy_api.input import CurvePoint + if TYPE_CHECKING: + Type = CurveInput_ + + class Input(WidgetInput): + def __init__(self, id: str, display_name: str=None, optional=False, tooltip: str=None, + socketless: bool=True, default: list[tuple[float, float]]=None, advanced: bool=None): + super().__init__(id, display_name, optional, tooltip, None, default, socketless, None, None, None, None, advanced) + if default is None: + self.default = [(0.0, 0.0), (1.0, 1.0)] + + def as_dict(self): + d = super().as_dict() + if self.default is not None: + d["default"] = {"points": [list(p) for p in self.default], "interpolation": "monotone_cubic"} + return d + + +@comfytype(io_type="BOUNDING_BOXES") +class BoundingBoxes(ComfyTypeIO): + class BoundingBoxWithMetadata(BoundingBox.BoundingBoxDict): + metadata: dict + Type = list[BoundingBoxWithMetadata] + + class Input(WidgetInput): + def __init__(self, id: str, display_name: str=None, optional=False, tooltip: str=None, + socketless: bool=True, default: list[dict]=None, advanced: bool=None): + super().__init__(id, display_name, optional, tooltip, None, default, socketless, None, None, None, None, advanced) + if default is None: + self.default = [] + + +@comfytype(io_type="HISTOGRAM") +class Histogram(ComfyTypeIO): + """A histogram represented as a list of bin counts.""" + Type = list[int] + + +@comfytype(io_type="RANGE") +class Range(ComfyTypeIO): + from comfy_api.input import RangeInput + if TYPE_CHECKING: + Type = RangeInput + + class Input(WidgetInput): + def __init__(self, id: str, display_name: str=None, optional=False, tooltip: str=None, + socketless: bool=True, default: dict=None, + display: str=None, + gradient_stops: list=None, + show_midpoint: bool=None, + midpoint_scale: str=None, + value_min: float=None, + value_max: float=None, + advanced: bool=None): + super().__init__(id, display_name, optional, tooltip, None, default, socketless, None, None, None, None, advanced) + if default is None: + self.default = {"min": 0.0, "max": 1.0} + self.display = display + self.gradient_stops = gradient_stops + self.show_midpoint = show_midpoint + self.midpoint_scale = midpoint_scale + self.value_min = value_min + self.value_max = value_max + + def as_dict(self): + return super().as_dict() | prune_dict({ + "display": self.display, + "gradient_stops": self.gradient_stops, + "show_midpoint": self.show_midpoint, + "midpoint_scale": self.midpoint_scale, + "value_min": self.value_min, + "value_max": self.value_max, + }) + + +DYNAMIC_INPUT_LOOKUP: dict[str, Callable[[dict[str, Any], dict[str, Any], tuple[str, dict[str, Any]], str, list[str] | None], None]] = {} +def register_dynamic_input_func(io_type: str, func: Callable[[dict[str, Any], dict[str, Any], tuple[str, dict[str, Any]], str, list[str] | None], None]): + DYNAMIC_INPUT_LOOKUP[io_type] = func + +def get_dynamic_input_func(io_type: str) -> Callable[[dict[str, Any], dict[str, Any], tuple[str, dict[str, Any]], str, list[str] | None], None]: + return DYNAMIC_INPUT_LOOKUP[io_type] + +def setup_dynamic_input_funcs(): + # Autogrow.Input + register_dynamic_input_func(Autogrow.io_type, Autogrow._expand_schema_for_dynamic) + # DynamicCombo.Input + register_dynamic_input_func(DynamicCombo.io_type, DynamicCombo._expand_schema_for_dynamic) + # DynamicSlot.Input + register_dynamic_input_func(DynamicSlot.io_type, DynamicSlot._expand_schema_for_dynamic) + +if len(DYNAMIC_INPUT_LOOKUP) == 0: + setup_dynamic_input_funcs() + +class V3Data(TypedDict): + hidden_inputs: dict[str, Any] + 'Dictionary where the keys are the hidden input ids and the values are the values of the hidden inputs.' + dynamic_paths: dict[str, Any] + 'Dictionary where the keys are the input ids and the values dictate how to turn the inputs into a nested dictionary.' + dynamic_paths_default_value: dict[str, Any] + 'Dictionary where the keys are the input ids and the values are a string from DynamicPathsDefaultValue for the inputs if value is None.' + create_dynamic_tuple: bool + 'When True, the value of the dynamic input will be in the format (value, path_key).' + +class HiddenHolder: + def __init__(self, unique_id: str, prompt: Any, + extra_pnginfo: Any, dynprompt: Any, + auth_token_comfy_org: str, api_key_comfy_org: str, + comfy_usage_source: str = None, **kwargs): + self.unique_id = unique_id + """UNIQUE_ID is the unique identifier of the node, and matches the id property of the node on the client side. It is commonly used in client-server communications (see messages).""" + self.prompt = prompt + """PROMPT is the complete prompt sent by the client to the server. See the prompt object for a full description.""" + self.extra_pnginfo = extra_pnginfo + """EXTRA_PNGINFO is a dictionary that will be copied into the metadata of any .png files saved. Custom nodes can store additional information in this dictionary for saving (or as a way to communicate with a downstream node).""" + self.dynprompt = dynprompt + """DYNPROMPT is an instance of comfy_execution.graph.DynamicPrompt. It differs from PROMPT in that it may mutate during the course of execution in response to Node Expansion.""" + self.auth_token_comfy_org = auth_token_comfy_org + """AUTH_TOKEN_COMFY_ORG is a token acquired from signing into a ComfyOrg account on frontend.""" + self.api_key_comfy_org = api_key_comfy_org + """API_KEY_COMFY_ORG is an API Key generated by ComfyOrg that allows skipping signing into a ComfyOrg account on frontend.""" + self.comfy_usage_source = comfy_usage_source + """COMFY_USAGE_SOURCE identifies the client that submitted the prompt (e.g. comfyui-frontend, comfy-cli, comfyui-mcp); forwarded to API nodes' upstream requests via the Comfy-Usage-Source header.""" + + def __getattr__(self, key: str): + '''If hidden variable not found, return None.''' + return None + + @classmethod + def from_dict(cls, d: dict | None): + if d is None: + d = {} + return cls( + unique_id=d.get(Hidden.unique_id, None), + prompt=d.get(Hidden.prompt, None), + extra_pnginfo=d.get(Hidden.extra_pnginfo, None), + dynprompt=d.get(Hidden.dynprompt, None), + auth_token_comfy_org=d.get(Hidden.auth_token_comfy_org, None), + api_key_comfy_org=d.get(Hidden.api_key_comfy_org, None), + comfy_usage_source=d.get(Hidden.comfy_usage_source, None), + ) + + @classmethod + def from_v3_data(cls, v3_data: V3Data | None) -> HiddenHolder: + return cls.from_dict(v3_data["hidden_inputs"] if v3_data else None) + +class Hidden(str, Enum): + ''' + Enumerator for requesting hidden variables in nodes. + ''' + unique_id = "UNIQUE_ID" + """UNIQUE_ID is the unique identifier of the node, and matches the id property of the node on the client side. It is commonly used in client-server communications (see messages).""" + prompt = "PROMPT" + """PROMPT is the complete prompt sent by the client to the server. See the prompt object for a full description.""" + extra_pnginfo = "EXTRA_PNGINFO" + """EXTRA_PNGINFO is a dictionary that will be copied into the metadata of any .png files saved. Custom nodes can store additional information in this dictionary for saving (or as a way to communicate with a downstream node).""" + dynprompt = "DYNPROMPT" + """DYNPROMPT is an instance of comfy_execution.graph.DynamicPrompt. It differs from PROMPT in that it may mutate during the course of execution in response to Node Expansion.""" + auth_token_comfy_org = "AUTH_TOKEN_COMFY_ORG" + """AUTH_TOKEN_COMFY_ORG is a token acquired from signing into a ComfyOrg account on frontend.""" + api_key_comfy_org = "API_KEY_COMFY_ORG" + """API_KEY_COMFY_ORG is an API Key generated by ComfyOrg that allows skipping signing into a ComfyOrg account on frontend.""" + comfy_usage_source = "COMFY_USAGE_SOURCE" + """COMFY_USAGE_SOURCE identifies the client that submitted the prompt (e.g. comfyui-frontend, comfy-cli, comfyui-mcp); forwarded to API nodes' upstream requests via the Comfy-Usage-Source header.""" + + +@dataclass +class NodeInfoV1: + input: dict=None + input_order: dict[str, list[str]]=None + is_input_list: bool=None + output: list[str]=None + output_is_list: list[bool]=None + output_name: list[str]=None + output_tooltips: list[str]=None + output_matchtypes: list[str]=None + name: str=None + display_name: str=None + description: str=None + python_module: Any=None + category: str=None + output_node: bool=None + deprecated: bool=None + experimental: bool=None + dev_only: bool=None + api_node: bool=None + price_badge: dict | None = None + search_aliases: list[str]=None + essentials_category: str=None + has_intermediate_output: bool=None + + +@dataclass +class PriceBadgeDepends: + widgets: list[str] = field(default_factory=list) + inputs: list[str] = field(default_factory=list) + input_groups: list[str] = field(default_factory=list) + + def validate(self) -> None: + if not isinstance(self.widgets, list) or any(not isinstance(x, str) for x in self.widgets): + raise ValueError("PriceBadgeDepends.widgets must be a list[str].") + if not isinstance(self.inputs, list) or any(not isinstance(x, str) for x in self.inputs): + raise ValueError("PriceBadgeDepends.inputs must be a list[str].") + if not isinstance(self.input_groups, list) or any(not isinstance(x, str) for x in self.input_groups): + raise ValueError("PriceBadgeDepends.input_groups must be a list[str].") + + def as_dict(self, schema_inputs: list["Input"]) -> dict[str, Any]: + # Build lookup: widget_id -> io_type + input_types: dict[str, str] = {} + for inp in schema_inputs: + all_inputs = inp.get_all() + input_types[inp.id] = inp.get_io_type() # First input is always the parent itself + for nested_inp in all_inputs[1:]: + # For DynamicCombo/DynamicSlot, nested inputs are prefixed with parent ID + # to match frontend naming convention (e.g., "should_texture.enable_pbr") + prefixed_id = f"{inp.id}.{nested_inp.id}" + input_types[prefixed_id] = nested_inp.get_io_type() + + # Enrich widgets with type information, raising error for unknown widgets + widgets_data: list[dict[str, str]] = [] + for w in self.widgets: + if w not in input_types: + raise ValueError( + f"PriceBadge depends_on.widgets references unknown widget '{w}'. " + f"Available widgets: {list(input_types.keys())}" + ) + widgets_data.append({"name": w, "type": input_types[w]}) + + return { + "widgets": widgets_data, + "inputs": self.inputs, + "input_groups": self.input_groups, + } + + +@dataclass +class PriceBadge: + expr: str + depends_on: PriceBadgeDepends = field(default_factory=PriceBadgeDepends) + engine: str = field(default="jsonata") + + def validate(self) -> None: + if self.engine != "jsonata": + raise ValueError(f"Unsupported PriceBadge.engine '{self.engine}'. Only 'jsonata' is supported.") + if not isinstance(self.expr, str) or not self.expr.strip(): + raise ValueError("PriceBadge.expr must be a non-empty string.") + self.depends_on.validate() + + def as_dict(self, schema_inputs: list["Input"]) -> dict[str, Any]: + return { + "engine": self.engine, + "depends_on": self.depends_on.as_dict(schema_inputs), + "expr": self.expr, + } + + +@dataclass +class Schema: + """Definition of V3 node properties.""" + + node_id: str + """ID of node - should be globally unique. If this is a custom node, add a prefix or postfix to avoid name clashes.""" + display_name: str = None + """Display name of node.""" + category: str = "sd" + """The category of the node, as per the "Add Node" menu.""" + inputs: list[Input] = field(default_factory=list) + outputs: list[Output] = field(default_factory=list) + hidden: list[Hidden] = field(default_factory=list) + description: str="" + """Node description, shown as a tooltip when hovering over the node.""" + search_aliases: list[str] = field(default_factory=list) + """Alternative names for search. Useful for synonyms, abbreviations, or old names after renaming.""" + is_input_list: bool = False + """A flag indicating if this node implements the additional code necessary to deal with OUTPUT_IS_LIST nodes. + + All inputs of ``type`` will become ``list[type]``, regardless of how many items are passed in. This also affects ``check_lazy_status``. + + From the docs: + + A node can also override the default input behaviour and receive the whole list in a single call. This is done by setting a class attribute `INPUT_IS_LIST` to ``True``. + + Comfy Docs: https://docs.comfy.org/custom-nodes/backend/lists#list-processing + """ + is_output_node: bool=False + """Flags this node as an output node, causing any inputs it requires to be executed. + + If a node is not connected to any output nodes, that node will not be executed. Usage:: + + From the docs: + + By default, a node is not considered an output. Set ``OUTPUT_NODE = True`` to specify that it is. + + Comfy Docs: https://docs.comfy.org/custom-nodes/backend/server_overview#output-node + """ + is_deprecated: bool=False + """Flags a node as deprecated, indicating to users that they should find alternatives to this node.""" + is_experimental: bool=False + """Flags a node as experimental, informing users that it may change or not work as expected.""" + is_dev_only: bool=False + """Flags a node as dev-only, hiding it from search/menus unless dev mode is enabled.""" + is_api_node: bool=False + """Flags a node as an API node. See: https://docs.comfy.org/tutorials/api-nodes/overview.""" + price_badge: PriceBadge | None = None + """Optional client-evaluated pricing badge declaration for this node.""" + not_idempotent: bool=False + """Flags a node as not idempotent; when True, the node will run and not reuse the cached outputs when identical inputs are provided on a different node in the graph.""" + enable_expand: bool=False + """Flags a node as expandable, allowing NodeOutput to include 'expand' property.""" + accept_all_inputs: bool=False + """When True, all inputs from the prompt will be passed to the node as kwargs, even if not defined in the schema.""" + essentials_category: str | None = None + """Optional category for the Essentials tab. Path-based like category field (e.g., 'Basic', 'Image Tools/Editing').""" + has_intermediate_output: bool=False + """Flags this node as having intermediate output that should persist across page refreshes. + + Nodes with this flag behave like output nodes (their UI results are cached and resent + to the frontend) but do NOT automatically get added to the execution list. This means + they will only execute if they are on the dependency path of a real output node. + + Use this for nodes with interactive/operable UI regions that produce intermediate outputs + (e.g., Image Crop, Painter) rather than final outputs (e.g., Save Image). + """ + + def validate(self): + '''Validate the schema: + - verify ids on inputs and outputs are unique - both internally and in relation to each other + ''' + nested_inputs: list[Input] = [] + for input in self.inputs: + if not isinstance(input, DynamicInput): + nested_inputs.extend(input.get_all()) + input_ids = [i.id for i in nested_inputs] + output_ids = [o.id for o in self.outputs] + input_set = set(input_ids) + output_set = set(output_ids) + issues: list[str] = [] + # verify ids are unique per list + if len(input_set) != len(input_ids): + issues.append(f"Input ids must be unique, but {[item for item, count in Counter(input_ids).items() if count > 1]} are not.") + if len(output_set) != len(output_ids): + issues.append(f"Output ids must be unique, but {[item for item, count in Counter(output_ids).items() if count > 1]} are not.") + if len(issues) > 0: + raise ValueError("\n".join(issues)) + # validate inputs and outputs + for input in self.inputs: + input.validate() + for output in self.outputs: + output.validate() + if self.price_badge is not None: + self.price_badge.validate() + + def finalize(self): + """Add hidden based on selected schema options, and give outputs without ids default ids.""" + # ensure inputs, outputs, and hidden are lists + if self.inputs is None: + self.inputs = [] + if self.outputs is None: + self.outputs = [] + if self.hidden is None: + self.hidden = [] + # if is an api_node, will need key-related hidden + if self.is_api_node: + if Hidden.auth_token_comfy_org not in self.hidden: + self.hidden.append(Hidden.auth_token_comfy_org) + if Hidden.api_key_comfy_org not in self.hidden: + self.hidden.append(Hidden.api_key_comfy_org) + if Hidden.comfy_usage_source not in self.hidden: + self.hidden.append(Hidden.comfy_usage_source) + # if is an output_node, will need prompt and extra_pnginfo + if self.is_output_node: + if Hidden.prompt not in self.hidden: + self.hidden.append(Hidden.prompt) + if Hidden.extra_pnginfo not in self.hidden: + self.hidden.append(Hidden.extra_pnginfo) + # give outputs without ids default ids + for i, output in enumerate(self.outputs): + if output.id is None: + output.id = f"_{i}_{output.io_type}_" + + def get_v1_info(self, cls) -> NodeInfoV1: + # get V1 inputs + input = create_input_dict_v1(self.inputs) + if self.hidden: + for hidden in self.hidden: + input.setdefault("hidden", {})[hidden.name] = (hidden.value,) + # create separate lists from output fields + output = [] + output_is_list = [] + output_name = [] + output_tooltips = [] + output_matchtypes = [] + any_matchtypes = False + if self.outputs: + for o in self.outputs: + output.append(o.io_type) + output_is_list.append(o.is_output_list) + output_name.append(o.display_name if o.display_name else o.io_type) + output_tooltips.append(o.tooltip if o.tooltip else None) + # special handling for MatchType + if isinstance(o, MatchType.Output): + output_matchtypes.append(o.template.template_id) + any_matchtypes = True + else: + output_matchtypes.append(None) + + # clear out lists that are all None + if not any_matchtypes: + output_matchtypes = None + + info = NodeInfoV1( + input=input, + input_order={key: list(value.keys()) for (key, value) in input.items()}, + is_input_list=self.is_input_list, + output=output, + output_is_list=output_is_list, + output_name=output_name, + output_tooltips=output_tooltips, + output_matchtypes=output_matchtypes, + name=self.node_id, + display_name=self.display_name, + category=self.category, + description=self.description, + output_node=self.is_output_node, + has_intermediate_output=self.has_intermediate_output, + deprecated=self.is_deprecated, + experimental=self.is_experimental, + dev_only=self.is_dev_only, + api_node=self.is_api_node, + python_module=getattr(cls, "RELATIVE_PYTHON_MODULE", "nodes"), + price_badge=self.price_badge.as_dict(self.inputs) if self.price_badge is not None else None, + search_aliases=self.search_aliases if self.search_aliases else None, + essentials_category=self.essentials_category, + ) + return info + +def get_finalized_class_inputs(d: dict[str, Any], live_inputs: dict[str, Any], include_hidden=False) -> tuple[dict[str, Any], V3Data]: + out_dict = { + "required": {}, + "optional": {}, + "dynamic_paths": {}, + "dynamic_paths_default_value": {}, + } + d = d.copy() + # ignore hidden for parsing + hidden = d.pop("hidden", None) + parse_class_inputs(out_dict, live_inputs, d) + if hidden is not None and include_hidden: + out_dict["hidden"] = hidden + v3_data = {} + dynamic_paths = out_dict.pop("dynamic_paths", None) + if dynamic_paths is not None and len(dynamic_paths) > 0: + v3_data["dynamic_paths"] = dynamic_paths + # this list is used for autogrow, in the case all inputs are optional and no values are passed + dynamic_paths_default_value = out_dict.pop("dynamic_paths_default_value", None) + if dynamic_paths_default_value is not None and len(dynamic_paths_default_value) > 0: + v3_data["dynamic_paths_default_value"] = dynamic_paths_default_value + return out_dict, hidden, v3_data + +def parse_class_inputs(out_dict: dict[str, Any], live_inputs: dict[str, Any], curr_dict: dict[str, Any], curr_prefix: list[str] | None=None) -> None: + for input_type, inner_d in curr_dict.items(): + for id, value in inner_d.items(): + io_type = value[0] + if io_type in DYNAMIC_INPUT_LOOKUP: + # dynamic inputs need to be handled with lookup functions + dynamic_input_func = get_dynamic_input_func(io_type) + new_prefix = handle_prefix(curr_prefix, id) + dynamic_input_func(out_dict, live_inputs, value, input_type, new_prefix) + else: + # non-dynamic inputs get directly transferred + finalized_id = finalize_prefix(curr_prefix, id) + out_dict[input_type][finalized_id] = value + if curr_prefix: + out_dict["dynamic_paths"][finalized_id] = finalized_id + +def create_input_dict_v1(inputs: list[Input]) -> dict: + input = { + "required": {} + } + for i in inputs: + add_to_dict_v1(i, input) + return input + +def add_to_dict_v1(i: Input, d: dict): + key = "optional" if i.optional else "required" + as_dict = i.as_dict() + # for v1, we don't want to include the optional key + as_dict.pop("optional", None) + d.setdefault(key, {})[i.id] = (i.get_io_type(), as_dict) + +class DynamicPathsDefaultValue: + EMPTY_DICT = "empty_dict" + +def build_nested_inputs(values: dict[str, Any], v3_data: V3Data): + paths = v3_data.get("dynamic_paths", None) + default_value_dict = v3_data.get("dynamic_paths_default_value", {}) + if paths is None: + return values + values = values.copy() + + result = {} + + create_tuple = v3_data.get("create_dynamic_tuple", False) + + for key, path in paths.items(): + parts = path.split(".") + current = result + + for i, p in enumerate(parts): + is_last = (i == len(parts) - 1) + + if is_last: + value = values.pop(key, None) + if value is None: + # see if a default value was provided for this key + default_option = default_value_dict.get(key, None) + if default_option == DynamicPathsDefaultValue.EMPTY_DICT: + value = {} + if create_tuple: + value = (value, key) + current[p] = value + else: + current = current.setdefault(p, {}) + + values.update(result) + return values + + +class _ComfyNodeBaseInternal(_ComfyNodeInternal): + """Common base class for storing internal methods and properties; DO NOT USE for defining nodes.""" + + RELATIVE_PYTHON_MODULE = None + SCHEMA = None + + # filled in during execution + hidden: HiddenHolder = None + + @classmethod + @abstractmethod + def define_schema(cls) -> Schema: + """Override this function with one that returns a Schema instance.""" + raise NotImplementedError + + @classmethod + @abstractmethod + def execute(cls, **kwargs) -> NodeOutput: + """Override this function with one that performs node's actions.""" + raise NotImplementedError + + @classmethod + def validate_inputs(cls, **kwargs) -> bool | str: + """Optionally, define this function to validate inputs; equivalent to V1's VALIDATE_INPUTS. + + If the function returns a string, it will be used as the validation error message for the node. + """ + raise NotImplementedError + + @classmethod + def fingerprint_inputs(cls, **kwargs) -> Any: + """Optionally, define this function to fingerprint inputs; equivalent to V1's IS_CHANGED. + + If this function returns the same value as last run, the node will not be executed.""" + raise NotImplementedError + + @classmethod + def check_lazy_status(cls, **kwargs) -> list[str]: + """Optionally, define this function to return a list of input names that should be evaluated. + + This basic mixin impl. requires all inputs. + + :kwargs: All node inputs will be included here. If the input is ``None``, it should be assumed that it has not yet been evaluated. \ + When using ``INPUT_IS_LIST = True``, unevaluated will instead be ``(None,)``. + + Params should match the nodes execution ``FUNCTION`` (self, and all inputs by name). + Will be executed repeatedly until it returns an empty list, or all requested items were already evaluated (and sent as params). + + Comfy Docs: https://docs.comfy.org/custom-nodes/backend/lazy_evaluation#defining-check-lazy-status + """ + return [name for name in kwargs if kwargs[name] is None] + + def __init__(self): + self.__class__.VALIDATE_CLASS() + + @classmethod + def GET_BASE_CLASS(cls): + return _ComfyNodeBaseInternal + + @final + @classmethod + def VALIDATE_CLASS(cls): + if first_real_override(cls, "define_schema") is None: + raise Exception(f"No define_schema function was defined for node class {cls.__name__}.") + if first_real_override(cls, "execute") is None: + raise Exception(f"No execute function was defined for node class {cls.__name__}.") + + @classproperty + def FUNCTION(cls): # noqa + if inspect.iscoroutinefunction(cls.execute): + return "EXECUTE_NORMALIZED_ASYNC" + return "EXECUTE_NORMALIZED" + + @final + @classmethod + def EXECUTE_NORMALIZED(cls, *args, **kwargs) -> NodeOutput: + to_return = cls.execute(*args, **kwargs) + if to_return is None: + to_return = NodeOutput() + elif isinstance(to_return, NodeOutput): + pass + elif isinstance(to_return, tuple): + to_return = NodeOutput(*to_return) + elif isinstance(to_return, dict): + to_return = NodeOutput.from_dict(to_return) + elif isinstance(to_return, ExecutionBlocker): + to_return = NodeOutput(block_execution=to_return.message) + else: + raise Exception(f"Invalid return type from node: {type(to_return)}") + if to_return.expand is not None and not cls.SCHEMA.enable_expand: + raise Exception(f"Node {cls.__name__} is not expandable, but expand included in NodeOutput; developer should set enable_expand=True on node's Schema to allow this.") + return to_return + + @final + @classmethod + async def EXECUTE_NORMALIZED_ASYNC(cls, *args, **kwargs) -> NodeOutput: + to_return = await cls.execute(*args, **kwargs) + if to_return is None: + to_return = NodeOutput() + elif isinstance(to_return, NodeOutput): + pass + elif isinstance(to_return, tuple): + to_return = NodeOutput(*to_return) + elif isinstance(to_return, dict): + to_return = NodeOutput.from_dict(to_return) + elif isinstance(to_return, ExecutionBlocker): + to_return = NodeOutput(block_execution=to_return.message) + else: + raise Exception(f"Invalid return type from node: {type(to_return)}") + if to_return.expand is not None and not cls.SCHEMA.enable_expand: + raise Exception(f"Node {cls.__name__} is not expandable, but expand included in NodeOutput; developer should set enable_expand=True on node's Schema to allow this.") + return to_return + + @final + @classmethod + def PREPARE_CLASS_CLONE(cls, v3_data: V3Data | None) -> type[ComfyNode]: + """Creates clone of real node class to prevent monkey-patching.""" + c_type: type[ComfyNode] = cls if is_class(cls) else type(cls) + type_clone: type[ComfyNode] = shallow_clone_class(c_type) + # set hidden + type_clone.hidden = HiddenHolder.from_v3_data(v3_data) + return type_clone + ############################################# + # V1 Backwards Compatibility code + #-------------------------------------------- + @final + @classmethod + def GET_NODE_INFO_V1(cls) -> dict[str, Any]: + schema = cls.GET_SCHEMA() + info = schema.get_v1_info(cls) + return asdict(info) + + _DESCRIPTION = None + @final + @classproperty + def DESCRIPTION(cls): # noqa + if cls._DESCRIPTION is None: + cls.GET_SCHEMA() + return cls._DESCRIPTION + + _CATEGORY = None + @final + @classproperty + def CATEGORY(cls): # noqa + if cls._CATEGORY is None: + cls.GET_SCHEMA() + return cls._CATEGORY + + _EXPERIMENTAL = None + @final + @classproperty + def EXPERIMENTAL(cls): # noqa + if cls._EXPERIMENTAL is None: + cls.GET_SCHEMA() + return cls._EXPERIMENTAL + + _DEPRECATED = None + @final + @classproperty + def DEPRECATED(cls): # noqa + if cls._DEPRECATED is None: + cls.GET_SCHEMA() + return cls._DEPRECATED + + _DEV_ONLY = None + @final + @classproperty + def DEV_ONLY(cls): # noqa + if cls._DEV_ONLY is None: + cls.GET_SCHEMA() + return cls._DEV_ONLY + + _API_NODE = None + @final + @classproperty + def API_NODE(cls): # noqa + if cls._API_NODE is None: + cls.GET_SCHEMA() + return cls._API_NODE + + _OUTPUT_NODE = None + @final + @classproperty + def OUTPUT_NODE(cls): # noqa + if cls._OUTPUT_NODE is None: + cls.GET_SCHEMA() + return cls._OUTPUT_NODE + + _HAS_INTERMEDIATE_OUTPUT = None + @final + @classproperty + def HAS_INTERMEDIATE_OUTPUT(cls): # noqa + if cls._HAS_INTERMEDIATE_OUTPUT is None: + cls.GET_SCHEMA() + return cls._HAS_INTERMEDIATE_OUTPUT + + _INPUT_IS_LIST = None + @final + @classproperty + def INPUT_IS_LIST(cls): # noqa + if cls._INPUT_IS_LIST is None: + cls.GET_SCHEMA() + return cls._INPUT_IS_LIST + _OUTPUT_IS_LIST = None + + @final + @classproperty + def OUTPUT_IS_LIST(cls): # noqa + if cls._OUTPUT_IS_LIST is None: + cls.GET_SCHEMA() + return cls._OUTPUT_IS_LIST + + _RETURN_TYPES = None + @final + @classproperty + def RETURN_TYPES(cls): # noqa + if cls._RETURN_TYPES is None: + cls.GET_SCHEMA() + return cls._RETURN_TYPES + + _RETURN_NAMES = None + @final + @classproperty + def RETURN_NAMES(cls): # noqa + if cls._RETURN_NAMES is None: + cls.GET_SCHEMA() + return cls._RETURN_NAMES + + _OUTPUT_TOOLTIPS = None + @final + @classproperty + def OUTPUT_TOOLTIPS(cls): # noqa + if cls._OUTPUT_TOOLTIPS is None: + cls.GET_SCHEMA() + return cls._OUTPUT_TOOLTIPS + + _NOT_IDEMPOTENT = None + @final + @classproperty + def NOT_IDEMPOTENT(cls): # noqa + if cls._NOT_IDEMPOTENT is None: + cls.GET_SCHEMA() + return cls._NOT_IDEMPOTENT + + _ACCEPT_ALL_INPUTS = None + @final + @classproperty + def ACCEPT_ALL_INPUTS(cls): # noqa + if cls._ACCEPT_ALL_INPUTS is None: + cls.GET_SCHEMA() + return cls._ACCEPT_ALL_INPUTS + + @final + @classmethod + def INPUT_TYPES(cls) -> dict[str, dict]: + schema = cls.FINALIZE_SCHEMA() + info = schema.get_v1_info(cls) + return info.input + + @final + @classmethod + def FINALIZE_SCHEMA(cls): + """Call define_schema and finalize it.""" + schema = cls.define_schema() + schema.finalize() + return schema + + @final + @classmethod + def GET_SCHEMA(cls) -> Schema: + """Validate node class, finalize schema, validate schema, and set expected class properties.""" + cls.VALIDATE_CLASS() + schema = cls.FINALIZE_SCHEMA() + schema.validate() + if cls._DESCRIPTION is None: + cls._DESCRIPTION = schema.description + if cls._CATEGORY is None: + cls._CATEGORY = schema.category + if cls._EXPERIMENTAL is None: + cls._EXPERIMENTAL = schema.is_experimental + if cls._DEPRECATED is None: + cls._DEPRECATED = schema.is_deprecated + if cls._DEV_ONLY is None: + cls._DEV_ONLY = schema.is_dev_only + if cls._API_NODE is None: + cls._API_NODE = schema.is_api_node + if cls._OUTPUT_NODE is None: + cls._OUTPUT_NODE = schema.is_output_node + if cls._HAS_INTERMEDIATE_OUTPUT is None: + cls._HAS_INTERMEDIATE_OUTPUT = schema.has_intermediate_output + if cls._INPUT_IS_LIST is None: + cls._INPUT_IS_LIST = schema.is_input_list + if cls._NOT_IDEMPOTENT is None: + cls._NOT_IDEMPOTENT = schema.not_idempotent + if cls._ACCEPT_ALL_INPUTS is None: + cls._ACCEPT_ALL_INPUTS = schema.accept_all_inputs + + if cls._RETURN_TYPES is None: + output = [] + output_name = [] + output_is_list = [] + output_tooltips = [] + if schema.outputs: + for o in schema.outputs: + output.append(o.io_type) + output_name.append(o.display_name if o.display_name else o.io_type) + output_is_list.append(o.is_output_list) + output_tooltips.append(o.tooltip if o.tooltip else None) + + cls._RETURN_TYPES = output + cls._RETURN_NAMES = output_name + cls._OUTPUT_IS_LIST = output_is_list + cls._OUTPUT_TOOLTIPS = output_tooltips + cls.SCHEMA = schema + return schema + #-------------------------------------------- + ############################################# + + +class ComfyNode(_ComfyNodeBaseInternal): + """Common base class for all V3 nodes.""" + + @classmethod + @abstractmethod + def define_schema(cls) -> Schema: + """Override this function with one that returns a Schema instance.""" + raise NotImplementedError + + @classmethod + @abstractmethod + def execute(cls, **kwargs) -> NodeOutput: + """Override this function with one that performs node's actions.""" + raise NotImplementedError + + @classmethod + def validate_inputs(cls, **kwargs) -> bool | str: + """Optionally, define this function to validate inputs; equivalent to V1's VALIDATE_INPUTS.""" + raise NotImplementedError + + @classmethod + def fingerprint_inputs(cls, **kwargs) -> Any: + """Optionally, define this function to fingerprint inputs; equivalent to V1's IS_CHANGED.""" + raise NotImplementedError + + @classmethod + def check_lazy_status(cls, **kwargs) -> list[str]: + """Optionally, define this function to return a list of input names that should be evaluated. + + This basic mixin impl. requires all inputs. + + :kwargs: All node inputs will be included here. If the input is ``None``, it should be assumed that it has not yet been evaluated. \ + When using ``INPUT_IS_LIST = True``, unevaluated will instead be ``(None,)``. + + Params should match the nodes execution ``FUNCTION`` (self, and all inputs by name). + Will be executed repeatedly until it returns an empty list, or all requested items were already evaluated (and sent as params). + + Comfy Docs: https://docs.comfy.org/custom-nodes/backend/lazy_evaluation#defining-check-lazy-status + """ + return [name for name in kwargs if kwargs[name] is None] + + @final + @classmethod + def GET_BASE_CLASS(cls): + """DO NOT override this class. Will break things in execution.py.""" + return ComfyNode + + +class NodeOutput(_NodeOutputInternal): + ''' + Standardized output of a node; can pass in any number of args and/or a UIOutput into 'ui' kwarg. + ''' + def __init__(self, *args: Any, ui: _UIOutput | dict=None, expand: dict=None, block_execution: str=None): + self.args = args + self.ui = ui + self.expand = expand + self.block_execution = block_execution + + @property + def result(self): + return self.args if len(self.args) > 0 else None + + @classmethod + def from_dict(cls, data: dict[str, Any]) -> NodeOutput: + args = () + ui = None + expand = None + if "result" in data: + result = data["result"] + if isinstance(result, ExecutionBlocker): + return cls(block_execution=result.message) + args = result + if "ui" in data: + ui = data["ui"] + if "expand" in data: + expand = data["expand"] + return cls(*args, ui=ui, expand=expand) + + def __getitem__(self, index) -> Any: + return self.args[index] + +class _UIOutput(ABC): + def __init__(self): + pass + + @abstractmethod + def as_dict(self) -> dict: + ... + + +class InputMapOldId(TypedDict): + """Map an old node input to a new node input by ID.""" + new_id: str + old_id: str + +class InputMapSetValue(TypedDict): + """Set a specific value for a new node input.""" + new_id: str + set_value: Any + +InputMap = InputMapOldId | InputMapSetValue +""" +Input mapping for node replacement. Type is inferred by dictionary keys: +- {"new_id": str, "old_id": str} - maps old input to new input +- {"new_id": str, "set_value": Any} - sets a specific value for new input +""" + +class OutputMap(TypedDict): + """Map outputs of node replacement via indexes.""" + new_idx: int + old_idx: int + +class NodeReplace: + """ + Defines a possible node replacement, mapping inputs and outputs of the old node to the new node. + + Also supports assigning specific values to the input widgets of the new node. + + Args: + new_node_id: The class name of the new replacement node. + old_node_id: The class name of the deprecated node. + old_widget_ids: Ordered list of input IDs for widgets that may not have an input slot + connected. The workflow JSON stores widget values by their relative position index, + not by ID. This list maps those positional indexes to input IDs, enabling the + replacement system to correctly identify widget values during node migration. + input_mapping: List of input mappings from old node to new node. + output_mapping: List of output mappings from old node to new node. + """ + def __init__(self, + new_node_id: str, + old_node_id: str, + old_widget_ids: list[str] | None=None, + input_mapping: list[InputMap] | None=None, + output_mapping: list[OutputMap] | None=None, + ): + self.new_node_id = new_node_id + self.old_node_id = old_node_id + self.old_widget_ids = old_widget_ids + self.input_mapping = input_mapping + self.output_mapping = output_mapping + + def as_dict(self): + """Create serializable representation of the node replacement.""" + return { + "new_node_id": self.new_node_id, + "old_node_id": self.old_node_id, + "old_widget_ids": self.old_widget_ids, + "input_mapping": list(self.input_mapping) if self.input_mapping else None, + "output_mapping": list(self.output_mapping) if self.output_mapping else None, + } + + +__all__ = [ + "FolderType", + "UploadType", + "RemoteOptions", + "NumberDisplay", + "ControlAfterGenerate", + + "comfytype", + "Custom", + "Input", + "WidgetInput", + "Output", + "ComfyTypeI", + "ComfyTypeIO", + # Supported Types + "Boolean", + "Int", + "Float", + "String", + "Combo", + "MultiCombo", + "Image", + "WanCameraEmbedding", + "Webcam", + "Mask", + "Latent", + "Conditioning", + "Sampler", + "Sigmas", + "Noise", + "Guider", + "Clip", + "ControlNet", + "Vae", + "Model", + "ModelPatch", + "ClipVision", + "ClipVisionOutput", + "BackgroundRemoval", + "AudioEncoder", + "AudioEncoderOutput", + "StyleModel", + "Gligen", + "UpscaleModel", + "LatentUpscaleModel", + "Audio", + "Video", + "SVG", + "LoraModel", + "LossMap", + "Voxel", + "Mesh", + "Splat", + "File3DAny", + "File3DGLB", + "File3DGLTF", + "File3DFBX", + "File3DOBJ", + "File3DSTL", + "File3DUSDZ", + "File3DPLY", + "File3DSPLAT", + "File3DSPZ", + "File3DKSPLAT", + "File3DSplatAny", + "File3DPointCloudAny", + "Hooks", + "HookKeyframes", + "TimestepsRange", + "LatentOperation", + "FlowControl", + "Accumulation", + "Load3DCamera", + "Load3DModelInfo", + "Load3D", + "Load3DAnimation", + "Compositor", + "Layers", + "Photomaker", + "Point", + "FaceAnalysis", + "BBOX", + "SEGS", + "AnyType", + "MultiType", + "Tracks", + "Dict", + "Array", + "Color", + # Dynamic Types + "MatchType", + "DynamicCombo", + "Autogrow", + # Other classes + "HiddenHolder", + "Hidden", + "NodeInfoV1", + "Schema", + "ComfyNode", + "NodeOutput", + "add_to_dict_v1", + "V3Data", + "ImageCompare", + "PriceBadgeDepends", + "PriceBadge", + "BoundingBox", + "BoundingBoxes", + "Colors", + "Curve", + "Histogram", + "Range", + "NodeReplace", +] diff --git a/docs/hel-892/h3-core-reference/core__comfy_extras__nodes_custom_sampler.py b/docs/hel-892/h3-core-reference/core__comfy_extras__nodes_custom_sampler.py new file mode 100644 index 00000000..c73a8f6d --- /dev/null +++ b/docs/hel-892/h3-core-reference/core__comfy_extras__nodes_custom_sampler.py @@ -0,0 +1,1232 @@ +import math +import comfy.samplers +import comfy.sampler_helpers +import comfy.patcher_extension +import comfy.sample +from comfy.k_diffusion import sampling as k_diffusion_sampling +from comfy.k_diffusion import sa_solver +import latent_preview +import torch +import comfy.utils +import node_helpers +from typing_extensions import override +from comfy_api.latest import ComfyExtension, io +import re + + +class BasicScheduler(io.ComfyNode): + @classmethod + def define_schema(cls): + return io.Schema( + node_id="BasicScheduler", + category="model/sampling/schedulers", + inputs=[ + io.Model.Input("model"), + io.Combo.Input("scheduler", options=comfy.samplers.SCHEDULER_NAMES), + io.Int.Input("steps", default=20, min=1, max=10000), + io.Float.Input("denoise", default=1.0, min=0.0, max=1.0, step=0.01), + ], + outputs=[io.Sigmas.Output()] + ) + + @classmethod + def execute(cls, model, scheduler, steps, denoise) -> io.NodeOutput: + total_steps = steps + if denoise < 1.0: + if denoise <= 0.0: + return io.NodeOutput(torch.FloatTensor([])) + total_steps = int(steps/denoise) + + sigmas = comfy.samplers.calculate_sigmas(model.get_model_object("model_sampling"), scheduler, total_steps).cpu() + sigmas = sigmas[-(steps + 1):] + return io.NodeOutput(sigmas) + + get_sigmas = execute + + +class KarrasScheduler(io.ComfyNode): + @classmethod + def define_schema(cls): + return io.Schema( + node_id="KarrasScheduler", + category="model/sampling/schedulers", + inputs=[ + io.Int.Input("steps", default=20, min=1, max=10000), + io.Float.Input("sigma_max", default=14.614642, min=0.0, max=5000.0, step=0.01, round=False, advanced=True), + io.Float.Input("sigma_min", default=0.0291675, min=0.0, max=5000.0, step=0.01, round=False, advanced=True), + io.Float.Input("rho", default=7.0, min=0.0, max=100.0, step=0.01, round=False, advanced=True), + ], + outputs=[io.Sigmas.Output()] + ) + + @classmethod + def execute(cls, steps, sigma_max, sigma_min, rho) -> io.NodeOutput: + sigmas = k_diffusion_sampling.get_sigmas_karras(n=steps, sigma_min=sigma_min, sigma_max=sigma_max, rho=rho) + return io.NodeOutput(sigmas) + + get_sigmas = execute + +class ExponentialScheduler(io.ComfyNode): + @classmethod + def define_schema(cls): + return io.Schema( + node_id="ExponentialScheduler", + category="model/sampling/schedulers", + inputs=[ + io.Int.Input("steps", default=20, min=1, max=10000), + io.Float.Input("sigma_max", default=14.614642, min=0.0, max=5000.0, step=0.01, round=False, advanced=True), + io.Float.Input("sigma_min", default=0.0291675, min=0.0, max=5000.0, step=0.01, round=False, advanced=True), + ], + outputs=[io.Sigmas.Output()] + ) + + @classmethod + def execute(cls, steps, sigma_max, sigma_min) -> io.NodeOutput: + sigmas = k_diffusion_sampling.get_sigmas_exponential(n=steps, sigma_min=sigma_min, sigma_max=sigma_max) + return io.NodeOutput(sigmas) + + get_sigmas = execute + +class PolyexponentialScheduler(io.ComfyNode): + @classmethod + def define_schema(cls): + return io.Schema( + node_id="PolyexponentialScheduler", + category="model/sampling/schedulers", + inputs=[ + io.Int.Input("steps", default=20, min=1, max=10000), + io.Float.Input("sigma_max", default=14.614642, min=0.0, max=5000.0, step=0.01, round=False, advanced=True), + io.Float.Input("sigma_min", default=0.0291675, min=0.0, max=5000.0, step=0.01, round=False, advanced=True), + io.Float.Input("rho", default=1.0, min=0.0, max=100.0, step=0.01, round=False, advanced=True), + ], + outputs=[io.Sigmas.Output()] + ) + + @classmethod + def execute(cls, steps, sigma_max, sigma_min, rho) -> io.NodeOutput: + sigmas = k_diffusion_sampling.get_sigmas_polyexponential(n=steps, sigma_min=sigma_min, sigma_max=sigma_max, rho=rho) + return io.NodeOutput(sigmas) + + get_sigmas = execute + +class LaplaceScheduler(io.ComfyNode): + @classmethod + def define_schema(cls): + return io.Schema( + node_id="LaplaceScheduler", + category="model/sampling/schedulers", + inputs=[ + io.Int.Input("steps", default=20, min=1, max=10000), + io.Float.Input("sigma_max", default=14.614642, min=0.0, max=5000.0, step=0.01, round=False, advanced=True), + io.Float.Input("sigma_min", default=0.0291675, min=0.0, max=5000.0, step=0.01, round=False, advanced=True), + io.Float.Input("mu", default=0.0, min=-10.0, max=10.0, step=0.1, round=False, advanced=True), + io.Float.Input("beta", default=0.5, min=0.0, max=10.0, step=0.1, round=False, advanced=True), + ], + outputs=[io.Sigmas.Output()] + ) + + @classmethod + def execute(cls, steps, sigma_max, sigma_min, mu, beta) -> io.NodeOutput: + sigmas = k_diffusion_sampling.get_sigmas_laplace(n=steps, sigma_min=sigma_min, sigma_max=sigma_max, mu=mu, beta=beta) + return io.NodeOutput(sigmas) + + get_sigmas = execute + + +class SDTurboScheduler(io.ComfyNode): + @classmethod + def define_schema(cls): + return io.Schema( + node_id="SDTurboScheduler", + category="model/sampling/schedulers", + inputs=[ + io.Model.Input("model"), + io.Int.Input("steps", default=1, min=1, max=10), + io.Float.Input("denoise", default=1.0, min=0, max=1.0, step=0.01), + ], + outputs=[io.Sigmas.Output()] + ) + + @classmethod + def execute(cls, model, steps, denoise) -> io.NodeOutput: + start_step = 10 - int(10 * denoise) + timesteps = torch.flip(torch.arange(1, 11) * 100 - 1, (0,))[start_step:start_step + steps] + sigmas = model.get_model_object("model_sampling").sigma(timesteps) + sigmas = torch.cat([sigmas, sigmas.new_zeros([1])]) + return io.NodeOutput(sigmas) + + get_sigmas = execute + +class BetaSamplingScheduler(io.ComfyNode): + @classmethod + def define_schema(cls): + return io.Schema( + node_id="BetaSamplingScheduler", + category="model/sampling/schedulers", + inputs=[ + io.Model.Input("model"), + io.Int.Input("steps", default=20, min=1, max=10000), + io.Float.Input("alpha", default=0.6, min=0.0, max=50.0, step=0.01, round=False, advanced=True), + io.Float.Input("beta", default=0.6, min=0.0, max=50.0, step=0.01, round=False, advanced=True), + ], + outputs=[io.Sigmas.Output()] + ) + + @classmethod + def execute(cls, model, steps, alpha, beta) -> io.NodeOutput: + sigmas = comfy.samplers.beta_scheduler(model.get_model_object("model_sampling"), steps, alpha=alpha, beta=beta) + return io.NodeOutput(sigmas) + + get_sigmas = execute + +class VPScheduler(io.ComfyNode): + @classmethod + def define_schema(cls): + return io.Schema( + node_id="VPScheduler", + category="model/sampling/schedulers", + inputs=[ + io.Int.Input("steps", default=20, min=1, max=10000), + io.Float.Input("beta_d", default=19.9, min=0.0, max=5000.0, step=0.01, round=False, advanced=True), #TODO: fix default values + io.Float.Input("beta_min", default=0.1, min=0.0, max=5000.0, step=0.01, round=False, advanced=True), + io.Float.Input("eps_s", default=0.001, min=0.0, max=1.0, step=0.0001, round=False, advanced=True), + ], + outputs=[io.Sigmas.Output()] + ) + + @classmethod + def execute(cls, steps, beta_d, beta_min, eps_s) -> io.NodeOutput: + sigmas = k_diffusion_sampling.get_sigmas_vp(n=steps, beta_d=beta_d, beta_min=beta_min, eps_s=eps_s) + return io.NodeOutput(sigmas) + + get_sigmas = execute + +class SplitSigmas(io.ComfyNode): + @classmethod + def define_schema(cls): + return io.Schema( + node_id="SplitSigmas", + category="model/sampling/sigmas", + inputs=[ + io.Sigmas.Input("sigmas"), + io.Int.Input("step", default=0, min=0, max=10000), + ], + outputs=[ + io.Sigmas.Output(display_name="high_sigmas"), + io.Sigmas.Output(display_name="low_sigmas"), + ] + ) + + @classmethod + def execute(cls, sigmas, step) -> io.NodeOutput: + sigmas1 = sigmas[:step + 1] + sigmas2 = sigmas[step:] + return io.NodeOutput(sigmas1, sigmas2) + + get_sigmas = execute + +class SplitSigmasDenoise(io.ComfyNode): + @classmethod + def define_schema(cls): + return io.Schema( + node_id="SplitSigmasDenoise", + category="model/sampling/sigmas", + inputs=[ + io.Sigmas.Input("sigmas"), + io.Float.Input("denoise", default=1.0, min=0.0, max=1.0, step=0.01), + ], + outputs=[ + io.Sigmas.Output(display_name="high_sigmas"), + io.Sigmas.Output(display_name="low_sigmas"), + ] + ) + + @classmethod + def execute(cls, sigmas, denoise) -> io.NodeOutput: + steps = max(sigmas.shape[-1] - 1, 0) + total_steps = round(steps * denoise) + sigmas1 = sigmas[:-(total_steps)] + sigmas2 = sigmas[-(total_steps + 1):] + return io.NodeOutput(sigmas1, sigmas2) + + get_sigmas = execute + +class FlipSigmas(io.ComfyNode): + @classmethod + def define_schema(cls): + return io.Schema( + node_id="FlipSigmas", + category="model/sampling/sigmas", + inputs=[io.Sigmas.Input("sigmas")], + outputs=[io.Sigmas.Output()] + ) + + @classmethod + def execute(cls, sigmas) -> io.NodeOutput: + if len(sigmas) == 0: + return io.NodeOutput(sigmas) + + sigmas = sigmas.flip(0) + if sigmas[0] == 0: + sigmas[0] = 0.0001 + return io.NodeOutput(sigmas) + + get_sigmas = execute + +class SetFirstSigma(io.ComfyNode): + @classmethod + def define_schema(cls): + return io.Schema( + node_id="SetFirstSigma", + category="model/sampling/sigmas", + inputs=[ + io.Sigmas.Input("sigmas"), + io.Float.Input("sigma", default=136.0, min=0.0, max=20000.0, step=0.001, round=False), + ], + outputs=[io.Sigmas.Output()] + ) + + @classmethod + def execute(cls, sigmas, sigma) -> io.NodeOutput: + sigmas = sigmas.clone() + sigmas[0] = sigma + return io.NodeOutput(sigmas) + + set_first_sigma = execute + +class ExtendIntermediateSigmas(io.ComfyNode): + @classmethod + def define_schema(cls): + return io.Schema( + node_id="ExtendIntermediateSigmas", + search_aliases=["interpolate sigmas"], + category="model/sampling/sigmas", + inputs=[ + io.Sigmas.Input("sigmas"), + io.Int.Input("steps", default=2, min=1, max=100), + io.Float.Input("start_at_sigma", default=-1.0, min=-1.0, max=20000.0, step=0.01, round=False), + io.Float.Input("end_at_sigma", default=12.0, min=0.0, max=20000.0, step=0.01, round=False), + io.Combo.Input("spacing", options=['linear', 'cosine', 'sine']), + ], + outputs=[io.Sigmas.Output()] + ) + + @classmethod + def execute(cls, sigmas: torch.Tensor, steps: int, start_at_sigma: float, end_at_sigma: float, spacing: str) -> io.NodeOutput: + if start_at_sigma < 0: + start_at_sigma = float("inf") + + interpolator = { + 'linear': lambda x: x, + 'cosine': lambda x: torch.sin(x*math.pi/2), + 'sine': lambda x: 1 - torch.cos(x*math.pi/2) + }[spacing] + + # linear space for our interpolation function + x = torch.linspace(0, 1, steps + 1, device=sigmas.device)[1:-1] + computed_spacing = interpolator(x) + + extended_sigmas = [] + for i in range(len(sigmas) - 1): + sigma_current = sigmas[i] + sigma_next = sigmas[i+1] + + extended_sigmas.append(sigma_current) + + if end_at_sigma <= sigma_current <= start_at_sigma: + interpolated_steps = computed_spacing * (sigma_next - sigma_current) + sigma_current + extended_sigmas.extend(interpolated_steps.tolist()) + + # Add the last sigma value + if len(sigmas) > 0: + extended_sigmas.append(sigmas[-1]) + + extended_sigmas = torch.FloatTensor(extended_sigmas) + + return io.NodeOutput(extended_sigmas) + + extend = execute + + +class SamplingPercentToSigma(io.ComfyNode): + @classmethod + def define_schema(cls): + return io.Schema( + node_id="SamplingPercentToSigma", + category="model/sampling/sigmas", + inputs=[ + io.Model.Input("model"), + io.Float.Input("sampling_percent", default=0.0, min=0.0, max=1.0, step=0.0001), + io.Boolean.Input("return_actual_sigma", default=False, tooltip="Return the actual sigma value instead of the value used for interval checks.\nThis only affects results at 0.0 and 1.0."), + ], + outputs=[io.Float.Output(display_name="sigma_value")] + ) + + @classmethod + def execute(cls, model, sampling_percent, return_actual_sigma) -> io.NodeOutput: + model_sampling = model.get_model_object("model_sampling") + sigma_val = model_sampling.percent_to_sigma(sampling_percent) + if return_actual_sigma: + if sampling_percent == 0.0: + sigma_val = model_sampling.sigma_max.item() + elif sampling_percent == 1.0: + sigma_val = model_sampling.sigma_min.item() + return io.NodeOutput(sigma_val) + + get_sigma = execute + + +class KSamplerSelect(io.ComfyNode): + @classmethod + def define_schema(cls): + return io.Schema( + node_id="KSamplerSelect", + category="model/sampling/samplers", + inputs=[io.Combo.Input("sampler_name", options=comfy.samplers.SAMPLER_NAMES)], + outputs=[io.Sampler.Output()] + ) + + @classmethod + def execute(cls, sampler_name) -> io.NodeOutput: + sampler = comfy.samplers.sampler_object(sampler_name) + return io.NodeOutput(sampler) + + get_sampler = execute + +class SamplerDPMPP_3M_SDE(io.ComfyNode): + @classmethod + def define_schema(cls): + return io.Schema( + node_id="SamplerDPMPP_3M_SDE", + category="model/sampling/samplers", + inputs=[ + io.Float.Input("eta", default=1.0, min=0.0, max=100.0, step=0.01, round=False, advanced=True), + io.Float.Input("s_noise", default=1.0, min=0.0, max=100.0, step=0.01, round=False, advanced=True), + io.Combo.Input("noise_device", options=['gpu', 'cpu'], advanced=True), + ], + outputs=[io.Sampler.Output()] + ) + + @classmethod + def execute(cls, eta, s_noise, noise_device) -> io.NodeOutput: + if noise_device == 'cpu': + sampler_name = "dpmpp_3m_sde" + else: + sampler_name = "dpmpp_3m_sde_gpu" + sampler = comfy.samplers.ksampler(sampler_name, {"eta": eta, "s_noise": s_noise}) + return io.NodeOutput(sampler) + + get_sampler = execute + +class SamplerDPMPP_2M_SDE(io.ComfyNode): + @classmethod + def define_schema(cls): + return io.Schema( + node_id="SamplerDPMPP_2M_SDE", + category="model/sampling/samplers", + inputs=[ + io.Combo.Input("solver_type", options=['midpoint', 'heun']), + io.Float.Input("eta", default=1.0, min=0.0, max=100.0, step=0.01, round=False, advanced=True), + io.Float.Input("s_noise", default=1.0, min=0.0, max=100.0, step=0.01, round=False, advanced=True), + io.Combo.Input("noise_device", options=['gpu', 'cpu'], advanced=True), + ], + outputs=[io.Sampler.Output()] + ) + + @classmethod + def execute(cls, solver_type, eta, s_noise, noise_device) -> io.NodeOutput: + if noise_device == 'cpu': + sampler_name = "dpmpp_2m_sde" + else: + sampler_name = "dpmpp_2m_sde_gpu" + sampler = comfy.samplers.ksampler(sampler_name, {"eta": eta, "s_noise": s_noise, "solver_type": solver_type}) + return io.NodeOutput(sampler) + + get_sampler = execute + + +class SamplerDPMPP_SDE(io.ComfyNode): + @classmethod + def define_schema(cls): + return io.Schema( + node_id="SamplerDPMPP_SDE", + category="model/sampling/samplers", + inputs=[ + io.Float.Input("eta", default=1.0, min=0.0, max=100.0, step=0.01, round=False, advanced=True), + io.Float.Input("s_noise", default=1.0, min=0.0, max=100.0, step=0.01, round=False, advanced=True), + io.Float.Input("r", default=0.5, min=0.0, max=100.0, step=0.01, round=False, advanced=True), + io.Combo.Input("noise_device", options=['gpu', 'cpu'], advanced=True), + ], + outputs=[io.Sampler.Output()] + ) + + @classmethod + def execute(cls, eta, s_noise, r, noise_device) -> io.NodeOutput: + if noise_device == 'cpu': + sampler_name = "dpmpp_sde" + else: + sampler_name = "dpmpp_sde_gpu" + sampler = comfy.samplers.ksampler(sampler_name, {"eta": eta, "s_noise": s_noise, "r": r}) + return io.NodeOutput(sampler) + + get_sampler = execute + +class SamplerDPMPP_2S_Ancestral(io.ComfyNode): + @classmethod + def define_schema(cls): + return io.Schema( + node_id="SamplerDPMPP_2S_Ancestral", + category="model/sampling/samplers", + inputs=[ + io.Float.Input("eta", default=1.0, min=0.0, max=100.0, step=0.01, round=False), + io.Float.Input("s_noise", default=1.0, min=0.0, max=100.0, step=0.01, round=False), + ], + outputs=[io.Sampler.Output()] + ) + + @classmethod + def execute(cls, eta, s_noise) -> io.NodeOutput: + sampler = comfy.samplers.ksampler("dpmpp_2s_ancestral", {"eta": eta, "s_noise": s_noise}) + return io.NodeOutput(sampler) + + get_sampler = execute + +class SamplerEulerAncestral(io.ComfyNode): + @classmethod + def define_schema(cls): + return io.Schema( + node_id="SamplerEulerAncestral", + category="model/sampling/samplers", + inputs=[ + io.Float.Input("eta", default=1.0, min=0.0, max=100.0, step=0.01, round=False, advanced=True), + io.Float.Input("s_noise", default=1.0, min=0.0, max=100.0, step=0.01, round=False, advanced=True), + ], + outputs=[io.Sampler.Output()] + ) + + @classmethod + def execute(cls, eta, s_noise) -> io.NodeOutput: + sampler = comfy.samplers.ksampler("euler_ancestral", {"eta": eta, "s_noise": s_noise}) + return io.NodeOutput(sampler) + + get_sampler = execute + +class SamplerEulerAncestralCFGPP(io.ComfyNode): + @classmethod + def define_schema(cls): + return io.Schema( + node_id="SamplerEulerAncestralCFGPP", + display_name="SamplerEulerAncestralCFG++", + category="model/sampling/samplers", + inputs=[ + io.Float.Input("eta", default=1.0, min=0.0, max=1.0, step=0.01, round=False), + io.Float.Input("s_noise", default=1.0, min=0.0, max=10.0, step=0.01, round=False), + ], + outputs=[io.Sampler.Output()] + ) + + @classmethod + def execute(cls, eta, s_noise) -> io.NodeOutput: + sampler = comfy.samplers.ksampler( + "euler_ancestral_cfg_pp", + {"eta": eta, "s_noise": s_noise}) + return io.NodeOutput(sampler) + + get_sampler = execute + +class SamplerLMS(io.ComfyNode): + @classmethod + def define_schema(cls): + return io.Schema( + node_id="SamplerLMS", + category="model/sampling/samplers", + inputs=[io.Int.Input("order", default=4, min=1, max=100, advanced=True)], + outputs=[io.Sampler.Output()] + ) + + @classmethod + def execute(cls, order) -> io.NodeOutput: + sampler = comfy.samplers.ksampler("lms", {"order": order}) + return io.NodeOutput(sampler) + + get_sampler = execute + +class SamplerDPMAdaptative(io.ComfyNode): + @classmethod + def define_schema(cls): + return io.Schema( + node_id="SamplerDPMAdaptative", + category="model/sampling/samplers", + inputs=[ + io.Int.Input("order", default=3, min=2, max=3, advanced=True), + io.Float.Input("rtol", default=0.05, min=0.0, max=100.0, step=0.01, round=False, advanced=True), + io.Float.Input("atol", default=0.0078, min=0.0, max=100.0, step=0.01, round=False, advanced=True), + io.Float.Input("h_init", default=0.05, min=0.0, max=100.0, step=0.01, round=False, advanced=True), + io.Float.Input("pcoeff", default=0.0, min=0.0, max=100.0, step=0.01, round=False, advanced=True), + io.Float.Input("icoeff", default=1.0, min=0.0, max=100.0, step=0.01, round=False, advanced=True), + io.Float.Input("dcoeff", default=0.0, min=0.0, max=100.0, step=0.01, round=False, advanced=True), + io.Float.Input("accept_safety", default=0.81, min=0.0, max=100.0, step=0.01, round=False, advanced=True), + io.Float.Input("eta", default=0.0, min=0.0, max=100.0, step=0.01, round=False, advanced=True), + io.Float.Input("s_noise", default=1.0, min=0.0, max=100.0, step=0.01, round=False, advanced=True), + ], + outputs=[io.Sampler.Output()] + ) + + @classmethod + def execute(cls, order, rtol, atol, h_init, pcoeff, icoeff, dcoeff, accept_safety, eta, s_noise) -> io.NodeOutput: + sampler = comfy.samplers.ksampler("dpm_adaptive", {"order": order, "rtol": rtol, "atol": atol, "h_init": h_init, "pcoeff": pcoeff, + "icoeff": icoeff, "dcoeff": dcoeff, "accept_safety": accept_safety, "eta": eta, + "s_noise":s_noise }) + return io.NodeOutput(sampler) + + get_sampler = execute + + +class SamplerER_SDE(io.ComfyNode): + @classmethod + def define_schema(cls): + return io.Schema( + node_id="SamplerER_SDE", + category="model/sampling/samplers", + inputs=[ + io.Combo.Input("solver_type", options=["ER-SDE", "Reverse-time SDE", "ODE"]), + io.Int.Input("max_stage", default=3, min=1, max=3, advanced=True), + io.Float.Input("eta", default=1.0, min=0.0, max=10.0, step=0.01, round=False, tooltip="Stochastic strength of SDEs.\nWhen eta=0, they reduce to deterministic ODE.\nLarge eta may cause invalid outputs. If this occurs, try decreasing this value.", advanced=True), + io.Float.Input("s_noise", default=1.0, min=0.0, max=100.0, step=0.01, round=False, advanced=True), + ], + outputs=[io.Sampler.Output()] + ) + + @classmethod + def execute(cls, solver_type, max_stage, eta, s_noise) -> io.NodeOutput: + # Extend existing noise scalers phi(x) with eta-controlled noise scalers: + # psi(x) = x**(1-eta) * phi(x)**eta + # where eta is constant and directly scales the h^2(t) contribution. + + def er_sde_noise_scaler(x: torch.Tensor) -> torch.Tensor: + return x * ((x ** 0.3).exp() + 10.0) ** eta + + def reverse_time_sde_noise_scaler(x: torch.Tensor) -> torch.Tensor: + return x ** (eta + 1) + + def ode_noise_scaler(x: torch.Tensor) -> torch.Tensor: + return x + + solver_scalers = { + "ER-SDE": er_sde_noise_scaler, + "Reverse-time SDE": reverse_time_sde_noise_scaler, + "ODE": ode_noise_scaler, + } + + if solver_type == "ODE" or eta == 0: + s_noise = 0.0 + solver_type = "ODE" + noise_scaler = solver_scalers[solver_type] + + sampler_name = "er_sde" + sampler = comfy.samplers.ksampler( + sampler_name, + {"s_noise": s_noise, "noise_scaler": noise_scaler, "max_stage": max_stage}, + ) + return io.NodeOutput(sampler) + + get_sampler = execute + + +class SamplerSASolver(io.ComfyNode): + @classmethod + def define_schema(cls): + return io.Schema( + node_id="SamplerSASolver", + search_aliases=["sde"], + category="model/sampling/samplers", + inputs=[ + io.Model.Input("model"), + io.Float.Input("eta", default=1.0, min=0.0, max=10.0, step=0.01, round=False, advanced=True), + io.Float.Input("sde_start_percent", default=0.2, min=0.0, max=1.0, step=0.001, advanced=True), + io.Float.Input("sde_end_percent", default=0.8, min=0.0, max=1.0, step=0.001, advanced=True), + io.Float.Input("s_noise", default=1.0, min=0.0, max=100.0, step=0.01, round=False, advanced=True), + io.Int.Input("predictor_order", default=3, min=1, max=6, advanced=True), + io.Int.Input("corrector_order", default=4, min=0, max=6, advanced=True), + io.Boolean.Input("use_pece", advanced=True), + io.Boolean.Input("simple_order_2", advanced=True), + ], + outputs=[io.Sampler.Output()] + ) + + @classmethod + def execute(cls, model, eta, sde_start_percent, sde_end_percent, s_noise, predictor_order, corrector_order, use_pece, simple_order_2) -> io.NodeOutput: + model_sampling = model.get_model_object("model_sampling") + start_sigma = model_sampling.percent_to_sigma(sde_start_percent) + end_sigma = model_sampling.percent_to_sigma(sde_end_percent) + tau_func = sa_solver.get_tau_interval_func(start_sigma, end_sigma, eta=eta) + + sampler_name = "sa_solver" + sampler = comfy.samplers.ksampler( + sampler_name, + { + "tau_func": tau_func, + "s_noise": s_noise, + "predictor_order": predictor_order, + "corrector_order": corrector_order, + "use_pece": use_pece, + "simple_order_2": simple_order_2, + }, + ) + return io.NodeOutput(sampler) + + get_sampler = execute + + +class SamplerSEEDS2(io.ComfyNode): + @classmethod + def define_schema(cls): + return io.Schema( + node_id="SamplerSEEDS2", + search_aliases=["sde", "exp heun"], + category="model/sampling/samplers", + inputs=[ + io.Combo.Input("solver_type", options=["phi_1", "phi_2"]), + io.Float.Input("eta", default=1.0, min=0.0, max=100.0, step=0.01, round=False, tooltip="Stochastic strength", advanced=True), + io.Float.Input("s_noise", default=1.0, min=0.0, max=100.0, step=0.01, round=False, tooltip="SDE noise multiplier", advanced=True), + io.Float.Input("r", default=0.5, min=0.01, max=1.0, step=0.01, round=False, tooltip="Relative step size for the intermediate stage (c2 node)", advanced=True), + ], + outputs=[io.Sampler.Output()], + description=( + "This sampler node can represent multiple samplers:\n\n" + "seeds_2\n" + "- default setting\n\n" + "exp_heun_2_x0\n" + "- solver_type=phi_2, r=1.0, eta=0.0\n\n" + "exp_heun_2_x0_sde\n" + "- solver_type=phi_2, r=1.0, eta=1.0, s_noise=1.0" + ) + ) + + @classmethod + def execute(cls, solver_type, eta, s_noise, r) -> io.NodeOutput: + sampler_name = "seeds_2" + sampler = comfy.samplers.ksampler( + sampler_name, + {"eta": eta, "s_noise": s_noise, "r": r, "solver_type": solver_type}, + ) + return io.NodeOutput(sampler) + + +class Noise_EmptyNoise: + def __init__(self): + self.seed = 0 + + def generate_noise(self, input_latent): + return comfy.sample.prepare_empty_noise(input_latent["samples"]) + + +class Noise_RandomNoise: + def __init__(self, seed): + self.seed = seed + + def generate_noise(self, input_latent): + latent_image = input_latent["samples"] + batch_inds = input_latent["batch_index"] if "batch_index" in input_latent else None + return comfy.sample.prepare_noise(latent_image, self.seed, batch_inds) + +class SamplerCustom(io.ComfyNode): + @classmethod + def define_schema(cls): + return io.Schema( + node_id="SamplerCustom", + category="model/sampling/custom", + inputs=[ + io.Model.Input("model"), + io.Boolean.Input("add_noise", default=True, advanced=True), + io.Int.Input("noise_seed", default=0, min=0, max=0xffffffffffffffff, control_after_generate=True), + io.Float.Input("cfg", default=8.0, min=0.0, max=100.0, step=0.1, round=0.01), + io.Conditioning.Input("positive"), + io.Conditioning.Input("negative"), + io.Sampler.Input("sampler"), + io.Sigmas.Input("sigmas"), + io.Latent.Input("latent_image"), + ], + outputs=[ + io.Latent.Output(display_name="output"), + io.Latent.Output(display_name="denoised_output"), + ] + ) + + @classmethod + def execute(cls, model, add_noise, noise_seed, cfg, positive, negative, sampler, sigmas, latent_image) -> io.NodeOutput: + latent = latent_image + latent_image = latent["samples"] + latent = latent.copy() + latent_image = comfy.sample.fix_empty_latent_channels(model, latent_image, latent.get("downscale_ratio_spacial", None), latent.get("downscale_ratio_temporal", None)) + latent["samples"] = latent_image + + if not add_noise: + noise = Noise_EmptyNoise().generate_noise(latent) + else: + noise = Noise_RandomNoise(noise_seed).generate_noise(latent) + + noise_mask = None + if "noise_mask" in latent: + noise_mask = latent["noise_mask"] + + x0_output = {} + callback = latent_preview.prepare_callback(model, sigmas.shape[-1] - 1, x0_output) + + disable_pbar = not comfy.utils.PROGRESS_BAR_ENABLED + samples = comfy.sample.sample_custom(model, noise, cfg, sampler, sigmas, positive, negative, latent_image, noise_mask=noise_mask, callback=callback, disable_pbar=disable_pbar, seed=noise_seed) + + out = latent.copy() + out.pop("downscale_ratio_spacial", None) + out.pop("downscale_ratio_temporal", None) + out["samples"] = samples + if "x0" in x0_output: + x0 = x0_output["x0"] + if samples.is_nested and not x0.is_nested: + latent_shapes = [x.shape for x in samples.unbind()] + x0 = comfy.nested_tensor.NestedTensor(comfy.utils.unpack_latents(x0, latent_shapes)) + x0_out = model.model.process_latent_out(x0.cpu()) + out_denoised = latent.copy() + out_denoised["samples"] = x0_out + else: + out_denoised = out + return io.NodeOutput(out, out_denoised) + + sample = execute + +class Guider_Basic(comfy.samplers.CFGGuider): + def set_conds(self, positive): + self.inner_set_conds({"positive": positive}) + +class BasicGuider(io.ComfyNode): + @classmethod + def define_schema(cls): + return io.Schema( + node_id="BasicGuider", + display_name="Basic Guider", + category="model/sampling/guiders", + inputs=[ + io.Model.Input("model"), + io.Conditioning.Input("conditioning"), + ], + outputs=[io.Guider.Output()] + ) + + @classmethod + def execute(cls, model, conditioning) -> io.NodeOutput: + guider = Guider_Basic(model) + guider.set_conds(conditioning) + return io.NodeOutput(guider) + + get_guider = execute + +class CFGGuider(io.ComfyNode): + @classmethod + def define_schema(cls): + return io.Schema( + node_id="CFGGuider", + display_name="CFG Guider", + category="model/sampling/guiders", + inputs=[ + io.Model.Input("model"), + io.Conditioning.Input("positive"), + io.Conditioning.Input("negative"), + io.Float.Input("cfg", default=8.0, min=0.0, max=100.0, step=0.1, round=0.01), + ], + outputs=[io.Guider.Output()] + ) + + @classmethod + def execute(cls, model, positive, negative, cfg) -> io.NodeOutput: + guider = comfy.samplers.CFGGuider(model) + guider.set_conds(positive, negative) + guider.set_cfg(cfg) + return io.NodeOutput(guider) + + get_guider = execute + +class Guider_DualCFG(comfy.samplers.CFGGuider): + def set_cfg(self, cfg1, cfg2, nested=False): + self.cfg1 = cfg1 + self.cfg2 = cfg2 + self.nested = nested + + def set_conds(self, positive, middle, negative): + middle = node_helpers.conditioning_set_values(middle, {"prompt_type": "negative"}) + self.inner_set_conds({"positive": positive, "middle": middle, "negative": negative}) + + def predict_noise(self, x, timestep, model_options={}, seed=None): + negative_cond = self.conds.get("negative", None) + middle_cond = self.conds.get("middle", None) + positive_cond = self.conds.get("positive", None) + + if self.nested: + out = comfy.samplers.calc_cond_batch(self.inner_model, [negative_cond, middle_cond, positive_cond], x, timestep, model_options) + pred_text = comfy.samplers.cfg_function(self.inner_model, out[2], out[1], self.cfg1, x, timestep, model_options=model_options, cond=positive_cond, uncond=middle_cond) + return out[0] + self.cfg2 * (pred_text - out[0]) + else: + if model_options.get("disable_cfg1_optimization", False) == False: + if math.isclose(self.cfg2, 1.0): + negative_cond = None + if math.isclose(self.cfg1, 1.0): + middle_cond = None + + out = comfy.samplers.calc_cond_batch(self.inner_model, [negative_cond, middle_cond, positive_cond], x, timestep, model_options) + return comfy.samplers.cfg_function(self.inner_model, out[1], out[0], self.cfg2, x, timestep, model_options=model_options, cond=middle_cond, uncond=negative_cond) + (out[2] - out[1]) * self.cfg1 + +class DualCFGGuider(io.ComfyNode): + @classmethod + def define_schema(cls): + return io.Schema( + node_id="DualCFGGuider", + search_aliases=["dual prompt guidance"], + display_name="Dual CFG Guider", + category="model/sampling/guiders", + inputs=[ + io.Model.Input("model"), + io.Conditioning.Input("cond1"), + io.Conditioning.Input("cond2"), + io.Conditioning.Input("negative"), + io.Float.Input("cfg_conds", default=8.0, min=0.0, max=100.0, step=0.1, round=0.01), + io.Float.Input("cfg_cond2_negative", default=8.0, min=0.0, max=100.0, step=0.1, round=0.01), + io.Combo.Input("style", options=["regular", "nested"]), + ], + outputs=[io.Guider.Output()] + ) + + @classmethod + def execute(cls, model, cond1, cond2, negative, cfg_conds, cfg_cond2_negative, style) -> io.NodeOutput: + guider = Guider_DualCFG(model) + guider.set_conds(cond1, cond2, negative) + guider.set_cfg(cfg_conds, cfg_cond2_negative, nested=(style == "nested")) + return io.NodeOutput(guider) + + get_guider = execute + +class Guider_DualModel(comfy.samplers.CFGGuider): + # Runs the positive (cond) pass on the main model and the negative (uncond) pass on a separate model + def __init__(self, model_patcher, uncond_model_patcher): + super().__init__(model_patcher) + self.uncond_model_patcher = uncond_model_patcher + self.uncond_inner = None + + def outer_sample(self, noise, latent_image, sampler, sigmas, denoise_mask=None, callback=None, disable_pbar=False, seed=None, latent_shapes=None): + self.uncond_inner = None + self.uncond_loaded = [] + self._uncond_neg = None + # skip at cfg 1.0 + if not math.isclose(self.cfg, 1.0): + uc = {"negative": list(map(lambda a: a.copy(), self.conds["negative"]))} + self.uncond_inner, uc, self.uncond_loaded = comfy.sampler_helpers.prepare_sampling( + self.uncond_model_patcher, noise.shape, uc, self.uncond_model_patcher.model_options) + self._uncond_neg = uc["negative"] + self.uncond_model_patcher.pre_run() + try: + return super().outer_sample(noise, latent_image, sampler, sigmas, denoise_mask, callback, disable_pbar, seed, latent_shapes=latent_shapes) + finally: + if self.uncond_inner is not None: + self.uncond_model_patcher.cleanup() + comfy.sampler_helpers.cleanup_models({"negative": self._uncond_neg}, self.uncond_loaded) + self.uncond_inner = None + + def inner_sample(self, noise, latent_image, device, sampler, sigmas, denoise_mask, callback, disable_pbar, seed, latent_shapes=None): + if self.uncond_inner is not None: + li = latent_image + if li is not None and torch.count_nonzero(li) > 0: + li = self.uncond_inner.process_latent_in(li) + self._uncond_conds = comfy.samplers.process_conds( + self.uncond_inner, noise, {"negative": self._uncond_neg}, device, li, denoise_mask, seed, latent_shapes=latent_shapes)["negative"] + return super().inner_sample(noise, latent_image, device, sampler, sigmas, denoise_mask, callback, disable_pbar, seed, latent_shapes=latent_shapes) + + def predict_noise(self, x, timestep, model_options={}, seed=None): + positive = self.conds.get("positive", None) + cond = comfy.samplers.calc_cond_batch(self.inner_model, [positive], x, timestep, model_options)[0] + # uncond model not loaded (base cfg==1/no negative), or cfg driven to 1.0 this step -> single model, cond only + if self.uncond_inner is None or (math.isclose(self.cfg, 1.0) and not model_options.get("disable_cfg1_optimization", False)): + return cond + + uncond_model_options = model_options + if "multigpu_clones" in model_options: # TODO: support multigpu instead of just running uncond on a single GPU + uncond_model_options = {k: v for k, v in model_options.items() if k != "multigpu_clones"} + uncond = comfy.samplers.calc_cond_batch(self.uncond_inner, [self._uncond_conds], x, timestep, uncond_model_options)[0] + return comfy.samplers.cfg_function(self.inner_model, cond, uncond, self.cfg, x, timestep, + model_options=model_options, cond=positive, uncond=self._uncond_conds) + +class DualModelGuider(io.ComfyNode): + @classmethod + def define_schema(cls): + return io.Schema( + node_id="DualModelGuider", + display_name="Dual Model CFG Guider", + category="model/sampling/guiders", + is_experimental=True, + inputs=[ + io.Model.Input("model", tooltip="Model used for the positive (conditional) pass."), + io.Model.Input("model_negative", optional=True, tooltip="Model used for the negative (unconditional) pass. Use the same model for ordinary CFG."), + io.Conditioning.Input("positive"), + io.Float.Input("cfg", default=4.0, min=0.0, max=100.0, step=0.1, round=0.01), + io.Conditioning.Input("negative", optional=True, tooltip="Negative conditioning run on the negative model. Leave unconnected for a text-free (image-only) unconditional pass."), + ], + outputs=[io.Guider.Output()], + ) + + @classmethod + def execute(cls, model, positive, cfg, model_negative=None, negative=None) -> io.NodeOutput: + if negative is None: + negative = [[None, {}]] # null cond -> no cross_attn -> model runs image-only + + guider = Guider_DualModel(model, model_negative) if model_negative is not None else comfy.samplers.CFGGuider(model) + guider.set_conds(positive, negative) + guider.set_cfg(cfg) + return io.NodeOutput(guider) + + get_guider = execute + +class DisableNoise(io.ComfyNode): + @classmethod + def define_schema(cls): + return io.Schema( + node_id="DisableNoise", + search_aliases=["zero noise"], + category="model/sampling/noise", + inputs=[], + outputs=[io.Noise.Output()] + ) + + @classmethod + def execute(cls) -> io.NodeOutput: + return io.NodeOutput(Noise_EmptyNoise()) + + get_noise = execute + + +class RandomNoise(io.ComfyNode): + @classmethod + def define_schema(cls): + return io.Schema( + node_id="RandomNoise", + category="model/sampling/noise", + inputs=[io.Int.Input("noise_seed", default=0, min=0, max=0xffffffffffffffff, control_after_generate=True)], + outputs=[io.Noise.Output()] + ) + + @classmethod + def execute(cls, noise_seed) -> io.NodeOutput: + return io.NodeOutput(Noise_RandomNoise(noise_seed)) + + get_noise = execute + + +class SamplerCustomAdvanced(io.ComfyNode): + @classmethod + def define_schema(cls): + return io.Schema( + node_id="SamplerCustomAdvanced", + category="model/sampling/custom", + inputs=[ + io.Noise.Input("noise"), + io.Guider.Input("guider"), + io.Sampler.Input("sampler"), + io.Sigmas.Input("sigmas"), + io.Latent.Input("latent_image"), + ], + outputs=[ + io.Latent.Output(display_name="output"), + io.Latent.Output(display_name="denoised_output"), + ] + ) + + @classmethod + def execute(cls, noise, guider, sampler, sigmas, latent_image) -> io.NodeOutput: + latent = latent_image + latent_image = latent["samples"] + latent = latent.copy() + latent_image = comfy.sample.fix_empty_latent_channels(guider.model_patcher, latent_image, latent.get("downscale_ratio_spacial", None), latent.get("downscale_ratio_temporal", None)) + latent["samples"] = latent_image + + noise_mask = None + if "noise_mask" in latent: + noise_mask = latent["noise_mask"] + + x0_output = {} + callback = latent_preview.prepare_callback(guider.model_patcher, sigmas.shape[-1] - 1, x0_output) + + disable_pbar = not comfy.utils.PROGRESS_BAR_ENABLED + samples = guider.sample(noise.generate_noise(latent), latent_image, sampler, sigmas, denoise_mask=noise_mask, callback=callback, disable_pbar=disable_pbar, seed=noise.seed) + samples = samples.to(comfy.model_management.intermediate_device()) + + out = latent.copy() + out.pop("downscale_ratio_spacial", None) + out.pop("downscale_ratio_temporal", None) + out["samples"] = samples + if "x0" in x0_output: + x0 = x0_output["x0"] + if samples.is_nested and not x0.is_nested: + latent_shapes = [x.shape for x in samples.unbind()] + x0 = comfy.nested_tensor.NestedTensor(comfy.utils.unpack_latents(x0, latent_shapes)) + x0_out = guider.model_patcher.model.process_latent_out(x0.cpu()) + out_denoised = latent.copy() + out_denoised["samples"] = x0_out + else: + out_denoised = out + return io.NodeOutput(out, out_denoised) + + sample = execute + +class AddNoise(io.ComfyNode): + @classmethod + def define_schema(cls): + return io.Schema( + node_id="AddNoise", + category="model/sampling/noise", + is_experimental=True, + inputs=[ + io.Model.Input("model"), + io.Noise.Input("noise"), + io.Sigmas.Input("sigmas"), + io.Latent.Input("latent_image"), + ], + outputs=[ + io.Latent.Output(), + ] + ) + + @classmethod + def execute(cls, model, noise, sigmas, latent_image) -> io.NodeOutput: + if len(sigmas) == 0: + return io.NodeOutput(latent_image) + + latent = latent_image + latent_image = latent["samples"] + + noisy = noise.generate_noise(latent) + + model_sampling = model.get_model_object("model_sampling") + process_latent_out = model.get_model_object("process_latent_out") + process_latent_in = model.get_model_object("process_latent_in") + + if len(sigmas) > 1: + scale = torch.abs(sigmas[0] - sigmas[-1]) + else: + scale = sigmas[0] + + if torch.count_nonzero(latent_image) > 0: #Don't shift the empty latent image. + latent_image = process_latent_in(latent_image) + noisy = model_sampling.noise_scaling(scale, noisy, latent_image) + noisy = process_latent_out(noisy) + noisy = torch.nan_to_num(noisy, nan=0.0, posinf=0.0, neginf=0.0) + + out = latent.copy() + out["samples"] = noisy + return io.NodeOutput(out) + + add_noise = execute + +class ManualSigmas(io.ComfyNode): + @classmethod + def define_schema(cls): + return io.Schema( + node_id="ManualSigmas", + search_aliases=["custom noise schedule", "define sigmas"], + category="model/sampling/sigmas", + is_experimental=True, + inputs=[ + io.String.Input("sigmas", default="1, 0.5", multiline=False) + ], + outputs=[io.Sigmas.Output()] + ) + + @classmethod + def execute(cls, sigmas) -> io.NodeOutput: + sigmas = re.findall(r"[-+]?(?:\d*\.*\d+)", sigmas) + sigmas = [float(i) for i in sigmas] + sigmas = torch.FloatTensor(sigmas) + return io.NodeOutput(sigmas) + +class CFGOverride(io.ComfyNode): + @classmethod + def define_schema(cls) -> io.Schema: + return io.Schema( + node_id="CFGOverride", + display_name="CFG Override", + description="Override cfg to a fixed value over a [start, end] percent (sigma) range. " + "With multiple overrides, the one nearest the sampler wins on overlap.", + category="model/sampling/guiders", + inputs=[ + io.Model.Input("model"), + io.Float.Input("cfg", default=1.0, min=0.0, max=100.0, step=0.1, round=0.01), + io.Float.Input("start_percent", default=0.0, min=0.0, max=1.0, step=0.001), + io.Float.Input("end_percent", default=1.0, min=0.0, max=1.0, step=0.001), + ], + outputs=[io.Model.Output()], + ) + + @classmethod + def execute(cls, model, cfg, start_percent, end_percent) -> io.NodeOutput: + ms = model.get_model_object("model_sampling") + sigma_hi = ms.percent_to_sigma(start_percent) # percent->sigma decreasing, so hi >= lo + sigma_lo = ms.percent_to_sigma(end_percent) + + def predict_noise_wrapper(executor, *args, **kwargs): + sigma = float(args[1].flatten()[0]) # args = (x, timestep, model_options, seed) + if not (sigma_lo <= sigma <= sigma_hi): + return executor(*args, **kwargs) + guider = executor.class_obj # guider.cfg feeds cond_scale + saved = guider.cfg + guider.cfg = cfg + try: + return executor(*args, **kwargs) + finally: + guider.cfg = saved # restore for other steps/overrides + + m = model.clone() + m.add_wrapper(comfy.patcher_extension.WrappersMP.PREDICT_NOISE, predict_noise_wrapper) + return io.NodeOutput(m) + + +class CustomSamplersExtension(ComfyExtension): + @override + async def get_node_list(self) -> list[type[io.ComfyNode]]: + return [ + SamplerCustom, + CFGOverride, + BasicScheduler, + KarrasScheduler, + ExponentialScheduler, + PolyexponentialScheduler, + LaplaceScheduler, + VPScheduler, + BetaSamplingScheduler, + SDTurboScheduler, + KSamplerSelect, + SamplerEulerAncestral, + SamplerEulerAncestralCFGPP, + SamplerLMS, + SamplerDPMPP_3M_SDE, + SamplerDPMPP_2M_SDE, + SamplerDPMPP_SDE, + SamplerDPMPP_2S_Ancestral, + SamplerDPMAdaptative, + SamplerER_SDE, + SamplerSASolver, + SamplerSEEDS2, + SplitSigmas, + SplitSigmasDenoise, + FlipSigmas, + SetFirstSigma, + ExtendIntermediateSigmas, + SamplingPercentToSigma, + CFGGuider, + DualCFGGuider, + DualModelGuider, + BasicGuider, + RandomNoise, + DisableNoise, + AddNoise, + SamplerCustomAdvanced, + ManualSigmas, + ] + + +async def comfy_entrypoint() -> CustomSamplersExtension: + return CustomSamplersExtension() diff --git a/docs/hel-892/h3-core-reference/core__comfy_extras__nodes_math.py b/docs/hel-892/h3-core-reference/core__comfy_extras__nodes_math.py new file mode 100644 index 00000000..0883c65a --- /dev/null +++ b/docs/hel-892/h3-core-reference/core__comfy_extras__nodes_math.py @@ -0,0 +1,126 @@ +"""Math expression node using simpleeval for safe evaluation. + +Provides a ComfyMathExpression node that evaluates math expressions +against dynamically-grown numeric inputs. +""" + + +import math +import string + +from simpleeval import simple_eval +from typing_extensions import override + +from comfy_api.latest import ComfyExtension, io + + +MAX_EXPONENT = 4000 + + +def _variadic_sum(*args): + """Support both sum(values) and sum(a, b, c).""" + if len(args) == 1 and hasattr(args[0], "__iter__"): + return sum(args[0]) + return sum(args) + + +def _safe_pow(base, exp): + """Wrap pow() with an exponent cap to prevent DoS via huge exponents. + + The ** operator is already guarded by simpleeval's safe_power, but + pow() as a callable bypasses that guard. + """ + if abs(exp) > MAX_EXPONENT: + raise ValueError(f"Exponent {exp} exceeds maximum allowed ({MAX_EXPONENT})") + return pow(base, exp) + + +MATH_FUNCTIONS = { + "sum": _variadic_sum, + "min": min, + "max": max, + "abs": abs, + "round": round, + "pow": _safe_pow, + "sqrt": math.sqrt, + "ceil": math.ceil, + "floor": math.floor, + "log": math.log, + "log2": math.log2, + "log10": math.log10, + "sin": math.sin, + "cos": math.cos, + "tan": math.tan, + "int": int, + "float": float, +} + + +class MathExpressionNode(io.ComfyNode): + """Evaluates a math expression against dynamically-grown inputs.""" + + @classmethod + def define_schema(cls) -> io.Schema: + autogrow = io.Autogrow.TemplateNames( + input=io.MultiType.Input("value", [io.Float, io.Int, io.Boolean]), + names=list(string.ascii_lowercase), + min=1, + ) + return io.Schema( + node_id="ComfyMathExpression", + display_name="Math Expression", + category="utilities", + search_aliases=[ + "expression", "formula", "calculate", "calculator", + "eval", "math", + ], + inputs=[ + io.String.Input("expression", default="a + b", multiline=True), + io.Autogrow.Input("values", template=autogrow), + ], + outputs=[ + io.Float.Output(display_name="FLOAT"), + io.Int.Output(display_name="INT"), + io.Boolean.Output(display_name="BOOL"), + ], + ) + + @classmethod + def execute( + cls, expression: str, values: io.Autogrow.Type + ) -> io.NodeOutput: + if not expression.strip(): + raise ValueError("Expression cannot be empty.") + + context: dict = dict(values) + context["values"] = list(values.values()) + + result = simple_eval(expression, names=context, functions=MATH_FUNCTIONS) + # bool check must come first because bool is a subclass of int in Python + if not isinstance(result, (int, float)): + raise ValueError( + f"Math Expression '{expression}' must evaluate to a numeric result, " + f"got {type(result).__name__}: {result!r}" + ) + try: + float_result = float(result) + except OverflowError: + raise ValueError( + f"Math Expression '{expression}' produced a result too large to " + f"represent as a float: {result}" + ) from None + if not math.isfinite(float_result): + raise ValueError( + f"Math Expression '{expression}' produced a non-finite result: {result}" + ) + return io.NodeOutput(float_result, int(result), bool(result)) + + +class MathExtension(ComfyExtension): + @override + async def get_node_list(self) -> list[type[io.ComfyNode]]: + return [MathExpressionNode] + + +async def comfy_entrypoint() -> MathExtension: + return MathExtension() diff --git a/docs/hel-892/h3-core-reference/core__comfy_extras__nodes_primitive.py b/docs/hel-892/h3-core-reference/core__comfy_extras__nodes_primitive.py new file mode 100644 index 00000000..35761863 --- /dev/null +++ b/docs/hel-892/h3-core-reference/core__comfy_extras__nodes_primitive.py @@ -0,0 +1,108 @@ +import sys +from typing_extensions import override + +from comfy_api.latest import ComfyExtension, io + + +class String(io.ComfyNode): + @classmethod + def define_schema(cls): + return io.Schema( + node_id="PrimitiveString", + search_aliases=["text", "string", "text box", "prompt"], + display_name="Text", + category="utilities/primitive", + inputs=[io.String.Input("value")], + outputs=[io.String.Output()] + ) + + @classmethod + def execute(cls, value: str) -> io.NodeOutput: + return io.NodeOutput(value) + + +class StringMultiline(io.ComfyNode): + @classmethod + def define_schema(cls): + return io.Schema( + node_id="PrimitiveStringMultiline", + search_aliases=["text", "string", "text multiline", "string multiline", "text box", "prompt"], + display_name="Text (Multiline)", + category="utilities/primitive", + essentials_category="Basics", + inputs=[io.String.Input("value", multiline=True)], + outputs=[io.String.Output()], + ) + + @classmethod + def execute(cls, value: str) -> io.NodeOutput: + return io.NodeOutput(value) + + +class Int(io.ComfyNode): + @classmethod + def define_schema(cls): + return io.Schema( + node_id="PrimitiveInt", + display_name="Int", + category="utilities/primitive", + inputs=[ + io.Int.Input("value", min=-sys.maxsize, max=sys.maxsize, control_after_generate=io.ControlAfterGenerate.fixed), + ], + outputs=[io.Int.Output()], + ) + + @classmethod + def execute(cls, value: int) -> io.NodeOutput: + return io.NodeOutput(value) + + +class Float(io.ComfyNode): + @classmethod + def define_schema(cls): + return io.Schema( + node_id="PrimitiveFloat", + display_name="Float", + category="utilities/primitive", + inputs=[ + io.Float.Input("value", min=-sys.maxsize, max=sys.maxsize, step=0.1), + ], + outputs=[io.Float.Output()], + ) + + @classmethod + def execute(cls, value: float) -> io.NodeOutput: + return io.NodeOutput(value) + + +class Boolean(io.ComfyNode): + @classmethod + def define_schema(cls): + return io.Schema( + node_id="PrimitiveBoolean", + display_name="Boolean", + category="utilities/primitive", + inputs=[ + io.Boolean.Input("value"), + ], + outputs=[io.Boolean.Output()], + ) + + @classmethod + def execute(cls, value: bool) -> io.NodeOutput: + return io.NodeOutput(value) + + +class PrimitivesExtension(ComfyExtension): + @override + async def get_node_list(self) -> list[type[io.ComfyNode]]: + return [ + String, + StringMultiline, + Int, + Float, + Boolean, + ] + +async def comfy_entrypoint() -> PrimitivesExtension: + return PrimitivesExtension() diff --git a/docs/hel-892/h3-core-reference/core__comfy_extras__nodes_resolution.py b/docs/hel-892/h3-core-reference/core__comfy_extras__nodes_resolution.py new file mode 100644 index 00000000..083e47ae --- /dev/null +++ b/docs/hel-892/h3-core-reference/core__comfy_extras__nodes_resolution.py @@ -0,0 +1,94 @@ +import math +from enum import Enum +from typing_extensions import override +from comfy_api.latest import ComfyExtension, io + + +class AspectRatio(str, Enum): + SQUARE = "1:1 (Square)" + PHOTO_V = "2:3 (Portrait Photo)" + PHOTO_H = "3:2 (Photo)" + STANDARD_V = "3:4 (Portrait Standard)" + STANDARD_H = "4:3 (Standard)" + WIDESCREEN_V = "9:16 (Portrait Widescreen)" + WIDESCREEN_H = "16:9 (Widescreen)" + ULTRAWIDE_H = "21:9 (Ultrawide)" + + +ASPECT_RATIOS: dict[AspectRatio, tuple[int, int]] = { + AspectRatio.SQUARE: (1, 1), + AspectRatio.PHOTO_V: (2, 3), + AspectRatio.PHOTO_H: (3, 2), + AspectRatio.STANDARD_V: (3, 4), + AspectRatio.STANDARD_H: (4, 3), + AspectRatio.WIDESCREEN_V: (9, 16), + AspectRatio.WIDESCREEN_H: (16, 9), + AspectRatio.ULTRAWIDE_H: (21, 9), +} + + +class ResolutionSelector(io.ComfyNode): + """Calculate width and height from aspect ratio and megapixel target.""" + + @classmethod + def define_schema(cls): + return io.Schema( + node_id="ResolutionSelector", + display_name="Resolution Selector", + category="utilities", + description="Calculate width and height from aspect ratio and megapixel target. Useful for setting up Empty Latent Image dimensions.", + inputs=[ + io.Combo.Input( + "aspect_ratio", + options=AspectRatio, + default=AspectRatio.SQUARE, + tooltip="The aspect ratio for the output dimensions.", + ), + io.Float.Input( + "megapixels", + default=1.0, + min=0.1, + max=16.0, + step=0.1, + tooltip="Target total megapixels. 1.0 MP ≈ 1024x1024 for square.", + ), + io.Int.Input( + id="multiple", + default=8, + min=8, + max=128, + step=4, + tooltip="Nearest multiple of the result to set the selected resolution to.", + advanced=True, + ), + ], + outputs=[ + io.Int.Output( + "width", tooltip="Calculated width in pixels multiplied by the selected multiple." + ), + io.Int.Output( + "height", tooltip="Calculated height in pixels multiplied by the selected multiple." + ), + ], + ) + + @classmethod + def execute(cls, aspect_ratio: str, megapixels: float, multiple: int) -> io.NodeOutput: + w_ratio, h_ratio = ASPECT_RATIOS[aspect_ratio] + total_pixels = megapixels * 1024 * 1024 + scale = math.sqrt(total_pixels / (w_ratio * h_ratio)) + width = round(w_ratio * scale / multiple) * multiple + height = round(h_ratio * scale / multiple) * multiple + return io.NodeOutput(width, height) + + +class ResolutionExtension(ComfyExtension): + @override + async def get_node_list(self) -> list[type[io.ComfyNode]]: + return [ + ResolutionSelector, + ] + + +async def comfy_entrypoint() -> ResolutionExtension: + return ResolutionExtension() diff --git a/docs/hel-892/h3-core-reference/core__nodes.py b/docs/hel-892/h3-core-reference/core__nodes.py new file mode 100644 index 00000000..1a3dd3f4 --- /dev/null +++ b/docs/hel-892/h3-core-reference/core__nodes.py @@ -0,0 +1,2595 @@ +import torch + + +import os +import sys +import json +import glob +import hashlib +import inspect + +import traceback +import math +import time +import random +import logging + +from PIL import Image, ImageOps, ImageSequence +from PIL.PngImagePlugin import PngInfo + +import numpy as np +import safetensors.torch + +import comfy.diffusers_load +import comfy.samplers +import comfy.sample +import comfy.sd +import comfy.utils +import comfy.controlnet +from comfy.comfy_types import IO, ComfyNodeABC, InputTypeDict, FileLocator +from comfy_api.internal import register_versions, ComfyAPIWithVersion +from comfy_api.version_list import supported_versions +from comfy_api.latest import io, ComfyExtension, InputImpl + +import comfy.clip_vision + +import comfy.model_management +from comfy.cli_args import args + +import importlib + +import folder_paths +import latent_preview +import node_helpers + +if args.enable_manager: + import comfyui_manager + +def before_node_execution(): + comfy.model_management.throw_exception_if_processing_interrupted() + +def interrupt_processing(value=True): + comfy.model_management.interrupt_current_processing(value) + +MAX_RESOLUTION=16384 + +class CLIPTextEncode(ComfyNodeABC): + @classmethod + def INPUT_TYPES(s) -> InputTypeDict: + return { + "required": { + "text": (IO.STRING, {"multiline": True, "dynamicPrompts": True, "tooltip": "The text to be encoded."}), + "clip": (IO.CLIP, {"tooltip": "The CLIP model used for encoding the text."}) + } + } + RETURN_TYPES = (IO.CONDITIONING,) + OUTPUT_TOOLTIPS = ("A conditioning containing the embedded text used to guide the diffusion model.",) + FUNCTION = "encode" + + CATEGORY = "model/conditioning" + DESCRIPTION = "Encodes a text prompt using a CLIP model into an embedding that can be used to guide the diffusion model towards generating specific images." + SEARCH_ALIASES = ["text", "prompt", "text prompt", "positive prompt", "negative prompt", "encode text", "text encoder", "encode prompt"] + + def encode(self, clip, text): + if clip is None: + raise RuntimeError("ERROR: clip input is invalid: None\n\nIf the clip is from a checkpoint loader node your checkpoint does not contain a valid clip or text encoder model.") + tokens = clip.tokenize(text) + return (clip.encode_from_tokens_scheduled(tokens), ) + + +class ConditioningCombine: + ESSENTIALS_CATEGORY = "Image Generation" + @classmethod + def INPUT_TYPES(s): + return {"required": {"conditioning_1": ("CONDITIONING", ), "conditioning_2": ("CONDITIONING", )}} + RETURN_TYPES = ("CONDITIONING",) + FUNCTION = "combine" + + CATEGORY = "model/conditioning/transform" + SEARCH_ALIASES = ["combine", "merge conditioning", "combine prompts", "merge prompts", "mix prompts", "add prompt"] + + def combine(self, conditioning_1, conditioning_2): + return (conditioning_1 + conditioning_2, ) + +class ConditioningAverage : + SEARCH_ALIASES = ["blend prompts", "interpolate conditioning", "mix prompts", "style fusion", "weighted blend"] + + @classmethod + def INPUT_TYPES(s): + return {"required": {"conditioning_to": ("CONDITIONING", ), "conditioning_from": ("CONDITIONING", ), + "conditioning_to_strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01}) + }} + RETURN_TYPES = ("CONDITIONING",) + FUNCTION = "addWeighted" + + CATEGORY = "model/conditioning/transform" + + def addWeighted(self, conditioning_to, conditioning_from, conditioning_to_strength): + out = [] + + if len(conditioning_from) > 1: + logging.warning("Warning: ConditioningAverage conditioning_from contains more than 1 cond, only the first one will actually be applied to conditioning_to.") + + cond_from = conditioning_from[0][0] + pooled_output_from = conditioning_from[0][1].get("pooled_output", None) + + for i in range(len(conditioning_to)): + t1 = conditioning_to[i][0] + pooled_output_to = conditioning_to[i][1].get("pooled_output", pooled_output_from) + t0 = cond_from[:,:t1.shape[1]] + if t0.shape[1] < t1.shape[1]: + t0 = torch.cat([t0] + [torch.zeros((1, (t1.shape[1] - t0.shape[1]), t1.shape[2]))], dim=1) + + tw = torch.mul(t1, conditioning_to_strength) + torch.mul(t0, (1.0 - conditioning_to_strength)) + t_to = conditioning_to[i][1].copy() + if pooled_output_from is not None and pooled_output_to is not None: + t_to["pooled_output"] = torch.mul(pooled_output_to, conditioning_to_strength) + torch.mul(pooled_output_from, (1.0 - conditioning_to_strength)) + elif pooled_output_from is not None: + t_to["pooled_output"] = pooled_output_from + + n = [tw, t_to] + out.append(n) + return (out, ) + +class ConditioningConcat: + @classmethod + def INPUT_TYPES(s): + return {"required": { + "conditioning_to": ("CONDITIONING",), + "conditioning_from": ("CONDITIONING",), + }} + RETURN_TYPES = ("CONDITIONING",) + FUNCTION = "concat" + + CATEGORY = "model/conditioning/transform" + + def concat(self, conditioning_to, conditioning_from): + out = [] + + if len(conditioning_from) > 1: + logging.warning("Warning: ConditioningConcat conditioning_from contains more than 1 cond, only the first one will actually be applied to conditioning_to.") + + cond_from = conditioning_from[0][0] + + for i in range(len(conditioning_to)): + t1 = conditioning_to[i][0] + tw = torch.cat((t1, cond_from),1) + n = [tw, conditioning_to[i][1].copy()] + out.append(n) + + return (out, ) + +class ConditioningMultiply: + SEARCH_ALIASES = ["scale conditioning", "scale prompt", "multiply conditioning", "multiply prompt"] + + @classmethod + def INPUT_TYPES(cls): + return {"required": {"conditioning": ("CONDITIONING", ), + "multiplier": ("FLOAT", {"default": 1.0, "min": -100.0, "max": 100.0, "step": 0.01}) + }} + RETURN_TYPES = ("CONDITIONING",) + FUNCTION = "multiply" + CATEGORY = "model/conditioning/transform" + + def multiply(self, conditioning, multiplier): + c = [] + for t in conditioning: + values = {} + pooled_output = t[1].get("pooled_output", None) + if pooled_output is not None: + values["pooled_output"] = pooled_output * multiplier + scaled = node_helpers.conditioning_set_values([[t[0] * multiplier, t[1]]], values)[0] + c.append(scaled) + return (c,) + +class ConditioningSetArea: + SEARCH_ALIASES = ["regional prompt", "area prompt", "spatial conditioning", "localized prompt"] + + @classmethod + def INPUT_TYPES(s): + return {"required": {"conditioning": ("CONDITIONING", ), + "width": ("INT", {"default": 64, "min": 64, "max": MAX_RESOLUTION, "step": 8}), + "height": ("INT", {"default": 64, "min": 64, "max": MAX_RESOLUTION, "step": 8}), + "x": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}), + "y": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}), + "strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}), + }} + RETURN_TYPES = ("CONDITIONING",) + FUNCTION = "append" + + CATEGORY = "model/conditioning/transform" + + def append(self, conditioning, width, height, x, y, strength): + c = node_helpers.conditioning_set_values(conditioning, {"area": (height // 8, width // 8, y // 8, x // 8), + "strength": strength, + "set_area_to_bounds": False}) + return (c, ) + +class ConditioningSetAreaPercentage: + @classmethod + def INPUT_TYPES(s): + return {"required": {"conditioning": ("CONDITIONING", ), + "width": ("FLOAT", {"default": 1.0, "min": 0, "max": 1.0, "step": 0.01}), + "height": ("FLOAT", {"default": 1.0, "min": 0, "max": 1.0, "step": 0.01}), + "x": ("FLOAT", {"default": 0, "min": 0, "max": 1.0, "step": 0.01}), + "y": ("FLOAT", {"default": 0, "min": 0, "max": 1.0, "step": 0.01}), + "strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}), + }} + RETURN_TYPES = ("CONDITIONING",) + FUNCTION = "append" + + CATEGORY = "model/conditioning/transform" + + def append(self, conditioning, width, height, x, y, strength): + c = node_helpers.conditioning_set_values(conditioning, {"area": ("percentage", height, width, y, x), + "strength": strength, + "set_area_to_bounds": False}) + return (c, ) + +class ConditioningSetAreaStrength: + @classmethod + def INPUT_TYPES(s): + return {"required": {"conditioning": ("CONDITIONING", ), + "strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}), + }} + RETURN_TYPES = ("CONDITIONING",) + FUNCTION = "append" + + CATEGORY = "model/conditioning/transform" + + def append(self, conditioning, strength): + c = node_helpers.conditioning_set_values(conditioning, {"strength": strength}) + return (c, ) + + +class ConditioningSetMask: + SEARCH_ALIASES = ["masked prompt", "regional inpaint conditioning", "mask conditioning"] + + @classmethod + def INPUT_TYPES(s): + return {"required": {"conditioning": ("CONDITIONING", ), + "mask": ("MASK", ), + "strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}), + "set_cond_area": (["default", "mask bounds"],), + }} + RETURN_TYPES = ("CONDITIONING",) + FUNCTION = "append" + + CATEGORY = "model/conditioning/transform" + + def append(self, conditioning, mask, set_cond_area, strength): + set_area_to_bounds = False + if set_cond_area != "default": + set_area_to_bounds = True + if len(mask.shape) < 3: + mask = mask.unsqueeze(0) + + c = node_helpers.conditioning_set_values(conditioning, {"mask": mask, + "set_area_to_bounds": set_area_to_bounds, + "mask_strength": strength}) + return (c, ) + +class ConditioningZeroOut: + SEARCH_ALIASES = ["null conditioning", "clear conditioning"] + + @classmethod + def INPUT_TYPES(s): + return {"required": {"conditioning": ("CONDITIONING", )}} + RETURN_TYPES = ("CONDITIONING",) + FUNCTION = "zero_out" + + CATEGORY = "model/conditioning/transform" + + def zero_out(self, conditioning): + c = [] + for t in conditioning: + d = t[1].copy() + pooled_output = d.get("pooled_output", None) + if pooled_output is not None: + d["pooled_output"] = torch.zeros_like(pooled_output) + conditioning_lyrics = d.get("conditioning_lyrics", None) + if conditioning_lyrics is not None: + d["conditioning_lyrics"] = torch.zeros_like(conditioning_lyrics) + conditioning_scale = d.get("conditioning_scale", None) + if conditioning_scale is not None: + d["conditioning_scale"] = torch.zeros_like(conditioning_scale) + n = [torch.zeros_like(t[0]), d] + c.append(n) + return (c, ) + +class ConditioningSetTimestepRange: + @classmethod + def INPUT_TYPES(s): + return {"required": {"conditioning": ("CONDITIONING", ), + "start": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1.0, "step": 0.001}), + "end": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.001}) + }} + RETURN_TYPES = ("CONDITIONING",) + FUNCTION = "set_range" + + CATEGORY = "model/conditioning/transform" + + def set_range(self, conditioning, start, end): + c = node_helpers.conditioning_set_values(conditioning, {"start_percent": start, "end_percent": end}) + return (c, ) + +class VAEDecode: + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "samples": ("LATENT", {"tooltip": "The latent to be decoded."}), + "vae": ("VAE", {"tooltip": "The VAE model used for decoding the latent."}) + } + } + RETURN_TYPES = ("IMAGE",) + OUTPUT_TOOLTIPS = ("The decoded image.",) + FUNCTION = "decode" + + CATEGORY = "model/latent" + DESCRIPTION = "Decodes latent images back into pixel space images." + SEARCH_ALIASES = ["decode", "decode latent", "latent to image", "render latent"] + + def decode(self, vae, samples): + latent = samples["samples"] + if latent.is_nested: + latent = latent.unbind()[0] + + images = vae.decode(latent) + if len(images.shape) == 5: #Combine batches + images = images.reshape(-1, images.shape[-3], images.shape[-2], images.shape[-1]) + return (images, ) + +class VAEDecodeTiled: + @classmethod + def INPUT_TYPES(s): + return {"required": {"samples": ("LATENT", ), "vae": ("VAE", ), + "tile_size": ("INT", {"default": 512, "min": 64, "max": 4096, "step": 32, "advanced": True}), + "overlap": ("INT", {"default": 64, "min": 0, "max": 4096, "step": 32, "advanced": True}), + "temporal_size": ("INT", {"default": 64, "min": 8, "max": 4096, "step": 4, "tooltip": "Only used for video VAEs: Amount of frames to decode at a time.", "advanced": True}), + "temporal_overlap": ("INT", {"default": 8, "min": 4, "max": 4096, "step": 4, "tooltip": "Only used for video VAEs: Amount of frames to overlap.", "advanced": True}), + }} + RETURN_TYPES = ("IMAGE",) + FUNCTION = "decode" + + CATEGORY = "model/latent" + + def decode(self, vae, samples, tile_size, overlap=64, temporal_size=64, temporal_overlap=8): + if tile_size < overlap * 4: + overlap = tile_size // 4 + if temporal_size < temporal_overlap * 2: + temporal_overlap = temporal_overlap // 2 + temporal_compression = vae.temporal_compression_decode() + if temporal_compression is not None: + temporal_size = max(2, temporal_size // temporal_compression) + temporal_overlap = max(1, min(temporal_size // 2, temporal_overlap // temporal_compression)) + else: + temporal_size = None + temporal_overlap = None + + latent = samples["samples"] + if latent.is_nested: + latent = latent.unbind()[0] + + compression = vae.spacial_compression_decode() + images = vae.decode_tiled(latent, tile_x=tile_size // compression, tile_y=tile_size // compression, overlap=overlap // compression, tile_t=temporal_size, overlap_t=temporal_overlap) + if len(images.shape) == 5: #Combine batches + images = images.reshape(-1, images.shape[-3], images.shape[-2], images.shape[-1]) + return (images, ) + +class VAEEncode: + @classmethod + def INPUT_TYPES(s): + return {"required": { "pixels": ("IMAGE", ), "vae": ("VAE", )}} + RETURN_TYPES = ("LATENT",) + FUNCTION = "encode" + + CATEGORY = "model/latent" + SEARCH_ALIASES = ["encode", "encode image", "image to latent"] + + def encode(self, vae, pixels): + t = vae.encode(pixels) + return ({"samples":t}, ) + +class VAEEncodeTiled: + @classmethod + def INPUT_TYPES(s): + return {"required": {"pixels": ("IMAGE", ), "vae": ("VAE", ), + "tile_size": ("INT", {"default": 512, "min": 64, "max": 4096, "step": 64, "advanced": True}), + "overlap": ("INT", {"default": 64, "min": 0, "max": 4096, "step": 32, "advanced": True}), + "temporal_size": ("INT", {"default": 64, "min": 8, "max": 4096, "step": 4, "tooltip": "Only used for video VAEs: Amount of frames to encode at a time.", "advanced": True}), + "temporal_overlap": ("INT", {"default": 8, "min": 4, "max": 4096, "step": 4, "tooltip": "Only used for video VAEs: Amount of frames to overlap.", "advanced": True}), + }} + RETURN_TYPES = ("LATENT",) + FUNCTION = "encode" + + CATEGORY = "model/latent" + + def encode(self, vae, pixels, tile_size, overlap, temporal_size=64, temporal_overlap=8): + t = vae.encode_tiled(pixels, tile_x=tile_size, tile_y=tile_size, overlap=overlap, tile_t=temporal_size, overlap_t=temporal_overlap) + return ({"samples": t}, ) + +class VAEEncodeForInpaint: + @classmethod + def INPUT_TYPES(s): + return {"required": { "pixels": ("IMAGE", ), "vae": ("VAE", ), "mask": ("MASK", ), "grow_mask_by": ("INT", {"default": 6, "min": 0, "max": 64, "step": 1}),}} + RETURN_TYPES = ("LATENT",) + FUNCTION = "encode" + + CATEGORY = "model/latent" + + def encode(self, vae, pixels, mask, grow_mask_by=6): + downscale_ratio = vae.spacial_compression_encode() + x = (pixels.shape[1] // downscale_ratio) * downscale_ratio + y = (pixels.shape[2] // downscale_ratio) * downscale_ratio + mask = torch.nn.functional.interpolate(mask.reshape((-1, 1, mask.shape[-2], mask.shape[-1])), size=(pixels.shape[1], pixels.shape[2]), mode="bilinear") + + pixels = pixels.clone() + if pixels.shape[1] != x or pixels.shape[2] != y: + x_offset = (pixels.shape[1] % downscale_ratio) // 2 + y_offset = (pixels.shape[2] % downscale_ratio) // 2 + pixels = pixels[:,x_offset:x + x_offset, y_offset:y + y_offset,:] + mask = mask[:,:,x_offset:x + x_offset, y_offset:y + y_offset] + + #grow mask by a few pixels to keep things seamless in latent space + if grow_mask_by == 0: + mask_erosion = mask + else: + kernel_tensor = torch.ones((1, 1, grow_mask_by, grow_mask_by)) + padding = math.ceil((grow_mask_by - 1) / 2) + + mask_erosion = torch.clamp(torch.nn.functional.conv2d(mask.round(), kernel_tensor, padding=padding), 0, 1) + + m = (1.0 - mask.round()).squeeze(1) + for i in range(3): + pixels[:,:,:,i] -= 0.5 + pixels[:,:,:,i] *= m + pixels[:,:,:,i] += 0.5 + t = vae.encode(pixels) + + return ({"samples":t, "noise_mask": (mask_erosion[:,:,:x,:y].round())}, ) + + +class InpaintModelConditioning: + @classmethod + def INPUT_TYPES(s): + return {"required": {"positive": ("CONDITIONING", ), + "negative": ("CONDITIONING", ), + "vae": ("VAE", ), + "pixels": ("IMAGE", ), + "mask": ("MASK", ), + "noise_mask": ("BOOLEAN", {"default": True, "tooltip": "Add a noise mask to the latent so sampling will only happen within the mask. Might improve results or completely break things depending on the model."}), + }} + + RETURN_TYPES = ("CONDITIONING","CONDITIONING","LATENT") + RETURN_NAMES = ("positive", "negative", "latent") + FUNCTION = "encode" + + CATEGORY = "model/conditioning" + + def encode(self, positive, negative, pixels, vae, mask, noise_mask=True): + x = (pixels.shape[1] // 8) * 8 + y = (pixels.shape[2] // 8) * 8 + mask = torch.nn.functional.interpolate(mask.reshape((-1, 1, mask.shape[-2], mask.shape[-1])), size=(pixels.shape[1], pixels.shape[2]), mode="bilinear") + + orig_pixels = pixels + pixels = orig_pixels.clone() + if pixels.shape[1] != x or pixels.shape[2] != y: + x_offset = (pixels.shape[1] % 8) // 2 + y_offset = (pixels.shape[2] % 8) // 2 + pixels = pixels[:,x_offset:x + x_offset, y_offset:y + y_offset,:] + mask = mask[:,:,x_offset:x + x_offset, y_offset:y + y_offset] + + m = (1.0 - mask.round()).squeeze(1) + for i in range(3): + pixels[:,:,:,i] -= 0.5 + pixels[:,:,:,i] *= m + pixels[:,:,:,i] += 0.5 + concat_latent = vae.encode(pixels) + orig_latent = vae.encode(orig_pixels) + + out_latent = {} + + out_latent["samples"] = orig_latent + if noise_mask: + out_latent["noise_mask"] = mask + + out = [] + for conditioning in [positive, negative]: + c = node_helpers.conditioning_set_values(conditioning, {"concat_latent_image": concat_latent, + "concat_mask": mask}) + out.append(c) + return (out[0], out[1], out_latent) + + +class SaveLatent: + SEARCH_ALIASES = ["export latent"] + + def __init__(self): + self.output_dir = folder_paths.get_output_directory() + + @classmethod + def INPUT_TYPES(s): + return { "required": { + "samples": ("LATENT",), + "filename_prefix": ("STRING", {"default": "latents/ComfyUI"})}, + "hidden": {"prompt": "PROMPT", "extra_pnginfo": "EXTRA_PNGINFO"}, + } + RETURN_TYPES = ("LATENT",) + RETURN_NAMES = ("samples",) + FUNCTION = "save" + + OUTPUT_NODE = True + + CATEGORY = "model/latent" + + def save(self, samples, filename_prefix="ComfyUI", prompt=None, extra_pnginfo=None): + full_output_folder, filename, counter, subfolder, filename_prefix = folder_paths.get_save_image_path(filename_prefix, self.output_dir) + + # support save metadata for latent sharing + prompt_info = "" + if prompt is not None: + prompt_info = json.dumps(prompt) + + metadata = None + if not args.disable_metadata: + metadata = {"prompt": prompt_info} + if extra_pnginfo is not None: + for x in extra_pnginfo: + metadata[x] = json.dumps(extra_pnginfo[x]) + + file = f"{filename}_{counter:05}_.latent" + + results: list[FileLocator] = [] + results.append({ + "filename": file, + "subfolder": subfolder, + "type": "output" + }) + + file = os.path.join(full_output_folder, file) + + output = {} + output["latent_tensor"] = samples["samples"].contiguous() + output["latent_format_version_0"] = torch.tensor([]) + + comfy.utils.save_torch_file(output, file, metadata=metadata) + return { "ui": { "latents": results }, "result": (samples,) } + + +class LoadLatent: + SEARCH_ALIASES = ["import latent", "open latent"] + + @classmethod + def INPUT_TYPES(s): + input_dir = folder_paths.get_input_directory() + files = [f for f in os.listdir(input_dir) if os.path.isfile(os.path.join(input_dir, f)) and f.endswith(".latent")] + return {"required": {"latent": [sorted(files), ]}, } + + CATEGORY = "model/latent" + + RETURN_TYPES = ("LATENT", ) + FUNCTION = "load" + + def load(self, latent): + latent_path = folder_paths.get_annotated_filepath(latent) + latent = safetensors.torch.load_file(latent_path, device="cpu") + multiplier = 1.0 + if "latent_format_version_0" not in latent: + multiplier = 1.0 / 0.18215 + samples = {"samples": latent["latent_tensor"].float() * multiplier} + return (samples, ) + + @classmethod + def IS_CHANGED(s, latent): + image_path = folder_paths.get_annotated_filepath(latent) + m = hashlib.sha256() + with open(image_path, 'rb') as f: + m.update(f.read()) + return m.digest().hex() + + @classmethod + def VALIDATE_INPUTS(s, latent): + if not folder_paths.exists_annotated_filepath(latent): + return "Invalid latent file: {}".format(latent) + return True + + +class CheckpointLoader: + SEARCH_ALIASES = ["load model", "model loader"] + + @classmethod + def INPUT_TYPES(s): + return {"required": { "config_name": (folder_paths.get_filename_list("configs"), ), + "ckpt_name": (folder_paths.get_filename_list("checkpoints"), )}} + RETURN_TYPES = ("MODEL", "CLIP", "VAE") + FUNCTION = "load_checkpoint" + + CATEGORY = "model/loaders" + DEPRECATED = True + + def load_checkpoint(self, config_name, ckpt_name): + config_path = folder_paths.get_full_path("configs", config_name) + ckpt_path = folder_paths.get_full_path_or_raise("checkpoints", ckpt_name) + return comfy.sd.load_checkpoint(config_path, ckpt_path, output_vae=True, output_clip=True, embedding_directory=folder_paths.get_folder_paths("embeddings")) + +class CheckpointLoaderSimple: + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "ckpt_name": (folder_paths.get_filename_list("checkpoints"), {"tooltip": "The name of the checkpoint (model) to load."}), + } + } + RETURN_TYPES = ("MODEL", "CLIP", "VAE") + OUTPUT_TOOLTIPS = ("The model used for denoising latents.", + "The CLIP model used for encoding text prompts.", + "The VAE model used for encoding and decoding images to and from latent space.") + FUNCTION = "load_checkpoint" + + CATEGORY = "model/loaders" + DESCRIPTION = "Loads a diffusion model checkpoint, diffusion models are used to denoise latents." + SEARCH_ALIASES = ["load model", "checkpoint", "model loader", "load checkpoint", "ckpt", "model"] + + def load_checkpoint(self, ckpt_name): + ckpt_path = folder_paths.get_full_path_or_raise("checkpoints", ckpt_name) + out = comfy.sd.load_checkpoint_guess_config(ckpt_path, output_vae=True, output_clip=True, embedding_directory=folder_paths.get_folder_paths("embeddings")) + return out[:3] + +class DiffusersLoader: + SEARCH_ALIASES = ["load diffusers model"] + + @classmethod + def _model_paths(cls): + paths = [] + for search_path in folder_paths.get_folder_paths("diffusers"): + if os.path.exists(search_path): + for root, subdir, files in os.walk(search_path, followlinks=True): + if "model_index.json" in files: + paths.append(os.path.relpath(root, start=search_path)) + return paths + + @classmethod + def INPUT_TYPES(cls): + return {"required": {"model_path": (cls._model_paths(),), }} + RETURN_TYPES = ("MODEL", "CLIP", "VAE") + FUNCTION = "load_checkpoint" + DEPRECATED = True + + CATEGORY = "model/loaders" + + def load_checkpoint(self, model_path, output_vae=True, output_clip=True): + if model_path not in self._model_paths(): + raise ValueError(f"Invalid diffusers model path: {model_path!r}") + + resolved_model_path = None + for search_path in folder_paths.get_folder_paths("diffusers"): + if os.path.exists(search_path): + path = os.path.join(search_path, model_path) + if os.path.isfile(os.path.join(path, "model_index.json")): + resolved_model_path = path + break + if resolved_model_path is None: + raise FileNotFoundError(f"Diffusers model {model_path!r} not found.") + + return comfy.diffusers_load.load_diffusers(resolved_model_path, output_vae=output_vae, output_clip=output_clip, embedding_directory=folder_paths.get_folder_paths("embeddings")) + + +class unCLIPCheckpointLoader: + @classmethod + def INPUT_TYPES(s): + return {"required": { "ckpt_name": (folder_paths.get_filename_list("checkpoints"), ), + }} + RETURN_TYPES = ("MODEL", "CLIP", "VAE", "CLIP_VISION") + FUNCTION = "load_checkpoint" + + CATEGORY = "model/loaders" + + def load_checkpoint(self, ckpt_name, output_vae=True, output_clip=True): + ckpt_path = folder_paths.get_full_path_or_raise("checkpoints", ckpt_name) + out = comfy.sd.load_checkpoint_guess_config(ckpt_path, output_vae=True, output_clip=True, output_clipvision=True, embedding_directory=folder_paths.get_folder_paths("embeddings")) + return out + +class CLIPSetLastLayer: + @classmethod + def INPUT_TYPES(s): + return {"required": { "clip": ("CLIP", ), + "stop_at_clip_layer": ("INT", {"default": -1, "min": -24, "max": -1, "step": 1, "advanced": True}), + }} + RETURN_TYPES = ("CLIP",) + FUNCTION = "set_last_layer" + + CATEGORY = "model/conditioning" + + def set_last_layer(self, clip, stop_at_clip_layer): + clip = clip.clone() + clip.clip_layer(stop_at_clip_layer) + return (clip,) + +class LoraLoader: + ESSENTIALS_CATEGORY = "Image Generation" + + def __init__(self): + self.loaded_lora = None + + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "model": ("MODEL", {"tooltip": "The diffusion model the LoRA will be applied to."}), + "clip": ("CLIP", {"tooltip": "The CLIP model the LoRA will be applied to."}), + "lora_name": (folder_paths.get_filename_list("loras"), {"tooltip": "The name of the LoRA."}), + "strength_model": ("FLOAT", {"default": 1.0, "min": -100.0, "max": 100.0, "step": 0.01, "tooltip": "How strongly to modify the diffusion model. This value can be negative."}), + "strength_clip": ("FLOAT", {"default": 1.0, "min": -100.0, "max": 100.0, "step": 0.01, "tooltip": "How strongly to modify the CLIP model. This value can be negative."}), + } + } + + RETURN_TYPES = ("MODEL", "CLIP") + OUTPUT_TOOLTIPS = ("The modified diffusion model.", "The modified CLIP model.") + FUNCTION = "load_lora" + + CATEGORY = "model/loaders" + DESCRIPTION = "This LoRA loader is used to modify both diffusion and CLIP models, altering the way in which latents are denoised such as applying styles. Multiple LoRA nodes can be linked together." + SEARCH_ALIASES = ["lora", "load lora", "apply lora", "lora loader", "lora model"] + + def load_lora(self, model, clip, lora_name, strength_model, strength_clip): + if strength_model == 0 and strength_clip == 0: + return (model, clip) + + lora_path = folder_paths.get_full_path_or_raise("loras", lora_name) + lora = None + lora_metadata = None + if self.loaded_lora is not None: + if self.loaded_lora[0] == lora_path: + lora = self.loaded_lora[1] + lora_metadata = self.loaded_lora[2] if len(self.loaded_lora) > 2 else None + else: + self.loaded_lora = None + + if lora is None: + lora, lora_metadata = comfy.utils.load_torch_file(lora_path, safe_load=True, return_metadata=True) + self.loaded_lora = (lora_path, lora, lora_metadata) + + model_lora, clip_lora = comfy.sd.load_lora_for_models(model, clip, lora, strength_model, strength_clip, lora_metadata=lora_metadata) + return (model_lora, clip_lora) + +class LoraLoaderModelOnly(LoraLoader): + @classmethod + def INPUT_TYPES(s): + return {"required": { "model": ("MODEL",), + "lora_name": (folder_paths.get_filename_list("loras"), ), + "strength_model": ("FLOAT", {"default": 1.0, "min": -100.0, "max": 100.0, "step": 0.01}), + }} + RETURN_TYPES = ("MODEL",) + DESCRIPTION = "This LoRAs loader is used to modify the diffusion model, altering the way in which latents are denoised such as applying styles. Multiple LoRA nodes can be linked together." + FUNCTION = "load_lora_model_only" + + def load_lora_model_only(self, model, lora_name, strength_model): + return (self.load_lora(model, None, lora_name, strength_model, 0)[0],) + +class VAELoader: + video_taes = ["taehv", "lighttaew2_2", "lighttaew2_1", "lighttaehy1_5", "taeltx_2"] + image_taes = ["taesd", "taesdxl", "taesd3", "taef1", "taef2"] + + @staticmethod + def vae_list(s): + vaes = folder_paths.get_filename_list("vae") + approx_vaes = folder_paths.get_filename_list("vae_approx") + have_img_encoder, have_img_decoder = set(), set() + for v in approx_vaes: + parts = v.split("_", 1) + if len(parts) != 2 or parts[0] not in s.image_taes: + for tae in s.video_taes: + if v.startswith(tae): + vaes.append(v) + break + continue + if parts[1].startswith("encoder."): + have_img_encoder.add(parts[0]) + elif parts[1].startswith("decoder."): + have_img_decoder.add(parts[0]) + vaes += [k for k in have_img_decoder if k in have_img_encoder] + vaes.append("pixel_space") + return vaes + + @staticmethod + def load_taesd(name): + sd = {} + approx_vaes = folder_paths.get_filename_list("vae_approx") + + encoder = next(filter(lambda a: a.startswith("{}_encoder.".format(name)), approx_vaes)) + decoder = next(filter(lambda a: a.startswith("{}_decoder.".format(name)), approx_vaes)) + + enc = comfy.utils.load_torch_file(folder_paths.get_full_path_or_raise("vae_approx", encoder)) + for k in enc: + sd["taesd_encoder.{}".format(k)] = enc[k] + + dec = comfy.utils.load_torch_file(folder_paths.get_full_path_or_raise("vae_approx", decoder)) + for k in dec: + sd["taesd_decoder.{}".format(k)] = dec[k] + + if name == "taesd": + sd["vae_scale"] = torch.tensor(0.18215) + sd["vae_shift"] = torch.tensor(0.0) + elif name == "taesdxl": + sd["vae_scale"] = torch.tensor(0.13025) + sd["vae_shift"] = torch.tensor(0.0) + elif name == "taesd3": + sd["vae_scale"] = torch.tensor(1.5305) + sd["vae_shift"] = torch.tensor(0.0609) + elif name == "taef1": + sd["vae_scale"] = torch.tensor(0.3611) + sd["vae_shift"] = torch.tensor(0.1159) + return sd + + @classmethod + def INPUT_TYPES(s): + return {"required": { "vae_name": (s.vae_list(s), )}} + RETURN_TYPES = ("VAE",) + FUNCTION = "load_vae" + + CATEGORY = "model/loaders" + + #TODO: scale factor? + def load_vae(self, vae_name): + metadata = None + vae_path = None + if vae_name == "pixel_space": + sd = {} + sd["pixel_space_vae"] = torch.tensor(1.0) + elif vae_name in self.image_taes: + sd = self.load_taesd(vae_name) + else: + if os.path.splitext(vae_name)[0] in self.video_taes: + vae_path = folder_paths.get_full_path_or_raise("vae_approx", vae_name) + else: + vae_path = folder_paths.get_full_path_or_raise("vae", vae_name) + sd, metadata = comfy.utils.load_torch_file(vae_path, return_metadata=True) + if vae_name == "taef2": + if metadata is None: + metadata = {"tae_latent_channels": 128} + else: + metadata["tae_latent_channels"] = 128 + vae = comfy.sd.VAE(sd=sd, metadata=metadata) + vae.throw_exception_if_invalid() + # Register a reload factory on the patcher so multigpu deepclones + # (Select VAE Device, future MultiGPU VAE work-units) can produce + # per-device clones from the same loader context. Only set when we + # actually have a single backing file -- pixel_space and the + # image TAESDs (composed from separate encoder/decoder files via + # load_taesd) are not addressable by a single vae_path. + if vae_path is not None: + vae.patcher.cached_patcher_init = (comfy.sd.load_vae_patcher, (vae_path, metadata, None)) + return (vae,) + +class ControlNetLoader: + @classmethod + def INPUT_TYPES(s): + return {"required": { "control_net_name": (folder_paths.get_filename_list("controlnet"), )}} + + RETURN_TYPES = ("CONTROL_NET",) + FUNCTION = "load_controlnet" + + CATEGORY = "model/loaders" + SEARCH_ALIASES = ["controlnet", "control net", "cn", "load controlnet", "controlnet loader"] + + def load_controlnet(self, control_net_name): + controlnet_path = folder_paths.get_full_path_or_raise("controlnet", control_net_name) + controlnet = comfy.controlnet.load_controlnet(controlnet_path) + if controlnet is None: + raise RuntimeError("ERROR: controlnet file is invalid and does not contain a valid controlnet model.") + return (controlnet,) + +class DiffControlNetLoader: + @classmethod + def INPUT_TYPES(s): + return {"required": { "model": ("MODEL",), + "control_net_name": (folder_paths.get_filename_list("controlnet"), )}} + + RETURN_TYPES = ("CONTROL_NET",) + FUNCTION = "load_controlnet" + + CATEGORY = "model/loaders" + + def load_controlnet(self, model, control_net_name): + controlnet_path = folder_paths.get_full_path_or_raise("controlnet", control_net_name) + controlnet = comfy.controlnet.load_controlnet(controlnet_path, model) + return (controlnet,) + + +class ControlNetApply: + @classmethod + def INPUT_TYPES(s): + return {"required": {"conditioning": ("CONDITIONING", ), + "control_net": ("CONTROL_NET", ), + "image": ("IMAGE", ), + "strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}) + }} + RETURN_TYPES = ("CONDITIONING",) + FUNCTION = "apply_controlnet" + + DEPRECATED = True + CATEGORY = "model/conditioning/controlnet" + + def apply_controlnet(self, conditioning, control_net, image, strength): + if strength == 0: + return (conditioning, ) + + c = [] + control_hint = image.movedim(-1,1) + for t in conditioning: + n = [t[0], t[1].copy()] + c_net = control_net.copy().set_cond_hint(control_hint, strength) + if 'control' in t[1]: + c_net.set_previous_controlnet(t[1]['control']) + n[1]['control'] = c_net + n[1]['control_apply_to_uncond'] = True + c.append(n) + return (c, ) + + +class ControlNetApplyAdvanced: + @classmethod + def INPUT_TYPES(s): + return {"required": {"positive": ("CONDITIONING", ), + "negative": ("CONDITIONING", ), + "control_net": ("CONTROL_NET", ), + "image": ("IMAGE", ), + "strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}), + "start_percent": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1.0, "step": 0.001}), + "end_percent": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.001}) + }, + "optional": {"vae": ("VAE", ), + } + } + + RETURN_TYPES = ("CONDITIONING","CONDITIONING") + RETURN_NAMES = ("positive", "negative") + FUNCTION = "apply_controlnet" + + CATEGORY = "model/conditioning/controlnet" + SEARCH_ALIASES = ["controlnet", "apply controlnet", "use controlnet", "control net"] + + def apply_controlnet(self, positive, negative, control_net, image, strength, start_percent, end_percent, vae=None, extra_concat=[]): + if strength == 0: + return (positive, negative) + + control_hint = image.movedim(-1,1) + cnets = {} + + out = [] + for conditioning in [positive, negative]: + c = [] + for t in conditioning: + d = t[1].copy() + + prev_cnet = d.get('control', None) + if prev_cnet in cnets: + c_net = cnets[prev_cnet] + else: + c_net = control_net.copy().set_cond_hint(control_hint, strength, (start_percent, end_percent), vae=vae, extra_concat=extra_concat) + c_net.set_previous_controlnet(prev_cnet) + cnets[prev_cnet] = c_net + + d['control'] = c_net + d['control_apply_to_uncond'] = False + n = [t[0], d] + c.append(n) + out.append(c) + return (out[0], out[1]) + + +class UNETLoader: + @classmethod + def INPUT_TYPES(s): + return {"required": { "unet_name": (folder_paths.get_filename_list("diffusion_models"), ), + "weight_dtype": (["default", "fp8_e4m3fn", "fp8_e4m3fn_fast", "fp8_e5m2"], {"advanced": True}) + }} + RETURN_TYPES = ("MODEL",) + FUNCTION = "load_unet" + + CATEGORY = "model/loaders" + + def load_unet(self, unet_name, weight_dtype): + model_options = {} + if weight_dtype == "fp8_e4m3fn": + model_options["dtype"] = torch.float8_e4m3fn + elif weight_dtype == "fp8_e4m3fn_fast": + model_options["dtype"] = torch.float8_e4m3fn + model_options["fp8_optimizations"] = True + elif weight_dtype == "fp8_e5m2": + model_options["dtype"] = torch.float8_e5m2 + + unet_path = folder_paths.get_full_path_or_raise("diffusion_models", unet_name) + model = comfy.sd.load_diffusion_model(unet_path, model_options=model_options) + return (model,) + +class CLIPLoader: + @classmethod + def INPUT_TYPES(s): + return {"required": { "clip_name": (folder_paths.get_filename_list("text_encoders"), ), + "type": (["stable_diffusion", "stable_cascade", "sd3", "stable_audio", "mochi", "ltxv", "pixart", "cosmos", "lumina2", "wan", "hidream", "chroma", "ace", "omnigen2", "qwen_image", "hunyuan_image", "flux2", "ovis", "longcat_image", "cogvideox", "lens", "pixeldit", "ideogram4", "boogu", "krea2", "joyimage", "mage", "minimax"], ), + }, + "optional": { + "device": (["default", "cpu"], {"advanced": True}), + }} + RETURN_TYPES = ("CLIP",) + FUNCTION = "load_clip" + + CATEGORY = "model/loaders" + + DESCRIPTION = "Recipes:\nsd: clip-l\nstable cascade: clip-g\nsd3: t5 xxl / clip-g / clip-l\nstable audio: t5 base\nmochi: t5 xxl\ncogvideox: t5 xxl (226-token padding)\ncosmos: old t5 xxl\nlumina2: gemma 2 2B\nwan: umt5 xxl\nhidream: llama-3.1 (Recommend) or t5\nomnigen2: qwen vl 2.5 3B\njoyimage: qwen3-vl 8B\nlens: gpt-oss-20b\npixeldit: gemma 2 2B elm\nminimax: MiniMax H3 Qwen3-VL or Music3 Qwen/RVQ" + + def load_clip(self, clip_name, type="stable_diffusion", device="default"): + clip_type = getattr(comfy.sd.CLIPType, type.upper(), comfy.sd.CLIPType.STABLE_DIFFUSION) + + model_options = {} + if device == "cpu": + model_options["load_device"] = model_options["offload_device"] = torch.device("cpu") + + clip_path = folder_paths.get_full_path_or_raise("text_encoders", clip_name) + clip = comfy.sd.load_clip(ckpt_paths=[clip_path], embedding_directory=folder_paths.get_folder_paths("embeddings"), clip_type=clip_type, model_options=model_options) + return (clip,) + +class DualCLIPLoader: + @classmethod + def INPUT_TYPES(s): + return {"required": { "clip_name1": (folder_paths.get_filename_list("text_encoders"), ), + "clip_name2": (folder_paths.get_filename_list("text_encoders"), ), + "type": (["sdxl", "sd3", "flux", "hunyuan_video", "hidream", "hunyuan_image", "hunyuan_video_15", "kandinsky5", "kandinsky5_image", "ltxv", "newbie", "ace"], ), + }, + "optional": { + "device": (["default", "cpu"], {"advanced": True}), + }} + RETURN_TYPES = ("CLIP",) + FUNCTION = "load_clip" + + CATEGORY = "model/loaders" + + DESCRIPTION = "Recipes:\nsdxl: clip-l, clip-g\nsd3: clip-l, clip-g / clip-l, t5 / clip-g, t5\nflux: clip-l, t5\nhidream: at least one of t5 or llama, recommended t5 and llama\nhunyuan_image: qwen2.5vl 7b and byt5 small\nnewbie: gemma-3-4b-it, jina clip v2" + + def load_clip(self, clip_name1, clip_name2, type, device="default"): + clip_type = getattr(comfy.sd.CLIPType, type.upper(), comfy.sd.CLIPType.STABLE_DIFFUSION) + + clip_path1 = folder_paths.get_full_path_or_raise("text_encoders", clip_name1) + clip_path2 = folder_paths.get_full_path_or_raise("text_encoders", clip_name2) + + model_options = {} + if device == "cpu": + model_options["load_device"] = model_options["offload_device"] = torch.device("cpu") + + clip = comfy.sd.load_clip(ckpt_paths=[clip_path1, clip_path2], embedding_directory=folder_paths.get_folder_paths("embeddings"), clip_type=clip_type, model_options=model_options) + return (clip,) + +class CLIPVisionLoader: + @classmethod + def INPUT_TYPES(s): + return {"required": { "clip_name": (folder_paths.get_filename_list("clip_vision"), ), + }} + RETURN_TYPES = ("CLIP_VISION",) + FUNCTION = "load_clip" + + CATEGORY = "model/loaders" + + def load_clip(self, clip_name): + clip_path = folder_paths.get_full_path_or_raise("clip_vision", clip_name) + clip_vision = comfy.clip_vision.load(clip_path) + if clip_vision is None: + raise RuntimeError("ERROR: clip vision file is invalid and does not contain a valid vision model.") + return (clip_vision,) + +class CLIPVisionEncode: + @classmethod + def INPUT_TYPES(s): + return {"required": { "clip_vision": ("CLIP_VISION",), + "image": ("IMAGE",), + "crop": (["center", "none"],) + }} + RETURN_TYPES = ("CLIP_VISION_OUTPUT",) + FUNCTION = "encode" + + CATEGORY = "model/conditioning" + + def encode(self, clip_vision, image, crop): + crop_image = True + if crop != "center": + crop_image = False + output = clip_vision.encode_image(image, crop=crop_image) + return (output,) + +class StyleModelLoader: + @classmethod + def INPUT_TYPES(s): + return {"required": { "style_model_name": (folder_paths.get_filename_list("style_models"), )}} + + RETURN_TYPES = ("STYLE_MODEL",) + FUNCTION = "load_style_model" + + CATEGORY = "model/loaders" + + def load_style_model(self, style_model_name): + style_model_path = folder_paths.get_full_path_or_raise("style_models", style_model_name) + style_model = comfy.sd.load_style_model(style_model_path) + return (style_model,) + + +class StyleModelApply: + SEARCH_ALIASES = ["style transfer"] + + @classmethod + def INPUT_TYPES(s): + return {"required": {"conditioning": ("CONDITIONING", ), + "style_model": ("STYLE_MODEL", ), + "clip_vision_output": ("CLIP_VISION_OUTPUT", ), + "strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}), + "strength_type": (["multiply", "attn_bias"], ), + }} + RETURN_TYPES = ("CONDITIONING",) + FUNCTION = "apply_stylemodel" + + CATEGORY = "model/conditioning" + + def apply_stylemodel(self, conditioning, style_model, clip_vision_output, strength, strength_type): + cond = style_model.get_cond(clip_vision_output).flatten(start_dim=0, end_dim=1).unsqueeze(dim=0) + if strength_type == "multiply": + cond *= strength + + n = cond.shape[1] + c_out = [] + for t in conditioning: + (txt, keys) = t + keys = keys.copy() + # even if the strength is 1.0 (i.e, no change), if there's already a mask, we have to add to it + if "attention_mask" in keys or (strength_type == "attn_bias" and strength != 1.0): + # math.log raises an error if the argument is zero + # torch.log returns -inf, which is what we want + attn_bias = torch.log(torch.Tensor([strength if strength_type == "attn_bias" else 1.0])) + # get the size of the mask image + mask_ref_size = keys.get("attention_mask_img_shape", (1, 1)) + n_ref = mask_ref_size[0] * mask_ref_size[1] + n_txt = txt.shape[1] + # grab the existing mask + mask = keys.get("attention_mask", None) + # create a default mask if it doesn't exist + if mask is None: + mask = torch.zeros((txt.shape[0], n_txt + n_ref, n_txt + n_ref), dtype=torch.float16) + # convert the mask dtype, because it might be boolean + # we want it to be interpreted as a bias + if mask.dtype == torch.bool: + # log(True) = log(1) = 0 + # log(False) = log(0) = -inf + mask = torch.log(mask.to(dtype=torch.float16)) + # now we make the mask bigger to add space for our new tokens + new_mask = torch.zeros((txt.shape[0], n_txt + n + n_ref, n_txt + n + n_ref), dtype=torch.float16) + # copy over the old mask, in quandrants + new_mask[:, :n_txt, :n_txt] = mask[:, :n_txt, :n_txt] + new_mask[:, :n_txt, n_txt+n:] = mask[:, :n_txt, n_txt:] + new_mask[:, n_txt+n:, :n_txt] = mask[:, n_txt:, :n_txt] + new_mask[:, n_txt+n:, n_txt+n:] = mask[:, n_txt:, n_txt:] + # now fill in the attention bias to our redux tokens + new_mask[:, :n_txt, n_txt:n_txt+n] = attn_bias + new_mask[:, n_txt+n:, n_txt:n_txt+n] = attn_bias + keys["attention_mask"] = new_mask.to(txt.device) + keys["attention_mask_img_shape"] = mask_ref_size + + c_out.append([torch.cat((txt, cond), dim=1), keys]) + + return (c_out,) + +class unCLIPConditioning: + @classmethod + def INPUT_TYPES(s): + return {"required": {"conditioning": ("CONDITIONING", ), + "clip_vision_output": ("CLIP_VISION_OUTPUT", ), + "strength": ("FLOAT", {"default": 1.0, "min": -10.0, "max": 10.0, "step": 0.01}), + "noise_augmentation": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1.0, "step": 0.01}), + }} + RETURN_TYPES = ("CONDITIONING",) + FUNCTION = "apply_adm" + + CATEGORY = "model/conditioning" + + def apply_adm(self, conditioning, clip_vision_output, strength, noise_augmentation): + if strength == 0: + return (conditioning, ) + + c = node_helpers.conditioning_set_values(conditioning, {"unclip_conditioning": [{"clip_vision_output": clip_vision_output, "strength": strength, "noise_augmentation": noise_augmentation}]}, append=True) + return (c, ) + +class GLIGENLoader: + @classmethod + def INPUT_TYPES(s): + return {"required": { "gligen_name": (folder_paths.get_filename_list("gligen"), )}} + + RETURN_TYPES = ("GLIGEN",) + FUNCTION = "load_gligen" + + CATEGORY = "model/loaders" + + def load_gligen(self, gligen_name): + gligen_path = folder_paths.get_full_path_or_raise("gligen", gligen_name) + gligen = comfy.sd.load_gligen(gligen_path) + return (gligen,) + +class GLIGENTextBoxApply: + @classmethod + def INPUT_TYPES(s): + return {"required": {"conditioning_to": ("CONDITIONING", ), + "clip": ("CLIP", ), + "gligen_textbox_model": ("GLIGEN", ), + "text": ("STRING", {"multiline": True, "dynamicPrompts": True}), + "width": ("INT", {"default": 64, "min": 8, "max": MAX_RESOLUTION, "step": 8}), + "height": ("INT", {"default": 64, "min": 8, "max": MAX_RESOLUTION, "step": 8}), + "x": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}), + "y": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}), + }} + RETURN_TYPES = ("CONDITIONING",) + FUNCTION = "append" + + CATEGORY = "model/conditioning/gligen" + + def append(self, conditioning_to, clip, gligen_textbox_model, text, width, height, x, y): + c = [] + cond, cond_pooled = clip.encode_from_tokens(clip.tokenize(text), return_pooled="unprojected") + for t in conditioning_to: + n = [t[0], t[1].copy()] + position_params = [(cond_pooled, height // 8, width // 8, y // 8, x // 8)] + prev = [] + if "gligen" in n[1]: + prev = n[1]['gligen'][2] + + n[1]['gligen'] = ("position", gligen_textbox_model, prev + position_params) + c.append(n) + return (c, ) + +class EmptyLatentImage: + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "width": ("INT", {"default": 512, "min": 16, "max": MAX_RESOLUTION, "step": 8, "tooltip": "The width of the latent images in pixels."}), + "height": ("INT", {"default": 512, "min": 16, "max": MAX_RESOLUTION, "step": 8, "tooltip": "The height of the latent images in pixels."}), + "batch_size": ("INT", {"default": 1, "min": 1, "max": 4096, "tooltip": "The number of latent images in the batch."}) + } + } + RETURN_TYPES = ("LATENT",) + OUTPUT_TOOLTIPS = ("The empty latent image batch.",) + FUNCTION = "generate" + + CATEGORY = "model/latent" + DESCRIPTION = "Create a new batch of empty latent images to be denoised via sampling." + SEARCH_ALIASES = ["empty", "empty latent", "new latent", "create latent", "blank latent", "blank"] + + def generate(self, width, height, batch_size=1): + latent = torch.zeros([batch_size, 4, height // 8, width // 8], device=comfy.model_management.intermediate_device(), dtype=comfy.model_management.intermediate_dtype()) + return ({"samples": latent, "downscale_ratio_spacial": 8}, ) + + +class LatentFromBatch: + SEARCH_ALIASES = ["select from batch", "pick latent", "batch subset"] + + @classmethod + def INPUT_TYPES(s): + return {"required": { "samples": ("LATENT",), + "batch_index": ("INT", {"default": 0, "min": -MAX_RESOLUTION, "max": MAX_RESOLUTION}), + "length": ("INT", {"default": 1, "min": 1, "max": 64}), + }} + RETURN_TYPES = ("LATENT",) + FUNCTION = "frombatch" + + CATEGORY = "model/latent/batch" + + def frombatch(self, samples, batch_index, length): + s = samples.copy() + s_in = samples["samples"] + if batch_index < 0: + batch_index += s_in.shape[0] + batch_index = max(0, min(s_in.shape[0] - 1, batch_index)) + length = min(s_in.shape[0] - batch_index, length) + s["samples"] = s_in[batch_index:batch_index + length].clone() + if "noise_mask" in samples: + masks = samples["noise_mask"] + if masks.shape[0] == 1: + s["noise_mask"] = masks.clone() + else: + if masks.shape[0] < s_in.shape[0]: + masks = masks.repeat(math.ceil(s_in.shape[0] / masks.shape[0]), 1, 1, 1)[:s_in.shape[0]] + s["noise_mask"] = masks[batch_index:batch_index + length].clone() + if "batch_index" not in s: + s["batch_index"] = [x for x in range(batch_index, batch_index+length)] + else: + s["batch_index"] = samples["batch_index"][batch_index:batch_index + length] + return (s,) + +class RepeatLatentBatch: + SEARCH_ALIASES = ["duplicate latent", "clone latent"] + + @classmethod + def INPUT_TYPES(s): + return {"required": { "samples": ("LATENT",), + "amount": ("INT", {"default": 1, "min": 1, "max": 64}), + }} + RETURN_TYPES = ("LATENT",) + FUNCTION = "repeat" + + CATEGORY = "model/latent/batch" + + def repeat(self, samples, amount): + s = samples.copy() + s_in = samples["samples"] + + s["samples"] = s_in.repeat((amount,) + ((1,) * (s_in.ndim - 1))) + if "noise_mask" in samples and samples["noise_mask"].shape[0] > 1: + masks = samples["noise_mask"] + if masks.shape[0] < s_in.shape[0]: + masks = masks.repeat((math.ceil(s_in.shape[0] / masks.shape[0]),) + ((1,) * (masks.ndim - 1)))[:s_in.shape[0]] + s["noise_mask"] = samples["noise_mask"].repeat((amount,) + ((1,) * (samples["noise_mask"].ndim - 1))) + if "batch_index" in s: + offset = max(s["batch_index"]) - min(s["batch_index"]) + 1 + s["batch_index"] = s["batch_index"] + [x + (i * offset) for i in range(1, amount) for x in s["batch_index"]] + return (s,) + +class LatentUpscale: + SEARCH_ALIASES = ["enlarge latent", "resize latent"] + + upscale_methods = ["nearest-exact", "bilinear", "area", "bicubic", "bislerp"] + crop_methods = ["disabled", "center"] + + @classmethod + def INPUT_TYPES(s): + return {"required": { "samples": ("LATENT",), "upscale_method": (s.upscale_methods,), + "width": ("INT", {"default": 512, "min": 0, "max": MAX_RESOLUTION, "step": 8}), + "height": ("INT", {"default": 512, "min": 0, "max": MAX_RESOLUTION, "step": 8}), + "crop": (s.crop_methods,)}} + RETURN_TYPES = ("LATENT",) + FUNCTION = "upscale" + + CATEGORY = "model/latent" + + def upscale(self, samples, upscale_method, width, height, crop): + if width == 0 and height == 0: + s = samples + else: + s = samples.copy() + + if width == 0: + height = max(64, height) + width = max(64, round(samples["samples"].shape[-1] * height / samples["samples"].shape[-2])) + elif height == 0: + width = max(64, width) + height = max(64, round(samples["samples"].shape[-2] * width / samples["samples"].shape[-1])) + else: + width = max(64, width) + height = max(64, height) + + s["samples"] = comfy.utils.common_upscale(samples["samples"], width // 8, height // 8, upscale_method, crop) + return (s,) + +class LatentUpscaleBy: + SEARCH_ALIASES = ["enlarge latent", "resize latent", "scale latent"] + + upscale_methods = ["nearest-exact", "bilinear", "area", "bicubic", "bislerp"] + + @classmethod + def INPUT_TYPES(s): + return {"required": { "samples": ("LATENT",), "upscale_method": (s.upscale_methods,), + "scale_by": ("FLOAT", {"default": 1.5, "min": 0.01, "max": 8.0, "step": 0.01}),}} + RETURN_TYPES = ("LATENT",) + FUNCTION = "upscale" + + CATEGORY = "model/latent" + + def upscale(self, samples, upscale_method, scale_by): + s = samples.copy() + width = round(samples["samples"].shape[-1] * scale_by) + height = round(samples["samples"].shape[-2] * scale_by) + s["samples"] = comfy.utils.common_upscale(samples["samples"], width, height, upscale_method, "disabled") + return (s,) + +class LatentRotate: + @classmethod + def INPUT_TYPES(s): + return {"required": { "samples": ("LATENT",), + "rotation": (["none", "90 degrees", "180 degrees", "270 degrees"],), + }} + RETURN_TYPES = ("LATENT",) + FUNCTION = "rotate" + + CATEGORY = "model/latent/transform" + + def rotate(self, samples, rotation): + s = samples.copy() + rotate_by = 0 + if rotation.startswith("90"): + rotate_by = 1 + elif rotation.startswith("180"): + rotate_by = 2 + elif rotation.startswith("270"): + rotate_by = 3 + + s["samples"] = torch.rot90(samples["samples"], k=rotate_by, dims=[3, 2]) + return (s,) + +class LatentFlip: + SEARCH_ALIASES = ["mirror latent"] + + @classmethod + def INPUT_TYPES(s): + return {"required": { "samples": ("LATENT",), + "flip_method": (["x-axis: vertically", "y-axis: horizontally"],), + }} + RETURN_TYPES = ("LATENT",) + FUNCTION = "flip" + + CATEGORY = "model/latent/transform" + + def flip(self, samples, flip_method): + s = samples.copy() + if flip_method.startswith("x"): + s["samples"] = torch.flip(samples["samples"], dims=[2]) + elif flip_method.startswith("y"): + s["samples"] = torch.flip(samples["samples"], dims=[3]) + + return (s,) + +class LatentComposite: + SEARCH_ALIASES = ["overlay latent", "layer latent", "paste latent"] + + @classmethod + def INPUT_TYPES(s): + return {"required": { "samples_to": ("LATENT",), + "samples_from": ("LATENT",), + "x": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}), + "y": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}), + "feather": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}), + }} + RETURN_TYPES = ("LATENT",) + FUNCTION = "composite" + + CATEGORY = "model/latent" + + def composite(self, samples_to, samples_from, x, y, composite_method="normal", feather=0): + x = x // 8 + y = y // 8 + feather = feather // 8 + samples_out = samples_to.copy() + s = samples_to["samples"].clone() + samples_to = samples_to["samples"] + samples_from = samples_from["samples"] + if feather == 0: + s[:,:,y:y+samples_from.shape[2],x:x+samples_from.shape[3]] = samples_from[:,:,:samples_to.shape[2] - y, :samples_to.shape[3] - x] + else: + samples_from = samples_from[:,:,:samples_to.shape[2] - y, :samples_to.shape[3] - x] + mask = torch.ones_like(samples_from) + for t in range(feather): + if y != 0: + mask[:,:,t:1+t,:] *= ((1.0/feather) * (t + 1)) + + if y + samples_from.shape[2] < samples_to.shape[2]: + mask[:,:,mask.shape[2] -1 -t: mask.shape[2]-t,:] *= ((1.0/feather) * (t + 1)) + if x != 0: + mask[:,:,:,t:1+t] *= ((1.0/feather) * (t + 1)) + if x + samples_from.shape[3] < samples_to.shape[3]: + mask[:,:,:,mask.shape[3]- 1 - t: mask.shape[3]- t] *= ((1.0/feather) * (t + 1)) + rev_mask = torch.ones_like(mask) - mask + s[:,:,y:y+samples_from.shape[2],x:x+samples_from.shape[3]] = samples_from[:,:,:samples_to.shape[2] - y, :samples_to.shape[3] - x] * mask + s[:,:,y:y+samples_from.shape[2],x:x+samples_from.shape[3]] * rev_mask + samples_out["samples"] = s + return (samples_out,) + +class LatentBlend: + SEARCH_ALIASES = ["mix latents", "interpolate latents"] + + @classmethod + def INPUT_TYPES(s): + return {"required": { + "samples1": ("LATENT",), + "samples2": ("LATENT",), + "blend_factor": ("FLOAT", { + "default": 0.5, + "min": 0, + "max": 1, + "step": 0.01 + }), + }} + + RETURN_TYPES = ("LATENT",) + FUNCTION = "blend" + + CATEGORY = "experimental" + + def blend(self, samples1, samples2, blend_factor:float, blend_mode: str="normal"): + + samples_out = samples1.copy() + samples1 = samples1["samples"] + samples2 = samples2["samples"] + + if samples1.shape != samples2.shape: + samples2.permute(0, 3, 1, 2) + samples2 = comfy.utils.common_upscale(samples2, samples1.shape[3], samples1.shape[2], 'bicubic', crop='center') + samples2.permute(0, 2, 3, 1) + + samples_blended = self.blend_mode(samples1, samples2, blend_mode) + samples_blended = samples1 * blend_factor + samples_blended * (1 - blend_factor) + samples_out["samples"] = samples_blended + return (samples_out,) + + def blend_mode(self, img1, img2, mode): + if mode == "normal": + return img2 + else: + raise ValueError(f"Unsupported blend mode: {mode}") + +class LatentCrop: + SEARCH_ALIASES = ["trim latent", "cut latent"] + + @classmethod + def INPUT_TYPES(s): + return {"required": { "samples": ("LATENT",), + "width": ("INT", {"default": 512, "min": 64, "max": MAX_RESOLUTION, "step": 8}), + "height": ("INT", {"default": 512, "min": 64, "max": MAX_RESOLUTION, "step": 8}), + "x": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}), + "y": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}), + }} + RETURN_TYPES = ("LATENT",) + FUNCTION = "crop" + + CATEGORY = "model/latent/transform" + + def crop(self, samples, width, height, x, y): + s = samples.copy() + samples = samples['samples'] + x = x // 8 + y = y // 8 + + #enfonce minimum size of 64 + if x > (samples.shape[3] - 8): + x = samples.shape[3] - 8 + if y > (samples.shape[2] - 8): + y = samples.shape[2] - 8 + + new_height = height // 8 + new_width = width // 8 + to_x = new_width + x + to_y = new_height + y + s['samples'] = samples[:,:,y:to_y, x:to_x] + return (s,) + +class SetLatentNoiseMask: + @classmethod + def INPUT_TYPES(s): + return {"required": { "samples": ("LATENT",), "mask": ("MASK",), }} + RETURN_TYPES = ("LATENT",) + FUNCTION = "set_mask" + + CATEGORY = "model/latent" + + def set_mask(self, samples, mask): + s = samples.copy() + s["noise_mask"] = mask.reshape((-1, 1, mask.shape[-2], mask.shape[-1])) + return (s,) + +def common_ksampler(model, seed, steps, cfg, sampler_name, scheduler, positive, negative, latent, denoise=1.0, disable_noise=False, start_step=None, last_step=None, force_full_denoise=False): + latent_image = latent["samples"] + latent_image = comfy.sample.fix_empty_latent_channels(model, latent_image, latent.get("downscale_ratio_spacial", None), latent.get("downscale_ratio_temporal", None)) + + if disable_noise: + noise = comfy.sample.prepare_empty_noise(latent_image) + else: + batch_inds = latent["batch_index"] if "batch_index" in latent else None + noise = comfy.sample.prepare_noise(latent_image, seed, batch_inds) + + noise_mask = None + if "noise_mask" in latent: + noise_mask = latent["noise_mask"] + + callback = latent_preview.prepare_callback(model, steps) + disable_pbar = not comfy.utils.PROGRESS_BAR_ENABLED + samples = comfy.sample.sample(model, noise, steps, cfg, sampler_name, scheduler, positive, negative, latent_image, + denoise=denoise, disable_noise=disable_noise, start_step=start_step, last_step=last_step, + force_full_denoise=force_full_denoise, noise_mask=noise_mask, callback=callback, disable_pbar=disable_pbar, seed=seed) + out = latent.copy() + out.pop("downscale_ratio_spacial", None) + out.pop("downscale_ratio_temporal", None) + out["samples"] = samples + return (out, ) + +class KSampler: + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "model": ("MODEL", {"tooltip": "The model used for denoising the input latent."}), + "seed": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff, "control_after_generate": True, "tooltip": "The random seed used for creating the noise."}), + "steps": ("INT", {"default": 20, "min": 1, "max": 10000, "tooltip": "The number of steps used in the denoising process."}), + "cfg": ("FLOAT", {"default": 8.0, "min": 0.0, "max": 100.0, "step":0.1, "round": 0.01, "tooltip": "The Classifier-Free Guidance scale balances creativity and adherence to the prompt. Higher values result in images more closely matching the prompt however too high values will negatively impact quality."}), + "sampler_name": (comfy.samplers.KSampler.SAMPLERS, {"tooltip": "The algorithm used when sampling, this can affect the quality, speed, and style of the generated output."}), + "scheduler": (comfy.samplers.KSampler.SCHEDULERS, {"tooltip": "The scheduler controls how noise is gradually removed to form the image."}), + "positive": ("CONDITIONING", {"tooltip": "The conditioning describing the attributes you want to include in the image."}), + "negative": ("CONDITIONING", {"tooltip": "The conditioning describing the attributes you want to exclude from the image."}), + "latent_image": ("LATENT", {"tooltip": "The latent image to denoise."}), + "denoise": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01, "tooltip": "The amount of denoising applied, lower values will maintain the structure of the initial image allowing for image to image sampling."}), + } + } + + RETURN_TYPES = ("LATENT",) + OUTPUT_TOOLTIPS = ("The denoised latent.",) + FUNCTION = "sample" + + CATEGORY = "model/sampling" + DESCRIPTION = "Uses the provided model, positive and negative conditioning to denoise the latent image." + SEARCH_ALIASES = ["sampler", "sample", "generate", "denoise", "diffuse", "txt2img", "img2img"] + + def sample(self, model, seed, steps, cfg, sampler_name, scheduler, positive, negative, latent_image, denoise=1.0): + return common_ksampler(model, seed, steps, cfg, sampler_name, scheduler, positive, negative, latent_image, denoise=denoise) + +class KSamplerAdvanced: + @classmethod + def INPUT_TYPES(s): + return {"required": + {"model": ("MODEL",), + "add_noise": (["enable", "disable"], {"advanced": True}), + "noise_seed": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff, "control_after_generate": True}), + "steps": ("INT", {"default": 20, "min": 1, "max": 10000}), + "cfg": ("FLOAT", {"default": 8.0, "min": 0.0, "max": 100.0, "step":0.1, "round": 0.01}), + "sampler_name": (comfy.samplers.KSampler.SAMPLERS, ), + "scheduler": (comfy.samplers.KSampler.SCHEDULERS, ), + "positive": ("CONDITIONING", ), + "negative": ("CONDITIONING", ), + "latent_image": ("LATENT", ), + "start_at_step": ("INT", {"default": 0, "min": 0, "max": 10000, "advanced": True}), + "end_at_step": ("INT", {"default": 10000, "min": 0, "max": 10000, "advanced": True}), + "return_with_leftover_noise": (["disable", "enable"], {"advanced": True}), + } + } + + RETURN_TYPES = ("LATENT",) + FUNCTION = "sample" + + CATEGORY = "model/sampling" + + def sample(self, model, add_noise, noise_seed, steps, cfg, sampler_name, scheduler, positive, negative, latent_image, start_at_step, end_at_step, return_with_leftover_noise, denoise=1.0): + force_full_denoise = True + if return_with_leftover_noise == "enable": + force_full_denoise = False + disable_noise = False + if add_noise == "disable": + disable_noise = True + return common_ksampler(model, noise_seed, steps, cfg, sampler_name, scheduler, positive, negative, latent_image, denoise=denoise, disable_noise=disable_noise, start_step=start_at_step, last_step=end_at_step, force_full_denoise=force_full_denoise) + +class SaveImage: + def __init__(self): + self.output_dir = folder_paths.get_output_directory() + self.type = "output" + self.prefix_append = "" + self.compress_level = 4 + + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "images": ("IMAGE", {"tooltip": "The images to save."}), + "filename_prefix": ("STRING", { + "default": "ComfyUI", + "tooltip": "The prefix for the file to save. This may include formatting information such as %date:yyyy-MM-dd% or %Empty Latent Image.width% to include values from nodes." + }) + }, + "hidden": { + "prompt": "PROMPT", "extra_pnginfo": "EXTRA_PNGINFO" + }, + } + + RETURN_TYPES = ("IMAGE",) + RETURN_NAMES = ("images",) + FUNCTION = "save_images" + + OUTPUT_NODE = True + + CATEGORY = "image" + ESSENTIALS_CATEGORY = "Basics" + DESCRIPTION = "Saves the input images to your ComfyUI output directory." + SEARCH_ALIASES = ["save", "save image", "export image", "output image", "write image", "download"] + + def save_images(self, images, filename_prefix="ComfyUI", prompt=None, extra_pnginfo=None): + filename_prefix += self.prefix_append + full_output_folder, filename, counter, subfolder, filename_prefix = folder_paths.get_save_image_path(filename_prefix, self.output_dir, images[0].shape[1], images[0].shape[0]) + results = list() + for (batch_number, image) in enumerate(images): + i = 255. * image.cpu().numpy() + img = Image.fromarray(np.clip(i, 0, 255).astype(np.uint8)) + metadata = None + if not args.disable_metadata: + metadata = PngInfo() + if prompt is not None: + metadata.add_text("prompt", json.dumps(prompt)) + if extra_pnginfo is not None: + for x in extra_pnginfo: + metadata.add_text(x, json.dumps(extra_pnginfo[x])) + + filename_with_batch_num = filename.replace("%batch_num%", str(batch_number)) + file = f"{filename_with_batch_num}_{counter:05}_.png" + img.save(os.path.join(full_output_folder, file), pnginfo=metadata, compress_level=self.compress_level) + results.append({ + "filename": file, + "subfolder": subfolder, + "type": self.type + }) + counter += 1 + + return { "ui": { "images": results }, "result" : (images,) } + +class PreviewImage(SaveImage): + def __init__(self): + self.output_dir = folder_paths.get_temp_directory() + self.type = "temp" + self.prefix_append = "_temp_" + ''.join(random.choice("abcdefghijklmnopqrstupvxyz") for x in range(5)) + self.compress_level = 1 + + SEARCH_ALIASES = ["preview", "preview image", "show image", "view image", "display image", "image viewer"] + DESCRIPTION = "Preview the images without saving them to the ComfyUI output directory." + + @classmethod + def INPUT_TYPES(s): + return {"required": + {"images": ("IMAGE", ), }, + "hidden": {"prompt": "PROMPT", "extra_pnginfo": "EXTRA_PNGINFO"}, + } + +class LoadImage: + @classmethod + def INPUT_TYPES(s): + input_dir = folder_paths.get_input_directory() + files = [f for f in os.listdir(input_dir) if os.path.isfile(os.path.join(input_dir, f))] + files = folder_paths.filter_files_content_types(files, ["image"]) + return {"required": + {"image": (sorted(files), {"image_upload": True})}, + } + + CATEGORY = "image" + ESSENTIALS_CATEGORY = "Basics" + SEARCH_ALIASES = ["load image", "open image", "import image", "image input", "upload image", "read image", "image loader"] + + RETURN_TYPES = ("IMAGE", "MASK") + FUNCTION = "load_image" + + def load_image(self, image): + image_path = folder_paths.get_annotated_filepath(image) + + dtype = comfy.model_management.intermediate_dtype() + device = comfy.model_management.intermediate_device() + + components = InputImpl.VideoFromFile(image_path).get_components() + if components.images.shape[0] > 0: + return (components.images.to(device=device, dtype=dtype), (1.0 - components.alpha[..., -1]).to(device=device, dtype=dtype) if components.alpha is not None else torch.zeros((components.images.shape[0], 64, 64), dtype=dtype, device=device)) + + # This code is left here to handle animated webp which pyav does not support loading + img = node_helpers.pillow(Image.open, image_path) + + output_images = [] + output_masks = [] + w, h = None, None + + for i in ImageSequence.Iterator(img): + i = node_helpers.pillow(ImageOps.exif_transpose, i) + + image = i.convert("RGB") + + if len(output_images) == 0: + w = image.size[0] + h = image.size[1] + + if image.size[0] != w or image.size[1] != h: + continue + + image = np.array(image).astype(np.float32) / 255.0 + image = torch.from_numpy(image)[None,] + if 'A' in i.getbands(): + mask = np.array(i.getchannel('A')).astype(np.float32) / 255.0 + mask = 1. - torch.from_numpy(mask) + else: + mask = torch.zeros((64, 64), dtype=torch.float32, device="cpu") + output_images.append(image.to(dtype=dtype)) + output_masks.append(mask.unsqueeze(0).to(dtype=dtype)) + + output_image = torch.cat(output_images, dim=0) + output_mask = torch.cat(output_masks, dim=0) + + return (output_image.to(device=device, dtype=dtype), output_mask.to(device=device, dtype=dtype)) + + @classmethod + def IS_CHANGED(s, image): + image_path = folder_paths.get_annotated_filepath(image) + m = hashlib.sha256() + with open(image_path, 'rb') as f: + m.update(f.read()) + return m.digest().hex() + + @classmethod + def VALIDATE_INPUTS(s, image): + if not folder_paths.exists_annotated_filepath(image): + return "Invalid image file: {}".format(image) + + return True + + +class LoadImageMask(LoadImage): + ESSENTIALS_CATEGORY = "Image Tools" + SEARCH_ALIASES = ["import mask", "alpha mask", "channel mask"] + + _color_channels = ["alpha", "red", "green", "blue"] + + @classmethod + def INPUT_TYPES(s): + types = super().INPUT_TYPES() + return { + "required": { + **types["required"], + "channel": (s._color_channels, ) + } + } + + CATEGORY = "image" + RETURN_TYPES = ("MASK",) + FUNCTION = "load_image_mask" + + def load_image_mask(self, image, channel): + image_tensor, mask_tensor = super().load_image(image) + c = channel[0].upper() + + if c == 'A': + return (mask_tensor,) + + channel_idx = {'R': 0, 'G': 1, 'B': 2}.get(c, 0) + + if channel_idx < image_tensor.shape[-1]: + return (image_tensor[..., channel_idx].clone(),) + else: + empty_mask = torch.zeros( + image_tensor.shape[:-1], + dtype=image_tensor.dtype, + device=image_tensor.device + ) + return (empty_mask,) + + @classmethod + def IS_CHANGED(s, image, channel): + return super().IS_CHANGED(image) + + +class LoadImageOutput(LoadImage): + SEARCH_ALIASES = ["output image", "previous generation"] + + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "image": ("COMBO", { + "image_upload": True, + "image_folder": "output", + "remote": { + "route": "/internal/files/output", + "refresh_button": True, + "control_after_refresh": "first", + }, + }), + } + } + + DESCRIPTION = "Load an image from the output folder. When the refresh button is clicked, the node will update the image list and automatically select the first image, allowing for easy iteration." + EXPERIMENTAL = True + FUNCTION = "load_image" + + +class ImageScale: + upscale_methods = ["nearest-exact", "bilinear", "area", "bicubic", "lanczos"] + crop_methods = ["disabled", "center"] + + @classmethod + def INPUT_TYPES(s): + return {"required": { "image": ("IMAGE",), "upscale_method": (s.upscale_methods,), + "width": ("INT", {"default": 512, "min": 0, "max": MAX_RESOLUTION, "step": 1}), + "height": ("INT", {"default": 512, "min": 0, "max": MAX_RESOLUTION, "step": 1}), + "crop": (s.crop_methods,)}} + RETURN_TYPES = ("IMAGE",) + FUNCTION = "upscale" + + CATEGORY = "image/upscaling" + ESSENTIALS_CATEGORY = "Image Tools" + SEARCH_ALIASES = ["resize", "resize image", "scale image", "image resize", "zoom", "zoom in", "change size"] + + def upscale(self, image, upscale_method, width, height, crop): + if width == 0 and height == 0: + s = image + else: + samples = image.movedim(-1,1) + + if width == 0: + width = max(1, round(samples.shape[3] * height / samples.shape[2])) + elif height == 0: + height = max(1, round(samples.shape[2] * width / samples.shape[3])) + + s = comfy.utils.common_upscale(samples, width, height, upscale_method, crop) + s = s.movedim(1,-1) + return (s,) + +class ImageScaleBy: + ESSENTIALS_CATEGORY = "Image Tools" + upscale_methods = ["nearest-exact", "bilinear", "area", "bicubic", "lanczos"] + + @classmethod + def INPUT_TYPES(s): + return {"required": { "image": ("IMAGE",), "upscale_method": (s.upscale_methods,), + "scale_by": ("FLOAT", {"default": 1.0, "min": 0.01, "max": 8.0, "step": 0.01}),}} + RETURN_TYPES = ("IMAGE",) + FUNCTION = "upscale" + + CATEGORY = "image/upscaling" + + def upscale(self, image, upscale_method, scale_by): + samples = image.movedim(-1,1) + width = round(samples.shape[3] * scale_by) + height = round(samples.shape[2] * scale_by) + s = comfy.utils.common_upscale(samples, width, height, upscale_method, "disabled") + s = s.movedim(1,-1) + return (s,) + +class ImageInvert: + SEARCH_ALIASES = ["reverse colors"] + ESSENTIALS_CATEGORY = "Image Tools" + + @classmethod + def INPUT_TYPES(s): + return {"required": { "image": ("IMAGE",)}} + + RETURN_TYPES = ("IMAGE",) + FUNCTION = "invert" + + CATEGORY = "image/color" + + def invert(self, image): + s = 1.0 - image + return (s,) + +class ImageBatch: + SEARCH_ALIASES = ["combine images", "merge images", "stack images"] + + @classmethod + def INPUT_TYPES(s): + return {"required": { "image1": ("IMAGE",), "image2": ("IMAGE",)}} + + RETURN_TYPES = ("IMAGE",) + FUNCTION = "batch" + + CATEGORY = "image/batch" + DEPRECATED = True + + def batch(self, image1, image2): + if image1.shape[-1] != image2.shape[-1]: + if image1.shape[-1] > image2.shape[-1]: + image2 = torch.nn.functional.pad(image2, (0,1), mode='constant', value=1.0) + else: + image1 = torch.nn.functional.pad(image1, (0,1), mode='constant', value=1.0) + if image1.shape[1:] != image2.shape[1:]: + image2 = comfy.utils.common_upscale(image2.movedim(-1,1), image1.shape[2], image1.shape[1], "bilinear", "center").movedim(1,-1) + s = torch.cat((image1, image2), dim=0) + return (s,) + +class EmptyImage: + def __init__(self, device="cpu"): + self.device = device + + @classmethod + def INPUT_TYPES(s): + return {"required": { "width": ("INT", {"default": 512, "min": 1, "max": MAX_RESOLUTION, "step": 1}), + "height": ("INT", {"default": 512, "min": 1, "max": MAX_RESOLUTION, "step": 1}), + "batch_size": ("INT", {"default": 1, "min": 1, "max": 4096}), + "color": ("INT", {"default": 0, "min": 0, "max": 0xFFFFFF, "step": 1, "display": "color"}), + }} + RETURN_TYPES = ("IMAGE",) + FUNCTION = "generate" + + CATEGORY = "image" + + def generate(self, width, height, batch_size=1, color=0): + dtype = comfy.model_management.intermediate_dtype() + device = comfy.model_management.intermediate_device() + r = torch.full([batch_size, height, width, 1], ((color >> 16) & 0xFF) / 0xFF, device=device, dtype=dtype) + g = torch.full([batch_size, height, width, 1], ((color >> 8) & 0xFF) / 0xFF, device=device, dtype=dtype) + b = torch.full([batch_size, height, width, 1], ((color) & 0xFF) / 0xFF, device=device, dtype=dtype) + return (torch.cat((r, g, b), dim=-1), ) + +class ImagePadForOutpaint: + SEARCH_ALIASES = ["extend canvas", "expand image"] + + @classmethod + def INPUT_TYPES(s): + return { + "required": { + "image": ("IMAGE",), + "left": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}), + "top": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}), + "right": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}), + "bottom": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}), + "feathering": ("INT", {"default": 40, "min": 0, "max": MAX_RESOLUTION, "step": 1, "advanced": True}), + } + } + + RETURN_TYPES = ("IMAGE", "MASK") + FUNCTION = "expand_image" + + CATEGORY = "image/transform" + + def expand_image(self, image, left, top, right, bottom, feathering): + d1, d2, d3, d4 = image.size() + + new_image = torch.ones( + (d1, d2 + top + bottom, d3 + left + right, d4), + dtype=torch.float32, + ) * 0.5 + + new_image[:, top:top + d2, left:left + d3, :] = image + + mask = torch.ones( + (d2 + top + bottom, d3 + left + right), + dtype=torch.float32, + ) + + t = torch.zeros( + (d2, d3), + dtype=torch.float32 + ) + + if feathering > 0 and feathering * 2 < d2 and feathering * 2 < d3: + + for i in range(d2): + for j in range(d3): + dt = i if top != 0 else d2 + db = d2 - i if bottom != 0 else d2 + + dl = j if left != 0 else d3 + dr = d3 - j if right != 0 else d3 + + d = min(dt, db, dl, dr) + + if d >= feathering: + continue + + v = (feathering - d) / feathering + + t[i, j] = v * v + + mask[top:top + d2, left:left + d3] = t + + return (new_image, mask.unsqueeze(0)) + + +NODE_CLASS_MAPPINGS = { + "KSampler": KSampler, + "CheckpointLoaderSimple": CheckpointLoaderSimple, + "CLIPTextEncode": CLIPTextEncode, + "CLIPSetLastLayer": CLIPSetLastLayer, + "VAEDecode": VAEDecode, + "VAEEncode": VAEEncode, + "VAEEncodeForInpaint": VAEEncodeForInpaint, + "VAELoader": VAELoader, + "EmptyLatentImage": EmptyLatentImage, + "LatentUpscale": LatentUpscale, + "LatentUpscaleBy": LatentUpscaleBy, + "LatentFromBatch": LatentFromBatch, + "RepeatLatentBatch": RepeatLatentBatch, + "SaveImage": SaveImage, + "PreviewImage": PreviewImage, + "LoadImage": LoadImage, + "LoadImageMask": LoadImageMask, + "LoadImageOutput": LoadImageOutput, + "ImageScale": ImageScale, + "ImageScaleBy": ImageScaleBy, + "ImageInvert": ImageInvert, + "ImageBatch": ImageBatch, + "ImagePadForOutpaint": ImagePadForOutpaint, + "EmptyImage": EmptyImage, + "ConditioningAverage": ConditioningAverage, + "ConditioningCombine": ConditioningCombine, + "ConditioningConcat": ConditioningConcat, + "ConditioningMultiply": ConditioningMultiply, + "ConditioningSetArea": ConditioningSetArea, + "ConditioningSetAreaPercentage": ConditioningSetAreaPercentage, + "ConditioningSetAreaStrength": ConditioningSetAreaStrength, + "ConditioningSetMask": ConditioningSetMask, + "KSamplerAdvanced": KSamplerAdvanced, + "SetLatentNoiseMask": SetLatentNoiseMask, + "LatentComposite": LatentComposite, + "LatentBlend": LatentBlend, + "LatentRotate": LatentRotate, + "LatentFlip": LatentFlip, + "LatentCrop": LatentCrop, + "LoraLoader": LoraLoader, + "CLIPLoader": CLIPLoader, + "UNETLoader": UNETLoader, + "DualCLIPLoader": DualCLIPLoader, + "CLIPVisionEncode": CLIPVisionEncode, + "StyleModelApply": StyleModelApply, + "unCLIPConditioning": unCLIPConditioning, + "ControlNetApply": ControlNetApply, + "ControlNetApplyAdvanced": ControlNetApplyAdvanced, + "ControlNetLoader": ControlNetLoader, + "DiffControlNetLoader": DiffControlNetLoader, + "StyleModelLoader": StyleModelLoader, + "CLIPVisionLoader": CLIPVisionLoader, + "VAEDecodeTiled": VAEDecodeTiled, + "VAEEncodeTiled": VAEEncodeTiled, + "unCLIPCheckpointLoader": unCLIPCheckpointLoader, + "GLIGENLoader": GLIGENLoader, + "GLIGENTextBoxApply": GLIGENTextBoxApply, + "InpaintModelConditioning": InpaintModelConditioning, + + "CheckpointLoader": CheckpointLoader, + "DiffusersLoader": DiffusersLoader, + + "LoadLatent": LoadLatent, + "SaveLatent": SaveLatent, + + "ConditioningZeroOut": ConditioningZeroOut, + "ConditioningSetTimestepRange": ConditioningSetTimestepRange, + "LoraLoaderModelOnly": LoraLoaderModelOnly, +} + +NODE_DISPLAY_NAME_MAPPINGS = { + # Sampling + "KSampler": "KSampler", + "KSamplerAdvanced": "KSampler (Advanced)", + # Loaders + "CheckpointLoader": "Load Checkpoint With Config (DEPRECATED)", + "CheckpointLoaderSimple": "Load Checkpoint", + "VAELoader": "Load VAE", + "LoraLoader": "Load LoRA (Model and CLIP)", + "LoraLoaderModelOnly": "Load LoRA", + "CLIPLoader": "Load CLIP", + "DualCLIPLoader": "Load CLIP (Dual)", + "ControlNetLoader": "Load ControlNet Model", + "DiffControlNetLoader": "Load ControlNet Model (diff)", + "StyleModelLoader": "Load Style Model", + "CLIPVisionLoader": "Load CLIP Vision", + "UNETLoader": "Load Diffusion Model", + "unCLIPCheckpointLoader": "Load unCLIP Checkpoint", + "GLIGENLoader": "Load GLIGEN Model", + "DiffusersLoader": "Load Diffusers Model (DEPRECATED)", + # Conditioning + "CLIPVisionEncode": "CLIP Vision Encode", + "StyleModelApply": "Apply Style Model", + "CLIPTextEncode": "CLIP Text Encode (Prompt)", + "CLIPSetLastLayer": "CLIP Set Last Layer", + "ConditioningCombine": "Conditioning (Combine)", + "ConditioningAverage ": "Conditioning (Average)", + "ConditioningAverage": "Conditioning (Average)", + "ConditioningConcat": "Conditioning (Concat)", + "ConditioningMultiply": "Conditioning (Multiply)", + "ConditioningSetArea": "Conditioning (Set Area)", + "ConditioningSetAreaPercentage": "Conditioning (Set Area with Percentage)", + "ConditioningSetAreaStrength": "Conditioning (Set Area Strength)", + "ConditioningSetMask": "Conditioning (Set Mask)", + "ControlNetApply": "Apply ControlNet (DEPRECATED)", + "ControlNetApplyAdvanced": "Apply ControlNet", + "GLIGENTextBoxApply": "Apply GLIGEN Text Box", + "ConditioningZeroOut": "Conditioning Zero Out", + # Latent + "LoadLatent": "Load Latent", + "SaveLatent": "Save Latent", + "VAEEncodeForInpaint": "VAE Encode (for Inpainting)", + "SetLatentNoiseMask": "Set Latent Noise Mask", + "VAEDecode": "VAE Decode", + "VAEEncode": "VAE Encode", + "LatentRotate": "Rotate Latent", + "LatentFlip": "Flip Latent", + "LatentCrop": "Crop Latent", + "EmptyLatentImage": "Empty Latent Image", + "LatentUpscale": "Upscale Latent", + "LatentUpscaleBy": "Upscale Latent By", + "LatentComposite": "Latent Composite", + "LatentBlend": "Latent Blend", + "LatentFromBatch" : "Get Latent From Batch", + "RepeatLatentBatch": "Repeat Latent Batch", + # Image + "EmptyImage": "Empty Image", + "SaveImage": "Save Image", + "PreviewImage": "Preview Image", + "LoadImage": "Load Image", + "LoadImageMask": "Load Image (as Mask)", + "LoadImageOutput": "Load Image (from Outputs)", + "ImageScale": "Upscale Image", + "ImageScaleBy": "Upscale Image By", + "ImageInvert": "Invert Image Colors", + "ImagePadForOutpaint": "Pad Image for Outpainting", + "ImageBatch": "Batch Images (DEPRECATED)", + "ImageCrop": "Crop Image", + "ImageStitch": "Stitch Images", + "ImageBlend": "Blend Images", + "ImageBlur": "Blur Image", + "ImageQuantize": "Quantize Image", + "ImageSharpen": "Sharpen Image", + "ImageScaleToTotalPixels": "Scale Image to Total Pixels", + "GetImageSize": "Get Image Size", + "VAEDecodeTiled": "VAE Decode (Tiled)", + "VAEEncodeTiled": "VAE Encode (Tiled)", +} + +EXTENSION_WEB_DIRS = {} + +# Dictionary of successfully loaded module names and associated directories. +LOADED_MODULE_DIRS = {} + + +def get_module_name(module_path: str) -> str: + """ + Returns the module name based on the given module path. + Examples: + get_module_name("C:/Users/username/ComfyUI/custom_nodes/my_custom_node.py") -> "my_custom_node" + get_module_name("C:/Users/username/ComfyUI/custom_nodes/my_custom_node") -> "my_custom_node" + get_module_name("C:/Users/username/ComfyUI/custom_nodes/my_custom_node/") -> "my_custom_node" + get_module_name("C:/Users/username/ComfyUI/custom_nodes/my_custom_node/__init__.py") -> "my_custom_node" + get_module_name("C:/Users/username/ComfyUI/custom_nodes/my_custom_node/__init__") -> "my_custom_node" + get_module_name("C:/Users/username/ComfyUI/custom_nodes/my_custom_node/__init__/") -> "my_custom_node" + get_module_name("C:/Users/username/ComfyUI/custom_nodes/my_custom_node.disabled") -> "custom_nodes + Args: + module_path (str): The path of the module. + Returns: + str: The module name. + """ + base_path = os.path.basename(module_path) + if os.path.isfile(module_path): + base_path = os.path.splitext(base_path)[0] + return base_path + + +async def load_custom_node(module_path: str, ignore=set(), module_parent="custom_nodes") -> bool: + module_name = get_module_name(module_path) + if os.path.isfile(module_path): + sp = os.path.splitext(module_path) + module_name = sp[0] + sys_module_name = module_name + elif os.path.isdir(module_path): + sys_module_name = module_path.replace(".", "_x_") + + try: + logging.debug("Trying to load custom node {}".format(module_path)) + if os.path.isfile(module_path): + module_spec = importlib.util.spec_from_file_location(sys_module_name, module_path) + module_dir = os.path.split(module_path)[0] + else: + module_spec = importlib.util.spec_from_file_location(sys_module_name, os.path.join(module_path, "__init__.py")) + module_dir = module_path + + module = importlib.util.module_from_spec(module_spec) + sys.modules[sys_module_name] = module + module_spec.loader.exec_module(module) + + LOADED_MODULE_DIRS[module_name] = os.path.abspath(module_dir) + + try: + from comfy_config import config_parser + + project_config = config_parser.extract_node_configuration(module_path) + + web_dir_name = project_config.tool_comfy.web + + if web_dir_name: + web_dir_path = os.path.join(module_path, web_dir_name) + + if os.path.isdir(web_dir_path): + project_name = project_config.project.name + + EXTENSION_WEB_DIRS[project_name] = web_dir_path + + logging.info("Automatically register web folder {} for {}".format(web_dir_name, project_name)) + except Exception as e: + logging.warning(f"Unable to parse pyproject.toml due to lack dependency pydantic-settings, please run 'pip install -r requirements.txt': {e}") + + if hasattr(module, "WEB_DIRECTORY") and getattr(module, "WEB_DIRECTORY") is not None: + web_dir = os.path.abspath(os.path.join(module_dir, getattr(module, "WEB_DIRECTORY"))) + if os.path.isdir(web_dir): + EXTENSION_WEB_DIRS[module_name] = web_dir + + # V1 node definition + if hasattr(module, "NODE_CLASS_MAPPINGS") and getattr(module, "NODE_CLASS_MAPPINGS") is not None: + for name, node_cls in module.NODE_CLASS_MAPPINGS.items(): + if name not in ignore: + NODE_CLASS_MAPPINGS[name] = node_cls + node_cls.RELATIVE_PYTHON_MODULE = "{}.{}".format(module_parent, get_module_name(module_path)) + if hasattr(module, "NODE_DISPLAY_NAME_MAPPINGS") and getattr(module, "NODE_DISPLAY_NAME_MAPPINGS") is not None: + NODE_DISPLAY_NAME_MAPPINGS.update(module.NODE_DISPLAY_NAME_MAPPINGS) + return True + # V3 Extension Definition + elif hasattr(module, "comfy_entrypoint"): + entrypoint = getattr(module, "comfy_entrypoint") + if not callable(entrypoint): + logging.warning(f"comfy_entrypoint in {module_path} is not callable, skipping.") + return False + try: + if inspect.iscoroutinefunction(entrypoint): + extension = await entrypoint() + else: + extension = entrypoint() + if not isinstance(extension, ComfyExtension): + logging.warning(f"comfy_entrypoint in {module_path} did not return a ComfyExtension, skipping.") + return False + await extension.on_load() + node_list = await extension.get_node_list() + if not isinstance(node_list, list): + logging.warning(f"comfy_entrypoint in {module_path} did not return a list of nodes, skipping.") + return False + for node_cls in node_list: + node_cls: io.ComfyNode + schema = node_cls.GET_SCHEMA() + if schema.node_id not in ignore: + NODE_CLASS_MAPPINGS[schema.node_id] = node_cls + node_cls.RELATIVE_PYTHON_MODULE = "{}.{}".format(module_parent, get_module_name(module_path)) + if schema.display_name is not None: + NODE_DISPLAY_NAME_MAPPINGS[schema.node_id] = schema.display_name + return True + except Exception as e: + logging.warning(f"Error while calling comfy_entrypoint in {module_path}: {e}") + return False + else: + logging.warning(f"Skip {module_path} module for custom nodes due to the lack of NODE_CLASS_MAPPINGS or comfy_entrypoint (need one).") + return False + except Exception as e: + logging.warning(traceback.format_exc()) + logging.warning(f"Cannot import {module_path} module for custom nodes: {e}") + return False + +async def init_external_custom_nodes(): + """ + Initializes the external custom nodes. + + This function loads custom nodes from the specified folder paths and imports them into the application. + It measures the import times for each custom node and logs the results. + + Returns: + None + """ + # TODO: remove at some point when custom nodes don't break. + sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(__file__)), "comfy")) + + base_node_names = set(NODE_CLASS_MAPPINGS.keys()) + node_paths = folder_paths.get_folder_paths("custom_nodes") + node_import_times = [] + for custom_node_path in node_paths: + possible_modules = os.listdir(os.path.realpath(custom_node_path)) + if "__pycache__" in possible_modules: + possible_modules.remove("__pycache__") + + for possible_module in possible_modules: + module_path = os.path.join(custom_node_path, possible_module) + if os.path.isfile(module_path) and os.path.splitext(module_path)[1] != ".py": + continue + if module_path.endswith(".disabled"): + continue + if args.disable_all_custom_nodes and possible_module not in args.whitelist_custom_nodes: + logging.info(f"Skipping {possible_module} due to disable_all_custom_nodes and whitelist_custom_nodes") + continue + + if args.enable_manager: + if comfyui_manager.should_be_disabled(module_path): + logging.info(f"Blocked by policy: {module_path}") + continue + + time_before = time.perf_counter() + success = await load_custom_node(module_path, base_node_names, module_parent="custom_nodes") + node_import_times.append((time.perf_counter() - time_before, module_path, success)) + + if len(node_import_times) > 0: + logging.info("\nImport times for custom nodes:") + for n in sorted(node_import_times): + if n[2]: + import_message = "" + else: + import_message = " (IMPORT FAILED)" + logging.info("{:6.1f} seconds{}: {}".format(n[0], import_message, n[1])) + logging.info("") + +async def init_builtin_extra_nodes(): + """ + Initializes the built-in extra nodes in ComfyUI. + + This function loads the extra node files located in the "comfy_extras" directory and imports them into ComfyUI. + If any of the extra node files fail to import, a warning message is logged. + + Returns: + None + """ + extras_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "comfy_extras") + extras_files = [ + "nodes_latent.py", + "nodes_hypernetwork.py", + "nodes_upscale_model.py", + "nodes_post_processing.py", + "nodes_mask.py", + "nodes_compositing.py", + "nodes_rebatch.py", + "nodes_model_merging.py", + "nodes_tomesd.py", + "nodes_clip_sdxl.py", + "nodes_canny.py", + "nodes_freelunch.py", + "nodes_custom_sampler.py", + "nodes_hypertile.py", + "nodes_model_advanced.py", + "nodes_model_downscale.py", + "nodes_images.py", + "nodes_video_model.py", + "nodes_ideogram4.py", + "nodes_bounding_boxes.py", + "nodes_json_prompt.py", + "nodes_train.py", + "nodes_dataset.py", + "nodes_sag.py", + "nodes_perpneg.py", + "nodes_stable3d.py", + "nodes_sdupscale.py", + "nodes_photomaker.py", + "nodes_pixart.py", + "nodes_cond.py", + "nodes_morphology.py", + "nodes_stable_cascade.py", + "nodes_differential_diffusion.py", + "nodes_ip2p.py", + "nodes_model_merging_model_specific.py", + "nodes_pag.py", + "nodes_align_your_steps.py", + "nodes_attention_multiply.py", + "nodes_advanced_samplers.py", + "nodes_webcam.py", + "nodes_audio.py", + "nodes_sd3.py", + "nodes_gits.py", + "nodes_controlnet.py", + "nodes_hunyuan.py", + "nodes_eps.py", + "nodes_flux.py", + "nodes_lora_extract.py", + "nodes_torch_compile.py", + "nodes_mochi.py", + "nodes_slg.py", + "nodes_mahiro.py", + "nodes_lt_upsampler.py", + "nodes_lt_audio.py", + "nodes_minimax_music.py", + "nodes_minimax_h3.py", + "nodes_lt.py", + "nodes_hooks.py", + "nodes_multigpu.py", + "nodes_load_3d.py", + "nodes_cosmos.py", + "nodes_video.py", + "nodes_lumina2.py", + "nodes_wan.py", + "nodes_bernini.py", + "nodes_lotus.py", + "nodes_hunyuan3d.py", + "nodes_primitive.py", + "nodes_cfg.py", + "nodes_optimalsteps.py", + "nodes_hidream.py", + "nodes_fresca.py", + "nodes_apg.py", + "nodes_preview_any.py", + "nodes_ace.py", + "nodes_string.py", + "nodes_camera_trajectory.py", + "nodes_edit_model.py", + "nodes_tcfg.py", + "nodes_seedvr.py", + "nodes_context_windows.py", + "nodes_qwen.py", + "nodes_mage.py", + "nodes_joyimage.py", + "nodes_boogu.py", + "nodes_chroma_radiance.py", + "nodes_pid.py", + "nodes_model_patch.py", + "nodes_easycache.py", + "nodes_audio_encoder.py", + "nodes_rope.py", + "nodes_logic.py", + "nodes_resolution.py", + "nodes_nop.py", + "nodes_kandinsky5.py", + "nodes_wanmove.py", + "nodes_ar_video.py", + "nodes_image_compare.py", + "nodes_zimage.py", + "nodes_glsl.py", + "nodes_lora_debug.py", + "nodes_textgen.py", + "nodes_text_overlay.py", + "nodes_color.py", + "nodes_toolkit.py", + "nodes_replacements.py", + "nodes_nag.py", + "nodes_sdpose.py", + "nodes_math.py", + "nodes_number_convert.py", + "nodes_painter.py", + "nodes_compositor.py", + "nodes_curve.py", + "nodes_bg_removal.py", + "nodes_rtdetr.py", + "nodes_frame_interpolation.py", + "nodes_sam3.py", + "nodes_scail.py", + "nodes_void.py", + "nodes_wandancer.py", + "nodes_hidream_o1.py", + "nodes_save_3d.py", + "nodes_moge.py", + "nodes_mediapipe.py", + "nodes_gaussian_splat.py", + "nodes_triposplat.py", + "nodes_depth_anything_3.py", + "nodes_seed.py", + "nodes_text.py", + ] + + import_failed = [] + for node_file in extras_files: + if not await load_custom_node(os.path.join(extras_dir, node_file), module_parent="comfy_extras"): + import_failed.append(node_file) + + return import_failed + + +async def init_builtin_api_nodes(): + api_nodes_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "comfy_api_nodes") + api_nodes_files = sorted(glob.glob(os.path.join(api_nodes_dir, "nodes_*.py"))) + + import_failed = [] + for node_file in api_nodes_files: + if not await load_custom_node(node_file, module_parent="comfy_api_nodes"): + import_failed.append(os.path.basename(node_file)) + + return import_failed + +async def init_public_apis(): + register_versions([ + ComfyAPIWithVersion( + version=getattr(v, "VERSION"), + api_class=v + ) for v in supported_versions + ]) + +async def init_extra_nodes(init_custom_nodes=True, init_api_nodes=True): + await init_public_apis() + + import_failed = await init_builtin_extra_nodes() + + import_failed_api = [] + if init_api_nodes: + import_failed_api = await init_builtin_api_nodes() + + if init_custom_nodes: + await init_external_custom_nodes() + else: + logging.info("Skipping loading of custom nodes") + + if len(import_failed_api) > 0: + logging.warning("WARNING: some comfy_api_nodes/ nodes did not import correctly. This may be because they are missing some dependencies.\n") + for node in import_failed_api: + logging.warning("IMPORT FAILED: {}".format(node)) + logging.warning("\nThis issue might be caused by new missing dependencies added the last time you updated ComfyUI.") + if args.windows_standalone_build: + logging.warning("Please run the update script: update/update_comfyui.bat") + else: + logging.warning("Please do a: pip install -r requirements.txt") + logging.warning("") + + if len(import_failed) > 0: + logging.warning("WARNING: some comfy_extras/ nodes did not import correctly. This may be because they are missing some dependencies.\n") + for node in import_failed: + logging.warning("IMPORT FAILED: {}".format(node)) + logging.warning("\nThis issue might be caused by new missing dependencies added the last time you updated ComfyUI.") + if args.windows_standalone_build: + logging.warning("Please run the update script: update/update_comfyui.bat") + else: + logging.warning("Please do a: pip install -r requirements.txt") + logging.warning("") + + return import_failed diff --git a/docs/hel-892/h3-core-reference/core__server.py b/docs/hel-892/h3-core-reference/core__server.py new file mode 100644 index 00000000..c9ffcaa0 --- /dev/null +++ b/docs/hel-892/h3-core-reference/core__server.py @@ -0,0 +1,1479 @@ +import errno +import os +import sys +import asyncio +import traceback +import time + +import nodes +import folder_paths +import execution +from comfy_execution.jobs import ( + JobStatus, + get_job, + get_all_jobs, + validate_job_id, + cancel_job, + CANCEL_PENDING, + CANCEL_RUNNING, +) +import uuid +import urllib +import json +import glob +import struct +import ssl +import socket +import ipaddress +from PIL import Image, ImageOps +from PIL.PngImagePlugin import PngInfo +from io import BytesIO + +import aiohttp +from aiohttp import web +import logging + +import mimetypes +from comfy.cli_args import args +from comfy.deploy_environment import get_deploy_environment +import comfy.utils +import comfy.model_management +from comfy_api import feature_flags +from comfy.comfy_api_env import get_environment_overrides +import node_helpers +from comfyui_version import __version__ +from app.frontend_management import FrontendManager, parse_version +from comfy_api.internal import _ComfyNodeInternal +from app.assets.seeder import asset_seeder +from app.assets.api.routes import register_assets_routes +from app.assets.services.ingest import register_file_in_place +from app.assets.services.path_utils import get_known_subfolder_tags +from app.assets.services.asset_management import resolve_hash_to_path + +from app.user_manager import UserManager +from app.model_manager import ModelFileManager +from app.custom_node_manager import CustomNodeManager +from app.subgraph_manager import SubgraphManager +from app.node_replace_manager import NodeReplaceManager +from typing import Optional, Union +from api_server.routes.internal.internal_routes import InternalRoutes +from protocol import BinaryEventTypes + +# Import cache control middleware +from middleware.cache_middleware import cache_control + +if args.enable_manager: + import comfyui_manager + + +def _remove_sensitive_from_queue(queue: list) -> list: + """Remove sensitive data (index 5) from queue item tuples.""" + return [item[:5] for item in queue] + + +async def send_socket_catch_exception(function, message): + try: + await function(message) + except (aiohttp.ClientError, aiohttp.ClientPayloadError, ConnectionResetError, BrokenPipeError, ConnectionError) as err: + logging.warning("send error: {}".format(err)) + +# Track deprecated paths that have been warned about to only warn once per file +_deprecated_paths_warned = set() + +@web.middleware +async def deprecation_warning(request: web.Request, handler): + """Middleware to warn about deprecated frontend API paths""" + path = request.path + + if path.startswith("/scripts/ui") or path.startswith("/extensions/core/"): + # Only warn once per unique file path + if path not in _deprecated_paths_warned: + _deprecated_paths_warned.add(path) + logging.warning( + f"[DEPRECATION WARNING] Detected import of deprecated legacy API: {path}. " + f"This is likely caused by a custom node extension using outdated APIs. " + f"Please update your extensions or contact the extension author for an updated version." + ) + + response: web.Response = await handler(request) + return response + + +@web.middleware +async def compress_body(request: web.Request, handler): + accept_encoding = request.headers.get("Accept-Encoding", "") + response: web.Response = await handler(request) + if not isinstance(response, web.Response): + return response + if response.content_type not in ["application/json", "text/plain"]: + return response + if response.body and "gzip" in accept_encoding: + response.enable_compression() + return response + + +def create_cors_middleware(allowed_origin: str): + @web.middleware + async def cors_middleware(request: web.Request, handler): + if request.method == "OPTIONS": + # Pre-flight request. Reply successfully: + response = web.Response() + else: + response = await handler(request) + + response.headers['Access-Control-Allow-Origin'] = allowed_origin + response.headers['Access-Control-Allow-Methods'] = 'POST, GET, DELETE, PUT, OPTIONS, PATCH' + response.headers['Access-Control-Allow-Headers'] = 'Content-Type, Authorization' + response.headers['Access-Control-Allow-Credentials'] = 'true' + return response + + return cors_middleware + + +def is_loopback(host): + if host is None: + return False + try: + if ipaddress.ip_address(host).is_loopback: + return True + else: + return False + except: + pass + + loopback = False + for family in (socket.AF_INET, socket.AF_INET6): + try: + r = socket.getaddrinfo(host, None, family, socket.SOCK_STREAM) + for family, _, _, _, sockaddr in r: + if not ipaddress.ip_address(sockaddr[0]).is_loopback: + return loopback + else: + loopback = True + except socket.gaierror: + pass + + return loopback + + +def create_origin_only_middleware(): + @web.middleware + async def origin_only_middleware(request: web.Request, handler): + if 'Sec-Fetch-Site' in request.headers: + sec_fetch_site = request.headers['Sec-Fetch-Site'] + if sec_fetch_site == 'cross-site': + return web.Response(status=403) + #this code is used to prevent the case where a random website can queue comfy workflows by making a POST to 127.0.0.1 which browsers don't prevent for some dumb reason. + #in that case the Host and Origin hostnames won't match + #I know the proper fix would be to add a cookie but this should take care of the problem in the meantime + if 'Host' in request.headers and 'Origin' in request.headers: + host = request.headers['Host'] + origin = request.headers['Origin'] + host_domain = host.lower() + parsed = urllib.parse.urlparse(origin) + origin_domain = parsed.netloc.lower() + host_domain_parsed = urllib.parse.urlsplit('//' + host_domain) + + #limit the check to when the host domain is localhost, this makes it slightly less safe but should still prevent the exploit + loopback = is_loopback(host_domain_parsed.hostname) + + if parsed.port is None: #if origin doesn't have a port strip it from the host to handle weird browsers, same for host + host_domain = host_domain_parsed.hostname + if host_domain_parsed.port is None: + origin_domain = parsed.hostname + + if loopback and host_domain is not None and origin_domain is not None and len(host_domain) > 0 and len(origin_domain) > 0: + if host_domain != origin_domain: + logging.warning("WARNING: request with non matching host and origin {} != {}, returning 403".format(host_domain, origin_domain)) + return web.Response(status=403) + + if request.method == "OPTIONS": + response = web.Response() + else: + response = await handler(request) + + return response + + return origin_only_middleware + + +def create_block_external_middleware(): + @web.middleware + async def block_external_middleware(request: web.Request, handler): + if request.method == "OPTIONS": + # Pre-flight request. Reply successfully: + response = web.Response() + else: + response = await handler(request) + + response.headers['Content-Security-Policy'] = "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval' blob:; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self'; connect-src 'self' data:; frame-src 'self'; object-src 'self';" + return response + + return block_external_middleware + + +class PromptServer(): + def __init__(self, loop): + PromptServer.instance = self + + self.user_manager = UserManager() + self.model_file_manager = ModelFileManager() + self.custom_node_manager = CustomNodeManager() + self.subgraph_manager = SubgraphManager() + self.node_replace_manager = NodeReplaceManager() + self.internal_routes = InternalRoutes(self) + self.supports = ["custom_nodes_from_web"] + self.prompt_queue = execution.PromptQueue(self) + self.loop = loop + self.messages = asyncio.Queue() + self.client_session:Optional[aiohttp.ClientSession] = None + self.number = 0 + + middlewares = [cache_control, deprecation_warning] + if args.enable_compress_response_body: + middlewares.append(compress_body) + + if args.enable_cors_header: + middlewares.append(create_cors_middleware(args.enable_cors_header)) + else: + middlewares.append(create_origin_only_middleware()) + + if args.disable_api_nodes: + middlewares.append(create_block_external_middleware()) + + if args.enable_manager: + middlewares.append(comfyui_manager.create_middleware()) + + max_upload_size = round(args.max_upload_size * 1024 * 1024) + self.app = web.Application(client_max_size=max_upload_size, middlewares=middlewares) + self.sockets = dict() + self.sockets_metadata = dict() + self.web_root = ( + FrontendManager.init_frontend(args.front_end_version) + if args.front_end_root is None + else args.front_end_root + ) + logging.info(f"[Prompt Server] web root: {self.web_root}") + if args.enable_assets: + register_assets_routes(self.app, self.user_manager) + else: + register_assets_routes(self.app) + asset_seeder.disable() + routes = web.RouteTableDef() + self.routes = routes + self.last_node_id = None + self.client_id = None + + self.on_prompt_handlers = [] + + @routes.get('/ws') + async def websocket_handler(request): + ws = web.WebSocketResponse() + await ws.prepare(request) + sid = request.rel_url.query.get('clientId', '') + if sid: + # Reusing existing session, remove old + self.sockets.pop(sid, None) + else: + sid = uuid.uuid4().hex + + # Store WebSocket for backward compatibility + self.sockets[sid] = ws + # Store metadata separately + self.sockets_metadata[sid] = {"feature_flags": {}} + + try: + # Send initial state to the new client + await self.send("status", {"status": self.get_queue_info(), "sid": sid}, sid) + # On reconnect if we are the currently executing client send the current node + if self.client_id == sid and self.last_node_id is not None: + await self.send("executing", { "node": self.last_node_id }, sid) + + # Flag to track if we've received the first message + first_message = True + + async for msg in ws: + if msg.type == aiohttp.WSMsgType.ERROR: + logging.warning('ws connection closed with exception %s' % ws.exception()) + elif msg.type == aiohttp.WSMsgType.TEXT: + try: + data = json.loads(msg.data) + # Check if first message is feature flags + if first_message and data.get("type") == "feature_flags": + # Store client feature flags + client_flags = data.get("data", {}) + self.sockets_metadata[sid]["feature_flags"] = client_flags + + # Send server feature flags in response + await self.send( + "feature_flags", + feature_flags.get_server_features(), + sid, + ) + + logging.debug( + f"Feature flags negotiated for client {sid}: {client_flags}" + ) + first_message = False + except json.JSONDecodeError: + logging.warning( + f"Invalid JSON received from client {sid}: {msg.data}" + ) + except Exception as e: + logging.error(f"Error processing WebSocket message: {e}") + finally: + self.sockets.pop(sid, None) + self.sockets_metadata.pop(sid, None) + return ws + + @routes.get("/") + async def get_root(request): + response = web.FileResponse(os.path.join(self.web_root, "index.html")) + response.headers['Cache-Control'] = 'no-store, must-revalidate' + response.headers["Pragma"] = "no-cache" + response.headers["Expires"] = "0" + return response + + @routes.get("/embeddings") + def get_embeddings(request): + embeddings = folder_paths.get_filename_list("embeddings") + return web.json_response(list(map(lambda a: os.path.splitext(a)[0], embeddings))) + + @routes.get("/models") + def list_model_types(request): + model_types = list(folder_paths.folder_names_and_paths.keys()) + + return web.json_response(model_types) + + @routes.get("/models/{folder}") + async def get_models(request): + folder = request.match_info.get("folder", None) + if folder not in folder_paths.folder_names_and_paths: + return web.Response(status=404) + files = folder_paths.get_filename_list(folder) + return web.json_response(files) + + @routes.get("/extensions") + async def get_extensions(request): + files = glob.glob(os.path.join( + glob.escape(self.web_root), 'extensions/**/*.js'), recursive=True) + + extensions = list(map(lambda f: "/" + os.path.relpath(f, self.web_root).replace("\\", "/"), files)) + + for name, dir in nodes.EXTENSION_WEB_DIRS.items(): + files = glob.glob(os.path.join(glob.escape(dir), '**/*.js'), recursive=True) + extensions.extend(list(map(lambda f: "/extensions/" + urllib.parse.quote( + name) + "/" + os.path.relpath(f, dir).replace("\\", "/"), files))) + + return web.json_response(extensions) + + def get_dir_by_type(dir_type): + if dir_type is None: + dir_type = "input" + + if dir_type == "input": + type_dir = folder_paths.get_input_directory() + elif dir_type == "temp": + type_dir = folder_paths.get_temp_directory() + elif dir_type == "output": + type_dir = folder_paths.get_output_directory() + + return type_dir, dir_type + + def compare_image_hash(filepath, image): + hasher = node_helpers.hasher() + + # function to compare hashes of two images to see if it already exists, fix to #3465 + if os.path.exists(filepath): + a = hasher() + b = hasher() + with open(filepath, "rb") as f: + a.update(f.read()) + b.update(image.file.read()) + image.file.seek(0) + return a.hexdigest() == b.hexdigest() + return False + + def image_upload(post, image_save_function=None): + image = post.get("image") + overwrite = post.get("overwrite") + image_is_duplicate = False + + image_upload_type = post.get("type") + upload_dir, image_upload_type = get_dir_by_type(image_upload_type) + + if image and image.file: + filename = image.filename + if not filename: + return web.Response(status=400) + + subfolder = post.get("subfolder", "") + full_output_folder = os.path.join(upload_dir, os.path.normpath(subfolder)) + filepath = os.path.abspath(os.path.join(full_output_folder, filename)) + + if os.path.commonpath((upload_dir, filepath)) != upload_dir: + return web.Response(status=400) + + if not os.path.exists(full_output_folder): + os.makedirs(full_output_folder) + + split = os.path.splitext(filename) + + if overwrite is not None and (overwrite == "true" or overwrite == "1"): + pass + else: + i = 1 + while os.path.exists(filepath): + if compare_image_hash(filepath, image): #compare hash to prevent saving of duplicates with same name, fix for #3465 + image_is_duplicate = True + break + filename = f"{split[0]} ({i}){split[1]}" + filepath = os.path.join(full_output_folder, filename) + i += 1 + + if not image_is_duplicate: + if image_save_function is not None: + image_save_function(image, post, filepath) + else: + with open(filepath, "wb") as f: + f.write(image.file.read()) + + resp = {"name" : filename, "subfolder": subfolder, "type": image_upload_type} + + if args.enable_assets: + try: + tag = image_upload_type if image_upload_type in ("input", "output") else "input" + tags = [tag] + tags.extend(get_known_subfolder_tags(subfolder)) + result = register_file_in_place(abs_path=filepath, name=filename, tags=tags) + resp["asset"] = { + "id": result.ref.id, + "name": result.ref.name, + "asset_hash": result.asset.hash, + "size": result.asset.size_bytes, + "mime_type": result.asset.mime_type, + "tags": result.tags, + } + except Exception: + logging.warning("Failed to register uploaded image as asset", exc_info=True) + + return web.json_response(resp) + else: + return web.Response(status=400) + + @routes.post("/upload/image") + async def upload_image(request): + post = await request.post() + return image_upload(post) + + + @routes.post("/upload/mask") + async def upload_mask(request): + post = await request.post() + + def image_save_function(image, post, filepath): + original_ref = json.loads(post.get("original_ref")) + filename, output_dir = folder_paths.annotated_filepath(original_ref['filename']) + + if not filename: + return web.Response(status=400) + + # validation for security: prevent accessing arbitrary path + if filename[0] == '/' or '..' in filename: + return web.Response(status=400) + + if output_dir is None: + type = original_ref.get("type", "output") + output_dir = folder_paths.get_directory_by_type(type) + + if output_dir is None: + return web.Response(status=400) + + if original_ref.get("subfolder", "") != "": + full_output_dir = os.path.join(output_dir, original_ref["subfolder"]) + if os.path.commonpath((os.path.abspath(full_output_dir), output_dir)) != output_dir: + return web.Response(status=403) + output_dir = full_output_dir + + file = os.path.join(output_dir, filename) + + if os.path.isfile(file): + with Image.open(file) as original_pil: + metadata = PngInfo() + if hasattr(original_pil,'text'): + for key in original_pil.text: + metadata.add_text(key, original_pil.text[key]) + original_pil = original_pil.convert('RGBA') + mask_pil = Image.open(image.file).convert('RGBA') + + # alpha copy + new_alpha = mask_pil.getchannel('A') + original_pil.putalpha(new_alpha) + original_pil.save(filepath, compress_level=4, pnginfo=metadata) + + return image_upload(post, image_save_function) + + @routes.get("/view") + async def view_image(request): + if "filename" in request.rel_url.query: + filename = request.rel_url.query["filename"] + + # The frontend's LoadImage combo widget uses asset_hash values + # (e.g. "blake3:...") as widget values. When litegraph renders the + # node preview, it constructs /view?filename=, so this + # endpoint must resolve blake3 hashes to their on-disk file paths. + if filename.startswith("blake3:"): + owner_id = self.user_manager.get_request_user_id(request) + result = resolve_hash_to_path(filename, owner_id=owner_id) + if result is None: + return web.Response(status=404) + file, filename, resolved_content_type = result.abs_path, result.download_name, result.content_type + else: + resolved_content_type = None + filename, output_dir = folder_paths.annotated_filepath(filename) + + if not filename: + return web.Response(status=400) + + # validation for security: prevent accessing arbitrary path + if filename[0] == '/' or '..' in filename: + return web.Response(status=400) + + if output_dir is None: + type = request.rel_url.query.get("type", "output") + output_dir = folder_paths.get_directory_by_type(type) + + if output_dir is None: + return web.Response(status=400) + + if "subfolder" in request.rel_url.query: + full_output_dir = os.path.join(output_dir, request.rel_url.query["subfolder"]) + if os.path.commonpath((os.path.abspath(full_output_dir), output_dir)) != output_dir: + return web.Response(status=403) + output_dir = full_output_dir + + filename = os.path.basename(filename) + file = os.path.join(output_dir, filename) + + if os.path.isfile(file): + if 'preview' in request.rel_url.query: + with Image.open(file) as img: + preview_info = request.rel_url.query['preview'].split(';') + image_format = preview_info[0] + if image_format not in ['webp', 'jpeg'] or 'a' in request.rel_url.query.get('channel', ''): + image_format = 'webp' + + quality = 90 + if preview_info[-1].isdigit(): + quality = int(preview_info[-1]) + + buffer = BytesIO() + if image_format in ['jpeg'] or request.rel_url.query.get('channel', '') == 'rgb': + img = img.convert("RGB") + img.save(buffer, format=image_format, quality=quality) + buffer.seek(0) + + return web.Response(body=buffer.read(), content_type=f'image/{image_format}', + headers={"Content-Disposition": f"filename=\"{filename}\""}) + + if 'channel' not in request.rel_url.query: + channel = 'rgba' + else: + channel = request.rel_url.query["channel"] + + if channel == 'rgb': + with Image.open(file) as img: + if img.mode == "RGBA": + r, g, b, a = img.split() + new_img = Image.merge('RGB', (r, g, b)) + else: + new_img = img.convert("RGB") + + buffer = BytesIO() + new_img.save(buffer, format='PNG') + buffer.seek(0) + + return web.Response(body=buffer.read(), content_type='image/png', + headers={"Content-Disposition": f"filename=\"{filename}\""}) + + elif channel == 'a': + with Image.open(file) as img: + if img.mode == "RGBA": + _, _, _, a = img.split() + else: + a = Image.new('L', img.size, 255) + + # alpha img + alpha_img = Image.new('RGBA', img.size) + alpha_img.putalpha(a) + alpha_buffer = BytesIO() + alpha_img.save(alpha_buffer, format='PNG') + alpha_buffer.seek(0) + + return web.Response(body=alpha_buffer.read(), content_type='image/png', + headers={"Content-Disposition": f"filename=\"{filename}\""}) + else: + # Use the content type from asset resolution if available, + # otherwise guess from the filename. + content_type = ( + resolved_content_type + or mimetypes.guess_type(filename)[0] + or 'application/octet-stream' + ) + + # For security, force renderable/active types (HTML, JS, + # CSS, SVG, XML — anything that can carry inline diff --git a/docs/hel-892/h3-core-reference/frontend__src__renderer__extensions__vueNodes__widgets__composables__useResolutionPreviewWidget.ts b/docs/hel-892/h3-core-reference/frontend__src__renderer__extensions__vueNodes__widgets__composables__useResolutionPreviewWidget.ts new file mode 100644 index 00000000..0603b2c1 --- /dev/null +++ b/docs/hel-892/h3-core-reference/frontend__src__renderer__extensions__vueNodes__widgets__composables__useResolutionPreviewWidget.ts @@ -0,0 +1,35 @@ +import type { LGraphNode } from '@/lib/litegraph/src/litegraph' +import type { + IResolutionPreviewWidget, + IWidgetResolutionPreviewOptions +} from '@/lib/litegraph/src/types/widgets' +import { isResolutionPreviewInputSpec } from '@/schemas/nodeDef/nodeDefSchemaV2' +import type { InputSpec as InputSpecV2 } from '@/schemas/nodeDef/nodeDefSchemaV2' +import type { ComfyWidgetConstructorV2 } from '@/scripts/widgets' + +export const useResolutionPreviewWidget = (): ComfyWidgetConstructorV2 => { + return ( + node: LGraphNode, + inputSpec: InputSpecV2 + ): IResolutionPreviewWidget => { + const spec = isResolutionPreviewInputSpec(inputSpec) ? inputSpec : undefined + const options: IWidgetResolutionPreviewOptions = { + serialize: false, + canvasOnly: false, + hideInPanel: true, + ratio_widget: spec?.ratio_widget, + megapixels_widget: spec?.megapixels_widget, + multiple_widget: spec?.multiple_widget + } + const rawWidget = node.addWidget( + 'resolutionpreview', + inputSpec.name, + null, + () => {}, + options + ) + rawWidget.serialize = false + + return rawWidget as IResolutionPreviewWidget + } +} diff --git a/docs/hel-892/h3-core-reference/frontend__src__schemas__nodeDefSchema.ts b/docs/hel-892/h3-core-reference/frontend__src__schemas__nodeDefSchema.ts new file mode 100644 index 00000000..e1040a4f --- /dev/null +++ b/docs/hel-892/h3-core-reference/frontend__src__schemas__nodeDefSchema.ts @@ -0,0 +1 @@ +export * from '@comfyorg/object-info-parser' diff --git a/docs/hel-892/h3-core-reference/frontend__src__schemas__nodeDef__migration.ts b/docs/hel-892/h3-core-reference/frontend__src__schemas__nodeDef__migration.ts new file mode 100644 index 00000000..22d91c16 --- /dev/null +++ b/docs/hel-892/h3-core-reference/frontend__src__schemas__nodeDef__migration.ts @@ -0,0 +1,143 @@ +import type { + ComfyNodeDef as ComfyNodeDefV2, + InputSpec as InputSpecV2, + OutputSpec as OutputSpecV2 +} from '@/schemas/nodeDef/nodeDefSchemaV2' +import type { + ComfyNodeDef as ComfyNodeDefV1, + InputSpec as InputSpecV1 +} from '@/schemas/nodeDefSchema' +import { + getComboSpecComboOptions, + isComboInputSpec, + isComboInputSpecV1 +} from '@/schemas/nodeDefSchema' + +/** + * Transforms a V1 node definition to V2 format + * @param nodeDefV1 The V1 node definition to transform + * @returns The transformed V2 node definition + */ +export function transformNodeDefV1ToV2( + nodeDefV1: ComfyNodeDefV1 +): ComfyNodeDefV2 { + // Transform inputs + const inputs: Record = {} + + // Process required inputs + if (nodeDefV1.input?.required) { + Object.entries(nodeDefV1.input.required).forEach(([name, inputSpecV1]) => { + inputs[name] = transformInputSpecV1ToV2(inputSpecV1, { + name, + isOptional: false + }) + }) + } + + // Process optional inputs + if (nodeDefV1.input?.optional) { + Object.entries(nodeDefV1.input.optional).forEach(([name, inputSpecV1]) => { + inputs[name] = transformInputSpecV1ToV2(inputSpecV1, { + name, + isOptional: true + }) + }) + } + + // Transform outputs + const outputs: OutputSpecV2[] = [] + + if (nodeDefV1.output) { + if (Array.isArray(nodeDefV1.output)) { + nodeDefV1.output.forEach((outputType, index) => { + const outputSpec: OutputSpecV2 = { + index, + name: nodeDefV1.output_name?.[index] || `output_${index}`, + type: Array.isArray(outputType) ? 'COMBO' : outputType, + is_list: nodeDefV1.output_is_list?.[index] || false, + tooltip: nodeDefV1.output_tooltips?.[index] + } + + // Add options for combo outputs + if (Array.isArray(outputType)) { + outputSpec.options = outputType + } + + outputs.push(outputSpec) + }) + } else { + console.warn('nodeDefV1.output is not an array:', nodeDefV1.output) + } + } + + // Create the V2 node definition + return { + inputs, + outputs, + hidden: nodeDefV1.input?.hidden, + name: nodeDefV1.name, + display_name: nodeDefV1.display_name, + description: nodeDefV1.description, + category: nodeDefV1.category, + output_node: nodeDefV1.output_node, + python_module: nodeDefV1.python_module, + deprecated: nodeDefV1.deprecated, + experimental: nodeDefV1.experimental + } +} + +/** + * Transforms a V1 input specification to V2 format + * @param inputSpecV1 The V1 input specification to transform + * @param name The name of the input + * @param isOptional Whether the input is optional + * @returns The transformed V2 input specification + */ +export function transformInputSpecV1ToV2( + inputSpecV1: InputSpecV1, + kwargs: { + name: string + isOptional?: boolean + } +): InputSpecV2 { + const { name, isOptional = false } = kwargs + + // Extract options from the input spec + const options = inputSpecV1[1] || {} + + // Base properties for all input types + const baseProps = { + name, + isOptional, + ...options + } + + // Handle different input types + if (isComboInputSpec(inputSpecV1)) { + return { + type: 'COMBO', + ...baseProps, + options: isComboInputSpecV1(inputSpecV1) + ? inputSpecV1[0] + : getComboSpecComboOptions(inputSpecV1) + } + } else if (typeof inputSpecV1[0] === 'string') { + // Handle standard types (INT, FLOAT, BOOLEAN, STRING) and custom types + return { + type: inputSpecV1[0], + ...baseProps + } + } + + // Fallback for any unhandled cases + return { + type: 'UNKNOWN', + ...baseProps + } +} + +export function transformInputSpecV2ToV1( + inputSpecV2: InputSpecV2 +): InputSpecV1 { + return [inputSpecV2.type, inputSpecV2] +} diff --git a/docs/hel-892/h3-core-reference/make_manifest.py b/docs/hel-892/h3-core-reference/make_manifest.py new file mode 100644 index 00000000..254bc345 --- /dev/null +++ b/docs/hel-892/h3-core-reference/make_manifest.py @@ -0,0 +1,155 @@ +"""Inventory immutable core bytes and reuse the SAME pinned frontend identity.""" + +import hashlib +import json +from pathlib import Path + +ROOT = Path(__file__).resolve().parent +CORE = "2f35f4a08176d993cded35dac3332be4f7287f41" +FRONTEND = "743be3f4fe2e374b0ee39f0ded56e7cb65a837c5" +ANCHORS = ( + "class StringMultiline", + "class Float", + "class ResolutionSelector", + "class AspectRatio", + "class MathExpressionNode", + "class RandomNoise", + "class BasicScheduler", + "def define_schema", + "async def get_node_list", + "async def comfy_entrypoint", + "class MultiType", + "class Autogrow", + "class TemplateNames", + "def as_dict", + "def _expand_schema_for_dynamic", + "node_id", + "get_node_list()", + "schema.node_id", + "nodes_primitive.py", + "nodes_resolution.py", + "nodes_math.py", + "nodes_custom_sampler.py", + "SCHEDULER_HANDLERS =", + "SCHEDULER_NAMES =", + "def execute", + "noise_seed", + "control_after_generate", + "getRestoredWidgetValue", + "createWidgetRestorationState", + "restoreNamed", + "serializeValue", + "widgets_values_named", + "serialiseWidgetValues", + "widget.options?.serialize", + "inputs[input.name]", + "applyAutogrow", + "addAutogrowGroup", + "autogrowOrdinalToName", + "onConnectionsChange", + "getOrderedInputSpecs", + "for (const inputSpec of orderedInputSpecs)", + "mode === 'fixed'", + "beforeQueued", + "afterQueued", + "applyDynamicInputs", + "RESOLUTION", + "serialize: false", + "fallbackWidgetsValuesNames", +) + + +def main(): + old = json.loads((ROOT.parent / "h3-reference/sources.json").read_bytes()) + rows = [] + for entry in old["sources"]: + if entry["id"].startswith("frontend:"): + row = dict(entry) + row["local_file"] = "../h3-reference/" + row["local_file"] + row["reuse"] = ( + "same frontend1.53.10 full commit, no core0.30.0 identity reused" + ) + rows.append(row) + existing = {r["id"] for r in rows} + for p in sorted(ROOT.glob("*__*")): + prefix, _, tail = p.name.partition("__") + if prefix not in ("core", "frontend"): + continue + filename = tail.replace("__", "/") + ident = f"{prefix}:{filename}" + if ident in existing: + # Already references the same full commit original, do not duplicate. + continue + repo, sha, tag = ( + ("Comfy-Org/ComfyUI", CORE, "v0.33.0") + if prefix == "core" + else ("Comfy-Org/ComfyUI_frontend", FRONTEND, "v1.53.10") + ) + lines = p.read_text().splitlines() + locations = { + f"{anchor}@{i}": [i, min(i + 4, len(lines))] + for anchor in ANCHORS + for i, line in enumerate(lines, 1) + if anchor in line + } + rows.append( + { + "id": ident, + "repository": f"https://github.com/{repo}", + "commit": sha, + "tag": tag, + "file": filename, + "lines": [[1, len(lines)]], + "rule_locations": locations, + "raw_url": f"https://raw.githubusercontent.com/{repo}/{sha}/{filename}", + "url": f"https://github.com/{repo}/blob/{sha}/{filename}", + "sha256": hashlib.sha256(p.read_bytes()).hexdigest(), + "local_file": p.name, + "license": "GPL-3.0", + "target_version_match": "unknown", + } + ) + identities = [] + for name, repo, ref, expected, local in ( + ("core-tag", "Comfy-Org/ComfyUI", "v0.33.0", CORE, "core-tag.json"), + ( + "frontend-tag", + "Comfy-Org/ComfyUI_frontend", + "v1.53.10", + FRONTEND, + "../h3-reference/ComfyUI_frontend-tag.json", + ), + ): + raw = (ROOT / local).read_bytes() + data = json.loads(raw) + assert data["object"]["sha"] == expected and data["object"]["type"] == "commit" + identities.append( + { + "id": name, + "raw_url": f"https://api.github.com/repos/{repo}/git/ref/tags/{ref}", + "local_file": local, + "sha256": hashlib.sha256(raw).hexdigest(), + "ref": f"refs/tags/{ref}", + "commit": expected, + } + ) + (ROOT / "sources.json").write_text( + json.dumps( + { + "schema_version": 1, + "authority": "public_reference_only_not_object_info", + "sources": rows, + "identity_observations": identities, + "target_installation": "unknown", + "source_graph_identity": "unknown", + "upstream_code_executed": False, + }, + ensure_ascii=False, + indent=2, + ) + + "\n" + ) + + +if __name__ == "__main__": + main() diff --git a/docs/hel-892/h3-core-reference/sources.json b/docs/hel-892/h3-core-reference/sources.json new file mode 100644 index 00000000..30e66692 --- /dev/null +++ b/docs/hel-892/h3-core-reference/sources.json @@ -0,0 +1,2487 @@ +{ + "schema_version": 1, + "authority": "public_reference_only_not_object_info", + "sources": [ + { + "id": "frontend:LICENSE", + "repository": "https://github.com/Comfy-Org/ComfyUI_frontend", + "commit": "743be3f4fe2e374b0ee39f0ded56e7cb65a837c5", + "tag": "v1.53.10", + "file": "LICENSE", + "lines": [ + [ + 1, + 674 + ] + ], + "rule_locations": {}, + "raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/743be3f4fe2e374b0ee39f0ded56e7cb65a837c5/LICENSE", + "url": "https://github.com/Comfy-Org/ComfyUI_frontend/blob/743be3f4fe2e374b0ee39f0ded56e7cb65a837c5/LICENSE", + "sha256": "3972dc9744f6499f0f9b2dbf76696f2ae7ad8af9b23dde66d6af86c9dfb36986", + "retrieved_at": "2026-10-29T22:42:08.788824+00:00", + "local_file": "../h3-reference/frontend__LICENSE", + "license": "GPL-3.0", + "target_version_match": "unknown", + "reuse": "same frontend1.53.10 full commit, no core0.30.0 identity reused" + }, + { + "id": "frontend:browser_tests/tests/subgraph/subgraphConvertAutogrowInputs.spec.ts", + "repository": "https://github.com/Comfy-Org/ComfyUI_frontend", + "commit": "743be3f4fe2e374b0ee39f0ded56e7cb65a837c5", + "tag": "v1.53.10", + "file": "browser_tests/tests/subgraph/subgraphConvertAutogrowInputs.spec.ts", + "lines": [ + [ + 1, + 146 + ] + ], + "rule_locations": {}, + "raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/743be3f4fe2e374b0ee39f0ded56e7cb65a837c5/browser_tests/tests/subgraph/subgraphConvertAutogrowInputs.spec.ts", + "url": "https://github.com/Comfy-Org/ComfyUI_frontend/blob/743be3f4fe2e374b0ee39f0ded56e7cb65a837c5/browser_tests/tests/subgraph/subgraphConvertAutogrowInputs.spec.ts", + "sha256": "8c36b92eace5d79aad2178e28e00248e6a54326febcadec9417d9df717668376", + "retrieved_at": "2026-10-29T22:42:09.180825+00:00", + "local_file": "../h3-reference/frontend__browser_tests__tests__subgraph__subgraphConvertAutogrowInputs.spec.ts", + "license": "GPL-3.0", + "target_version_match": "unknown", + "reuse": "same frontend1.53.10 full commit, no core0.30.0 identity reused" + }, + { + "id": "frontend:src/core/graph/widgets/dynamicWidgets.ts", + "repository": "https://github.com/Comfy-Org/ComfyUI_frontend", + "commit": "743be3f4fe2e374b0ee39f0ded56e7cb65a837c5", + "tag": "v1.53.10", + "file": "src/core/graph/widgets/dynamicWidgets.ts", + "lines": [ + [ + 1, + 710 + ] + ], + "rule_locations": { + "onConfigure@276": [ + 276, + 280 + ], + "serialize: false@91": [ + 91, + 95 + ], + "getRestoredWidgetValue@149": [ + 149, + 153 + ], + "applyAutogrow@306": [ + 306, + 310 + ], + "applyAutogrow@684": [ + 684, + 688 + ], + "addAutogrowGroup@477": [ + 477, + 481 + ], + "addAutogrowGroup@560": [ + 560, + 564 + ], + "addAutogrowGroup@709": [ + 709, + 710 + ] + }, + "raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/743be3f4fe2e374b0ee39f0ded56e7cb65a837c5/src/core/graph/widgets/dynamicWidgets.ts", + "url": "https://github.com/Comfy-Org/ComfyUI_frontend/blob/743be3f4fe2e374b0ee39f0ded56e7cb65a837c5/src/core/graph/widgets/dynamicWidgets.ts", + "sha256": "57a09e023d1e46313292a230ad0d2b1fa2654038d83eac227b08c65da6865f60", + "retrieved_at": "2026-10-29T22:42:09.384825+00:00", + "local_file": "../h3-reference/frontend__src__core__graph__widgets__dynamicWidgets.ts", + "license": "GPL-3.0", + "target_version_match": "unknown", + "reuse": "same frontend1.53.10 full commit, no core0.30.0 identity reused" + }, + { + "id": "frontend:src/extensions/core/previewAny.ts", + "repository": "https://github.com/Comfy-Org/ComfyUI_frontend", + "commit": "743be3f4fe2e374b0ee39f0ded56e7cb65a837c5", + "tag": "v1.53.10", + "file": "src/extensions/core/previewAny.ts", + "lines": [ + [ + 1, + 42 + ] + ], + "rule_locations": { + "onNodeCreated@24": [ + 24, + 28 + ], + "onNodeCreated@25": [ + 25, + 29 + ], + "onNodeCreated@26": [ + 26, + 30 + ], + "registerExtension@16": [ + 16, + 20 + ], + "addTextPreviewWidgets@8": [ + 8, + 12 + ], + "addTextPreviewWidgets@27": [ + 27, + 31 + ] + }, + "raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/743be3f4fe2e374b0ee39f0ded56e7cb65a837c5/src/extensions/core/previewAny.ts", + "url": "https://github.com/Comfy-Org/ComfyUI_frontend/blob/743be3f4fe2e374b0ee39f0ded56e7cb65a837c5/src/extensions/core/previewAny.ts", + "sha256": "da8f4361b054d8619c09b4abaae1c2c464d6c8927968e60f18e61b467d2a3366", + "retrieved_at": "2026-10-29T22:42:09.588825+00:00", + "local_file": "../h3-reference/frontend__src__extensions__core__previewAny.ts", + "license": "GPL-3.0", + "target_version_match": "unknown", + "reuse": "same frontend1.53.10 full commit, no core0.30.0 identity reused" + }, + { + "id": "frontend:src/extensions/core/textPreviewWidgets.ts", + "repository": "https://github.com/Comfy-Org/ComfyUI_frontend", + "commit": "743be3f4fe2e374b0ee39f0ded56e7cb65a837c5", + "tag": "v1.53.10", + "file": "src/extensions/core/textPreviewWidgets.ts", + "lines": [ + [ + 1, + 85 + ] + ], + "rule_locations": { + "serialize = false@53": [ + 53, + 57 + ], + "serialize = false@66": [ + 66, + 70 + ], + "serialize = false@67": [ + 67, + 71 + ], + "serialize: false@39": [ + 39, + 43 + ], + "addTextPreviewWidgets@21": [ + 21, + 25 + ], + "preview.serialize@53": [ + 53, + 57 + ], + "modeWidget.serialize@67": [ + 67, + 71 + ] + }, + "raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/743be3f4fe2e374b0ee39f0ded56e7cb65a837c5/src/extensions/core/textPreviewWidgets.ts", + "url": "https://github.com/Comfy-Org/ComfyUI_frontend/blob/743be3f4fe2e374b0ee39f0ded56e7cb65a837c5/src/extensions/core/textPreviewWidgets.ts", + "sha256": "453e4c11c902e84dc9950475f8439d4364d0244bfe370c4b74770b84c2592a75", + "retrieved_at": "2026-10-29T22:42:09.796826+00:00", + "local_file": "../h3-reference/frontend__src__extensions__core__textPreviewWidgets.ts", + "license": "GPL-3.0", + "target_version_match": "unknown", + "reuse": "same frontend1.53.10 full commit, no core0.30.0 identity reused" + }, + { + "id": "frontend:src/extensions/core/widgetInputs.ts", + "repository": "https://github.com/Comfy-Org/ComfyUI_frontend", + "commit": "743be3f4fe2e374b0ee39f0ded56e7cb65a837c5", + "tag": "v1.53.10", + "file": "src/extensions/core/widgetInputs.ts", + "lines": [ + [ + 1, + 675 + ] + ], + "rule_locations": { + "control_after_generate@316": [ + 316, + 320 + ], + "onConfigure@613": [ + 613, + 617 + ], + "onConfigure@614": [ + 614, + 618 + ], + "registerExtension@577": [ + 577, + 581 + ], + "getRestoredWidgetValue@278": [ + 278, + 282 + ] + }, + "raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/743be3f4fe2e374b0ee39f0ded56e7cb65a837c5/src/extensions/core/widgetInputs.ts", + "url": "https://github.com/Comfy-Org/ComfyUI_frontend/blob/743be3f4fe2e374b0ee39f0ded56e7cb65a837c5/src/extensions/core/widgetInputs.ts", + "sha256": "27e77900db9568b200be249f0ace4adbbe9cd259671683b4b5438114afc9cfa8", + "retrieved_at": "2026-10-29T22:42:10.004826+00:00", + "local_file": "../h3-reference/frontend__src__extensions__core__widgetInputs.ts", + "license": "GPL-3.0", + "target_version_match": "unknown", + "reuse": "same frontend1.53.10 full commit, no core0.30.0 identity reused" + }, + { + "id": "frontend:src/lib/litegraph/src/LGraph.ts", + "repository": "https://github.com/Comfy-Org/ComfyUI_frontend", + "commit": "743be3f4fe2e374b0ee39f0ded56e7cb65a837c5", + "tag": "v1.53.10", + "file": "src/lib/litegraph/src/LGraph.ts", + "lines": [ + [ + 1, + 3458 + ] + ], + "rule_locations": { + "onConfigure@166": [ + 166, + 170 + ], + "onConfigure@667": [ + 667, + 671 + ], + "onConfigure@3076": [ + 3076, + 3080 + ], + "extensionConfigureView@166": [ + 166, + 170 + ], + "extensionConfigureView@3076": [ + 3076, + 3080 + ] + }, + "raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/743be3f4fe2e374b0ee39f0ded56e7cb65a837c5/src/lib/litegraph/src/LGraph.ts", + "url": "https://github.com/Comfy-Org/ComfyUI_frontend/blob/743be3f4fe2e374b0ee39f0ded56e7cb65a837c5/src/lib/litegraph/src/LGraph.ts", + "sha256": "7a99223d5e212b5d6c278b747be8a62bb9ad6b1e93d32be435b8bb8593d339fe", + "retrieved_at": "2026-10-29T22:42:10.220826+00:00", + "local_file": "../h3-reference/frontend__src__lib__litegraph__src__LGraph.ts", + "license": "GPL-3.0", + "target_version_match": "unknown", + "reuse": "same frontend1.53.10 full commit, no core0.30.0 identity reused" + }, + { + "id": "frontend:src/lib/litegraph/src/LGraphNode.ts", + "repository": "https://github.com/Comfy-Org/ComfyUI_frontend", + "commit": "743be3f4fe2e374b0ee39f0ded56e7cb65a837c5", + "tag": "v1.53.10", + "file": "src/lib/litegraph/src/LGraphNode.ts", + "lines": [ + [ + 1, + 4528 + ] + ], + "rule_locations": { + "onConfigure@72": [ + 72, + 76 + ], + "onConfigure@293": [ + 293, + 297 + ], + "onConfigure@849": [ + 849, + 853 + ], + "onConfigure@1221": [ + 1221, + 1225 + ], + "onNodeCreated@863": [ + 863, + 867 + ], + "widgets_values_named@185": [ + 185, + 189 + ], + "widgets_values_named@189": [ + 189, + 193 + ], + "widgets_values_named@194": [ + 194, + 198 + ], + "widgets_values_named@1194": [ + 1194, + 1198 + ], + "restoreNamed@206": [ + 206, + 210 + ], + "getRestoredWidgetValue@1201": [ + 1201, + 1205 + ], + "getRestoredWidgetValue@2300": [ + 2300, + 2304 + ], + "serialiseWidgetValues@172": [ + 172, + 176 + ], + "serialiseWidgetValues@1271": [ + 1271, + 1275 + ], + "extensionConfigureView@72": [ + 72, + 76 + ], + "extensionConfigureView@1221": [ + 1221, + 1225 + ] + }, + "raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/743be3f4fe2e374b0ee39f0ded56e7cb65a837c5/src/lib/litegraph/src/LGraphNode.ts", + "url": "https://github.com/Comfy-Org/ComfyUI_frontend/blob/743be3f4fe2e374b0ee39f0ded56e7cb65a837c5/src/lib/litegraph/src/LGraphNode.ts", + "sha256": "7951aec0dac4d5700ef09dd8e54bbbeb97d8c5c9ff1cf3eb98368ce32ff37b03", + "retrieved_at": "2026-10-29T22:42:10.444826+00:00", + "local_file": "../h3-reference/frontend__src__lib__litegraph__src__LGraphNode.ts", + "license": "GPL-3.0", + "target_version_match": "unknown", + "reuse": "same frontend1.53.10 full commit, no core0.30.0 identity reused" + }, + { + "id": "frontend:src/lib/litegraph/src/extensionPersistence.ts", + "repository": "https://github.com/Comfy-Org/ComfyUI_frontend", + "commit": "743be3f4fe2e374b0ee39f0ded56e7cb65a837c5", + "tag": "v1.53.10", + "file": "src/lib/litegraph/src/extensionPersistence.ts", + "lines": [ + [ + 1, + 257 + ] + ], + "rule_locations": { + "onConfigure@249": [ + 249, + 253 + ], + "widgets_values_named@63": [ + 63, + 67 + ], + "extensionConfigureView@249": [ + 249, + 253 + ] + }, + "raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/743be3f4fe2e374b0ee39f0ded56e7cb65a837c5/src/lib/litegraph/src/extensionPersistence.ts", + "url": "https://github.com/Comfy-Org/ComfyUI_frontend/blob/743be3f4fe2e374b0ee39f0ded56e7cb65a837c5/src/lib/litegraph/src/extensionPersistence.ts", + "sha256": "b95de167f8d7de3e777b9448baa45268c1a30ceb07f449146ba6f6f0004ec4c5", + "retrieved_at": "2026-10-29T22:42:10.828827+00:00", + "local_file": "../h3-reference/frontend__src__lib__litegraph__src__extensionPersistence.ts", + "license": "GPL-3.0", + "target_version_match": "unknown", + "reuse": "same frontend1.53.10 full commit, no core0.30.0 identity reused" + }, + { + "id": "frontend:src/lib/litegraph/src/litegraph.ts", + "repository": "https://github.com/Comfy-Org/ComfyUI_frontend", + "commit": "743be3f4fe2e374b0ee39f0ded56e7cb65a837c5", + "tag": "v1.53.10", + "file": "src/lib/litegraph/src/litegraph.ts", + "lines": [ + [ + 1, + 182 + ] + ], + "rule_locations": {}, + "raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/743be3f4fe2e374b0ee39f0ded56e7cb65a837c5/src/lib/litegraph/src/litegraph.ts", + "url": "https://github.com/Comfy-Org/ComfyUI_frontend/blob/743be3f4fe2e374b0ee39f0ded56e7cb65a837c5/src/lib/litegraph/src/litegraph.ts", + "sha256": "ad7ab001707b7438993ce9f7be75bdf579452bb75bfac35aa5a599fcfdf54d3a", + "retrieved_at": "2026-10-29T22:42:11.032827+00:00", + "local_file": "../h3-reference/frontend__src__lib__litegraph__src__litegraph.ts", + "license": "GPL-3.0", + "target_version_match": "unknown", + "reuse": "same frontend1.53.10 full commit, no core0.30.0 identity reused" + }, + { + "id": "frontend:src/lib/litegraph/src/subgraph/ExecutableNodeDTO.ts", + "repository": "https://github.com/Comfy-Org/ComfyUI_frontend", + "commit": "743be3f4fe2e374b0ee39f0ded56e7cb65a837c5", + "tag": "v1.53.10", + "file": "src/lib/litegraph/src/subgraph/ExecutableNodeDTO.ts", + "lines": [ + [ + 1, + 431 + ] + ], + "rule_locations": {}, + "raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/743be3f4fe2e374b0ee39f0ded56e7cb65a837c5/src/lib/litegraph/src/subgraph/ExecutableNodeDTO.ts", + "url": "https://github.com/Comfy-Org/ComfyUI_frontend/blob/743be3f4fe2e374b0ee39f0ded56e7cb65a837c5/src/lib/litegraph/src/subgraph/ExecutableNodeDTO.ts", + "sha256": "0c0ca487822a9f86324925c2fb4ea59c6c032ad5d042a83ac367cb15196454fe", + "retrieved_at": "2026-10-29T22:42:11.244827+00:00", + "local_file": "../h3-reference/frontend__src__lib__litegraph__src__subgraph__ExecutableNodeDTO.ts", + "license": "GPL-3.0", + "target_version_match": "unknown", + "reuse": "same frontend1.53.10 full commit, no core0.30.0 identity reused" + }, + { + "id": "frontend:src/lib/litegraph/src/utils/namedValuesShadowDiff.ts", + "repository": "https://github.com/Comfy-Org/ComfyUI_frontend", + "commit": "743be3f4fe2e374b0ee39f0ded56e7cb65a837c5", + "tag": "v1.53.10", + "file": "src/lib/litegraph/src/utils/namedValuesShadowDiff.ts", + "lines": [ + [ + 1, + 51 + ] + ], + "rule_locations": {}, + "raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/743be3f4fe2e374b0ee39f0ded56e7cb65a837c5/src/lib/litegraph/src/utils/namedValuesShadowDiff.ts", + "url": "https://github.com/Comfy-Org/ComfyUI_frontend/blob/743be3f4fe2e374b0ee39f0ded56e7cb65a837c5/src/lib/litegraph/src/utils/namedValuesShadowDiff.ts", + "sha256": "b5c31e5f10a3a245545bf3db7a40a0fd9221abe95c35665ef0e715043c7e10a9", + "retrieved_at": "2026-10-29T22:42:11.448828+00:00", + "local_file": "../h3-reference/frontend__src__lib__litegraph__src__utils__namedValuesShadowDiff.ts", + "license": "GPL-3.0", + "target_version_match": "unknown", + "reuse": "same frontend1.53.10 full commit, no core0.30.0 identity reused" + }, + { + "id": "frontend:src/renderer/extensions/vueNodes/widgets/composables/useBooleanWidget.ts", + "repository": "https://github.com/Comfy-Org/ComfyUI_frontend", + "commit": "743be3f4fe2e374b0ee39f0ded56e7cb65a837c5", + "tag": "v1.53.10", + "file": "src/renderer/extensions/vueNodes/widgets/composables/useBooleanWidget.ts", + "lines": [ + [ + 1, + 31 + ] + ], + "rule_locations": {}, + "raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/743be3f4fe2e374b0ee39f0ded56e7cb65a837c5/src/renderer/extensions/vueNodes/widgets/composables/useBooleanWidget.ts", + "url": "https://github.com/Comfy-Org/ComfyUI_frontend/blob/743be3f4fe2e374b0ee39f0ded56e7cb65a837c5/src/renderer/extensions/vueNodes/widgets/composables/useBooleanWidget.ts", + "sha256": "36f477f75561e0c7bfc2c6757906724f8ff2c8660ace26759f3f07493877fece", + "retrieved_at": "2026-10-29T22:42:11.836828+00:00", + "local_file": "../h3-reference/frontend__src__renderer__extensions__vueNodes__widgets__composables__useBooleanWidget.ts", + "license": "GPL-3.0", + "target_version_match": "unknown", + "reuse": "same frontend1.53.10 full commit, no core0.30.0 identity reused" + }, + { + "id": "frontend:src/renderer/extensions/vueNodes/widgets/composables/useComboWidget.ts", + "repository": "https://github.com/Comfy-Org/ComfyUI_frontend", + "commit": "743be3f4fe2e374b0ee39f0ded56e7cb65a837c5", + "tag": "v1.53.10", + "file": "src/renderer/extensions/vueNodes/widgets/composables/useComboWidget.ts", + "lines": [ + [ + 1, + 327 + ] + ], + "rule_locations": { + "control_after_generate@92": [ + 92, + 96 + ], + "control_after_generate@94": [ + 94, + 98 + ], + "control_after_generate@95": [ + 95, + 99 + ], + "control_after_generate@216": [ + 216, + 220 + ], + "control_after_generate@221": [ + 221, + 225 + ], + "control_after_generate@222": [ + 222, + 226 + ], + "control_after_generate@292": [ + 292, + 296 + ], + "control_after_generate@298": [ + 298, + 302 + ], + "control_after_generate@299": [ + 299, + 303 + ] + }, + "raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/743be3f4fe2e374b0ee39f0ded56e7cb65a837c5/src/renderer/extensions/vueNodes/widgets/composables/useComboWidget.ts", + "url": "https://github.com/Comfy-Org/ComfyUI_frontend/blob/743be3f4fe2e374b0ee39f0ded56e7cb65a837c5/src/renderer/extensions/vueNodes/widgets/composables/useComboWidget.ts", + "sha256": "8c6f99ea29a94a3b51d939b3aa9f1081515e5eb601cc0f7215ccf140e1bbb6e9", + "retrieved_at": "2026-10-29T22:42:12.136828+00:00", + "local_file": "../h3-reference/frontend__src__renderer__extensions__vueNodes__widgets__composables__useComboWidget.ts", + "license": "GPL-3.0", + "target_version_match": "unknown", + "reuse": "same frontend1.53.10 full commit, no core0.30.0 identity reused" + }, + { + "id": "frontend:src/renderer/extensions/vueNodes/widgets/composables/useFloatWidget.ts", + "repository": "https://github.com/Comfy-Org/ComfyUI_frontend", + "commit": "743be3f4fe2e374b0ee39f0ded56e7cb65a837c5", + "tag": "v1.53.10", + "file": "src/renderer/extensions/vueNodes/widgets/composables/useFloatWidget.ts", + "lines": [ + [ + 1, + 100 + ] + ], + "rule_locations": { + "control_after_generate@84": [ + 84, + 88 + ] + }, + "raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/743be3f4fe2e374b0ee39f0ded56e7cb65a837c5/src/renderer/extensions/vueNodes/widgets/composables/useFloatWidget.ts", + "url": "https://github.com/Comfy-Org/ComfyUI_frontend/blob/743be3f4fe2e374b0ee39f0ded56e7cb65a837c5/src/renderer/extensions/vueNodes/widgets/composables/useFloatWidget.ts", + "sha256": "8485d1edc17e911e65e38055e704045245f2de8310a54b87d429e7ed111accef", + "retrieved_at": "2026-10-29T22:42:12.336829+00:00", + "local_file": "../h3-reference/frontend__src__renderer__extensions__vueNodes__widgets__composables__useFloatWidget.ts", + "license": "GPL-3.0", + "target_version_match": "unknown", + "reuse": "same frontend1.53.10 full commit, no core0.30.0 identity reused" + }, + { + "id": "frontend:src/renderer/extensions/vueNodes/widgets/composables/useIntWidget.ts", + "repository": "https://github.com/Comfy-Org/ComfyUI_frontend", + "commit": "743be3f4fe2e374b0ee39f0ded56e7cb65a837c5", + "tag": "v1.53.10", + "file": "src/renderer/extensions/vueNodes/widgets/composables/useIntWidget.ts", + "lines": [ + [ + 1, + 93 + ] + ], + "rule_locations": { + "control_after_generate@71": [ + 71, + 75 + ], + "control_after_generate@76": [ + 76, + 80 + ], + "control_after_generate@77": [ + 77, + 81 + ] + }, + "raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/743be3f4fe2e374b0ee39f0ded56e7cb65a837c5/src/renderer/extensions/vueNodes/widgets/composables/useIntWidget.ts", + "url": "https://github.com/Comfy-Org/ComfyUI_frontend/blob/743be3f4fe2e374b0ee39f0ded56e7cb65a837c5/src/renderer/extensions/vueNodes/widgets/composables/useIntWidget.ts", + "sha256": "8720d5a8194c9987eddbb42d0e925bcbb20e96e94f52c5f21750ba90b2113e02", + "retrieved_at": "2026-10-29T22:42:12.532829+00:00", + "local_file": "../h3-reference/frontend__src__renderer__extensions__vueNodes__widgets__composables__useIntWidget.ts", + "license": "GPL-3.0", + "target_version_match": "unknown", + "reuse": "same frontend1.53.10 full commit, no core0.30.0 identity reused" + }, + { + "id": "frontend:src/renderer/extensions/vueNodes/widgets/composables/useStringWidget.ts", + "repository": "https://github.com/Comfy-Org/ComfyUI_frontend", + "commit": "743be3f4fe2e374b0ee39f0ded56e7cb65a837c5", + "tag": "v1.53.10", + "file": "src/renderer/extensions/vueNodes/widgets/composables/useStringWidget.ts", + "lines": [ + [ + 1, + 102 + ] + ], + "rule_locations": {}, + "raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/743be3f4fe2e374b0ee39f0ded56e7cb65a837c5/src/renderer/extensions/vueNodes/widgets/composables/useStringWidget.ts", + "url": "https://github.com/Comfy-Org/ComfyUI_frontend/blob/743be3f4fe2e374b0ee39f0ded56e7cb65a837c5/src/renderer/extensions/vueNodes/widgets/composables/useStringWidget.ts", + "sha256": "7a463ecb0a34f6b7aa59ac6b81fb92a253c5681f88f0bec1c9c2accaa013d505", + "retrieved_at": "2026-10-29T22:42:12.732829+00:00", + "local_file": "../h3-reference/frontend__src__renderer__extensions__vueNodes__widgets__composables__useStringWidget.ts", + "license": "GPL-3.0", + "target_version_match": "unknown", + "reuse": "same frontend1.53.10 full commit, no core0.30.0 identity reused" + }, + { + "id": "frontend:src/scripts/app.ts", + "repository": "https://github.com/Comfy-Org/ComfyUI_frontend", + "commit": "743be3f4fe2e374b0ee39f0ded56e7cb65a837c5", + "tag": "v1.53.10", + "file": "src/scripts/app.ts", + "lines": [ + [ + 1, + 2602 + ] + ], + "rule_locations": { + "control_after_generate@1500": [ + 1500, + 1504 + ], + "onConfigure@934": [ + 934, + 938 + ], + "onConfigure@935": [ + 935, + 939 + ], + "onConfigure@936": [ + 936, + 940 + ], + "onConfigure@939": [ + 939, + 943 + ], + "onConfigure@941": [ + 941, + 945 + ], + "onNodeCreated@741": [ + 741, + 745 + ], + "onNodeCreated@2010": [ + 2010, + 2014 + ], + "onNodeCreated@2033": [ + 2033, + 2037 + ], + "onNodeCreated@2039": [ + 2039, + 2043 + ], + "registerExtension@2436": [ + 2436, + 2440 + ], + "registerExtension@2437": [ + 2437, + 2441 + ], + "widgets_values_named@2345": [ + 2345, + 2349 + ], + "beforeQueued@1758": [ + 1758, + 1762 + ], + "beforeQueued@1760": [ + 1760, + 1764 + ], + "afterQueued@1970": [ + 1970, + 1974 + ], + "afterQueued@1974": [ + 1974, + 1978 + ], + "Promise.all@1182": [ + 1182, + 1186 + ] + }, + "raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/743be3f4fe2e374b0ee39f0ded56e7cb65a837c5/src/scripts/app.ts", + "url": "https://github.com/Comfy-Org/ComfyUI_frontend/blob/743be3f4fe2e374b0ee39f0ded56e7cb65a837c5/src/scripts/app.ts", + "sha256": "ba650ea75b14affbdd1fbf4d821679d29dde59bd09986666a4734c8a160f7027", + "retrieved_at": "2026-10-29T22:42:13.096830+00:00", + "local_file": "../h3-reference/frontend__src__scripts__app.ts", + "license": "GPL-3.0", + "target_version_match": "unknown", + "reuse": "same frontend1.53.10 full commit, no core0.30.0 identity reused" + }, + { + "id": "frontend:src/scripts/valueControl.ts", + "repository": "https://github.com/Comfy-Org/ComfyUI_frontend", + "commit": "743be3f4fe2e374b0ee39f0ded56e7cb65a837c5", + "tag": "v1.53.10", + "file": "src/scripts/valueControl.ts", + "lines": [ + [ + 1, + 158 + ] + ], + "rule_locations": { + "beforeQueued@43": [ + 43, + 47 + ], + "afterQueued@44": [ + 44, + 48 + ], + "mode === 'fixed'@76": [ + 76, + 80 + ] + }, + "raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/743be3f4fe2e374b0ee39f0ded56e7cb65a837c5/src/scripts/valueControl.ts", + "url": "https://github.com/Comfy-Org/ComfyUI_frontend/blob/743be3f4fe2e374b0ee39f0ded56e7cb65a837c5/src/scripts/valueControl.ts", + "sha256": "007c7204d1fe88d156e07fee783a55e79fa7610e98a8a9f7761704a076a60458", + "retrieved_at": "2026-10-29T22:42:13.284830+00:00", + "local_file": "../h3-reference/frontend__src__scripts__valueControl.ts", + "license": "GPL-3.0", + "target_version_match": "unknown", + "reuse": "same frontend1.53.10 full commit, no core0.30.0 identity reused" + }, + { + "id": "frontend:src/scripts/widgets.ts", + "repository": "https://github.com/Comfy-Org/ComfyUI_frontend", + "commit": "743be3f4fe2e374b0ee39f0ded56e7cb65a837c5", + "tag": "v1.53.10", + "file": "src/scripts/widgets.ts", + "lines": [ + [ + 1, + 256 + ] + ], + "rule_locations": { + "control_after_generate@85": [ + 85, + 89 + ], + "control_after_generate@99": [ + 99, + 103 + ], + "control_after_generate@140": [ + 140, + 144 + ], + "serialize: false@145": [ + 145, + 149 + ], + "serialize: false@172": [ + 172, + 176 + ], + "beforeQueued@206": [ + 206, + 210 + ], + "afterQueued@216": [ + 216, + 220 + ] + }, + "raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/743be3f4fe2e374b0ee39f0ded56e7cb65a837c5/src/scripts/widgets.ts", + "url": "https://github.com/Comfy-Org/ComfyUI_frontend/blob/743be3f4fe2e374b0ee39f0ded56e7cb65a837c5/src/scripts/widgets.ts", + "sha256": "932a143a1a48c93aa3bee43b6dc3f932cd7f9a946802530650b4acdd41d36bd5", + "retrieved_at": "2026-10-29T22:42:13.480830+00:00", + "local_file": "../h3-reference/frontend__src__scripts__widgets.ts", + "license": "GPL-3.0", + "target_version_match": "unknown", + "reuse": "same frontend1.53.10 full commit, no core0.30.0 identity reused" + }, + { + "id": "frontend:src/services/extensionService.ts", + "repository": "https://github.com/Comfy-Org/ComfyUI_frontend", + "commit": "743be3f4fe2e374b0ee39f0ded56e7cb65a837c5", + "tag": "v1.53.10", + "file": "src/services/extensionService.ts", + "lines": [ + [ + 1, + 259 + ] + ], + "rule_locations": { + "registerExtension@74": [ + 74, + 78 + ], + "registerExtension@75": [ + 75, + 79 + ], + "registerExtension@88": [ + 88, + 92 + ], + "registerExtension@255": [ + 255, + 259 + ], + "Promise.all@55": [ + 55, + 59 + ], + "Promise.all@213": [ + 213, + 217 + ], + "import('../extensions/core/index')@53": [ + 53, + 57 + ] + }, + "raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/743be3f4fe2e374b0ee39f0ded56e7cb65a837c5/src/services/extensionService.ts", + "url": "https://github.com/Comfy-Org/ComfyUI_frontend/blob/743be3f4fe2e374b0ee39f0ded56e7cb65a837c5/src/services/extensionService.ts", + "sha256": "48997cd9726608e5483e44f4c1e9b7ce7183839deeb8393b861b7d631a43ff61", + "retrieved_at": "2026-10-29T22:42:13.672830+00:00", + "local_file": "../h3-reference/frontend__src__services__extensionService.ts", + "license": "GPL-3.0", + "target_version_match": "unknown", + "reuse": "same frontend1.53.10 full commit, no core0.30.0 identity reused" + }, + { + "id": "frontend:src/services/litegraphService.ts", + "repository": "https://github.com/Comfy-Org/ComfyUI_frontend", + "commit": "743be3f4fe2e374b0ee39f0ded56e7cb65a837c5", + "tag": "v1.53.10", + "file": "src/services/litegraphService.ts", + "lines": [ + [ + 1, + 1030 + ] + ], + "rule_locations": { + "migrateWidgetsValues@82": [ + 82, + 86 + ], + "migrateWidgetsValues@509": [ + 509, + 513 + ], + "migrateWidgetsValues@616": [ + 616, + 620 + ], + "for (const inputSpec of orderedInputSpecs)@362": [ + 362, + 366 + ], + "for (const inputSpec of orderedInputSpecs)@363": [ + 363, + 367 + ], + "getOrderedInputSpecs@84": [ + 84, + 88 + ], + "getOrderedInputSpecs@359": [ + 359, + 363 + ] + }, + "raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/743be3f4fe2e374b0ee39f0ded56e7cb65a837c5/src/services/litegraphService.ts", + "url": "https://github.com/Comfy-Org/ComfyUI_frontend/blob/743be3f4fe2e374b0ee39f0ded56e7cb65a837c5/src/services/litegraphService.ts", + "sha256": "84ffdeae56bc73065fd2a44ae924b6ab4fd48bb7e79a710210e858cce508784e", + "retrieved_at": "2026-10-29T22:42:13.876831+00:00", + "local_file": "../h3-reference/frontend__src__services__litegraphService.ts", + "license": "GPL-3.0", + "target_version_match": "unknown", + "reuse": "same frontend1.53.10 full commit, no core0.30.0 identity reused" + }, + { + "id": "frontend:src/stores/extensionStore.ts", + "repository": "https://github.com/Comfy-Org/ComfyUI_frontend", + "commit": "743be3f4fe2e374b0ee39f0ded56e7cb65a837c5", + "tag": "v1.53.10", + "file": "src/stores/extensionStore.ts", + "lines": [ + [ + 1, + 114 + ] + ], + "rule_locations": { + "registerExtension@58": [ + 58, + 62 + ], + "registerExtension@108": [ + 108, + 112 + ] + }, + "raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/743be3f4fe2e374b0ee39f0ded56e7cb65a837c5/src/stores/extensionStore.ts", + "url": "https://github.com/Comfy-Org/ComfyUI_frontend/blob/743be3f4fe2e374b0ee39f0ded56e7cb65a837c5/src/stores/extensionStore.ts", + "sha256": "9cd3261e0417d5334efa69a77266c6fdb1c53fb7f923a68457a65e47133af1a3", + "retrieved_at": "2026-10-29T22:42:14.068831+00:00", + "local_file": "../h3-reference/frontend__src__stores__extensionStore.ts", + "license": "GPL-3.0", + "target_version_match": "unknown", + "reuse": "same frontend1.53.10 full commit, no core0.30.0 identity reused" + }, + { + "id": "frontend:src/stores/widgetValueStore.ts", + "repository": "https://github.com/Comfy-Org/ComfyUI_frontend", + "commit": "743be3f4fe2e374b0ee39f0ded56e7cb65a837c5", + "tag": "v1.53.10", + "file": "src/stores/widgetValueStore.ts", + "lines": [ + [ + 1, + 465 + ] + ], + "rule_locations": { + "restoreNamed@24": [ + 24, + 28 + ], + "restoreNamed@83": [ + 83, + 87 + ], + "getRestoredWidgetValue@75": [ + 75, + 79 + ], + "getRestoredWidgetValue@448": [ + 448, + 452 + ] + }, + "raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/743be3f4fe2e374b0ee39f0ded56e7cb65a837c5/src/stores/widgetValueStore.ts", + "url": "https://github.com/Comfy-Org/ComfyUI_frontend/blob/743be3f4fe2e374b0ee39f0ded56e7cb65a837c5/src/stores/widgetValueStore.ts", + "sha256": "ecf18bbc714070a7e67a00599ae09b711d1b6eebf5675dd7a6d56ef6d3a3e40a", + "retrieved_at": "2026-10-29T22:42:14.260831+00:00", + "local_file": "../h3-reference/frontend__src__stores__widgetValueStore.ts", + "license": "GPL-3.0", + "target_version_match": "unknown", + "reuse": "same frontend1.53.10 full commit, no core0.30.0 identity reused" + }, + { + "id": "frontend:src/utils/executionUtil.ts", + "repository": "https://github.com/Comfy-Org/ComfyUI_frontend", + "commit": "743be3f4fe2e374b0ee39f0ded56e7cb65a837c5", + "tag": "v1.53.10", + "file": "src/utils/executionUtil.ts", + "lines": [ + [ + 1, + 192 + ] + ], + "rule_locations": { + "serializeValue@134": [ + 134, + 138 + ], + "serializeValue@135": [ + 135, + 139 + ], + "widget.options?.serialize@132": [ + 132, + 136 + ], + "inputs[input.name] =@159": [ + 159, + 163 + ], + "inputs[input.name] =@163": [ + 163, + 167 + ] + }, + "raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/743be3f4fe2e374b0ee39f0ded56e7cb65a837c5/src/utils/executionUtil.ts", + "url": "https://github.com/Comfy-Org/ComfyUI_frontend/blob/743be3f4fe2e374b0ee39f0ded56e7cb65a837c5/src/utils/executionUtil.ts", + "sha256": "b29fd312e66c7415fa4c720654ac121dc67600b0c1fedf079b6575a174960698", + "retrieved_at": "2026-10-29T22:42:14.456831+00:00", + "local_file": "../h3-reference/frontend__src__utils__executionUtil.ts", + "license": "GPL-3.0", + "target_version_match": "unknown", + "reuse": "same frontend1.53.10 full commit, no core0.30.0 identity reused" + }, + { + "id": "frontend:src/utils/litegraphUtil.ts", + "repository": "https://github.com/Comfy-Org/ComfyUI_frontend", + "commit": "743be3f4fe2e374b0ee39f0ded56e7cb65a837c5", + "tag": "v1.53.10", + "file": "src/utils/litegraphUtil.ts", + "lines": [ + [ + 1, + 389 + ] + ], + "rule_locations": { + "control_after_generate@210": [ + 210, + 214 + ], + "migrateWidgetsValues@199": [ + 199, + 203 + ], + "beforeQueued@178": [ + 178, + 182 + ], + "afterQueued@178": [ + 178, + 182 + ] + }, + "raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/743be3f4fe2e374b0ee39f0ded56e7cb65a837c5/src/utils/litegraphUtil.ts", + "url": "https://github.com/Comfy-Org/ComfyUI_frontend/blob/743be3f4fe2e374b0ee39f0ded56e7cb65a837c5/src/utils/litegraphUtil.ts", + "sha256": "a53156165b73ab9f35435f2c5041b004cd8529602f4a54831bc74b86ac889dea", + "retrieved_at": "2026-10-29T22:42:14.836832+00:00", + "local_file": "../h3-reference/frontend__src__utils__litegraphUtil.ts", + "license": "GPL-3.0", + "target_version_match": "unknown", + "reuse": "same frontend1.53.10 full commit, no core0.30.0 identity reused" + }, + { + "id": "frontend:src/workbench/utils/nodeDefOrderingUtil.ts", + "repository": "https://github.com/Comfy-Org/ComfyUI_frontend", + "commit": "743be3f4fe2e374b0ee39f0ded56e7cb65a837c5", + "tag": "v1.53.10", + "file": "src/workbench/utils/nodeDefOrderingUtil.ts", + "lines": [ + [ + 1, + 108 + ] + ], + "rule_locations": { + "getOrderedInputSpecs@13": [ + 13, + 17 + ] + }, + "raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/743be3f4fe2e374b0ee39f0ded56e7cb65a837c5/src/workbench/utils/nodeDefOrderingUtil.ts", + "url": "https://github.com/Comfy-Org/ComfyUI_frontend/blob/743be3f4fe2e374b0ee39f0ded56e7cb65a837c5/src/workbench/utils/nodeDefOrderingUtil.ts", + "sha256": "27e98379fef3cb7158b2968d1b920ff16db662e4e0c5252ed62c7c7edc6f2227", + "retrieved_at": "2026-10-29T22:42:15.268832+00:00", + "local_file": "../h3-reference/frontend__src__workbench__utils__nodeDefOrderingUtil.ts", + "license": "GPL-3.0", + "target_version_match": "unknown", + "reuse": "same frontend1.53.10 full commit, no core0.30.0 identity reused" + }, + { + "id": "core:LICENSE", + "repository": "https://github.com/Comfy-Org/ComfyUI", + "commit": "2f35f4a08176d993cded35dac3332be4f7287f41", + "tag": "v0.33.0", + "file": "LICENSE", + "lines": [ + [ + 1, + 674 + ] + ], + "rule_locations": {}, + "raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI/2f35f4a08176d993cded35dac3332be4f7287f41/LICENSE", + "url": "https://github.com/Comfy-Org/ComfyUI/blob/2f35f4a08176d993cded35dac3332be4f7287f41/LICENSE", + "sha256": "3972dc9744f6499f0f9b2dbf76696f2ae7ad8af9b23dde66d6af86c9dfb36986", + "local_file": "core__LICENSE", + "license": "GPL-3.0", + "target_version_match": "unknown" + }, + { + "id": "core:comfy/samplers.py", + "repository": "https://github.com/Comfy-Org/ComfyUI", + "commit": "2f35f4a08176d993cded35dac3332be4f7287f41", + "tag": "v0.33.0", + "file": "comfy/samplers.py", + "lines": [ + [ + 1, + 1463 + ] + ], + "rule_locations": { + "SCHEDULER_HANDLERS =@1365": [ + 1365, + 1369 + ], + "SCHEDULER_NAMES =@1376": [ + 1376, + 1380 + ] + }, + "raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI/2f35f4a08176d993cded35dac3332be4f7287f41/comfy/samplers.py", + "url": "https://github.com/Comfy-Org/ComfyUI/blob/2f35f4a08176d993cded35dac3332be4f7287f41/comfy/samplers.py", + "sha256": "69498999dd1198c05fa64fa2a7b7090d21090c470d2304191e483a0543fcefd2", + "local_file": "core__comfy__samplers.py", + "license": "GPL-3.0", + "target_version_match": "unknown" + }, + { + "id": "core:comfy_api/latest/_io.py", + "repository": "https://github.com/Comfy-Org/ComfyUI", + "commit": "2f35f4a08176d993cded35dac3332be4f7287f41", + "tag": "v0.33.0", + "file": "comfy_api/latest/_io.py", + "lines": [ + [ + 1, + 2497 + ] + ], + "rule_locations": { + "class Float@294": [ + 294, + 298 + ], + "def define_schema@1925": [ + 1925, + 1929 + ], + "def define_schema@2238": [ + 2238, + 2242 + ], + "class MultiType@958": [ + 958, + 962 + ], + "class Autogrow@1083": [ + 1083, + 1087 + ], + "class TemplateNames@1136": [ + 1136, + 1140 + ], + "def as_dict@63": [ + 63, + 67 + ], + "def as_dict@175": [ + 175, + 179 + ], + "def as_dict@204": [ + 204, + 208 + ], + "def as_dict@224": [ + 224, + 228 + ], + "def as_dict@261": [ + 261, + 265 + ], + "def as_dict@284": [ + 284, + 288 + ], + "def as_dict@312": [ + 312, + 316 + ], + "def as_dict@337": [ + 337, + 341 + ], + "def as_dict@381": [ + 381, + 385 + ], + "def as_dict@410": [ + 410, + 414 + ], + "def as_dict@1000": [ + 1000, + 1004 + ], + "def as_dict@1023": [ + 1023, + 1027 + ], + "def as_dict@1035": [ + 1035, + 1039 + ], + "def as_dict@1048": [ + 1048, + 1052 + ], + "def as_dict@1109": [ + 1109, + 1113 + ], + "def as_dict@1129": [ + 1129, + 1133 + ], + "def as_dict@1144": [ + 1144, + 1148 + ], + "def as_dict@1156": [ + 1156, + 1160 + ], + "def as_dict@1228": [ + 1228, + 1232 + ], + "def as_dict@1243": [ + 1243, + 1247 + ], + "def as_dict@1297": [ + 1297, + 1301 + ], + "def as_dict@1328": [ + 1328, + 1332 + ], + "def as_dict@1342": [ + 1342, + 1346 + ], + "def as_dict@1376": [ + 1376, + 1380 + ], + "def as_dict@1398": [ + 1398, + 1402 + ], + "def as_dict@1451": [ + 1451, + 1455 + ], + "def as_dict@1592": [ + 1592, + 1596 + ], + "def as_dict@1634": [ + 1634, + 1638 + ], + "def as_dict@2319": [ + 2319, + 2323 + ], + "def as_dict@2374": [ + 2374, + 2378 + ], + "def _expand_schema_for_dynamic@1168": [ + 1168, + 1172 + ], + "def _expand_schema_for_dynamic@1255": [ + 1255, + 1259 + ], + "def _expand_schema_for_dynamic@1310": [ + 1310, + 1314 + ], + "node_id@1646": [ + 1646, + 1650 + ], + "node_id@1805": [ + 1805, + 1809 + ], + "node_id@2352": [ + 2352, + 2356 + ], + "node_id@2353": [ + 2353, + 2357 + ], + "node_id@2362": [ + 2362, + 2366 + ], + "node_id@2363": [ + 2363, + 2367 + ], + "node_id@2368": [ + 2368, + 2372 + ], + "node_id@2369": [ + 2369, + 2373 + ], + "node_id@2377": [ + 2377, + 2381 + ], + "node_id@2378": [ + 2378, + 2382 + ], + "def execute@1931": [ + 1931, + 1935 + ], + "def execute@2244": [ + 2244, + 2248 + ], + "control_after_generate@274": [ + 274, + 278 + ], + "control_after_generate@280": [ + 280, + 284 + ], + "control_after_generate@289": [ + 289, + 293 + ], + "control_after_generate@359": [ + 359, + 363 + ], + "control_after_generate@375": [ + 375, + 379 + ], + "control_after_generate@385": [ + 385, + 389 + ], + "control_after_generate@402": [ + 402, + 406 + ], + "control_after_generate@404": [ + 404, + 408 + ] + }, + "raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI/2f35f4a08176d993cded35dac3332be4f7287f41/comfy_api/latest/_io.py", + "url": "https://github.com/Comfy-Org/ComfyUI/blob/2f35f4a08176d993cded35dac3332be4f7287f41/comfy_api/latest/_io.py", + "sha256": "495aefa059aad4eed4181aa7fbb415679d3f269651e9fc6f542bdac1b99dd40f", + "local_file": "core__comfy_api__latest___io.py", + "license": "GPL-3.0", + "target_version_match": "unknown" + }, + { + "id": "core:comfy_extras/nodes_custom_sampler.py", + "repository": "https://github.com/Comfy-Org/ComfyUI", + "commit": "2f35f4a08176d993cded35dac3332be4f7287f41", + "tag": "v0.33.0", + "file": "comfy_extras/nodes_custom_sampler.py", + "lines": [ + [ + 1, + 1232 + ] + ], + "rule_locations": { + "class RandomNoise@1003": [ + 1003, + 1007 + ], + "class BasicScheduler@17": [ + 17, + 21 + ], + "def define_schema@19": [ + 19, + 23 + ], + "def define_schema@49": [ + 49, + 53 + ], + "def define_schema@71": [ + 71, + 75 + ], + "def define_schema@92": [ + 92, + 96 + ], + "def define_schema@114": [ + 114, + 118 + ], + "def define_schema@138": [ + 138, + 142 + ], + "def define_schema@162": [ + 162, + 166 + ], + "def define_schema@184": [ + 184, + 188 + ], + "def define_schema@206": [ + 206, + 210 + ], + "def define_schema@230": [ + 230, + 234 + ], + "def define_schema@256": [ + 256, + 260 + ], + "def define_schema@278": [ + 278, + 282 + ], + "def define_schema@299": [ + 299, + 303 + ], + "def define_schema@353": [ + 353, + 357 + ], + "def define_schema@381": [ + 381, + 385 + ], + "def define_schema@398": [ + 398, + 402 + ], + "def define_schema@423": [ + 423, + 427 + ], + "def define_schema@450": [ + 450, + 454 + ], + "def define_schema@476": [ + 476, + 480 + ], + "def define_schema@496": [ + 496, + 500 + ], + "def define_schema@516": [ + 516, + 520 + ], + "def define_schema@539": [ + 539, + 543 + ], + "def define_schema@556": [ + 556, + 560 + ], + "def define_schema@587": [ + 587, + 591 + ], + "def define_schema@638": [ + 638, + 642 + ], + "def define_schema@683": [ + 683, + 687 + ], + "def define_schema@735": [ + 735, + 739 + ], + "def define_schema@803": [ + 803, + 807 + ], + "def define_schema@825": [ + 825, + 829 + ], + "def define_schema@879": [ + 879, + 883 + ], + "def define_schema@957": [ + 957, + 961 + ], + "def define_schema@987": [ + 987, + 991 + ], + "def define_schema@1005": [ + 1005, + 1009 + ], + "def define_schema@1022": [ + 1022, + 1026 + ], + "def define_schema@1078": [ + 1078, + 1082 + ], + "def define_schema@1127": [ + 1127, + 1131 + ], + "def define_schema@1148": [ + 1148, + 1152 + ], + "async def get_node_list@1189": [ + 1189, + 1193 + ], + "async def comfy_entrypoint@1231": [ + 1231, + 1232 + ], + "node_id@21": [ + 21, + 25 + ], + "node_id@51": [ + 51, + 55 + ], + "node_id@73": [ + 73, + 77 + ], + "node_id@94": [ + 94, + 98 + ], + "node_id@116": [ + 116, + 120 + ], + "node_id@140": [ + 140, + 144 + ], + "node_id@164": [ + 164, + 168 + ], + "node_id@186": [ + 186, + 190 + ], + "node_id@208": [ + 208, + 212 + ], + "node_id@232": [ + 232, + 236 + ], + "node_id@258": [ + 258, + 262 + ], + "node_id@280": [ + 280, + 284 + ], + "node_id@301": [ + 301, + 305 + ], + "node_id@355": [ + 355, + 359 + ], + "node_id@383": [ + 383, + 387 + ], + "node_id@400": [ + 400, + 404 + ], + "node_id@425": [ + 425, + 429 + ], + "node_id@452": [ + 452, + 456 + ], + "node_id@478": [ + 478, + 482 + ], + "node_id@498": [ + 498, + 502 + ], + "node_id@518": [ + 518, + 522 + ], + "node_id@541": [ + 541, + 545 + ], + "node_id@558": [ + 558, + 562 + ], + "node_id@589": [ + 589, + 593 + ], + "node_id@640": [ + 640, + 644 + ], + "node_id@685": [ + 685, + 689 + ], + "node_id@737": [ + 737, + 741 + ], + "node_id@805": [ + 805, + 809 + ], + "node_id@827": [ + 827, + 831 + ], + "node_id@881": [ + 881, + 885 + ], + "node_id@959": [ + 959, + 963 + ], + "node_id@989": [ + 989, + 993 + ], + "node_id@1007": [ + 1007, + 1011 + ], + "node_id@1024": [ + 1024, + 1028 + ], + "node_id@1080": [ + 1080, + 1084 + ], + "node_id@1129": [ + 1129, + 1133 + ], + "node_id@1150": [ + 1150, + 1154 + ], + "def execute@33": [ + 33, + 37 + ], + "def execute@63": [ + 63, + 67 + ], + "def execute@84": [ + 84, + 88 + ], + "def execute@106": [ + 106, + 110 + ], + "def execute@129": [ + 129, + 133 + ], + "def execute@151": [ + 151, + 155 + ], + "def execute@176": [ + 176, + 180 + ], + "def execute@198": [ + 198, + 202 + ], + "def execute@221": [ + 221, + 225 + ], + "def execute@245": [ + 245, + 249 + ], + "def execute@265": [ + 265, + 269 + ], + "def execute@290": [ + 290, + 294 + ], + "def execute@315": [ + 315, + 319 + ], + "def execute@366": [ + 366, + 370 + ], + "def execute@390": [ + 390, + 394 + ], + "def execute@411": [ + 411, + 415 + ], + "def execute@437": [ + 437, + 441 + ], + "def execute@464": [ + 464, + 468 + ], + "def execute@488": [ + 488, + 492 + ], + "def execute@508": [ + 508, + 512 + ], + "def execute@529": [ + 529, + 533 + ], + "def execute@548": [ + 548, + 552 + ], + "def execute@576": [ + 576, + 580 + ], + "def execute@601": [ + 601, + 605 + ], + "def execute@658": [ + 658, + 662 + ], + "def execute@707": [ + 707, + 711 + ], + "def execute@757": [ + 757, + 761 + ], + "def execute@816": [ + 816, + 820 + ], + "def execute@840": [ + 840, + 844 + ], + "def execute@898": [ + 898, + 902 + ], + "def execute@974": [ + 974, + 978 + ], + "def execute@997": [ + 997, + 1001 + ], + "def execute@1014": [ + 1014, + 1018 + ], + "def execute@1040": [ + 1040, + 1044 + ], + "def execute@1095": [ + 1095, + 1099 + ], + "def execute@1140": [ + 1140, + 1144 + ], + "def execute@1165": [ + 1165, + 1169 + ], + "noise_seed@742": [ + 742, + 746 + ], + "noise_seed@757": [ + 757, + 761 + ], + "noise_seed@767": [ + 767, + 771 + ], + "noise_seed@777": [ + 777, + 781 + ], + "noise_seed@1009": [ + 1009, + 1013 + ], + "noise_seed@1014": [ + 1014, + 1018 + ], + "noise_seed@1015": [ + 1015, + 1019 + ], + "control_after_generate@742": [ + 742, + 746 + ], + "control_after_generate@1009": [ + 1009, + 1013 + ] + }, + "raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI/2f35f4a08176d993cded35dac3332be4f7287f41/comfy_extras/nodes_custom_sampler.py", + "url": "https://github.com/Comfy-Org/ComfyUI/blob/2f35f4a08176d993cded35dac3332be4f7287f41/comfy_extras/nodes_custom_sampler.py", + "sha256": "b0ba1521c72475e06fed15db004274ed7c8bb2bf73f1d58849faf6f9f9d264fe", + "local_file": "core__comfy_extras__nodes_custom_sampler.py", + "license": "GPL-3.0", + "target_version_match": "unknown" + }, + { + "id": "core:comfy_extras/nodes_math.py", + "repository": "https://github.com/Comfy-Org/ComfyUI", + "commit": "2f35f4a08176d993cded35dac3332be4f7287f41", + "tag": "v0.33.0", + "file": "comfy_extras/nodes_math.py", + "lines": [ + [ + 1, + 126 + ] + ], + "rule_locations": { + "class MathExpressionNode@59": [ + 59, + 63 + ], + "def define_schema@63": [ + 63, + 67 + ], + "async def get_node_list@121": [ + 121, + 125 + ], + "async def comfy_entrypoint@125": [ + 125, + 126 + ], + "node_id@70": [ + 70, + 74 + ], + "def execute@89": [ + 89, + 93 + ] + }, + "raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI/2f35f4a08176d993cded35dac3332be4f7287f41/comfy_extras/nodes_math.py", + "url": "https://github.com/Comfy-Org/ComfyUI/blob/2f35f4a08176d993cded35dac3332be4f7287f41/comfy_extras/nodes_math.py", + "sha256": "b117db3e5eadf7e1689a7a2edaad9436bb6282ab3d57865ec2cd78004de9fb88", + "local_file": "core__comfy_extras__nodes_math.py", + "license": "GPL-3.0", + "target_version_match": "unknown" + }, + { + "id": "core:comfy_extras/nodes_primitive.py", + "repository": "https://github.com/Comfy-Org/ComfyUI", + "commit": "2f35f4a08176d993cded35dac3332be4f7287f41", + "tag": "v0.33.0", + "file": "comfy_extras/nodes_primitive.py", + "lines": [ + [ + 1, + 108 + ] + ], + "rule_locations": { + "class StringMultiline@24": [ + 24, + 28 + ], + "class Float@60": [ + 60, + 64 + ], + "def define_schema@9": [ + 9, + 13 + ], + "def define_schema@26": [ + 26, + 30 + ], + "def define_schema@44": [ + 44, + 48 + ], + "def define_schema@62": [ + 62, + 66 + ], + "def define_schema@80": [ + 80, + 84 + ], + "async def get_node_list@98": [ + 98, + 102 + ], + "async def comfy_entrypoint@107": [ + 107, + 108 + ], + "node_id@11": [ + 11, + 15 + ], + "node_id@28": [ + 28, + 32 + ], + "node_id@46": [ + 46, + 50 + ], + "node_id@64": [ + 64, + 68 + ], + "node_id@82": [ + 82, + 86 + ], + "def execute@20": [ + 20, + 24 + ], + "def execute@38": [ + 38, + 42 + ], + "def execute@56": [ + 56, + 60 + ], + "def execute@74": [ + 74, + 78 + ], + "def execute@92": [ + 92, + 96 + ], + "control_after_generate@50": [ + 50, + 54 + ] + }, + "raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI/2f35f4a08176d993cded35dac3332be4f7287f41/comfy_extras/nodes_primitive.py", + "url": "https://github.com/Comfy-Org/ComfyUI/blob/2f35f4a08176d993cded35dac3332be4f7287f41/comfy_extras/nodes_primitive.py", + "sha256": "ee3882214ebdd0d20c8061691075cebb1642c303e162f6d22ae525d75aa59b2d", + "local_file": "core__comfy_extras__nodes_primitive.py", + "license": "GPL-3.0", + "target_version_match": "unknown" + }, + { + "id": "core:comfy_extras/nodes_resolution.py", + "repository": "https://github.com/Comfy-Org/ComfyUI", + "commit": "2f35f4a08176d993cded35dac3332be4f7287f41", + "tag": "v0.33.0", + "file": "comfy_extras/nodes_resolution.py", + "lines": [ + [ + 1, + 94 + ] + ], + "rule_locations": { + "class ResolutionSelector@30": [ + 30, + 34 + ], + "class AspectRatio@7": [ + 7, + 11 + ], + "def define_schema@34": [ + 34, + 38 + ], + "async def get_node_list@87": [ + 87, + 91 + ], + "async def comfy_entrypoint@93": [ + 93, + 94 + ], + "node_id@36": [ + 36, + 40 + ], + "def execute@76": [ + 76, + 80 + ] + }, + "raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI/2f35f4a08176d993cded35dac3332be4f7287f41/comfy_extras/nodes_resolution.py", + "url": "https://github.com/Comfy-Org/ComfyUI/blob/2f35f4a08176d993cded35dac3332be4f7287f41/comfy_extras/nodes_resolution.py", + "sha256": "2c6ca2d3d91a7f2945642729233ab015983a574d53a50a91caff60aa9b950090", + "local_file": "core__comfy_extras__nodes_resolution.py", + "license": "GPL-3.0", + "target_version_match": "unknown" + }, + { + "id": "core:nodes.py", + "repository": "https://github.com/Comfy-Org/ComfyUI", + "commit": "2f35f4a08176d993cded35dac3332be4f7287f41", + "tag": "v0.33.0", + "file": "nodes.py", + "lines": [ + [ + 1, + 2595 + ] + ], + "rule_locations": { + "node_id@2322": [ + 2322, + 2326 + ], + "node_id@2323": [ + 2323, + 2327 + ], + "node_id@2326": [ + 2326, + 2330 + ], + "get_node_list()@2315": [ + 2315, + 2319 + ], + "schema.node_id@2322": [ + 2322, + 2326 + ], + "schema.node_id@2323": [ + 2323, + 2327 + ], + "schema.node_id@2326": [ + 2326, + 2330 + ], + "nodes_primitive.py@2468": [ + 2468, + 2472 + ], + "nodes_resolution.py@2493": [ + 2493, + 2497 + ], + "nodes_math.py@2509": [ + 2509, + 2513 + ], + "nodes_custom_sampler.py@2413": [ + 2413, + 2417 + ], + "noise_seed@1631": [ + 1631, + 1635 + ], + "noise_seed@1650": [ + 1650, + 1654 + ], + "noise_seed@1657": [ + 1657, + 1661 + ], + "control_after_generate@1602": [ + 1602, + 1606 + ], + "control_after_generate@1631": [ + 1631, + 1635 + ], + "RESOLUTION@54": [ + 54, + 58 + ], + "RESOLUTION@191": [ + 191, + 195 + ], + "RESOLUTION@192": [ + 192, + 196 + ], + "RESOLUTION@193": [ + 193, + 197 + ], + "RESOLUTION@194": [ + 194, + 198 + ], + "RESOLUTION@1221": [ + 1221, + 1225 + ], + "RESOLUTION@1222": [ + 1222, + 1226 + ], + "RESOLUTION@1223": [ + 1223, + 1227 + ], + "RESOLUTION@1224": [ + 1224, + 1228 + ], + "RESOLUTION@1250": [ + 1250, + 1254 + ], + "RESOLUTION@1251": [ + 1251, + 1255 + ], + "RESOLUTION@1274": [ + 1274, + 1278 + ], + "RESOLUTION@1341": [ + 1341, + 1345 + ], + "RESOLUTION@1342": [ + 1342, + 1346 + ], + "RESOLUTION@1442": [ + 1442, + 1446 + ], + "RESOLUTION@1443": [ + 1443, + 1447 + ], + "RESOLUTION@1444": [ + 1444, + 1448 + ], + "RESOLUTION@1528": [ + 1528, + 1532 + ], + "RESOLUTION@1529": [ + 1529, + 1533 + ], + "RESOLUTION@1530": [ + 1530, + 1534 + ], + "RESOLUTION@1531": [ + 1531, + 1535 + ], + "RESOLUTION@1889": [ + 1889, + 1893 + ], + "RESOLUTION@1890": [ + 1890, + 1894 + ], + "RESOLUTION@1982": [ + 1982, + 1986 + ], + "RESOLUTION@1983": [ + 1983, + 1987 + ], + "RESOLUTION@2008": [ + 2008, + 2012 + ], + "RESOLUTION@2009": [ + 2009, + 2013 + ], + "RESOLUTION@2010": [ + 2010, + 2014 + ], + "RESOLUTION@2011": [ + 2011, + 2015 + ], + "RESOLUTION@2012": [ + 2012, + 2016 + ] + }, + "raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI/2f35f4a08176d993cded35dac3332be4f7287f41/nodes.py", + "url": "https://github.com/Comfy-Org/ComfyUI/blob/2f35f4a08176d993cded35dac3332be4f7287f41/nodes.py", + "sha256": "38f918673c5300bc2d355e02f1131a7b1f97548337e7623754dafaea412008e8", + "local_file": "core__nodes.py", + "license": "GPL-3.0", + "target_version_match": "unknown" + }, + { + "id": "core:server.py", + "repository": "https://github.com/Comfy-Org/ComfyUI", + "commit": "2f35f4a08176d993cded35dac3332be4f7287f41", + "tag": "v0.33.0", + "file": "server.py", + "lines": [ + [ + 1, + 1479 + ] + ], + "rule_locations": { + "node_id@264": [ + 264, + 268 + ], + "node_id@289": [ + 289, + 293 + ], + "node_id@290": [ + 290, + 294 + ], + "node_id@1470": [ + 1470, + 1474 + ], + "node_id@1474": [ + 1474, + 1478 + ], + "node_id@1476": [ + 1476, + 1479 + ], + "node_id@1477": [ + 1477, + 1479 + ] + }, + "raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI/2f35f4a08176d993cded35dac3332be4f7287f41/server.py", + "url": "https://github.com/Comfy-Org/ComfyUI/blob/2f35f4a08176d993cded35dac3332be4f7287f41/server.py", + "sha256": "74573b10465505b88b618da86059878e3a56418f84c7dae4073c8824aee35a6c", + "local_file": "core__server.py", + "license": "GPL-3.0", + "target_version_match": "unknown" + }, + { + "id": "frontend:src/renderer/extensions/vueNodes/widgets/components/WidgetResolutionPreview.vue", + "repository": "https://github.com/Comfy-Org/ComfyUI_frontend", + "commit": "743be3f4fe2e374b0ee39f0ded56e7cb65a837c5", + "tag": "v1.53.10", + "file": "src/renderer/extensions/vueNodes/widgets/components/WidgetResolutionPreview.vue", + "lines": [ + [ + 1, + 106 + ] + ], + "rule_locations": { + "nodes_resolution.py@65": [ + 65, + 69 + ] + }, + "raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/743be3f4fe2e374b0ee39f0ded56e7cb65a837c5/src/renderer/extensions/vueNodes/widgets/components/WidgetResolutionPreview.vue", + "url": "https://github.com/Comfy-Org/ComfyUI_frontend/blob/743be3f4fe2e374b0ee39f0ded56e7cb65a837c5/src/renderer/extensions/vueNodes/widgets/components/WidgetResolutionPreview.vue", + "sha256": "453ca63d6aa986e57967bd4cd05a83a343a242636faf303d445dd51ca869f50f", + "local_file": "frontend__src__renderer__extensions__vueNodes__widgets__components__WidgetResolutionPreview.vue", + "license": "GPL-3.0", + "target_version_match": "unknown" + }, + { + "id": "frontend:src/renderer/extensions/vueNodes/widgets/composables/useResolutionPreviewWidget.ts", + "repository": "https://github.com/Comfy-Org/ComfyUI_frontend", + "commit": "743be3f4fe2e374b0ee39f0ded56e7cb65a837c5", + "tag": "v1.53.10", + "file": "src/renderer/extensions/vueNodes/widgets/composables/useResolutionPreviewWidget.ts", + "lines": [ + [ + 1, + 35 + ] + ], + "rule_locations": { + "serialize: false@17": [ + 17, + 21 + ] + }, + "raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/743be3f4fe2e374b0ee39f0ded56e7cb65a837c5/src/renderer/extensions/vueNodes/widgets/composables/useResolutionPreviewWidget.ts", + "url": "https://github.com/Comfy-Org/ComfyUI_frontend/blob/743be3f4fe2e374b0ee39f0ded56e7cb65a837c5/src/renderer/extensions/vueNodes/widgets/composables/useResolutionPreviewWidget.ts", + "sha256": "4316e8869b8673488ea9b136dbd4027160626c53cab9372fa1ca7aab059cf124", + "local_file": "frontend__src__renderer__extensions__vueNodes__widgets__composables__useResolutionPreviewWidget.ts", + "license": "GPL-3.0", + "target_version_match": "unknown" + }, + { + "id": "frontend:src/schemas/nodeDefSchema.ts", + "repository": "https://github.com/Comfy-Org/ComfyUI_frontend", + "commit": "743be3f4fe2e374b0ee39f0ded56e7cb65a837c5", + "tag": "v1.53.10", + "file": "src/schemas/nodeDefSchema.ts", + "lines": [ + [ + 1, + 1 + ] + ], + "rule_locations": {}, + "raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/743be3f4fe2e374b0ee39f0ded56e7cb65a837c5/src/schemas/nodeDefSchema.ts", + "url": "https://github.com/Comfy-Org/ComfyUI_frontend/blob/743be3f4fe2e374b0ee39f0ded56e7cb65a837c5/src/schemas/nodeDefSchema.ts", + "sha256": "70157c929336212ed1c7ea7e2b774c391b2466c2eaf99d441dd3b6af50e2b8b5", + "local_file": "frontend__src__schemas__nodeDefSchema.ts", + "license": "GPL-3.0", + "target_version_match": "unknown" + }, + { + "id": "frontend:src/schemas/nodeDef/migration.ts", + "repository": "https://github.com/Comfy-Org/ComfyUI_frontend", + "commit": "743be3f4fe2e374b0ee39f0ded56e7cb65a837c5", + "tag": "v1.53.10", + "file": "src/schemas/nodeDef/migration.ts", + "lines": [ + [ + 1, + 143 + ] + ], + "rule_locations": {}, + "raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/743be3f4fe2e374b0ee39f0ded56e7cb65a837c5/src/schemas/nodeDef/migration.ts", + "url": "https://github.com/Comfy-Org/ComfyUI_frontend/blob/743be3f4fe2e374b0ee39f0ded56e7cb65a837c5/src/schemas/nodeDef/migration.ts", + "sha256": "ae357da184625b93c492c0b73ce9bd2f3b49d158ca19a2944c6500f924a7a533", + "local_file": "frontend__src__schemas__nodeDef__migration.ts", + "license": "GPL-3.0", + "target_version_match": "unknown" + } + ], + "identity_observations": [ + { + "id": "core-tag", + "raw_url": "https://api.github.com/repos/Comfy-Org/ComfyUI/git/ref/tags/v0.33.0", + "local_file": "core-tag.json", + "sha256": "17b7e8adb8c4ca6a06be1d6c540e52735c61c8a18dbdf0d40d467e67a161e2e6", + "ref": "refs/tags/v0.33.0", + "commit": "2f35f4a08176d993cded35dac3332be4f7287f41" + }, + { + "id": "frontend-tag", + "raw_url": "https://api.github.com/repos/Comfy-Org/ComfyUI_frontend/git/ref/tags/v1.53.10", + "local_file": "../h3-reference/ComfyUI_frontend-tag.json", + "sha256": "f7075151c00a25e083c709273050c53b65cd6f1f3f4598f171fed3d486d046f2", + "ref": "refs/tags/v1.53.10", + "commit": "743be3f4fe2e374b0ee39f0ded56e7cb65a837c5" + } + ], + "target_installation": "unknown", + "source_graph_identity": "unknown", + "upstream_code_executed": false +} diff --git a/docs/hel-892/h3-core-reference/verify_identity.py b/docs/hel-892/h3-core-reference/verify_identity.py new file mode 100644 index 00000000..9e78718f --- /dev/null +++ b/docs/hel-892/h3-core-reference/verify_identity.py @@ -0,0 +1,47 @@ +"""Recheck mutable tag identity fields; byte SHA is only the saved observation.""" + +import hashlib +import json +from pathlib import Path +from urllib.request import urlopen + +ROOT = Path(__file__).resolve().parent + + +def main(): + manifest = json.loads((ROOT / "sources.json").read_bytes()) + rows = [] + for entry in manifest["identity_observations"]: + raw = (ROOT / entry["local_file"]).read_bytes() + assert hashlib.sha256(raw).hexdigest() == entry["sha256"] + with urlopen(entry["raw_url"], timeout=30) as response: + now = json.loads(response.read()) + assert now["ref"] == entry["ref"] and now["object"]["type"] == "commit" + assert now["object"]["sha"] == entry["commit"] + rows.append( + { + "id": entry["id"], + "url": entry["raw_url"], + "ref": now["ref"], + "commit": now["object"]["sha"], + "saved_observation_sha256": entry["sha256"], + "byte_identity_required": False, + } + ) + (ROOT.parent / "h3-core-evidence/identity-refetched.json").write_text( + json.dumps( + { + "observations": rows, + "target_installation": "unknown", + "source_graph_identity": "unknown", + "upstream_executed": False, + }, + ensure_ascii=False, + indent=2, + ) + + "\n" + ) + + +if __name__ == "__main__": + main()