HEL-892: add pinned frontend 1.41.20 grid reference conversion
Co-authored-by: multica-agent <github@multica.ai>
This commit is contained in:
@@ -40,6 +40,7 @@ from calliope.comfyui.serialization_reference import (
|
||||
serialize_reference_widgets,
|
||||
)
|
||||
from calliope.comfyui.structure_reference import (
|
||||
GRID_PROFILE,
|
||||
PROMOTED_PROFILES,
|
||||
SCAIL_LOAD_PROFILES,
|
||||
SETGET_COMMIT,
|
||||
@@ -303,6 +304,7 @@ REFERENCE_PROFILES = (
|
||||
*SETGET_PROFILES,
|
||||
*VIDEOINFO_PROFILES,
|
||||
*SCAIL_LOAD_PROFILES,
|
||||
GRID_PROFILE,
|
||||
)
|
||||
|
||||
|
||||
@@ -499,11 +501,62 @@ def vhs_field_evidence(source, prompt):
|
||||
return fields
|
||||
|
||||
|
||||
def grid_field_evidence(source, prompt):
|
||||
"""Every scalar/physical edge and metadata pointer in the fixed grid scope."""
|
||||
layouts = {
|
||||
"LoadImage": ("image", "upload"),
|
||||
"SaveImage": ("filename_prefix",),
|
||||
"ImageStitch": ("direction", "match_image_size", "spacing_width", "spacing_color"),
|
||||
"ResizeImageMaskNode": (
|
||||
"resize_type",
|
||||
"resize_type.width",
|
||||
"resize_type.height",
|
||||
"resize_type.crop",
|
||||
"scale_method",
|
||||
),
|
||||
}
|
||||
fields = []
|
||||
for i, node in enumerate(source["nodes"]):
|
||||
nid = str(node["id"])
|
||||
if node["type"] in ("Note", "MarkdownNote"):
|
||||
continue
|
||||
actual = prompt[nid]
|
||||
assert actual["class_type"] == node["type"]
|
||||
assert actual["_meta"] == {"title": node.get("title") or node["type"]}
|
||||
for name, value in actual["inputs"].items():
|
||||
socket = next(s for s in node["inputs"] if s["name"] == name)
|
||||
if socket.get("link") is not None:
|
||||
j, edge = next(
|
||||
(j, e) for j, e in enumerate(source["links"]) if e[0] == socket["link"]
|
||||
)
|
||||
expected, pointer = [str(edge[1]), edge[2]], f"/links/{j}"
|
||||
else:
|
||||
w = layouts[node["type"]].index(name)
|
||||
expected, pointer = node["widgets_values"][w], f"/nodes/{i}/widgets_values/{w}"
|
||||
assert type(value) is type(expected) and value == expected
|
||||
fields.append(
|
||||
{
|
||||
"node_id": nid,
|
||||
"field": name,
|
||||
"value": value,
|
||||
"json_type": type(value).__name__,
|
||||
"source_pointer": pointer,
|
||||
"class_pointer": f"/nodes/{i}/type",
|
||||
"title_pointer": f"/nodes/{i}/title"
|
||||
if node.get("title")
|
||||
else f"/nodes/{i}/type",
|
||||
"contract_manifest": "grid-reference/sources.json",
|
||||
}
|
||||
)
|
||||
return fields
|
||||
|
||||
|
||||
def profile_attempt(source, profile):
|
||||
expected = {
|
||||
**STRUCTURE_PROFILES,
|
||||
**PROMOTED_PROFILES,
|
||||
CASE04_PROFILE: "1.53.6",
|
||||
GRID_PROFILE: "1.41.20",
|
||||
**VHS_PROFILES,
|
||||
**SETGET_PROFILES,
|
||||
**VIDEOINFO_PROFILES,
|
||||
@@ -684,6 +737,10 @@ def profile_attempt(source, profile):
|
||||
if profile in VHS_PROFILES
|
||||
else "crop-split-reference/verified-facts.json"
|
||||
)
|
||||
if profile == GRID_PROFILE:
|
||||
assumptions["grid_contract"] = "grid-reference/sources.json"
|
||||
assumptions["core_version"] = "0.17.0"
|
||||
assumptions["ue_policy"] = "reject_even_empty_metadata; implementation_not_pinned"
|
||||
declared_frontend = (source.get("extra") or {}).get("frontendVersion")
|
||||
assumptions["source_frontend_declaration"] = declared_frontend
|
||||
if profile in VHS_PROFILES:
|
||||
@@ -781,7 +838,9 @@ def profile_attempt(source, profile):
|
||||
else {}
|
||||
),
|
||||
**(
|
||||
{"field_evidence": asr_field_evidence(source, result.prompt)}
|
||||
{"field_evidence": grid_field_evidence(source, result.prompt)}
|
||||
if profile == GRID_PROFILE
|
||||
else {"field_evidence": asr_field_evidence(source, result.prompt)}
|
||||
if profile == ASR_PROFILE
|
||||
else {"field_evidence": vhs_field_evidence(source, result.prompt)}
|
||||
if profile in VHS_PROFILES
|
||||
@@ -897,7 +956,9 @@ def audit_library(repo: Path, profiles=REFERENCE_PROFILES, *, baseline_profiles=
|
||||
}
|
||||
if baseline_profiles is None:
|
||||
excluded_profiles = (
|
||||
SCAIL_LOAD_PROFILES
|
||||
(GRID_PROFILE,)
|
||||
if GRID_PROFILE in profiles
|
||||
else SCAIL_LOAD_PROFILES
|
||||
if any(p in SCAIL_LOAD_PROFILES for p in profiles)
|
||||
else VIDEOINFO_PROFILES
|
||||
if any(p in VIDEOINFO_PROFILES for p in profiles)
|
||||
|
||||
@@ -15,6 +15,7 @@ import math
|
||||
from typing import Any
|
||||
|
||||
from .structure_reference import (
|
||||
GRID_PROFILE,
|
||||
SCAIL_LOAD_DELEGATES,
|
||||
SCAIL_LOAD_PROFILES,
|
||||
SETGET_PROFILES,
|
||||
@@ -96,6 +97,199 @@ _LAYOUTS = {
|
||||
}
|
||||
|
||||
|
||||
def grid_definitions():
|
||||
"""Pinned core 0.17.0, only the scale-dimensions IMAGE specialization.
|
||||
|
||||
This is an offline reference schema, never object_info or a registration.
|
||||
Dynamic keys stay flat in graphToPrompt; the backend reconstructs its dict.
|
||||
"""
|
||||
|
||||
def spec(inputs, outputs, optional=None):
|
||||
return {
|
||||
"input": {
|
||||
"required": {k: [v] for k, v in inputs.items()},
|
||||
"optional": {k: [v] for k, v in (optional or {}).items()},
|
||||
},
|
||||
"output": outputs,
|
||||
}
|
||||
|
||||
return {
|
||||
"LoadImage": spec({"image": "COMBO"}, ["IMAGE", "MASK"]),
|
||||
"SaveImage": spec({"images": "IMAGE", "filename_prefix": "STRING"}, []),
|
||||
"ImageStitch": spec(
|
||||
{
|
||||
"image1": "IMAGE",
|
||||
"direction": "COMBO",
|
||||
"match_image_size": "BOOLEAN",
|
||||
"spacing_width": "INT",
|
||||
"spacing_color": "COMBO",
|
||||
},
|
||||
["IMAGE"],
|
||||
{"image2": "IMAGE"},
|
||||
),
|
||||
"ResizeImageMaskNode": spec(
|
||||
{
|
||||
"input": "IMAGE",
|
||||
"resize_type": "COMFY_DYNAMICCOMBO_V3",
|
||||
"resize_type.width": "INT",
|
||||
"resize_type.height": "INT",
|
||||
"resize_type.crop": "COMBO",
|
||||
"scale_method": "COMBO",
|
||||
},
|
||||
["IMAGE"],
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
def serialize_grid_node(node):
|
||||
"""Restored saved state only, backed by grid-reference/sources.json.
|
||||
|
||||
The dynamic setter inserts named children immediately after the selector;
|
||||
LGraphNode.configure then continues its live widget iterator. This bounded
|
||||
implementation accepts only its exact scale dimensions layout. It does not
|
||||
infer a layout from names in a saved array or run upload/queue callbacks.
|
||||
Even empty UE metadata remains rejected: no UE7.7 implementation is pinned.
|
||||
"""
|
||||
ct, props = node.get("type"), node.get("properties") or {}
|
||||
if ct not in grid_definitions():
|
||||
raise ValueError("四宫格固定参考未覆盖节点")
|
||||
if props.get("cnr_id") != "comfy-core" or props.get("ver") != "0.17.0":
|
||||
raise ValueError("四宫格需要精确comfy-core0.17.0声明")
|
||||
if props.get("aux_id") is not None:
|
||||
raise ValueError("四宫格提供方身份冲突")
|
||||
if type(node.get("mode", 0)) is not int or node.get("mode", 0) != 0:
|
||||
raise ValueError("四宫格仅正常mode=0")
|
||||
for container in (node, props):
|
||||
if any(
|
||||
k in container
|
||||
for k in (
|
||||
"widgets",
|
||||
"widgets_values_named",
|
||||
"serializeValue",
|
||||
"comfyDynamic",
|
||||
"onConfigure",
|
||||
"onSerialize",
|
||||
"getInputLink",
|
||||
"resolveInput",
|
||||
"resolveOutput",
|
||||
"onExecute",
|
||||
"isVirtualNode",
|
||||
"applyToGraph",
|
||||
"beforeQueued",
|
||||
"afterQueued",
|
||||
)
|
||||
):
|
||||
raise ValueError("四宫格不覆盖自定义构造/恢复/序列化钩子")
|
||||
if any(
|
||||
k in container
|
||||
for k in (
|
||||
"ue_properties",
|
||||
"widget_ue_connectable",
|
||||
"input_ue_unconnectable",
|
||||
)
|
||||
):
|
||||
raise ValueError("UE7.7实现与加载顺序未固定;空映射不证明没有控件改写")
|
||||
layouts = {
|
||||
"LoadImage": (("image", str), ("upload", str)),
|
||||
"SaveImage": (("filename_prefix", str),),
|
||||
"ImageStitch": _LAYOUTS["ImageStitch"],
|
||||
"ResizeImageMaskNode": (
|
||||
("resize_type", str),
|
||||
("resize_type.width", int),
|
||||
("resize_type.height", int),
|
||||
("resize_type.crop", str),
|
||||
("scale_method", str),
|
||||
),
|
||||
}
|
||||
values, layout = node.get("widgets_values"), layouts[ct]
|
||||
if not isinstance(values, list) or len(values) != len(layout):
|
||||
raise ValueError("四宫格保存控件必须匹配固定构造的完整位置数组")
|
||||
if any(type(v) is not kind for v, (_, kind) in zip(values, layout)):
|
||||
raise ValueError("四宫格控件标量类型不符")
|
||||
result = dict(zip((name for name, _ in layout), values))
|
||||
definitions = grid_definitions()[ct]
|
||||
expected = {
|
||||
**definitions["input"]["required"],
|
||||
**definitions["input"]["optional"],
|
||||
}
|
||||
if ct == "LoadImage":
|
||||
expected["upload"] = ["IMAGEUPLOAD"]
|
||||
if result.pop("upload") != "image":
|
||||
raise ValueError("LoadImage上传保存态必须为image,不能混入执行输入")
|
||||
if ct == "ResizeImageMaskNode":
|
||||
expected["input"] = ["IMAGE,MASK"]
|
||||
if result["resize_type"] != "scale dimensions":
|
||||
raise ValueError("未覆盖的Resize动态分支,不能重解释位置数组")
|
||||
if any(not 0 <= result[k] <= 16384 for k in ("resize_type.width", "resize_type.height")):
|
||||
raise ValueError("Resize尺寸超出固定构造范围")
|
||||
if result["resize_type.crop"] not in ("disabled", "center"):
|
||||
raise ValueError("Resize裁剪枚举未覆盖")
|
||||
if result["scale_method"] not in (
|
||||
"nearest-exact",
|
||||
"bilinear",
|
||||
"area",
|
||||
"bicubic",
|
||||
"lanczos",
|
||||
):
|
||||
raise ValueError("Resize插值枚举未覆盖")
|
||||
if ct == "SaveImage" and "%" in result["filename_prefix"]:
|
||||
raise ValueError("SaveImage替换表达式需要图/日期上下文;仅接受序列化不变前缀")
|
||||
if ct == "ImageStitch":
|
||||
if result["direction"] not in ("right", "down", "left", "up"):
|
||||
raise ValueError("拼接方向枚举未覆盖")
|
||||
if result["spacing_color"] not in ("white", "black", "red", "green", "blue"):
|
||||
raise ValueError("拼接颜色枚举未覆盖")
|
||||
if not 0 <= result["spacing_width"] <= 1024 or result["spacing_width"] % 2:
|
||||
raise ValueError("拼接间距不是固定步长的不变值")
|
||||
sockets = node.get("inputs", [])
|
||||
names = [s.get("name") for s in sockets]
|
||||
input_order = {
|
||||
"LoadImage": ["image", "upload"],
|
||||
"SaveImage": ["images", "filename_prefix"],
|
||||
"ImageStitch": [
|
||||
"image1",
|
||||
"image2",
|
||||
"direction",
|
||||
"match_image_size",
|
||||
"spacing_width",
|
||||
"spacing_color",
|
||||
],
|
||||
"ResizeImageMaskNode": [
|
||||
"input",
|
||||
"resize_type",
|
||||
"resize_type.width",
|
||||
"resize_type.height",
|
||||
"resize_type.crop",
|
||||
"scale_method",
|
||||
],
|
||||
}
|
||||
if names != input_order[ct] or set(names) != set(expected):
|
||||
raise ValueError("四宫格缺少/额外/重复限定输入字段")
|
||||
for socket in sockets:
|
||||
name = socket["name"]
|
||||
if socket.get("type") != expected[name][0]:
|
||||
raise ValueError("四宫格输入类型与固定构造不符")
|
||||
if name in dict(layout):
|
||||
if socket.get("widget") != {"name": name}:
|
||||
raise ValueError("四宫格控件限定名不符或含覆盖")
|
||||
elif "widget" in socket:
|
||||
raise ValueError("四宫格物理输入带未知控件")
|
||||
if name in ("upload", "resize_type") and socket.get("link") is not None:
|
||||
raise ValueError("上传/动态分支选择器外线未覆盖")
|
||||
outputs = node.get("outputs", [])
|
||||
output_names = {
|
||||
"LoadImage": ["IMAGE", "MASK"],
|
||||
"ImageStitch": ["IMAGE"],
|
||||
"ResizeImageMaskNode": ["resized"],
|
||||
"SaveImage": [],
|
||||
}[ct]
|
||||
if [s.get("type") for s in outputs] != definitions["output"] or [
|
||||
s.get("name") for s in outputs
|
||||
] != output_names:
|
||||
raise ValueError("四宫格全部输出原槽/类型/名字不符")
|
||||
return result
|
||||
|
||||
|
||||
def reference_definitions(profile: str = PROFILE) -> dict[str, Any]:
|
||||
"""Only opt-in public reference schemas; no model/file availability assertion."""
|
||||
|
||||
@@ -108,6 +302,8 @@ def reference_definitions(profile: str = PROFILE) -> dict[str, Any]:
|
||||
"output": outputs,
|
||||
}
|
||||
|
||||
if profile == GRID_PROFILE:
|
||||
return grid_definitions()
|
||||
if profile in SCAIL_LOAD_PROFILES:
|
||||
return reference_definitions(SCAIL_LOAD_DELEGATES[profile])
|
||||
if profile in VIDEOINFO_PROFILES:
|
||||
@@ -190,6 +386,8 @@ 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 == GRID_PROFILE:
|
||||
return serialize_grid_node(node)
|
||||
if profile in SCAIL_LOAD_PROFILES:
|
||||
if node.get("type") == "VHS_LoadVideo":
|
||||
return serialize_scail_load_node(node)
|
||||
|
||||
@@ -13,6 +13,8 @@ from dataclasses import dataclass, field
|
||||
from typing import Any
|
||||
from uuid import UUID
|
||||
|
||||
GRID_PROFILE = "comfy-frontend-1.41.20-core-0.17.0-grid-reference"
|
||||
|
||||
SETGET_COMMIT = "ab72eda7ffad6280422d71ab7d54d3fb87c0ba18"
|
||||
SETGET_PROFILES = {
|
||||
f"comfy-frontend-{v}-kj-setget-ab72eda7-vhs-reference": v for v in ("1.37.11", "1.48.6")
|
||||
@@ -802,3 +804,94 @@ def _expand(source, profile, widgets=False, case04=False):
|
||||
"extra": deepcopy(source.get("extra", {})),
|
||||
}
|
||||
return Structure(graph, issues, unresolved, resolved)
|
||||
|
||||
|
||||
def validate_grid_structure(source):
|
||||
"""Only direct root links under the pinned 1.41.20 reference premise.
|
||||
|
||||
IMAGE -> IMAGE,MASK is the single supported MatchType specialization.
|
||||
No UE implementation identity is inferred from an empty saved mapping.
|
||||
"""
|
||||
if (source.get("extra") or {}).get("frontendVersion") != "1.41.20":
|
||||
raise ValueError("四宫格参考需要显式前端1.41.20")
|
||||
if (source.get("definitions") or {}).get("subgraphs"):
|
||||
raise ValueError("四宫格参考不覆盖子图")
|
||||
extra = source.get("extra") or {}
|
||||
if extra.get("workflowRendererVersion", "LG") != "LG":
|
||||
raise ValueError("四宫格只覆盖LG保存态")
|
||||
for key in ("ue_links", "links_added_by_ue"):
|
||||
if key in extra and extra[key] != []:
|
||||
raise ValueError("四宫格参考只覆盖空UE连线数组")
|
||||
nodes = {}
|
||||
for node in source["nodes"]:
|
||||
nid = _id(node["id"])
|
||||
if nid in nodes:
|
||||
raise ValueError("重复节点ID")
|
||||
nodes[nid] = node
|
||||
if type(node.get("mode", 0)) is not int or node.get("mode", 0) != 0:
|
||||
raise ValueError("四宫格仅正常mode=0")
|
||||
if node.get("type") in ("Note", "MarkdownNote") and (
|
||||
node.get("inputs") or node.get("outputs")
|
||||
):
|
||||
raise ValueError("虚拟说明节点不得带执行连线")
|
||||
links = {}
|
||||
for edge in source.get("links", []):
|
||||
if not isinstance(edge, list) or len(edge) != 6:
|
||||
raise ValueError("四宫格只接受六字段连线")
|
||||
lid, a, oslot, b, islot, typ = edge
|
||||
if type(lid) is not int or lid < 0 or lid in links:
|
||||
raise ValueError("重复或非法连线ID")
|
||||
a, b = _id(a), _id(b)
|
||||
for nid, slot, direction in ((a, oslot, "outputs"), (b, islot, "inputs")):
|
||||
if (
|
||||
nid not in nodes
|
||||
or type(slot) is not int
|
||||
or not (0 <= slot < len(nodes[nid].get(direction, [])))
|
||||
):
|
||||
raise ValueError("连线原槽缺失或非法")
|
||||
origin, target = nodes[a]["outputs"][oslot], nodes[b]["inputs"][islot]
|
||||
accepted = origin.get("type") == target.get("type") == typ
|
||||
if nodes[b].get("type") == "ResizeImageMaskNode" and target.get("name") == "input":
|
||||
accepted = typ == origin.get("type") == "IMAGE" and target.get("type") == "IMAGE,MASK"
|
||||
if not accepted:
|
||||
raise ValueError("连线类型与精确槽不符,未覆盖的MatchType分支")
|
||||
ids = origin.get("links") or []
|
||||
if any(type(x) is not int for x in ids) or ids.count(lid) != 1:
|
||||
raise ValueError("输出与连线不互指")
|
||||
if type(target.get("link")) is not int or target["link"] != lid:
|
||||
raise ValueError("输入与连线不互指")
|
||||
links[lid] = edge
|
||||
for nid, n in nodes.items():
|
||||
for direction in ("inputs", "outputs"):
|
||||
for slot, socket in enumerate(n.get(direction, [])):
|
||||
ids = (
|
||||
[socket["link"]]
|
||||
if direction == "inputs" and socket.get("link") is not None
|
||||
else (socket.get("links") or [])
|
||||
if direction == "outputs"
|
||||
else []
|
||||
)
|
||||
for lid in ids:
|
||||
if type(lid) is not int or lid not in links:
|
||||
raise ValueError("槽引用未知连线")
|
||||
edge = links[lid]
|
||||
offset = 1 if direction == "outputs" else 3
|
||||
if [str(edge[offset]), edge[offset + 1]] != [nid, slot]:
|
||||
raise ValueError("槽引用错误端点")
|
||||
# graphToPrompt's execution ordering requires an acyclic direct graph here.
|
||||
visiting, visited = set(), set()
|
||||
|
||||
def visit(nid):
|
||||
if nid in visiting:
|
||||
raise ValueError("四宫格参考不支持环")
|
||||
if nid in visited:
|
||||
return
|
||||
visiting.add(nid)
|
||||
for e in links.values():
|
||||
if str(e[3]) == nid:
|
||||
visit(str(e[1]))
|
||||
visiting.remove(nid)
|
||||
visited.add(nid)
|
||||
|
||||
for nid in nodes:
|
||||
visit(nid)
|
||||
|
||||
@@ -36,6 +36,7 @@ from .serialization_reference import (
|
||||
validate_reroute,
|
||||
)
|
||||
from .structure_reference import (
|
||||
GRID_PROFILE,
|
||||
PROMOTED_PROFILES,
|
||||
SCAIL_LOAD_PROFILES,
|
||||
SETGET_PROFILES,
|
||||
@@ -43,6 +44,7 @@ from .structure_reference import (
|
||||
VIDEOINFO_PROFILES,
|
||||
expand_reference_subgraphs,
|
||||
project_reference_setget,
|
||||
validate_grid_structure,
|
||||
)
|
||||
|
||||
|
||||
@@ -72,6 +74,7 @@ def convert_reference(source: Any, profile: str = PROFILE) -> Conversion:
|
||||
profile
|
||||
not in (
|
||||
PROFILE,
|
||||
GRID_PROFILE,
|
||||
ASR_PROFILE,
|
||||
*MEDIA_PROFILES,
|
||||
SEPARATION_PROFILE,
|
||||
@@ -96,6 +99,8 @@ def convert_reference(source: Any, profile: str = PROFILE) -> Conversion:
|
||||
True,
|
||||
)
|
||||
try:
|
||||
if profile == GRID_PROFILE:
|
||||
validate_grid_structure(source)
|
||||
if profile in (*SETGET_PROFILES, *VIDEOINFO_PROFILES, *SCAIL_LOAD_PROFILES):
|
||||
expected = {**SETGET_PROFILES, **VIDEOINFO_PROFILES, **SCAIL_LOAD_PROFILES}[profile]
|
||||
declared = (source.get("extra") or {}).get("frontendVersion")
|
||||
@@ -212,9 +217,13 @@ def convert_reference(source: Any, profile: str = PROFILE) -> Conversion:
|
||||
if profile in (PRIMITIVE_PROFILE, PREVIEW_PROFILE) and source != original:
|
||||
result.diagnostic_graph = source
|
||||
except (ValueError, TypeError, KeyError, AttributeError, IndexError) as exc:
|
||||
return Conversion(None, [{"code": "invalid_reference_contract", "message": str(exc)}], True)
|
||||
issue = {"code": "invalid_reference_contract", "message": str(exc)}
|
||||
if profile == GRID_PROFILE:
|
||||
issue["pointer"] = "/"
|
||||
return Conversion(None, [issue], True)
|
||||
result.reference_only = True
|
||||
if profile in (
|
||||
GRID_PROFILE,
|
||||
ASR_PROFILE,
|
||||
*MEDIA_PROFILES,
|
||||
SEPARATION_PROFILE,
|
||||
@@ -231,7 +240,17 @@ def _convert(
|
||||
issues: list[dict[str, Any]] = []
|
||||
|
||||
def fail(code: str, message: str, node_id: Any = "") -> None:
|
||||
issues.append({"code": code, "message": message, "node_id": str(node_id)})
|
||||
issue = {"code": code, "message": message, "node_id": str(node_id)}
|
||||
if reference and reference_profile == GRID_PROFILE:
|
||||
issue["pointer"] = next(
|
||||
(
|
||||
f"/nodes/{i}"
|
||||
for i, n in enumerate(source.get("nodes", []))
|
||||
if str(n.get("id")) == str(node_id)
|
||||
),
|
||||
"/",
|
||||
)
|
||||
issues.append(issue)
|
||||
|
||||
if not isinstance(source, dict):
|
||||
return Conversion(None, [{"code": "invalid_format", "message": "源文件不是 JSON 对象"}])
|
||||
@@ -281,6 +300,7 @@ def _convert(
|
||||
**STRUCTURE_PROFILES,
|
||||
**PROMOTED_PROFILES,
|
||||
CASE04_PROFILE: "1.53.6",
|
||||
GRID_PROFILE: "1.41.20",
|
||||
**VHS_PROFILES,
|
||||
**SETGET_PROFILES,
|
||||
**VIDEOINFO_PROFILES,
|
||||
|
||||
@@ -369,6 +369,7 @@ def test_library_actual_delta_keeps_every_old_attempt_and_all_six_golden_compari
|
||||
*audit.SETGET_PROFILES,
|
||||
*audit.VIDEOINFO_PROFILES,
|
||||
*audit.SCAIL_LOAD_PROFILES,
|
||||
audit.GRID_PROFILE,
|
||||
)
|
||||
)
|
||||
baseline = tuple(p for p in profiles if p != SEPARATION_PROFILE)
|
||||
|
||||
@@ -360,6 +360,7 @@ def test_all_old_fourteen_profiles_attempts_gaps_and_six_differences_unchanged()
|
||||
*audit.SETGET_PROFILES,
|
||||
*audit.VIDEOINFO_PROFILES,
|
||||
*audit.SCAIL_LOAD_PROFILES,
|
||||
audit.GRID_PROFILE,
|
||||
)
|
||||
)
|
||||
profiles = tuple(p for p in historical_profiles if p not in CROP_SPLIT_PROFILES)
|
||||
|
||||
@@ -0,0 +1,360 @@
|
||||
"""Fixed saved-state reference only: synthetic no-UE fixtures are not user exports."""
|
||||
|
||||
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.serialization_reference import serialize_grid_node
|
||||
from calliope.comfyui.structure_reference import GRID_PROFILE
|
||||
from calliope.comfyui.ui2api import convert, convert_reference
|
||||
|
||||
REPO = Path(__file__).resolve().parents[2]
|
||||
PATH = next((REPO / "example_ComfyUI_workflows").rglob("图像合并成四宫格.json"))
|
||||
|
||||
|
||||
def graph(real=False):
|
||||
g = json.loads(PATH.read_bytes())
|
||||
if not real:
|
||||
# Explicit synthetic premise. Never mutate the immutable source or write
|
||||
# this counterfactual as an actual library candidate.
|
||||
for n in g["nodes"]:
|
||||
n["properties"].pop("ue_properties", None)
|
||||
return g
|
||||
|
||||
|
||||
def node(g, nid):
|
||||
return next(n for n in g["nodes"] if n["id"] == nid)
|
||||
|
||||
|
||||
def test_real_graph_stays_closed_at_exact_ue_pointers():
|
||||
g = graph(True)
|
||||
original = copy.deepcopy(g)
|
||||
result = convert_reference(g, GRID_PROFILE)
|
||||
assert result.prompt is None and result.reference_only and g == original
|
||||
rejected = [i for i in result.issues if i["code"] == "reference_widget_unverified"]
|
||||
assert {i["node_id"] for i in rejected} == {
|
||||
"12",
|
||||
"13",
|
||||
"14",
|
||||
"15",
|
||||
"16",
|
||||
"17",
|
||||
"18",
|
||||
"19",
|
||||
"21",
|
||||
}
|
||||
for issue in rejected:
|
||||
assert "UE7.7" in issue["message"]
|
||||
i = int(issue["pointer"].split("/")[-1])
|
||||
assert str(g["nodes"][i]["id"]) == issue["node_id"]
|
||||
attempt = audit.profile_attempt(g, GRID_PROFILE)
|
||||
assert attempt["status"] == "rejected" and "candidate_prompt" not in attempt
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"width,height,crop,method",
|
||||
[
|
||||
(2048, 2048, "center", "lanczos"),
|
||||
(0, 1234, "disabled", "area"),
|
||||
(16384, 0, "center", "bilinear"),
|
||||
(345, 678, "disabled", "nearest-exact"),
|
||||
(3, 4, "center", "bicubic"),
|
||||
],
|
||||
)
|
||||
def test_dynamic_restored_layout_keeps_qualified_names_types_and_metadata(
|
||||
width, height, crop, method
|
||||
):
|
||||
g = graph()
|
||||
node(g, 21)["widgets_values"] = ["scale dimensions", width, height, crop, method]
|
||||
node(g, 19)["widgets_values"] = ["saved-prefix-中文"]
|
||||
node(g, 21)["title"] = "精确尺寸"
|
||||
before = copy.deepcopy(g)
|
||||
result = convert_reference(g, GRID_PROFILE)
|
||||
assert result.prompt is not None, result.issues
|
||||
assert result.reference_only and g == before and convert(g).prompt is None
|
||||
assert result.serialization_stage == "restored_saved_state_before_queue_hooks"
|
||||
assert result.prompt["21"]["inputs"] == {
|
||||
"resize_type": "scale dimensions",
|
||||
"resize_type.width": width,
|
||||
"resize_type.height": height,
|
||||
"resize_type.crop": crop,
|
||||
"scale_method": method,
|
||||
"input": ["18", 0],
|
||||
}
|
||||
assert result.prompt["21"]["_meta"] == {"title": "精确尺寸"}
|
||||
assert result.prompt["19"]["inputs"]["filename_prefix"] == "saved-prefix-中文"
|
||||
assert "24" not in result.prompt
|
||||
assert all("upload" not in n["inputs"] for n in result.prompt.values())
|
||||
evidence = audit.grid_field_evidence(g, result.prompt)
|
||||
assert len(evidence) == 30 # 22 scalars plus eight physical edges.
|
||||
assert (
|
||||
next(e for e in evidence if e["field"] == "resize_type.width")["source_pointer"]
|
||||
== "/nodes/3/widgets_values/1"
|
||||
)
|
||||
|
||||
|
||||
def test_physical_image_links_use_original_slots_and_changed_instances():
|
||||
g = graph()
|
||||
# Replace top-left with the fourth image. Keep all reverse records valid.
|
||||
node(g, 12)["outputs"][0]["links"] = []
|
||||
node(g, 15)["outputs"][0]["links"].append(11)
|
||||
next(e for e in g["links"] if e[0] == 11)[1] = 15
|
||||
node(g, 15)["widgets_values"][0] = "synthetic-fourth.png"
|
||||
result = convert_reference(g, GRID_PROFILE)
|
||||
assert result.prompt is not None, result.issues
|
||||
assert result.prompt["16"]["inputs"]["image1"] == ["15", 0]
|
||||
assert result.prompt["15"]["inputs"]["image"] == "synthetic-fourth.png"
|
||||
assert result.prompt["17"]["inputs"]["image2"] == ["15", 0]
|
||||
assert result.prompt["19"]["inputs"]["images"] == ["21", 0]
|
||||
|
||||
|
||||
def test_qualified_dimension_link_overrides_saved_scalar_only_in_synthetic_pipeline(monkeypatch):
|
||||
from calliope.comfyui import ui2api
|
||||
from calliope.comfyui.serialization_reference import grid_definitions
|
||||
|
||||
g = graph()
|
||||
n = node(g, 21)
|
||||
n["inputs"][2]["link"] = 100
|
||||
g["links"].append([100, 99, 0, 21, 2, "INT"])
|
||||
g["nodes"].append(
|
||||
{
|
||||
"id": 99,
|
||||
"type": "SyntheticIntSource",
|
||||
"mode": 0,
|
||||
"inputs": [],
|
||||
"outputs": [{"name": "INT", "type": "INT", "links": [100]}],
|
||||
}
|
||||
)
|
||||
# This invented source is deliberately outside the public profile. An actual
|
||||
# graph with it must close; only a test-local serializer verifies precedence.
|
||||
assert convert_reference(g, GRID_PROFILE).prompt is None
|
||||
original = ui2api.serialize_reference_widgets
|
||||
|
||||
def serialize(node, profile):
|
||||
return {} if node["type"] == "SyntheticIntSource" else original(node, profile)
|
||||
|
||||
monkeypatch.setattr(ui2api, "serialize_reference_widgets", serialize)
|
||||
definitions = grid_definitions()
|
||||
definitions["SyntheticIntSource"] = {"input": {"required": {}}, "output": ["INT"]}
|
||||
result = ui2api._convert(g, definitions, reference=True, reference_profile=GRID_PROFILE)
|
||||
assert result.prompt is not None, result.issues
|
||||
assert result.prompt["21"]["inputs"]["resize_type.width"] == ["99", 0]
|
||||
assert result.prompt["21"]["inputs"]["resize_type.height"] == 2048
|
||||
n["widgets_values"][1] = 17
|
||||
assert ui2api._convert(g, definitions, reference=True, reference_profile=GRID_PROFILE).prompt[
|
||||
"21"
|
||||
]["inputs"]["resize_type.width"] == ["99", 0]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"mutation",
|
||||
[
|
||||
"branch",
|
||||
"missing_value",
|
||||
"extra_value",
|
||||
"named_object",
|
||||
"width_bool",
|
||||
"height_float",
|
||||
"negative_width",
|
||||
"oversize",
|
||||
"crop",
|
||||
"method",
|
||||
"provider",
|
||||
"version",
|
||||
"aux",
|
||||
"short_commit",
|
||||
"frontend",
|
||||
"missing_frontend",
|
||||
"renderer",
|
||||
"mode",
|
||||
"bool_mode",
|
||||
"missing_socket",
|
||||
"extra_socket",
|
||||
"qualified_name",
|
||||
"widget_name",
|
||||
"widget_override",
|
||||
"socket_type",
|
||||
"output_name",
|
||||
"output_type",
|
||||
"extra_output",
|
||||
"bool_slot",
|
||||
"bad_slot",
|
||||
"reverse",
|
||||
"type_edge",
|
||||
"extra_edge_field",
|
||||
"duplicate_edge",
|
||||
"missing_edge",
|
||||
"unknown_node",
|
||||
"note_edge",
|
||||
"subgraph",
|
||||
"ue_empty",
|
||||
"ue_nested",
|
||||
"ue_top",
|
||||
"ue_graph",
|
||||
"ue_bad_array",
|
||||
"custom_serializer",
|
||||
"custom_dynamic",
|
||||
"hook",
|
||||
"upload_value",
|
||||
"upload_link",
|
||||
"spacing_bool",
|
||||
"spacing_odd",
|
||||
"direction",
|
||||
"color",
|
||||
"selector_link",
|
||||
"layout_order",
|
||||
"cycle",
|
||||
"filename_expression",
|
||||
],
|
||||
)
|
||||
def test_any_unknown_branch_layout_type_slot_extension_or_identity_closes_whole_graph(mutation):
|
||||
g = graph()
|
||||
n = node(g, 21)
|
||||
if mutation == "branch":
|
||||
n["widgets_values"][0] = "scale by"
|
||||
elif mutation == "missing_value":
|
||||
n["widgets_values"].pop(2)
|
||||
elif mutation == "extra_value":
|
||||
n["widgets_values"].append(0)
|
||||
elif mutation == "named_object":
|
||||
n["widgets_values"] = {"width": 2048}
|
||||
elif mutation == "width_bool":
|
||||
n["widgets_values"][1] = True
|
||||
elif mutation == "height_float":
|
||||
n["widgets_values"][2] = 2048.0
|
||||
elif mutation == "negative_width":
|
||||
n["widgets_values"][1] = -1
|
||||
elif mutation == "oversize":
|
||||
n["widgets_values"][2] = 16385
|
||||
elif mutation == "crop":
|
||||
n["widgets_values"][3] = "unknown"
|
||||
elif mutation == "method":
|
||||
n["widgets_values"][4] = "unknown"
|
||||
elif mutation == "provider":
|
||||
n["properties"]["cnr_id"] = "other"
|
||||
elif mutation == "version":
|
||||
n["properties"]["ver"] = "0.21.1"
|
||||
elif mutation == "short_commit":
|
||||
n["properties"]["ver"] = "63d1bbdb"
|
||||
elif mutation == "aux":
|
||||
n["properties"]["aux_id"] = "other"
|
||||
elif mutation == "frontend":
|
||||
g["extra"]["frontendVersion"] = "1.41.21"
|
||||
elif mutation == "missing_frontend":
|
||||
g["extra"].pop("frontendVersion")
|
||||
elif mutation == "renderer":
|
||||
g["extra"]["workflowRendererVersion"] = "Vue"
|
||||
elif mutation == "mode":
|
||||
n["mode"] = 4
|
||||
elif mutation == "bool_mode":
|
||||
n["mode"] = False
|
||||
elif mutation == "missing_socket":
|
||||
n["inputs"].pop(2)
|
||||
elif mutation == "extra_socket":
|
||||
n["inputs"].append(copy.deepcopy(n["inputs"][2]))
|
||||
elif mutation == "qualified_name":
|
||||
n["inputs"][2]["name"] = "width"
|
||||
elif mutation == "widget_name":
|
||||
n["inputs"][2]["widget"]["name"] = "width"
|
||||
elif mutation == "widget_override":
|
||||
n["inputs"][2]["widget"]["serializeValue"] = "unknown"
|
||||
elif mutation == "socket_type":
|
||||
n["inputs"][2]["type"] = "FLOAT"
|
||||
elif mutation == "output_name":
|
||||
n["outputs"][0]["name"] = "IMAGE"
|
||||
elif mutation == "output_type":
|
||||
n["outputs"][0]["type"] = "MASK"
|
||||
elif mutation == "extra_output":
|
||||
n["outputs"].append({"name": "unused", "type": "IMAGE"})
|
||||
elif mutation == "bool_slot":
|
||||
g["links"][0][2] = False
|
||||
elif mutation == "bad_slot":
|
||||
g["links"][0][2] = 1
|
||||
elif mutation == "reverse":
|
||||
node(g, 12)["outputs"][0]["links"] = []
|
||||
elif mutation == "type_edge":
|
||||
g["links"][0][5] = "MASK"
|
||||
elif mutation == "extra_edge_field":
|
||||
g["links"][0].append("unknown")
|
||||
elif mutation == "duplicate_edge":
|
||||
g["links"].append(copy.deepcopy(g["links"][0]))
|
||||
elif mutation == "missing_edge":
|
||||
g["links"].pop()
|
||||
elif mutation == "unknown_node":
|
||||
node(g, 12)["type"] = "unknown"
|
||||
elif mutation == "note_edge":
|
||||
node(g, 24)["outputs"] = [{"type": "IMAGE", "name": "IMAGE"}]
|
||||
elif mutation == "subgraph":
|
||||
g["definitions"] = {"subgraphs": [{"id": "unknown"}]}
|
||||
elif mutation == "ue_empty":
|
||||
n["properties"]["ue_properties"] = {}
|
||||
elif mutation == "ue_nested":
|
||||
n["properties"]["ue_properties"] = {"widget_ue_connectable": {"resize_type.width": True}}
|
||||
elif mutation == "ue_top":
|
||||
n["widget_ue_connectable"] = {"width": True}
|
||||
elif mutation == "ue_graph":
|
||||
g["extra"]["ue_links"] = [1]
|
||||
elif mutation == "ue_bad_array":
|
||||
g["extra"]["ue_links"] = {}
|
||||
elif mutation == "custom_serializer":
|
||||
n["serializeValue"] = "unknown"
|
||||
elif mutation == "custom_dynamic":
|
||||
n["properties"]["comfyDynamic"] = {}
|
||||
elif mutation == "hook":
|
||||
n["onConfigure"] = "unknown"
|
||||
elif mutation == "upload_value":
|
||||
node(g, 12)["widgets_values"][1] = "file"
|
||||
elif mutation == "upload_link":
|
||||
node(g, 12)["inputs"][1]["link"] = 11
|
||||
elif mutation == "spacing_bool":
|
||||
node(g, 16)["widgets_values"][2] = False
|
||||
elif mutation == "spacing_odd":
|
||||
node(g, 16)["widgets_values"][2] = 3
|
||||
elif mutation == "direction":
|
||||
node(g, 16)["widgets_values"][0] = "unknown"
|
||||
elif mutation == "color":
|
||||
node(g, 16)["widgets_values"][3] = "unknown"
|
||||
elif mutation == "selector_link":
|
||||
n["inputs"][1]["link"] = 19
|
||||
elif mutation == "layout_order":
|
||||
n["inputs"][2:4] = list(reversed(n["inputs"][2:4]))
|
||||
elif mutation == "filename_expression":
|
||||
node(g, 19)["widgets_values"] = ["%date:yyyy-MM-dd%"]
|
||||
elif mutation == "cycle":
|
||||
# Valid reciprocal IMAGE slots but a real cycle 18 -> 21 -> 18.
|
||||
node(g, 16)["outputs"][0]["links"].remove(15)
|
||||
n["outputs"][0]["links"].append(15)
|
||||
next(e for e in g["links"] if e[0] == 15)[1] = 21
|
||||
result = convert_reference(g, GRID_PROFILE)
|
||||
assert result.prompt is None and result.issues and result.reference_only, mutation
|
||||
|
||||
|
||||
def test_fixed_sources_and_original_profile_cohorts_remain_identical():
|
||||
assert verify(REPO / "docs/hel-892/grid-reference")["sources_verified"]
|
||||
old = json.loads((REPO / "docs/hel-892/scail-load-evidence/library.json").read_bytes())
|
||||
profiles = tuple(old["profiles"])
|
||||
assert len(profiles) == 24 and tuple(audit.REFERENCE_PROFILES[:-1]) == profiles
|
||||
current = audit.audit_library(REPO, baseline_profiles=profiles)
|
||||
for before, after in zip(old["cases"], current["cases"]):
|
||||
assert before["source_path"] == after["source_path"]
|
||||
assert before["attempts"] == after["attempts"][:24]
|
||||
assert before.get("comparisons") == after.get("comparisons")
|
||||
assert before["candidate_hashes"] == after["candidate_hashes"]
|
||||
before = audit.audit_library(REPO, profiles)
|
||||
assert old["gap_groups"] == before["gap_groups"]
|
||||
assert current["coverage_delta"]["new_complete_paths"] == []
|
||||
assert current["cases"][0]["execution_verified"] is False
|
||||
|
||||
|
||||
def test_load_save_exact_core_identity_and_upload_is_not_execution_field():
|
||||
g = graph()
|
||||
for nid in (12, 13, 14, 15, 19):
|
||||
n = node(g, nid)
|
||||
assert serialize_grid_node(n)
|
||||
n["properties"]["ver"] = "0.21.1"
|
||||
with pytest.raises(ValueError, match="精确"):
|
||||
serialize_grid_node(n)
|
||||
@@ -242,7 +242,7 @@ def test_exact_historical_emission_is_not_user_provenance():
|
||||
assert cls.lineno > 0
|
||||
assert '"VHS_LoadVideo": LoadVideoUpload,' in (ROOT / "videohelpersuite__nodes.py").read_text()
|
||||
assert serialize_scail_load_node(loader())["custom_width"] == 0
|
||||
assert len(audit.REFERENCE_PROFILES) == 24
|
||||
assert len([p for p in audit.REFERENCE_PROFILES if p != audit.GRID_PROFILE]) == 24
|
||||
|
||||
|
||||
def test_named_map_order_external_removal_and_old_contracts():
|
||||
|
||||
@@ -335,7 +335,8 @@ def test_wrong_frontend_missing_policy_and_profile_inventory():
|
||||
[
|
||||
p
|
||||
for p in audit.REFERENCE_PROFILES
|
||||
if p not in (*audit.VIDEOINFO_PROFILES, *audit.SCAIL_LOAD_PROFILES)
|
||||
if p
|
||||
not in (*audit.VIDEOINFO_PROFILES, *audit.SCAIL_LOAD_PROFILES, audit.GRID_PROFILE)
|
||||
]
|
||||
)
|
||||
== 20
|
||||
@@ -416,7 +417,13 @@ def test_historical_18_profiles_attempts_gaps_and_six_comparisons_unchanged():
|
||||
baseline = tuple(
|
||||
p
|
||||
for p in audit.REFERENCE_PROFILES
|
||||
if p not in (*SETGET_PROFILES, *audit.VIDEOINFO_PROFILES, *audit.SCAIL_LOAD_PROFILES)
|
||||
if p
|
||||
not in (
|
||||
*SETGET_PROFILES,
|
||||
*audit.VIDEOINFO_PROFILES,
|
||||
*audit.SCAIL_LOAD_PROFILES,
|
||||
audit.GRID_PROFILE,
|
||||
)
|
||||
)
|
||||
now = audit.audit_library(REPO, baseline_profiles=baseline)
|
||||
actual_old = audit.audit_library(REPO, baseline)
|
||||
|
||||
@@ -289,7 +289,13 @@ def test_old_sixteen_attempts_gaps_candidates_and_six_comparisons_protected():
|
||||
historical_profiles = tuple(
|
||||
p
|
||||
for p in audit.REFERENCE_PROFILES
|
||||
if p not in (*audit.SETGET_PROFILES, *audit.VIDEOINFO_PROFILES, *audit.SCAIL_LOAD_PROFILES)
|
||||
if p
|
||||
not in (
|
||||
*audit.SETGET_PROFILES,
|
||||
*audit.VIDEOINFO_PROFILES,
|
||||
*audit.SCAIL_LOAD_PROFILES,
|
||||
audit.GRID_PROFILE,
|
||||
)
|
||||
)
|
||||
profiles = tuple(p for p in historical_profiles if p not in VHS_PROFILES)
|
||||
baseline = audit.audit_library(REPO, profiles)
|
||||
|
||||
@@ -275,7 +275,16 @@ def test_real_entities_strict_source_schema_and_old_profiles_stay_frozen():
|
||||
result = convert_reference(source, PROFILE)
|
||||
assert result.prompt is None and result.issues
|
||||
assert all(a["status"] != "complete_reference_candidate" for a in row["attempts"])
|
||||
assert len([p for p in audit.REFERENCE_PROFILES if p not in audit.SCAIL_LOAD_PROFILES]) == 22
|
||||
assert (
|
||||
len(
|
||||
[
|
||||
p
|
||||
for p in audit.REFERENCE_PROFILES
|
||||
if p not in (*audit.SCAIL_LOAD_PROFILES, audit.GRID_PROFILE)
|
||||
]
|
||||
)
|
||||
== 22
|
||||
)
|
||||
assert tuple(audit.REFERENCE_PROFILES[:20]) == tuple(old["profiles"])
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,386 @@
|
||||
"""Recompute grid 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 = "0609341afaab955755b2f17d64e449727f65784c"
|
||||
|
||||
|
||||
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.structure_reference import (
|
||||
GRID_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/grid-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/scail-load-evidence/library.json").read_bytes()
|
||||
)
|
||||
profiles = tuple(old["profiles"])
|
||||
assert len(profiles) == 24
|
||||
assert profiles == tuple(p for p in audit.REFERENCE_PROFILES if p != GRID_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"][:24]
|
||||
assert a.get("comparisons") == b.get("comparisons") == c.get("comparisons")
|
||||
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 1.41.20 profile; applicability is not 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 copy import deepcopy
|
||||
|
||||
from calliope.comfyui.ui2api import convert_reference
|
||||
|
||||
target = next((repo / "example_ComfyUI_workflows").rglob("图像合并成四宫格.json"))
|
||||
source = json.loads(target.read_bytes())
|
||||
actual = convert_reference(source, GRID_PROFILE)
|
||||
assert actual.prompt is None
|
||||
row = next(
|
||||
r
|
||||
for r in now["cases"]
|
||||
if r["source_path"] == target.relative_to(repo).as_posix()
|
||||
)
|
||||
assert row["comparison_status"] == "comparison_unavailable"
|
||||
write(
|
||||
"actual-grid.json",
|
||||
{
|
||||
"source_path": row["source_path"],
|
||||
"source_sha256": row["source_sha256"],
|
||||
"profile": GRID_PROFILE,
|
||||
"prompt": actual.prompt,
|
||||
"issues": actual.issues,
|
||||
"comparison_status": row["comparison_status"],
|
||||
"ue_record": "all nine entities have ue_properties.version=7.7, both maps empty; implementation and hook ordering unknown",
|
||||
"source_nodes": source["nodes"],
|
||||
"source_edges": source["links"],
|
||||
"original_bytes_modified": False,
|
||||
},
|
||||
)
|
||||
# Deliberately counterfactual. This NEVER enters the library candidate report.
|
||||
synthetic = deepcopy(source)
|
||||
for n in synthetic["nodes"]:
|
||||
n["properties"].pop("ue_properties", None)
|
||||
result = convert_reference(synthetic, GRID_PROFILE)
|
||||
assert result.prompt is not None, result.issues
|
||||
fields = audit.grid_field_evidence(synthetic, result.prompt)
|
||||
assert len(fields) == 30
|
||||
write(
|
||||
"synthetic-no-ue-grid.json",
|
||||
{
|
||||
"authority": "synthetic_no_ue_counterfactual_not_original_conversion_or_API_export",
|
||||
"premise": "ue_properties removed only in a deep copy; actual source always refused",
|
||||
"candidate_sha256": audit.canonical_sha(result.prompt),
|
||||
"candidate_prompt": result.prompt,
|
||||
"field_evidence": fields,
|
||||
"metadata": [
|
||||
{
|
||||
"node_id": str(n["id"]),
|
||||
"source_pointer": f"/nodes/{i}",
|
||||
"value": result.prompt[str(n["id"])]["_meta"],
|
||||
}
|
||||
for i, n in enumerate(source["nodes"])
|
||||
if str(n["id"]) in result.prompt
|
||||
],
|
||||
"excluded_virtual_note": {
|
||||
"pointer": "/nodes/8",
|
||||
"node_id": "24",
|
||||
"reason": "pinned MarkdownNote.isVirtualNode=true; no edges",
|
||||
},
|
||||
"comparison_status": "comparison_unavailable",
|
||||
"execution_verified": False,
|
||||
},
|
||||
)
|
||||
inventory = row["inventory"]
|
||||
|
||||
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",
|
||||
]
|
||||
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 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",
|
||||
},
|
||||
)
|
||||
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 [
|
||||
"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()
|
||||
@@ -0,0 +1,674 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
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.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
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 <https://www.gnu.org/licenses/>.
|
||||
|
||||
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:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
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
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
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
|
||||
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1 @@
|
||||
from ._io import * # noqa: F403
|
||||
@@ -0,0 +1,849 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import nodes
|
||||
import folder_paths
|
||||
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import math
|
||||
import torch
|
||||
import comfy.utils
|
||||
|
||||
from server import PromptServer
|
||||
from comfy_api.latest import ComfyExtension, IO, UI
|
||||
from typing_extensions import override
|
||||
|
||||
SVG = IO.SVG.Type # TODO: temporary solution for backward compatibility, will be removed later.
|
||||
|
||||
MAX_RESOLUTION = nodes.MAX_RESOLUTION
|
||||
|
||||
class ImageCrop(IO.ComfyNode):
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
return IO.Schema(
|
||||
node_id="ImageCrop",
|
||||
search_aliases=["trim"],
|
||||
display_name="Image Crop (Deprecated)",
|
||||
category="image/transform",
|
||||
is_deprecated=True,
|
||||
essentials_category="Image Tools",
|
||||
inputs=[
|
||||
IO.Image.Input("image"),
|
||||
IO.Int.Input("width", default=512, min=1, max=nodes.MAX_RESOLUTION, step=1),
|
||||
IO.Int.Input("height", default=512, min=1, max=nodes.MAX_RESOLUTION, step=1),
|
||||
IO.Int.Input("x", default=0, min=0, max=nodes.MAX_RESOLUTION, step=1),
|
||||
IO.Int.Input("y", default=0, min=0, max=nodes.MAX_RESOLUTION, step=1),
|
||||
],
|
||||
outputs=[IO.Image.Output()],
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def execute(cls, image, width, height, x, y) -> IO.NodeOutput:
|
||||
x = min(x, image.shape[2] - 1)
|
||||
y = min(y, image.shape[1] - 1)
|
||||
to_x = width + x
|
||||
to_y = height + y
|
||||
img = image[:,y:to_y, x:to_x, :]
|
||||
return IO.NodeOutput(img)
|
||||
|
||||
crop = execute # TODO: remove
|
||||
|
||||
|
||||
class ImageCropV2(IO.ComfyNode):
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
return IO.Schema(
|
||||
node_id="ImageCropV2",
|
||||
search_aliases=["trim"],
|
||||
display_name="Image Crop",
|
||||
category="image/transform",
|
||||
inputs=[
|
||||
IO.Image.Input("image"),
|
||||
IO.BoundingBox.Input("crop_region", component="ImageCrop"),
|
||||
],
|
||||
outputs=[IO.Image.Output()],
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def execute(cls, image, crop_region) -> IO.NodeOutput:
|
||||
x = crop_region.get("x", 0)
|
||||
y = crop_region.get("y", 0)
|
||||
width = crop_region.get("width", 512)
|
||||
height = crop_region.get("height", 512)
|
||||
|
||||
x = min(x, image.shape[2] - 1)
|
||||
y = min(y, image.shape[1] - 1)
|
||||
to_x = width + x
|
||||
to_y = height + y
|
||||
img = image[:,y:to_y, x:to_x, :]
|
||||
return IO.NodeOutput(img, ui=UI.PreviewImage(img))
|
||||
|
||||
|
||||
class BoundingBox(IO.ComfyNode):
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
return IO.Schema(
|
||||
node_id="PrimitiveBoundingBox",
|
||||
display_name="Bounding Box",
|
||||
category="utils/primitive",
|
||||
inputs=[
|
||||
IO.Int.Input("x", default=0, min=0, max=MAX_RESOLUTION),
|
||||
IO.Int.Input("y", default=0, min=0, max=MAX_RESOLUTION),
|
||||
IO.Int.Input("width", default=512, min=1, max=MAX_RESOLUTION),
|
||||
IO.Int.Input("height", default=512, min=1, max=MAX_RESOLUTION),
|
||||
],
|
||||
outputs=[IO.BoundingBox.Output()],
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def execute(cls, x, y, width, height) -> IO.NodeOutput:
|
||||
return IO.NodeOutput({"x": x, "y": y, "width": width, "height": height})
|
||||
|
||||
|
||||
class RepeatImageBatch(IO.ComfyNode):
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
return IO.Schema(
|
||||
node_id="RepeatImageBatch",
|
||||
search_aliases=["duplicate image", "clone image"],
|
||||
category="image/batch",
|
||||
inputs=[
|
||||
IO.Image.Input("image"),
|
||||
IO.Int.Input("amount", default=1, min=1, max=4096),
|
||||
],
|
||||
outputs=[IO.Image.Output()],
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def execute(cls, image, amount) -> IO.NodeOutput:
|
||||
s = image.repeat((amount, 1,1,1))
|
||||
return IO.NodeOutput(s)
|
||||
|
||||
repeat = execute # TODO: remove
|
||||
|
||||
|
||||
class ImageFromBatch(IO.ComfyNode):
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
return IO.Schema(
|
||||
node_id="ImageFromBatch",
|
||||
search_aliases=["select image", "pick from batch", "extract image"],
|
||||
category="image/batch",
|
||||
inputs=[
|
||||
IO.Image.Input("image"),
|
||||
IO.Int.Input("batch_index", default=0, min=0, max=4095),
|
||||
IO.Int.Input("length", default=1, min=1, max=4096),
|
||||
],
|
||||
outputs=[IO.Image.Output()],
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def execute(cls, image, batch_index, length) -> IO.NodeOutput:
|
||||
s_in = image
|
||||
batch_index = min(s_in.shape[0] - 1, batch_index)
|
||||
length = min(s_in.shape[0] - batch_index, length)
|
||||
s = s_in[batch_index:batch_index + length].clone()
|
||||
return IO.NodeOutput(s)
|
||||
|
||||
frombatch = execute # TODO: remove
|
||||
|
||||
|
||||
class ImageAddNoise(IO.ComfyNode):
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
return IO.Schema(
|
||||
node_id="ImageAddNoise",
|
||||
search_aliases=["film grain"],
|
||||
category="image",
|
||||
inputs=[
|
||||
IO.Image.Input("image"),
|
||||
IO.Int.Input(
|
||||
"seed",
|
||||
default=0,
|
||||
min=0,
|
||||
max=0xFFFFFFFFFFFFFFFF,
|
||||
control_after_generate=True,
|
||||
tooltip="The random seed used for creating the noise.",
|
||||
),
|
||||
IO.Float.Input("strength", default=0.5, min=0.0, max=1.0, step=0.01),
|
||||
],
|
||||
outputs=[IO.Image.Output()],
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def execute(cls, image, seed, strength) -> IO.NodeOutput:
|
||||
generator = torch.manual_seed(seed)
|
||||
s = torch.clip((image + strength * torch.randn(image.size(), generator=generator, device="cpu").to(image)), min=0.0, max=1.0)
|
||||
return IO.NodeOutput(s)
|
||||
|
||||
repeat = execute # TODO: remove
|
||||
|
||||
|
||||
class SaveAnimatedWEBP(IO.ComfyNode):
|
||||
COMPRESS_METHODS = {"default": 4, "fastest": 0, "slowest": 6}
|
||||
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
return IO.Schema(
|
||||
node_id="SaveAnimatedWEBP",
|
||||
category="image/animation",
|
||||
inputs=[
|
||||
IO.Image.Input("images"),
|
||||
IO.String.Input("filename_prefix", default="ComfyUI"),
|
||||
IO.Float.Input("fps", default=6.0, min=0.01, max=1000.0, step=0.01),
|
||||
IO.Boolean.Input("lossless", default=True),
|
||||
IO.Int.Input("quality", default=80, min=0, max=100),
|
||||
IO.Combo.Input("method", options=list(cls.COMPRESS_METHODS.keys())),
|
||||
# "num_frames": ("INT", {"default": 0, "min": 0, "max": 8192}),
|
||||
],
|
||||
hidden=[IO.Hidden.prompt, IO.Hidden.extra_pnginfo],
|
||||
is_output_node=True,
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def execute(cls, images, fps, filename_prefix, lossless, quality, method, num_frames=0) -> IO.NodeOutput:
|
||||
return IO.NodeOutput(
|
||||
ui=UI.ImageSaveHelper.get_save_animated_webp_ui(
|
||||
images=images,
|
||||
filename_prefix=filename_prefix,
|
||||
cls=cls,
|
||||
fps=fps,
|
||||
lossless=lossless,
|
||||
quality=quality,
|
||||
method=cls.COMPRESS_METHODS.get(method)
|
||||
)
|
||||
)
|
||||
|
||||
save_images = execute # TODO: remove
|
||||
|
||||
|
||||
class SaveAnimatedPNG(IO.ComfyNode):
|
||||
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
return IO.Schema(
|
||||
node_id="SaveAnimatedPNG",
|
||||
category="image/animation",
|
||||
inputs=[
|
||||
IO.Image.Input("images"),
|
||||
IO.String.Input("filename_prefix", default="ComfyUI"),
|
||||
IO.Float.Input("fps", default=6.0, min=0.01, max=1000.0, step=0.01),
|
||||
IO.Int.Input("compress_level", default=4, min=0, max=9, advanced=True),
|
||||
],
|
||||
hidden=[IO.Hidden.prompt, IO.Hidden.extra_pnginfo],
|
||||
is_output_node=True,
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def execute(cls, images, fps, compress_level, filename_prefix="ComfyUI") -> IO.NodeOutput:
|
||||
return IO.NodeOutput(
|
||||
ui=UI.ImageSaveHelper.get_save_animated_png_ui(
|
||||
images=images,
|
||||
filename_prefix=filename_prefix,
|
||||
cls=cls,
|
||||
fps=fps,
|
||||
compress_level=compress_level,
|
||||
)
|
||||
)
|
||||
|
||||
save_images = execute # TODO: remove
|
||||
|
||||
|
||||
class ImageStitch(IO.ComfyNode):
|
||||
"""Upstreamed from https://github.com/kijai/ComfyUI-KJNodes"""
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
return IO.Schema(
|
||||
node_id="ImageStitch",
|
||||
search_aliases=["combine images", "join images", "concatenate images", "side by side"],
|
||||
display_name="Image Stitch",
|
||||
description="Stitches image2 to image1 in the specified direction.\n"
|
||||
"If image2 is not provided, returns image1 unchanged.\n"
|
||||
"Optional spacing can be added between images.",
|
||||
category="image/transform",
|
||||
inputs=[
|
||||
IO.Image.Input("image1"),
|
||||
IO.Combo.Input("direction", options=["right", "down", "left", "up"], default="right"),
|
||||
IO.Boolean.Input("match_image_size", default=True),
|
||||
IO.Int.Input("spacing_width", default=0, min=0, max=1024, step=2, advanced=True),
|
||||
IO.Combo.Input("spacing_color", options=["white", "black", "red", "green", "blue"], default="white", advanced=True),
|
||||
IO.Image.Input("image2", optional=True),
|
||||
],
|
||||
outputs=[IO.Image.Output()],
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def execute(
|
||||
cls,
|
||||
image1,
|
||||
direction,
|
||||
match_image_size,
|
||||
spacing_width,
|
||||
spacing_color,
|
||||
image2=None,
|
||||
) -> IO.NodeOutput:
|
||||
if image2 is None:
|
||||
return IO.NodeOutput(image1)
|
||||
|
||||
# Handle batch size differences
|
||||
if image1.shape[0] != image2.shape[0]:
|
||||
max_batch = max(image1.shape[0], image2.shape[0])
|
||||
if image1.shape[0] < max_batch:
|
||||
image1 = torch.cat(
|
||||
[image1, image1[-1:].repeat(max_batch - image1.shape[0], 1, 1, 1)]
|
||||
)
|
||||
if image2.shape[0] < max_batch:
|
||||
image2 = torch.cat(
|
||||
[image2, image2[-1:].repeat(max_batch - image2.shape[0], 1, 1, 1)]
|
||||
)
|
||||
|
||||
# Match image sizes if requested
|
||||
if match_image_size:
|
||||
h1, w1 = image1.shape[1:3]
|
||||
h2, w2 = image2.shape[1:3]
|
||||
aspect_ratio = w2 / h2
|
||||
|
||||
if direction in ["left", "right"]:
|
||||
target_h, target_w = h1, int(h1 * aspect_ratio)
|
||||
else: # up, down
|
||||
target_w, target_h = w1, int(w1 / aspect_ratio)
|
||||
|
||||
image2 = comfy.utils.common_upscale(
|
||||
image2.movedim(-1, 1), target_w, target_h, "lanczos", "disabled"
|
||||
).movedim(1, -1)
|
||||
|
||||
color_map = {
|
||||
"white": 1.0,
|
||||
"black": 0.0,
|
||||
"red": (1.0, 0.0, 0.0),
|
||||
"green": (0.0, 1.0, 0.0),
|
||||
"blue": (0.0, 0.0, 1.0),
|
||||
}
|
||||
|
||||
color_val = color_map[spacing_color]
|
||||
|
||||
# When not matching sizes, pad to align non-concat dimensions
|
||||
if not match_image_size:
|
||||
h1, w1 = image1.shape[1:3]
|
||||
h2, w2 = image2.shape[1:3]
|
||||
pad_value = 0.0
|
||||
if not isinstance(color_val, tuple):
|
||||
pad_value = color_val
|
||||
|
||||
if direction in ["left", "right"]:
|
||||
# For horizontal concat, pad heights to match
|
||||
if h1 != h2:
|
||||
target_h = max(h1, h2)
|
||||
if h1 < target_h:
|
||||
pad_h = target_h - h1
|
||||
pad_top, pad_bottom = pad_h // 2, pad_h - pad_h // 2
|
||||
image1 = torch.nn.functional.pad(image1, (0, 0, 0, 0, pad_top, pad_bottom), mode='constant', value=pad_value)
|
||||
if h2 < target_h:
|
||||
pad_h = target_h - h2
|
||||
pad_top, pad_bottom = pad_h // 2, pad_h - pad_h // 2
|
||||
image2 = torch.nn.functional.pad(image2, (0, 0, 0, 0, pad_top, pad_bottom), mode='constant', value=pad_value)
|
||||
else: # up, down
|
||||
# For vertical concat, pad widths to match
|
||||
if w1 != w2:
|
||||
target_w = max(w1, w2)
|
||||
if w1 < target_w:
|
||||
pad_w = target_w - w1
|
||||
pad_left, pad_right = pad_w // 2, pad_w - pad_w // 2
|
||||
image1 = torch.nn.functional.pad(image1, (0, 0, pad_left, pad_right), mode='constant', value=pad_value)
|
||||
if w2 < target_w:
|
||||
pad_w = target_w - w2
|
||||
pad_left, pad_right = pad_w // 2, pad_w - pad_w // 2
|
||||
image2 = torch.nn.functional.pad(image2, (0, 0, pad_left, pad_right), mode='constant', value=pad_value)
|
||||
|
||||
# Ensure same number of channels
|
||||
if image1.shape[-1] != image2.shape[-1]:
|
||||
max_channels = max(image1.shape[-1], image2.shape[-1])
|
||||
if image1.shape[-1] < max_channels:
|
||||
image1 = torch.cat(
|
||||
[
|
||||
image1,
|
||||
torch.ones(
|
||||
*image1.shape[:-1],
|
||||
max_channels - image1.shape[-1],
|
||||
device=image1.device,
|
||||
),
|
||||
],
|
||||
dim=-1,
|
||||
)
|
||||
if image2.shape[-1] < max_channels:
|
||||
image2 = torch.cat(
|
||||
[
|
||||
image2,
|
||||
torch.ones(
|
||||
*image2.shape[:-1],
|
||||
max_channels - image2.shape[-1],
|
||||
device=image2.device,
|
||||
),
|
||||
],
|
||||
dim=-1,
|
||||
)
|
||||
|
||||
# Add spacing if specified
|
||||
if spacing_width > 0:
|
||||
spacing_width = spacing_width + (spacing_width % 2) # Ensure even
|
||||
|
||||
if direction in ["left", "right"]:
|
||||
spacing_shape = (
|
||||
image1.shape[0],
|
||||
max(image1.shape[1], image2.shape[1]),
|
||||
spacing_width,
|
||||
image1.shape[-1],
|
||||
)
|
||||
else:
|
||||
spacing_shape = (
|
||||
image1.shape[0],
|
||||
spacing_width,
|
||||
max(image1.shape[2], image2.shape[2]),
|
||||
image1.shape[-1],
|
||||
)
|
||||
|
||||
spacing = torch.full(spacing_shape, 0.0, device=image1.device)
|
||||
if isinstance(color_val, tuple):
|
||||
for i, c in enumerate(color_val):
|
||||
if i < spacing.shape[-1]:
|
||||
spacing[..., i] = c
|
||||
if spacing.shape[-1] == 4: # Add alpha
|
||||
spacing[..., 3] = 1.0
|
||||
else:
|
||||
spacing[..., : min(3, spacing.shape[-1])] = color_val
|
||||
if spacing.shape[-1] == 4:
|
||||
spacing[..., 3] = 1.0
|
||||
|
||||
# Concatenate images
|
||||
images = [image2, image1] if direction in ["left", "up"] else [image1, image2]
|
||||
if spacing_width > 0:
|
||||
images.insert(1, spacing)
|
||||
|
||||
concat_dim = 2 if direction in ["left", "right"] else 1
|
||||
return IO.NodeOutput(torch.cat(images, dim=concat_dim))
|
||||
|
||||
stitch = execute # TODO: remove
|
||||
|
||||
|
||||
class ResizeAndPadImage(IO.ComfyNode):
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
return IO.Schema(
|
||||
node_id="ResizeAndPadImage",
|
||||
search_aliases=["fit to size"],
|
||||
category="image/transform",
|
||||
inputs=[
|
||||
IO.Image.Input("image"),
|
||||
IO.Int.Input("target_width", default=512, min=1, max=nodes.MAX_RESOLUTION, step=1),
|
||||
IO.Int.Input("target_height", default=512, min=1, max=nodes.MAX_RESOLUTION, step=1),
|
||||
IO.Combo.Input("padding_color", options=["white", "black"], advanced=True),
|
||||
IO.Combo.Input("interpolation", options=["area", "bicubic", "nearest-exact", "bilinear", "lanczos"], advanced=True),
|
||||
],
|
||||
outputs=[IO.Image.Output()],
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def execute(cls, image, target_width, target_height, padding_color, interpolation) -> IO.NodeOutput:
|
||||
batch_size, orig_height, orig_width, channels = image.shape
|
||||
|
||||
scale_w = target_width / orig_width
|
||||
scale_h = target_height / orig_height
|
||||
scale = min(scale_w, scale_h)
|
||||
|
||||
new_width = int(orig_width * scale)
|
||||
new_height = int(orig_height * scale)
|
||||
|
||||
image_permuted = image.permute(0, 3, 1, 2)
|
||||
|
||||
resized = comfy.utils.common_upscale(image_permuted, new_width, new_height, interpolation, "disabled")
|
||||
|
||||
pad_value = 0.0 if padding_color == "black" else 1.0
|
||||
padded = torch.full(
|
||||
(batch_size, channels, target_height, target_width),
|
||||
pad_value,
|
||||
dtype=image.dtype,
|
||||
device=image.device
|
||||
)
|
||||
|
||||
y_offset = (target_height - new_height) // 2
|
||||
x_offset = (target_width - new_width) // 2
|
||||
|
||||
padded[:, :, y_offset:y_offset + new_height, x_offset:x_offset + new_width] = resized
|
||||
|
||||
output = padded.permute(0, 2, 3, 1)
|
||||
return IO.NodeOutput(output)
|
||||
|
||||
resize_and_pad = execute # TODO: remove
|
||||
|
||||
|
||||
class SaveSVGNode(IO.ComfyNode):
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
return IO.Schema(
|
||||
node_id="SaveSVGNode",
|
||||
search_aliases=["export vector", "save vector graphics"],
|
||||
description="Save SVG files on disk.",
|
||||
category="image/save",
|
||||
inputs=[
|
||||
IO.SVG.Input("svg"),
|
||||
IO.String.Input(
|
||||
"filename_prefix",
|
||||
default="svg/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=[IO.Hidden.prompt, IO.Hidden.extra_pnginfo],
|
||||
is_output_node=True,
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def execute(cls, svg: IO.SVG.Type, filename_prefix="svg/ComfyUI") -> IO.NodeOutput:
|
||||
full_output_folder, filename, counter, subfolder, filename_prefix = folder_paths.get_save_image_path(filename_prefix, folder_paths.get_output_directory())
|
||||
results: list[UI.SavedResult] = []
|
||||
|
||||
# Prepare metadata JSON
|
||||
metadata_dict = {}
|
||||
if cls.hidden.prompt is not None:
|
||||
metadata_dict["prompt"] = cls.hidden.prompt
|
||||
if cls.hidden.extra_pnginfo is not None:
|
||||
metadata_dict.update(cls.hidden.extra_pnginfo)
|
||||
|
||||
# Convert metadata to JSON string
|
||||
metadata_json = json.dumps(metadata_dict, indent=2) if metadata_dict else None
|
||||
|
||||
|
||||
for batch_number, svg_bytes in enumerate(svg.data):
|
||||
filename_with_batch_num = filename.replace("%batch_num%", str(batch_number))
|
||||
file = f"{filename_with_batch_num}_{counter:05}_.svg"
|
||||
|
||||
# Read SVG content
|
||||
svg_bytes.seek(0)
|
||||
svg_content = svg_bytes.read().decode('utf-8')
|
||||
|
||||
# Inject metadata if available
|
||||
if metadata_json:
|
||||
# Create metadata element with CDATA section
|
||||
metadata_element = f""" <metadata>
|
||||
<![CDATA[
|
||||
{metadata_json}
|
||||
]]>
|
||||
</metadata>
|
||||
"""
|
||||
# Insert metadata after opening svg tag using regex with a replacement function
|
||||
def replacement(match):
|
||||
# match.group(1) contains the captured <svg> tag
|
||||
return match.group(1) + '\n' + metadata_element
|
||||
|
||||
# Apply the substitution
|
||||
svg_content = re.sub(r'(<svg[^>]*>)', replacement, svg_content, flags=re.UNICODE)
|
||||
|
||||
# Write the modified SVG to file
|
||||
with open(os.path.join(full_output_folder, file), 'wb') as svg_file:
|
||||
svg_file.write(svg_content.encode('utf-8'))
|
||||
|
||||
results.append(UI.SavedResult(filename=file, subfolder=subfolder, type=IO.FolderType.output))
|
||||
counter += 1
|
||||
return IO.NodeOutput(ui={"images": results})
|
||||
|
||||
save_svg = execute # TODO: remove
|
||||
|
||||
|
||||
class GetImageSize(IO.ComfyNode):
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
return IO.Schema(
|
||||
node_id="GetImageSize",
|
||||
search_aliases=["dimensions", "resolution", "image info"],
|
||||
display_name="Get Image Size",
|
||||
description="Returns width and height of the image, and passes it through unchanged.",
|
||||
category="image",
|
||||
inputs=[
|
||||
IO.Image.Input("image"),
|
||||
],
|
||||
outputs=[
|
||||
IO.Int.Output(display_name="width"),
|
||||
IO.Int.Output(display_name="height"),
|
||||
IO.Int.Output(display_name="batch_size"),
|
||||
],
|
||||
hidden=[IO.Hidden.unique_id],
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def execute(cls, image) -> IO.NodeOutput:
|
||||
height = image.shape[1]
|
||||
width = image.shape[2]
|
||||
batch_size = image.shape[0]
|
||||
|
||||
# Send progress text to display size on the node
|
||||
if cls.hidden.unique_id:
|
||||
PromptServer.instance.send_progress_text(f"width: {width}, height: {height}\n batch size: {batch_size}", cls.hidden.unique_id)
|
||||
|
||||
return IO.NodeOutput(width, height, batch_size)
|
||||
|
||||
get_size = execute # TODO: remove
|
||||
|
||||
|
||||
class ImageRotate(IO.ComfyNode):
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
return IO.Schema(
|
||||
node_id="ImageRotate",
|
||||
display_name="Image Rotate",
|
||||
search_aliases=["turn", "flip orientation"],
|
||||
category="image/transform",
|
||||
essentials_category="Image Tools",
|
||||
inputs=[
|
||||
IO.Image.Input("image"),
|
||||
IO.Combo.Input("rotation", options=["none", "90 degrees", "180 degrees", "270 degrees"]),
|
||||
],
|
||||
outputs=[IO.Image.Output()],
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def execute(cls, image, rotation) -> IO.NodeOutput:
|
||||
rotate_by = 0
|
||||
if rotation.startswith("90"):
|
||||
rotate_by = 1
|
||||
elif rotation.startswith("180"):
|
||||
rotate_by = 2
|
||||
elif rotation.startswith("270"):
|
||||
rotate_by = 3
|
||||
|
||||
image = torch.rot90(image, k=rotate_by, dims=[2, 1])
|
||||
return IO.NodeOutput(image)
|
||||
|
||||
rotate = execute # TODO: remove
|
||||
|
||||
|
||||
class ImageFlip(IO.ComfyNode):
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
return IO.Schema(
|
||||
node_id="ImageFlip",
|
||||
search_aliases=["mirror", "reflect"],
|
||||
category="image/transform",
|
||||
inputs=[
|
||||
IO.Image.Input("image"),
|
||||
IO.Combo.Input("flip_method", options=["x-axis: vertically", "y-axis: horizontally"]),
|
||||
],
|
||||
outputs=[IO.Image.Output()],
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def execute(cls, image, flip_method) -> IO.NodeOutput:
|
||||
if flip_method.startswith("x"):
|
||||
image = torch.flip(image, dims=[1])
|
||||
elif flip_method.startswith("y"):
|
||||
image = torch.flip(image, dims=[2])
|
||||
|
||||
return IO.NodeOutput(image)
|
||||
|
||||
flip = execute # TODO: remove
|
||||
|
||||
|
||||
class ImageScaleToMaxDimension(IO.ComfyNode):
|
||||
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
return IO.Schema(
|
||||
node_id="ImageScaleToMaxDimension",
|
||||
category="image/upscaling",
|
||||
inputs=[
|
||||
IO.Image.Input("image"),
|
||||
IO.Combo.Input(
|
||||
"upscale_method",
|
||||
options=["area", "lanczos", "bilinear", "nearest-exact", "bilinear", "bicubic"],
|
||||
),
|
||||
IO.Int.Input("largest_size", default=512, min=0, max=MAX_RESOLUTION, step=1),
|
||||
],
|
||||
outputs=[IO.Image.Output()],
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def execute(cls, image, upscale_method, largest_size) -> IO.NodeOutput:
|
||||
height = image.shape[1]
|
||||
width = image.shape[2]
|
||||
|
||||
if height > width:
|
||||
width = round((width / height) * largest_size)
|
||||
height = largest_size
|
||||
elif width > height:
|
||||
height = round((height / width) * largest_size)
|
||||
width = largest_size
|
||||
else:
|
||||
height = largest_size
|
||||
width = largest_size
|
||||
|
||||
samples = image.movedim(-1, 1)
|
||||
s = comfy.utils.common_upscale(samples, width, height, upscale_method, "disabled")
|
||||
s = s.movedim(1, -1)
|
||||
return IO.NodeOutput(s)
|
||||
|
||||
upscale = execute # TODO: remove
|
||||
|
||||
|
||||
class SplitImageToTileList(IO.ComfyNode):
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
return IO.Schema(
|
||||
node_id="SplitImageToTileList",
|
||||
category="image/batch",
|
||||
search_aliases=["split image", "tile image", "slice image"],
|
||||
display_name="Split Image into List of Tiles",
|
||||
description="Splits an image into a batched list of tiles with a specified overlap.",
|
||||
inputs=[
|
||||
IO.Image.Input("image"),
|
||||
IO.Int.Input("tile_width", default=1024, min=64, max=MAX_RESOLUTION),
|
||||
IO.Int.Input("tile_height", default=1024, min=64, max=MAX_RESOLUTION),
|
||||
IO.Int.Input("overlap", default=128, min=0, max=4096),
|
||||
],
|
||||
outputs=[
|
||||
IO.Image.Output(is_output_list=True),
|
||||
],
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def get_grid_coords(width, height, tile_width, tile_height, overlap):
|
||||
coords = []
|
||||
stride_x = round(max(tile_width * 0.25, tile_width - overlap))
|
||||
stride_y = round(max(tile_width * 0.25, tile_height - overlap))
|
||||
|
||||
y = 0
|
||||
while y < height:
|
||||
x = 0
|
||||
y_end = min(y + tile_height, height)
|
||||
y_start = max(0, y_end - tile_height)
|
||||
|
||||
while x < width:
|
||||
x_end = min(x + tile_width, width)
|
||||
x_start = max(0, x_end - tile_width)
|
||||
|
||||
coords.append((x_start, y_start, x_end, y_end))
|
||||
|
||||
if x_end >= width:
|
||||
break
|
||||
x += stride_x
|
||||
|
||||
if y_end >= height:
|
||||
break
|
||||
y += stride_y
|
||||
|
||||
return coords
|
||||
|
||||
@classmethod
|
||||
def execute(cls, image, tile_width, tile_height, overlap):
|
||||
b, h, w, c = image.shape
|
||||
coords = cls.get_grid_coords(w, h, tile_width, tile_height, overlap)
|
||||
|
||||
output_list = []
|
||||
for (x_start, y_start, x_end, y_end) in coords:
|
||||
tile = image[:, y_start:y_end, x_start:x_end, :]
|
||||
output_list.append(tile)
|
||||
|
||||
return IO.NodeOutput(output_list)
|
||||
|
||||
|
||||
class ImageMergeTileList(IO.ComfyNode):
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
return IO.Schema(
|
||||
node_id="ImageMergeTileList",
|
||||
display_name="Merge List of Tiles to Image",
|
||||
category="image/batch",
|
||||
search_aliases=["split image", "tile image", "slice image"],
|
||||
is_input_list=True,
|
||||
inputs=[
|
||||
IO.Image.Input("image_list"),
|
||||
IO.Int.Input("final_width", default=1024, min=64, max=32768),
|
||||
IO.Int.Input("final_height", default=1024, min=64, max=32768),
|
||||
IO.Int.Input("overlap", default=128, min=0, max=4096),
|
||||
],
|
||||
outputs=[
|
||||
IO.Image.Output(is_output_list=False),
|
||||
],
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def execute(cls, image_list, final_width, final_height, overlap):
|
||||
w = final_width[0]
|
||||
h = final_height[0]
|
||||
ovlp = overlap[0]
|
||||
feather_str = 1.0
|
||||
|
||||
first_tile = image_list[0]
|
||||
b, t_h, t_w, c = first_tile.shape
|
||||
device = first_tile.device
|
||||
dtype = first_tile.dtype
|
||||
|
||||
coords = SplitImageToTileList.get_grid_coords(w, h, t_w, t_h, ovlp)
|
||||
|
||||
canvas = torch.zeros((b, h, w, c), device=device, dtype=dtype)
|
||||
weights = torch.zeros((b, h, w, 1), device=device, dtype=dtype)
|
||||
|
||||
if ovlp > 0:
|
||||
y_w = torch.sin(math.pi * torch.linspace(0, 1, t_h, device=device, dtype=dtype))
|
||||
x_w = torch.sin(math.pi * torch.linspace(0, 1, t_w, device=device, dtype=dtype))
|
||||
y_w = torch.clamp(y_w, min=1e-5)
|
||||
x_w = torch.clamp(x_w, min=1e-5)
|
||||
|
||||
sine_mask = (y_w.unsqueeze(1) * x_w.unsqueeze(0)).unsqueeze(0).unsqueeze(-1)
|
||||
flat_mask = torch.ones_like(sine_mask)
|
||||
|
||||
weight_mask = torch.lerp(flat_mask, sine_mask, feather_str)
|
||||
else:
|
||||
weight_mask = torch.ones((1, t_h, t_w, 1), device=device, dtype=dtype)
|
||||
|
||||
for i, (x_start, y_start, x_end, y_end) in enumerate(coords):
|
||||
if i >= len(image_list):
|
||||
break
|
||||
|
||||
tile = image_list[i]
|
||||
|
||||
region_h = y_end - y_start
|
||||
region_w = x_end - x_start
|
||||
|
||||
real_h = min(region_h, tile.shape[1])
|
||||
real_w = min(region_w, tile.shape[2])
|
||||
|
||||
y_end_actual = y_start + real_h
|
||||
x_end_actual = x_start + real_w
|
||||
|
||||
tile_crop = tile[:, :real_h, :real_w, :]
|
||||
mask_crop = weight_mask[:, :real_h, :real_w, :]
|
||||
|
||||
canvas[:, y_start:y_end_actual, x_start:x_end_actual, :] += tile_crop * mask_crop
|
||||
weights[:, y_start:y_end_actual, x_start:x_end_actual, :] += mask_crop
|
||||
|
||||
weights[weights == 0] = 1.0
|
||||
merged_image = canvas / weights
|
||||
|
||||
return IO.NodeOutput(merged_image)
|
||||
|
||||
|
||||
class ImagesExtension(ComfyExtension):
|
||||
@override
|
||||
async def get_node_list(self) -> list[type[IO.ComfyNode]]:
|
||||
return [
|
||||
ImageCrop,
|
||||
ImageCropV2,
|
||||
BoundingBox,
|
||||
RepeatImageBatch,
|
||||
ImageFromBatch,
|
||||
ImageAddNoise,
|
||||
SaveAnimatedWEBP,
|
||||
SaveAnimatedPNG,
|
||||
SaveSVGNode,
|
||||
ImageStitch,
|
||||
ResizeAndPadImage,
|
||||
GetImageSize,
|
||||
ImageRotate,
|
||||
ImageFlip,
|
||||
ImageScaleToMaxDimension,
|
||||
SplitImageToTileList,
|
||||
ImageMergeTileList,
|
||||
]
|
||||
|
||||
|
||||
async def comfy_entrypoint() -> ImagesExtension:
|
||||
return ImagesExtension()
|
||||
@@ -0,0 +1,679 @@
|
||||
from typing_extensions import override
|
||||
import numpy as np
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
from PIL import Image
|
||||
import math
|
||||
from enum import Enum
|
||||
from typing import TypedDict, Literal
|
||||
|
||||
import comfy.utils
|
||||
import comfy.model_management
|
||||
from comfy_extras.nodes_latent import reshape_latent_to
|
||||
import node_helpers
|
||||
from comfy_api.latest import ComfyExtension, io
|
||||
from nodes import MAX_RESOLUTION
|
||||
|
||||
class Blend(io.ComfyNode):
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
return io.Schema(
|
||||
node_id="ImageBlend",
|
||||
display_name="Image Blend",
|
||||
category="image/postprocessing",
|
||||
inputs=[
|
||||
io.Image.Input("image1"),
|
||||
io.Image.Input("image2"),
|
||||
io.Float.Input("blend_factor", default=0.5, min=0.0, max=1.0, step=0.01),
|
||||
io.Combo.Input("blend_mode", options=["normal", "multiply", "screen", "overlay", "soft_light", "difference"]),
|
||||
],
|
||||
outputs=[
|
||||
io.Image.Output(),
|
||||
],
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def execute(cls, image1: torch.Tensor, image2: torch.Tensor, blend_factor: float, blend_mode: str) -> io.NodeOutput:
|
||||
image1, image2 = node_helpers.image_alpha_fix(image1, image2)
|
||||
image2 = image2.to(image1.device)
|
||||
if image1.shape != image2.shape:
|
||||
image2 = image2.permute(0, 3, 1, 2)
|
||||
image2 = comfy.utils.common_upscale(image2, image1.shape[2], image1.shape[1], upscale_method='bicubic', crop='center')
|
||||
image2 = image2.permute(0, 2, 3, 1)
|
||||
|
||||
blended_image = cls.blend_mode(image1, image2, blend_mode)
|
||||
blended_image = image1 * (1 - blend_factor) + blended_image * blend_factor
|
||||
blended_image = torch.clamp(blended_image, 0, 1)
|
||||
return io.NodeOutput(blended_image)
|
||||
|
||||
@classmethod
|
||||
def blend_mode(cls, img1, img2, mode):
|
||||
if mode == "normal":
|
||||
return img2
|
||||
elif mode == "multiply":
|
||||
return img1 * img2
|
||||
elif mode == "screen":
|
||||
return 1 - (1 - img1) * (1 - img2)
|
||||
elif mode == "overlay":
|
||||
return torch.where(img1 <= 0.5, 2 * img1 * img2, 1 - 2 * (1 - img1) * (1 - img2))
|
||||
elif mode == "soft_light":
|
||||
return torch.where(img2 <= 0.5, img1 - (1 - 2 * img2) * img1 * (1 - img1), img1 + (2 * img2 - 1) * (cls.g(img1) - img1))
|
||||
elif mode == "difference":
|
||||
return img1 - img2
|
||||
raise ValueError(f"Unsupported blend mode: {mode}")
|
||||
|
||||
@classmethod
|
||||
def g(cls, x):
|
||||
return torch.where(x <= 0.25, ((16 * x - 12) * x + 4) * x, torch.sqrt(x))
|
||||
|
||||
def gaussian_kernel(kernel_size: int, sigma: float, device=None):
|
||||
x, y = torch.meshgrid(torch.linspace(-1, 1, kernel_size, device=device), torch.linspace(-1, 1, kernel_size, device=device), indexing="ij")
|
||||
d = torch.sqrt(x * x + y * y)
|
||||
g = torch.exp(-(d * d) / (2.0 * sigma * sigma))
|
||||
return g / g.sum()
|
||||
|
||||
class Blur(io.ComfyNode):
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
return io.Schema(
|
||||
node_id="ImageBlur",
|
||||
display_name="Image Blur",
|
||||
category="image/postprocessing",
|
||||
inputs=[
|
||||
io.Image.Input("image"),
|
||||
io.Int.Input("blur_radius", default=1, min=1, max=31, step=1),
|
||||
io.Float.Input("sigma", default=1.0, min=0.1, max=10.0, step=0.1),
|
||||
],
|
||||
outputs=[
|
||||
io.Image.Output(),
|
||||
],
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def execute(cls, image: torch.Tensor, blur_radius: int, sigma: float) -> io.NodeOutput:
|
||||
if blur_radius == 0:
|
||||
return io.NodeOutput(image)
|
||||
|
||||
image = image.to(comfy.model_management.get_torch_device())
|
||||
batch_size, height, width, channels = image.shape
|
||||
|
||||
kernel_size = blur_radius * 2 + 1
|
||||
kernel = gaussian_kernel(kernel_size, sigma, device=image.device).repeat(channels, 1, 1).unsqueeze(1)
|
||||
|
||||
image = image.permute(0, 3, 1, 2) # Torch wants (B, C, H, W) we use (B, H, W, C)
|
||||
padded_image = F.pad(image, (blur_radius,blur_radius,blur_radius,blur_radius), 'reflect')
|
||||
blurred = F.conv2d(padded_image, kernel, padding=kernel_size // 2, groups=channels)[:,:,blur_radius:-blur_radius, blur_radius:-blur_radius]
|
||||
blurred = blurred.permute(0, 2, 3, 1)
|
||||
|
||||
return io.NodeOutput(blurred.to(comfy.model_management.intermediate_device()))
|
||||
|
||||
|
||||
class Quantize(io.ComfyNode):
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
return io.Schema(
|
||||
node_id="ImageQuantize",
|
||||
category="image/postprocessing",
|
||||
inputs=[
|
||||
io.Image.Input("image"),
|
||||
io.Int.Input("colors", default=256, min=1, max=256, step=1),
|
||||
io.Combo.Input("dither", options=["none", "floyd-steinberg", "bayer-2", "bayer-4", "bayer-8", "bayer-16"]),
|
||||
],
|
||||
outputs=[
|
||||
io.Image.Output(),
|
||||
],
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def bayer(im, pal_im, order):
|
||||
def normalized_bayer_matrix(n):
|
||||
if n == 0:
|
||||
return np.zeros((1,1), "float32")
|
||||
else:
|
||||
q = 4 ** n
|
||||
m = q * normalized_bayer_matrix(n - 1)
|
||||
return np.bmat(((m-1.5, m+0.5), (m+1.5, m-0.5))) / q
|
||||
|
||||
num_colors = len(pal_im.getpalette()) // 3
|
||||
spread = 2 * 256 / num_colors
|
||||
bayer_n = int(math.log2(order))
|
||||
bayer_matrix = torch.from_numpy(spread * normalized_bayer_matrix(bayer_n) + 0.5)
|
||||
|
||||
result = torch.from_numpy(np.array(im).astype(np.float32))
|
||||
tw = math.ceil(result.shape[0] / bayer_matrix.shape[0])
|
||||
th = math.ceil(result.shape[1] / bayer_matrix.shape[1])
|
||||
tiled_matrix = bayer_matrix.tile(tw, th).unsqueeze(-1)
|
||||
result.add_(tiled_matrix[:result.shape[0],:result.shape[1]]).clamp_(0, 255)
|
||||
result = result.to(dtype=torch.uint8)
|
||||
|
||||
im = Image.fromarray(result.cpu().numpy())
|
||||
im = im.quantize(palette=pal_im, dither=Image.Dither.NONE)
|
||||
return im
|
||||
|
||||
@classmethod
|
||||
def execute(cls, image: torch.Tensor, colors: int, dither: str) -> io.NodeOutput:
|
||||
batch_size, height, width, _ = image.shape
|
||||
result = torch.zeros_like(image)
|
||||
|
||||
for b in range(batch_size):
|
||||
im = Image.fromarray((image[b] * 255).to(torch.uint8).numpy(), mode='RGB')
|
||||
|
||||
pal_im = im.quantize(colors=colors) # Required as described in https://github.com/python-pillow/Pillow/issues/5836
|
||||
|
||||
if dither == "none":
|
||||
quantized_image = im.quantize(palette=pal_im, dither=Image.Dither.NONE)
|
||||
elif dither == "floyd-steinberg":
|
||||
quantized_image = im.quantize(palette=pal_im, dither=Image.Dither.FLOYDSTEINBERG)
|
||||
elif dither.startswith("bayer"):
|
||||
order = int(dither.split('-')[-1])
|
||||
quantized_image = Quantize.bayer(im, pal_im, order)
|
||||
|
||||
quantized_array = torch.tensor(np.array(quantized_image.convert("RGB"))).float() / 255
|
||||
result[b] = quantized_array
|
||||
|
||||
return io.NodeOutput(result)
|
||||
|
||||
class Sharpen(io.ComfyNode):
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
return io.Schema(
|
||||
node_id="ImageSharpen",
|
||||
category="image/postprocessing",
|
||||
inputs=[
|
||||
io.Image.Input("image"),
|
||||
io.Int.Input("sharpen_radius", default=1, min=1, max=31, step=1, advanced=True),
|
||||
io.Float.Input("sigma", default=1.0, min=0.1, max=10.0, step=0.01, advanced=True),
|
||||
io.Float.Input("alpha", default=1.0, min=0.0, max=5.0, step=0.01, advanced=True),
|
||||
],
|
||||
outputs=[
|
||||
io.Image.Output(),
|
||||
],
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def execute(cls, image: torch.Tensor, sharpen_radius: int, sigma:float, alpha: float) -> io.NodeOutput:
|
||||
if sharpen_radius == 0:
|
||||
return io.NodeOutput(image)
|
||||
|
||||
batch_size, height, width, channels = image.shape
|
||||
image = image.to(comfy.model_management.get_torch_device())
|
||||
|
||||
kernel_size = sharpen_radius * 2 + 1
|
||||
kernel = gaussian_kernel(kernel_size, sigma, device=image.device) * -(alpha*10)
|
||||
kernel = kernel.to(dtype=image.dtype)
|
||||
center = kernel_size // 2
|
||||
kernel[center, center] = kernel[center, center] - kernel.sum() + 1.0
|
||||
kernel = kernel.repeat(channels, 1, 1).unsqueeze(1)
|
||||
|
||||
tensor_image = image.permute(0, 3, 1, 2) # Torch wants (B, C, H, W) we use (B, H, W, C)
|
||||
tensor_image = F.pad(tensor_image, (sharpen_radius,sharpen_radius,sharpen_radius,sharpen_radius), 'reflect')
|
||||
sharpened = F.conv2d(tensor_image, kernel, padding=center, groups=channels)[:,:,sharpen_radius:-sharpen_radius, sharpen_radius:-sharpen_radius]
|
||||
sharpened = sharpened.permute(0, 2, 3, 1)
|
||||
|
||||
result = torch.clamp(sharpened, 0, 1)
|
||||
|
||||
return io.NodeOutput(result.to(comfy.model_management.intermediate_device()))
|
||||
|
||||
class ImageScaleToTotalPixels(io.ComfyNode):
|
||||
upscale_methods = ["nearest-exact", "bilinear", "area", "bicubic", "lanczos"]
|
||||
crop_methods = ["disabled", "center"]
|
||||
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
return io.Schema(
|
||||
node_id="ImageScaleToTotalPixels",
|
||||
category="image/upscaling",
|
||||
inputs=[
|
||||
io.Image.Input("image"),
|
||||
io.Combo.Input("upscale_method", options=cls.upscale_methods),
|
||||
io.Float.Input("megapixels", default=1.0, min=0.01, max=16.0, step=0.01),
|
||||
io.Int.Input("resolution_steps", default=1, min=1, max=256, advanced=True),
|
||||
],
|
||||
outputs=[
|
||||
io.Image.Output(),
|
||||
],
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def execute(cls, image, upscale_method, megapixels, resolution_steps) -> io.NodeOutput:
|
||||
samples = image.movedim(-1,1)
|
||||
total = megapixels * 1024 * 1024
|
||||
|
||||
scale_by = math.sqrt(total / (samples.shape[3] * samples.shape[2]))
|
||||
width = round(samples.shape[3] * scale_by / resolution_steps) * resolution_steps
|
||||
height = round(samples.shape[2] * scale_by / resolution_steps) * resolution_steps
|
||||
|
||||
s = comfy.utils.common_upscale(samples, int(width), int(height), upscale_method, "disabled")
|
||||
s = s.movedim(1,-1)
|
||||
return io.NodeOutput(s)
|
||||
|
||||
class ResizeType(str, Enum):
|
||||
SCALE_BY = "scale by multiplier"
|
||||
SCALE_DIMENSIONS = "scale dimensions"
|
||||
SCALE_LONGER_DIMENSION = "scale longer dimension"
|
||||
SCALE_SHORTER_DIMENSION = "scale shorter dimension"
|
||||
SCALE_WIDTH = "scale width"
|
||||
SCALE_HEIGHT = "scale height"
|
||||
SCALE_TOTAL_PIXELS = "scale total pixels"
|
||||
MATCH_SIZE = "match size"
|
||||
SCALE_TO_MULTIPLE = "scale to multiple"
|
||||
|
||||
def is_image(input: torch.Tensor) -> bool:
|
||||
# images have 4 dimensions: [batch, height, width, channels]
|
||||
# masks have 3 dimensions: [batch, height, width]
|
||||
return len(input.shape) == 4
|
||||
|
||||
def init_image_mask_input(input: torch.Tensor, is_type_image: bool) -> torch.Tensor:
|
||||
if is_type_image:
|
||||
input = input.movedim(-1, 1)
|
||||
else:
|
||||
input = input.unsqueeze(1)
|
||||
return input
|
||||
|
||||
def finalize_image_mask_input(input: torch.Tensor, is_type_image: bool) -> torch.Tensor:
|
||||
if is_type_image:
|
||||
input = input.movedim(1, -1)
|
||||
else:
|
||||
input = input.squeeze(1)
|
||||
return input
|
||||
|
||||
def scale_by(input: torch.Tensor, multiplier: float, scale_method: str) -> torch.Tensor:
|
||||
is_type_image = is_image(input)
|
||||
input = init_image_mask_input(input, is_type_image)
|
||||
width = round(input.shape[-1] * multiplier)
|
||||
height = round(input.shape[-2] * multiplier)
|
||||
|
||||
input = comfy.utils.common_upscale(input, width, height, scale_method, "disabled")
|
||||
input = finalize_image_mask_input(input, is_type_image)
|
||||
return input
|
||||
|
||||
def scale_dimensions(input: torch.Tensor, width: int, height: int, scale_method: str, crop: str="disabled") -> torch.Tensor:
|
||||
if width == 0 and height == 0:
|
||||
return input
|
||||
is_type_image = is_image(input)
|
||||
input = init_image_mask_input(input, is_type_image)
|
||||
|
||||
if width == 0:
|
||||
width = max(1, round(input.shape[-1] * height / input.shape[-2]))
|
||||
elif height == 0:
|
||||
height = max(1, round(input.shape[-2] * width / input.shape[-1]))
|
||||
|
||||
input = comfy.utils.common_upscale(input, width, height, scale_method, crop)
|
||||
input = finalize_image_mask_input(input, is_type_image)
|
||||
return input
|
||||
|
||||
def scale_longer_dimension(input: torch.Tensor, longer_size: int, scale_method: str) -> torch.Tensor:
|
||||
is_type_image = is_image(input)
|
||||
input = init_image_mask_input(input, is_type_image)
|
||||
width = input.shape[-1]
|
||||
height = input.shape[-2]
|
||||
|
||||
if height > width:
|
||||
width = round((width / height) * longer_size)
|
||||
height = longer_size
|
||||
elif width > height:
|
||||
height = round((height / width) * longer_size)
|
||||
width = longer_size
|
||||
else:
|
||||
height = longer_size
|
||||
width = longer_size
|
||||
|
||||
input = comfy.utils.common_upscale(input, width, height, scale_method, "disabled")
|
||||
input = finalize_image_mask_input(input, is_type_image)
|
||||
return input
|
||||
|
||||
def scale_shorter_dimension(input: torch.Tensor, shorter_size: int, scale_method: str) -> torch.Tensor:
|
||||
is_type_image = is_image(input)
|
||||
input = init_image_mask_input(input, is_type_image)
|
||||
width = input.shape[-1]
|
||||
height = input.shape[-2]
|
||||
|
||||
if height < width:
|
||||
width = round((width / height) * shorter_size)
|
||||
height = shorter_size
|
||||
elif width < height:
|
||||
height = round((height / width) * shorter_size)
|
||||
width = shorter_size
|
||||
else:
|
||||
height = shorter_size
|
||||
width = shorter_size
|
||||
|
||||
input = comfy.utils.common_upscale(input, width, height, scale_method, "disabled")
|
||||
input = finalize_image_mask_input(input, is_type_image)
|
||||
return input
|
||||
|
||||
def scale_total_pixels(input: torch.Tensor, megapixels: float, scale_method: str) -> torch.Tensor:
|
||||
is_type_image = is_image(input)
|
||||
input = init_image_mask_input(input, is_type_image)
|
||||
total = int(megapixels * 1024 * 1024)
|
||||
|
||||
scale_by = math.sqrt(total / (input.shape[-1] * input.shape[-2]))
|
||||
width = round(input.shape[-1] * scale_by)
|
||||
height = round(input.shape[-2] * scale_by)
|
||||
|
||||
input = comfy.utils.common_upscale(input, width, height, scale_method, "disabled")
|
||||
input = finalize_image_mask_input(input, is_type_image)
|
||||
return input
|
||||
|
||||
def scale_match_size(input: torch.Tensor, match: torch.Tensor, scale_method: str, crop: str) -> torch.Tensor:
|
||||
is_type_image = is_image(input)
|
||||
input = init_image_mask_input(input, is_type_image)
|
||||
match = init_image_mask_input(match, is_image(match))
|
||||
|
||||
width = match.shape[-1]
|
||||
height = match.shape[-2]
|
||||
input = comfy.utils.common_upscale(input, width, height, scale_method, crop)
|
||||
input = finalize_image_mask_input(input, is_type_image)
|
||||
return input
|
||||
|
||||
def scale_to_multiple_cover(input: torch.Tensor, multiple: int, scale_method: str) -> torch.Tensor:
|
||||
if multiple <= 1:
|
||||
return input
|
||||
is_type_image = is_image(input)
|
||||
if is_type_image:
|
||||
_, height, width, _ = input.shape
|
||||
else:
|
||||
_, height, width = input.shape
|
||||
target_w = (width // multiple) * multiple
|
||||
target_h = (height // multiple) * multiple
|
||||
if target_w == 0 or target_h == 0:
|
||||
return input
|
||||
if target_w == width and target_h == height:
|
||||
return input
|
||||
s_w = target_w / width
|
||||
s_h = target_h / height
|
||||
if s_w >= s_h:
|
||||
scaled_w = target_w
|
||||
scaled_h = int(math.ceil(height * s_w))
|
||||
if scaled_h < target_h:
|
||||
scaled_h = target_h
|
||||
else:
|
||||
scaled_h = target_h
|
||||
scaled_w = int(math.ceil(width * s_h))
|
||||
if scaled_w < target_w:
|
||||
scaled_w = target_w
|
||||
input = init_image_mask_input(input, is_type_image)
|
||||
input = comfy.utils.common_upscale(input, scaled_w, scaled_h, scale_method, "disabled")
|
||||
input = finalize_image_mask_input(input, is_type_image)
|
||||
x0 = (scaled_w - target_w) // 2
|
||||
y0 = (scaled_h - target_h) // 2
|
||||
x1 = x0 + target_w
|
||||
y1 = y0 + target_h
|
||||
if is_type_image:
|
||||
return input[:, y0:y1, x0:x1, :]
|
||||
return input[:, y0:y1, x0:x1]
|
||||
|
||||
class ResizeImageMaskNode(io.ComfyNode):
|
||||
scale_methods = ["nearest-exact", "bilinear", "area", "bicubic", "lanczos"]
|
||||
crop_methods = ["disabled", "center"]
|
||||
|
||||
class ResizeTypedDict(TypedDict):
|
||||
resize_type: ResizeType
|
||||
scale_method: Literal["nearest-exact", "bilinear", "area", "bicubic", "lanczos"]
|
||||
crop: Literal["disabled", "center"]
|
||||
multiplier: float
|
||||
width: int
|
||||
height: int
|
||||
longer_size: int
|
||||
shorter_size: int
|
||||
megapixels: float
|
||||
multiple: int
|
||||
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
template = io.MatchType.Template("input_type", [io.Image, io.Mask])
|
||||
crop_combo = io.Combo.Input(
|
||||
"crop",
|
||||
options=cls.crop_methods,
|
||||
default="center",
|
||||
tooltip="How to handle aspect ratio mismatch: 'disabled' stretches to fit, 'center' crops to maintain aspect ratio.",
|
||||
)
|
||||
return io.Schema(
|
||||
node_id="ResizeImageMaskNode",
|
||||
display_name="Resize Image/Mask",
|
||||
description="Resize an image or mask using various scaling methods.",
|
||||
category="transform",
|
||||
search_aliases=["resize", "resize image", "resize mask", "scale", "scale image", "scale mask", "image resize", "change size", "dimensions", "shrink", "enlarge"],
|
||||
inputs=[
|
||||
io.MatchType.Input("input", template=template),
|
||||
io.DynamicCombo.Input(
|
||||
"resize_type",
|
||||
tooltip="Select how to resize: by exact dimensions, scale factor, matching another image, etc.",
|
||||
options=[
|
||||
io.DynamicCombo.Option(ResizeType.SCALE_DIMENSIONS, [
|
||||
io.Int.Input("width", default=512, min=0, max=MAX_RESOLUTION, step=1, tooltip="Target width in pixels. Set to 0 to auto-calculate from height while preserving aspect ratio."),
|
||||
io.Int.Input("height", default=512, min=0, max=MAX_RESOLUTION, step=1, tooltip="Target height in pixels. Set to 0 to auto-calculate from width while preserving aspect ratio."),
|
||||
crop_combo,
|
||||
]),
|
||||
io.DynamicCombo.Option(ResizeType.SCALE_BY, [
|
||||
io.Float.Input("multiplier", default=1.00, min=0.01, max=8.0, step=0.01, tooltip="Scale factor (e.g., 2.0 doubles size, 0.5 halves size)."),
|
||||
]),
|
||||
io.DynamicCombo.Option(ResizeType.SCALE_LONGER_DIMENSION, [
|
||||
io.Int.Input("longer_size", default=512, min=0, max=MAX_RESOLUTION, step=1, tooltip="The longer edge will be resized to this value. Aspect ratio is preserved."),
|
||||
]),
|
||||
io.DynamicCombo.Option(ResizeType.SCALE_SHORTER_DIMENSION, [
|
||||
io.Int.Input("shorter_size", default=512, min=0, max=MAX_RESOLUTION, step=1, tooltip="The shorter edge will be resized to this value. Aspect ratio is preserved."),
|
||||
]),
|
||||
io.DynamicCombo.Option(ResizeType.SCALE_WIDTH, [
|
||||
io.Int.Input("width", default=512, min=0, max=MAX_RESOLUTION, step=1, tooltip="Target width in pixels. Height auto-adjusts to preserve aspect ratio."),
|
||||
]),
|
||||
io.DynamicCombo.Option(ResizeType.SCALE_HEIGHT, [
|
||||
io.Int.Input("height", default=512, min=0, max=MAX_RESOLUTION, step=1, tooltip="Target height in pixels. Width auto-adjusts to preserve aspect ratio."),
|
||||
]),
|
||||
io.DynamicCombo.Option(ResizeType.SCALE_TOTAL_PIXELS, [
|
||||
io.Float.Input("megapixels", default=1.0, min=0.01, max=16.0, step=0.01, tooltip="Target total megapixels (e.g., 1.0 ≈ 1024×1024). Aspect ratio is preserved."),
|
||||
]),
|
||||
io.DynamicCombo.Option(ResizeType.MATCH_SIZE, [
|
||||
io.MultiType.Input("match", [io.Image, io.Mask], tooltip="Resize input to match the dimensions of this reference image or mask."),
|
||||
crop_combo,
|
||||
]),
|
||||
io.DynamicCombo.Option(ResizeType.SCALE_TO_MULTIPLE, [
|
||||
io.Int.Input("multiple", default=8, min=1, max=MAX_RESOLUTION, step=1, tooltip="Resize so width and height are divisible by this number. Useful for latent alignment (e.g., 8 or 64)."),
|
||||
]),
|
||||
],
|
||||
),
|
||||
io.Combo.Input(
|
||||
"scale_method",
|
||||
options=cls.scale_methods,
|
||||
default="area",
|
||||
tooltip="Interpolation algorithm. 'area' is best for downscaling, 'lanczos' for upscaling, 'nearest-exact' for pixel art.",
|
||||
),
|
||||
],
|
||||
outputs=[io.MatchType.Output(template=template, display_name="resized")]
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def execute(cls, input: io.Image.Type | io.Mask.Type, scale_method: io.Combo.Type, resize_type: ResizeTypedDict) -> io.NodeOutput:
|
||||
selected_type = resize_type["resize_type"]
|
||||
if selected_type == ResizeType.SCALE_BY:
|
||||
return io.NodeOutput(scale_by(input, resize_type["multiplier"], scale_method))
|
||||
elif selected_type == ResizeType.SCALE_DIMENSIONS:
|
||||
return io.NodeOutput(scale_dimensions(input, resize_type["width"], resize_type["height"], scale_method, resize_type["crop"]))
|
||||
elif selected_type == ResizeType.SCALE_LONGER_DIMENSION:
|
||||
return io.NodeOutput(scale_longer_dimension(input, resize_type["longer_size"], scale_method))
|
||||
elif selected_type == ResizeType.SCALE_SHORTER_DIMENSION:
|
||||
return io.NodeOutput(scale_shorter_dimension(input, resize_type["shorter_size"], scale_method))
|
||||
elif selected_type == ResizeType.SCALE_WIDTH:
|
||||
return io.NodeOutput(scale_dimensions(input, resize_type["width"], 0, scale_method))
|
||||
elif selected_type == ResizeType.SCALE_HEIGHT:
|
||||
return io.NodeOutput(scale_dimensions(input, 0, resize_type["height"], scale_method))
|
||||
elif selected_type == ResizeType.SCALE_TOTAL_PIXELS:
|
||||
return io.NodeOutput(scale_total_pixels(input, resize_type["megapixels"], scale_method))
|
||||
elif selected_type == ResizeType.MATCH_SIZE:
|
||||
return io.NodeOutput(scale_match_size(input, resize_type["match"], scale_method, resize_type["crop"]))
|
||||
elif selected_type == ResizeType.SCALE_TO_MULTIPLE:
|
||||
return io.NodeOutput(scale_to_multiple_cover(input, resize_type["multiple"], scale_method))
|
||||
raise ValueError(f"Unsupported resize type: {selected_type}")
|
||||
|
||||
def batch_images(images: list[torch.Tensor]) -> torch.Tensor | None:
|
||||
if len(images) == 0:
|
||||
return None
|
||||
# first, get the max channels count
|
||||
max_channels = max(image.shape[-1] for image in images)
|
||||
# then, pad all images to have the same channels count
|
||||
padded_images: list[torch.Tensor] = []
|
||||
for image in images:
|
||||
if image.shape[-1] < max_channels:
|
||||
padded_images.append(torch.nn.functional.pad(image, (0,1), mode='constant', value=1.0))
|
||||
else:
|
||||
padded_images.append(image)
|
||||
# resize all images to be the same size as the first image
|
||||
resized_images: list[torch.Tensor] = []
|
||||
first_image_shape = padded_images[0].shape
|
||||
for image in padded_images:
|
||||
if image.shape[1:] != first_image_shape[1:]:
|
||||
resized_images.append(comfy.utils.common_upscale(image.movedim(-1,1), first_image_shape[2], first_image_shape[1], "bilinear", "center").movedim(1,-1))
|
||||
else:
|
||||
resized_images.append(image)
|
||||
# batch the images in the format [b, h, w, c]
|
||||
return torch.cat(resized_images, dim=0)
|
||||
|
||||
def batch_masks(masks: list[torch.Tensor]) -> torch.Tensor | None:
|
||||
if len(masks) == 0:
|
||||
return None
|
||||
# resize all masks to be the same size as the first mask
|
||||
resized_masks: list[torch.Tensor] = []
|
||||
first_mask_shape = masks[0].shape
|
||||
for mask in masks:
|
||||
if mask.shape[1:] != first_mask_shape[1:]:
|
||||
mask = init_image_mask_input(mask, is_type_image=False)
|
||||
mask = comfy.utils.common_upscale(mask, first_mask_shape[2], first_mask_shape[1], "bilinear", "center")
|
||||
resized_masks.append(finalize_image_mask_input(mask, is_type_image=False))
|
||||
else:
|
||||
resized_masks.append(mask)
|
||||
# batch the masks in the format [b, h, w]
|
||||
return torch.cat(resized_masks, dim=0)
|
||||
|
||||
def batch_latents(latents: list[dict[str, torch.Tensor]]) -> dict[str, torch.Tensor] | None:
|
||||
if len(latents) == 0:
|
||||
return None
|
||||
samples_out = latents[0].copy()
|
||||
samples_out["batch_index"] = []
|
||||
first_samples = latents[0]["samples"]
|
||||
tensors: list[torch.Tensor] = []
|
||||
for latent in latents:
|
||||
# first, deal with latent tensors
|
||||
tensors.append(reshape_latent_to(first_samples.shape, latent["samples"], repeat_batch=False))
|
||||
# next, deal with batch_index
|
||||
samples_out["batch_index"].extend(latent.get("batch_index", [x for x in range(0, latent["samples"].shape[0])]))
|
||||
samples_out["samples"] = torch.cat(tensors, dim=0)
|
||||
return samples_out
|
||||
|
||||
class BatchImagesNode(io.ComfyNode):
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
autogrow_template = io.Autogrow.TemplatePrefix(io.Image.Input("image"), prefix="image", min=2, max=50)
|
||||
return io.Schema(
|
||||
node_id="BatchImagesNode",
|
||||
display_name="Batch Images",
|
||||
category="image",
|
||||
essentials_category="Image Tools",
|
||||
search_aliases=["batch", "image batch", "batch images", "combine images", "merge images", "stack images"],
|
||||
inputs=[
|
||||
io.Autogrow.Input("images", template=autogrow_template)
|
||||
],
|
||||
outputs=[
|
||||
io.Image.Output()
|
||||
]
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def execute(cls, images: io.Autogrow.Type) -> io.NodeOutput:
|
||||
return io.NodeOutput(batch_images(list(images.values())))
|
||||
|
||||
class BatchMasksNode(io.ComfyNode):
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
autogrow_template = io.Autogrow.TemplatePrefix(io.Mask.Input("mask"), prefix="mask", min=2, max=50)
|
||||
return io.Schema(
|
||||
node_id="BatchMasksNode",
|
||||
search_aliases=["combine masks", "stack masks", "merge masks"],
|
||||
display_name="Batch Masks",
|
||||
category="mask",
|
||||
inputs=[
|
||||
io.Autogrow.Input("masks", template=autogrow_template)
|
||||
],
|
||||
outputs=[
|
||||
io.Mask.Output()
|
||||
]
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def execute(cls, masks: io.Autogrow.Type) -> io.NodeOutput:
|
||||
return io.NodeOutput(batch_masks(list(masks.values())))
|
||||
|
||||
class BatchLatentsNode(io.ComfyNode):
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
autogrow_template = io.Autogrow.TemplatePrefix(io.Latent.Input("latent"), prefix="latent", min=2, max=50)
|
||||
return io.Schema(
|
||||
node_id="BatchLatentsNode",
|
||||
search_aliases=["combine latents", "stack latents", "merge latents"],
|
||||
display_name="Batch Latents",
|
||||
category="latent",
|
||||
inputs=[
|
||||
io.Autogrow.Input("latents", template=autogrow_template)
|
||||
],
|
||||
outputs=[
|
||||
io.Latent.Output()
|
||||
]
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def execute(cls, latents: io.Autogrow.Type) -> io.NodeOutput:
|
||||
return io.NodeOutput(batch_latents(list(latents.values())))
|
||||
|
||||
class BatchImagesMasksLatentsNode(io.ComfyNode):
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
matchtype_template = io.MatchType.Template("input", allowed_types=[io.Image, io.Mask, io.Latent])
|
||||
autogrow_template = io.Autogrow.TemplatePrefix(
|
||||
io.MatchType.Input("input", matchtype_template),
|
||||
prefix="input", min=1, max=50)
|
||||
return io.Schema(
|
||||
node_id="BatchImagesMasksLatentsNode",
|
||||
search_aliases=["combine batch", "merge batch", "stack inputs"],
|
||||
display_name="Batch Images/Masks/Latents",
|
||||
category="util",
|
||||
inputs=[
|
||||
io.Autogrow.Input("inputs", template=autogrow_template)
|
||||
],
|
||||
outputs=[
|
||||
io.MatchType.Output(id=None, template=matchtype_template)
|
||||
]
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def execute(cls, inputs: io.Autogrow.Type) -> io.NodeOutput:
|
||||
batched = None
|
||||
values = list(inputs.values())
|
||||
# latents
|
||||
if isinstance(values[0], dict):
|
||||
batched = batch_latents(values)
|
||||
# images
|
||||
elif is_image(values[0]):
|
||||
batched = batch_images(values)
|
||||
# masks
|
||||
else:
|
||||
batched = batch_masks(values)
|
||||
return io.NodeOutput(batched)
|
||||
|
||||
|
||||
class PostProcessingExtension(ComfyExtension):
|
||||
@override
|
||||
async def get_node_list(self) -> list[type[io.ComfyNode]]:
|
||||
return [
|
||||
Blend,
|
||||
Blur,
|
||||
Quantize,
|
||||
Sharpen,
|
||||
ImageScaleToTotalPixels,
|
||||
ResizeImageMaskNode,
|
||||
BatchImagesNode,
|
||||
BatchMasksNode,
|
||||
BatchLatentsNode,
|
||||
# BatchImagesMasksLatentsNode,
|
||||
]
|
||||
|
||||
async def comfy_entrypoint() -> PostProcessingExtension:
|
||||
return PostProcessingExtension()
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,674 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
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.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
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 <https://www.gnu.org/licenses/>.
|
||||
|
||||
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:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
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
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
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
|
||||
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||
+206
@@ -0,0 +1,206 @@
|
||||
import { setActivePinia } from 'pinia'
|
||||
import { createTestingPinia } from '@pinia/testing'
|
||||
import { describe, expect, test } from 'vitest'
|
||||
import { LGraph, LGraphNode } from '@/lib/litegraph/src/litegraph'
|
||||
import { transformInputSpecV1ToV2 } from '@/schemas/nodeDef/migration'
|
||||
import type { InputSpec } from '@/schemas/nodeDefSchema'
|
||||
import { useLitegraphService } from '@/services/litegraphService'
|
||||
import type { HasInitialMinSize } from '@/services/litegraphService'
|
||||
|
||||
setActivePinia(createTestingPinia())
|
||||
type DynamicInputs = ('INT' | 'STRING' | 'IMAGE' | DynamicInputs)[][]
|
||||
|
||||
const { addNodeInput } = useLitegraphService()
|
||||
|
||||
function nextTick() {
|
||||
return new Promise<void>((r) => requestAnimationFrame(() => r()))
|
||||
}
|
||||
|
||||
function addDynamicCombo(node: LGraphNode, inputs: DynamicInputs) {
|
||||
const namePrefix = `${node.widgets?.length ?? 0}`
|
||||
function getSpec(
|
||||
inputs: DynamicInputs,
|
||||
depth: number = 0
|
||||
): { key: string; inputs: object }[] {
|
||||
return inputs.map((group, groupIndex) => {
|
||||
const inputs = group.map((input, inputIndex) => [
|
||||
`${namePrefix}.${depth}.${inputIndex}`,
|
||||
Array.isArray(input)
|
||||
? ['COMFY_DYNAMICCOMBO_V3', { options: getSpec(input, depth + 1) }]
|
||||
: [input, {}]
|
||||
])
|
||||
return {
|
||||
key: `${groupIndex}`,
|
||||
inputs: { required: Object.fromEntries(inputs) }
|
||||
}
|
||||
})
|
||||
}
|
||||
const inputSpec: Required<InputSpec> = [
|
||||
'COMFY_DYNAMICCOMBO_V3',
|
||||
{ options: getSpec(inputs) }
|
||||
]
|
||||
addNodeInput(
|
||||
node,
|
||||
transformInputSpecV1ToV2(inputSpec, { name: namePrefix, isOptional: false })
|
||||
)
|
||||
}
|
||||
function addAutogrow(node: LGraphNode, template: unknown) {
|
||||
addNodeInput(
|
||||
node,
|
||||
transformInputSpecV1ToV2(['COMFY_AUTOGROW_V3', { template }], {
|
||||
name: `${node.inputs.length}`,
|
||||
isOptional: false
|
||||
})
|
||||
)
|
||||
}
|
||||
function connectInput(node: LGraphNode, inputIndex: number, graph: LGraph) {
|
||||
const node2 = testNode()
|
||||
node2.addOutput('out', '*')
|
||||
graph.add(node2)
|
||||
node2.connect(0, node, inputIndex)
|
||||
}
|
||||
function testNode() {
|
||||
const node: LGraphNode & Partial<HasInitialMinSize> = new LGraphNode('test')
|
||||
node.widgets = []
|
||||
node._initialMinSize = { width: 1, height: 1 }
|
||||
node.constructor.nodeData = {
|
||||
name: 'testnode'
|
||||
} as typeof node.constructor.nodeData
|
||||
return node as LGraphNode & Required<Pick<LGraphNode, 'widgets'>>
|
||||
}
|
||||
|
||||
describe('Dynamic Combos', () => {
|
||||
test('Can add widget on selection', () => {
|
||||
const node = testNode()
|
||||
addDynamicCombo(node, [['INT'], ['INT', 'STRING']])
|
||||
expect(node.widgets.length).toBe(2)
|
||||
node.widgets[0].value = '1'
|
||||
expect(node.widgets.length).toBe(3)
|
||||
})
|
||||
test('Can add nested widgets', () => {
|
||||
const node = testNode()
|
||||
addDynamicCombo(node, [['INT'], [[[], ['STRING']]]])
|
||||
expect(node.widgets.length).toBe(2)
|
||||
node.widgets[0].value = '1'
|
||||
expect(node.widgets.length).toBe(2)
|
||||
node.widgets[1].value = '1'
|
||||
expect(node.widgets.length).toBe(3)
|
||||
})
|
||||
test('Can add input', () => {
|
||||
const node = testNode()
|
||||
addDynamicCombo(node, [['INT'], ['IMAGE']])
|
||||
expect(node.widgets.length).toBe(2)
|
||||
node.widgets[0].value = '1'
|
||||
expect(node.widgets.length).toBe(1)
|
||||
expect(node.inputs.length).toBe(2)
|
||||
expect(node.inputs[1].type).toBe('IMAGE')
|
||||
})
|
||||
test('Dynamically added inputs are well ordered', () => {
|
||||
const node = testNode()
|
||||
addDynamicCombo(node, [['INT'], ['IMAGE']])
|
||||
addDynamicCombo(node, [['INT'], ['IMAGE']])
|
||||
node.widgets[2].value = '1'
|
||||
node.widgets[0].value = '1'
|
||||
expect(node.widgets.length).toBe(2)
|
||||
expect(node.inputs.length).toBe(4)
|
||||
expect(node.inputs[1].name).toBe('0.0.0.0')
|
||||
expect(node.inputs[3].name).toBe('2.2.0.0')
|
||||
})
|
||||
})
|
||||
describe('Autogrow', () => {
|
||||
const inputsSpec = { required: { image: ['IMAGE', {}] } }
|
||||
test('Can name by prefix', () => {
|
||||
const graph = new LGraph()
|
||||
const node = testNode()
|
||||
graph.add(node)
|
||||
addAutogrow(node, { input: inputsSpec, prefix: 'test' })
|
||||
connectInput(node, 0, graph)
|
||||
connectInput(node, 1, graph)
|
||||
connectInput(node, 2, graph)
|
||||
expect(node.inputs.length).toBe(4)
|
||||
expect(node.inputs[0].name).toBe('0.test0')
|
||||
expect(node.inputs[2].name).toBe('0.test2')
|
||||
})
|
||||
test('Can name by list of names', () => {
|
||||
const graph = new LGraph()
|
||||
const node = testNode()
|
||||
graph.add(node)
|
||||
addAutogrow(node, { input: inputsSpec, names: ['a', 'b', 'c'] })
|
||||
connectInput(node, 0, graph)
|
||||
connectInput(node, 1, graph)
|
||||
connectInput(node, 2, graph)
|
||||
expect(node.inputs.length).toBe(3)
|
||||
expect(node.inputs[0].name).toBe('0.a')
|
||||
expect(node.inputs[2].name).toBe('0.c')
|
||||
})
|
||||
test('Can add autogrow with min input count', () => {
|
||||
const node = testNode()
|
||||
addAutogrow(node, { min: 4, input: inputsSpec })
|
||||
expect(node.inputs.length).toBe(4)
|
||||
})
|
||||
test('Adding connections will cause growth up to max', () => {
|
||||
const graph = new LGraph()
|
||||
const node = testNode()
|
||||
graph.add(node)
|
||||
addAutogrow(node, { min: 1, input: inputsSpec, prefix: 'test', max: 3 })
|
||||
expect(node.inputs.length).toBe(1)
|
||||
|
||||
connectInput(node, 0, graph)
|
||||
expect(node.inputs.length).toBe(2)
|
||||
connectInput(node, 1, graph)
|
||||
expect(node.inputs.length).toBe(3)
|
||||
connectInput(node, 2, graph)
|
||||
expect(node.inputs.length).toBe(3)
|
||||
})
|
||||
test('Removing connections decreases to min', async () => {
|
||||
const graph = new LGraph()
|
||||
const node = testNode()
|
||||
graph.add(node)
|
||||
addAutogrow(node, { min: 4, input: inputsSpec, prefix: 'test' })
|
||||
connectInput(node, 3, graph)
|
||||
connectInput(node, 4, graph)
|
||||
connectInput(node, 5, graph)
|
||||
expect(node.inputs.length).toBe(7)
|
||||
|
||||
node.disconnectInput(4)
|
||||
await nextTick()
|
||||
expect(node.inputs.length).toBe(6)
|
||||
node.disconnectInput(3)
|
||||
await nextTick()
|
||||
expect(node.inputs.length).toBe(5)
|
||||
|
||||
connectInput(node, 0, graph)
|
||||
expect(node.inputs.length).toBe(5)
|
||||
node.disconnectInput(0)
|
||||
await nextTick()
|
||||
expect(node.inputs.length).toBe(5)
|
||||
})
|
||||
test('Can deserialize a complex node', async () => {
|
||||
const graph = new LGraph()
|
||||
const node = testNode()
|
||||
graph.add(node)
|
||||
addAutogrow(node, { min: 1, input: inputsSpec, prefix: 'a' })
|
||||
addAutogrow(node, { min: 1, input: inputsSpec, prefix: 'b' })
|
||||
addNodeInput(node, { name: 'aa', isOptional: false, type: 'IMAGE' })
|
||||
|
||||
connectInput(node, 0, graph)
|
||||
connectInput(node, 1, graph)
|
||||
connectInput(node, 3, graph)
|
||||
connectInput(node, 4, graph)
|
||||
|
||||
const serialized = graph.serialize()
|
||||
graph.clear()
|
||||
graph.configure(serialized)
|
||||
const newNode = graph.nodes[0]!
|
||||
|
||||
expect(newNode.inputs.map((i) => i.name)).toStrictEqual([
|
||||
'0.a0',
|
||||
'0.a1',
|
||||
'0.a2',
|
||||
'1.b0',
|
||||
'1.b1',
|
||||
'1.b2',
|
||||
'aa'
|
||||
])
|
||||
})
|
||||
})
|
||||
+601
@@ -0,0 +1,601 @@
|
||||
import { remove } from 'es-toolkit'
|
||||
import { shallowReactive } from 'vue'
|
||||
|
||||
import { useChainCallback } from '@/composables/functional/useChainCallback'
|
||||
import type {
|
||||
ISlotType,
|
||||
INodeInputSlot,
|
||||
INodeOutputSlot
|
||||
} from '@/lib/litegraph/src/interfaces'
|
||||
import type { LGraphNode } from '@/lib/litegraph/src/LGraphNode'
|
||||
import { LiteGraph } from '@/lib/litegraph/src/litegraph'
|
||||
import type { LLink } from '@/lib/litegraph/src/LLink'
|
||||
import { commonType } from '@/lib/litegraph/src/utils/type'
|
||||
import { transformInputSpecV1ToV2 } from '@/schemas/nodeDef/migration'
|
||||
import type { ComboInputSpec, InputSpec } from '@/schemas/nodeDefSchema'
|
||||
import type { InputSpec as InputSpecV2 } from '@/schemas/nodeDef/nodeDefSchemaV2'
|
||||
import {
|
||||
zAutogrowOptions,
|
||||
zDynamicComboInputSpec
|
||||
} from '@/schemas/nodeDefSchema'
|
||||
import { useLitegraphService } from '@/services/litegraphService'
|
||||
import { app } from '@/scripts/app'
|
||||
import type { ComfyApp } from '@/scripts/app'
|
||||
|
||||
const INLINE_INPUTS = false
|
||||
|
||||
type MatchTypeNode = LGraphNode &
|
||||
Pick<Required<LGraphNode>, 'onConnectionsChange'> & {
|
||||
comfyDynamic: { matchType: Record<string, Record<string, string>> }
|
||||
}
|
||||
type AutogrowNode = LGraphNode &
|
||||
Pick<Required<LGraphNode>, 'onConnectionsChange' | 'widgets'> & {
|
||||
comfyDynamic: {
|
||||
autogrow: Record<
|
||||
string,
|
||||
{
|
||||
min: number
|
||||
max: number
|
||||
inputSpecs: InputSpecV2[]
|
||||
prefix?: string
|
||||
names?: string[]
|
||||
}
|
||||
>
|
||||
}
|
||||
}
|
||||
|
||||
function ensureWidgetForInput(node: LGraphNode, input: INodeInputSlot) {
|
||||
node.widgets ??= []
|
||||
const { widget } = input
|
||||
if (widget && node.widgets.some((w) => w.name === widget.name)) return
|
||||
node.widgets.push({
|
||||
draw(ctx, _n, _w, y) {
|
||||
ctx.save()
|
||||
ctx.fillStyle = LiteGraph.NODE_TEXT_COLOR
|
||||
ctx.fillText(input.label ?? input.name, 20, y + 15)
|
||||
ctx.restore()
|
||||
},
|
||||
name: input.name,
|
||||
options: {},
|
||||
serialize: false,
|
||||
type: 'shim',
|
||||
y: 0
|
||||
})
|
||||
input.alwaysVisible = true
|
||||
input.widget = { name: input.name }
|
||||
}
|
||||
|
||||
function dynamicComboWidget(
|
||||
node: LGraphNode,
|
||||
inputName: string,
|
||||
untypedInputData: InputSpec,
|
||||
appArg: ComfyApp,
|
||||
widgetName?: string
|
||||
) {
|
||||
const { addNodeInput } = useLitegraphService()
|
||||
const parseResult = zDynamicComboInputSpec.safeParse(untypedInputData)
|
||||
if (!parseResult.success) throw new Error('invalid DynamicCombo spec')
|
||||
const inputData = parseResult.data
|
||||
const options = Object.fromEntries(
|
||||
inputData[1].options.map(({ key, inputs }) => [key, inputs])
|
||||
)
|
||||
const subSpec: ComboInputSpec = [Object.keys(options), {}]
|
||||
const { widget, minWidth, minHeight } = app.widgets['COMBO'](
|
||||
node,
|
||||
inputName,
|
||||
subSpec,
|
||||
appArg,
|
||||
widgetName
|
||||
)
|
||||
function isInGroup(e: { name: string }): boolean {
|
||||
return e.name.startsWith(inputName + '.')
|
||||
}
|
||||
const updateWidgets = (value?: string) => {
|
||||
if (!node.widgets) throw new Error('Not Reachable')
|
||||
const newSpec = value ? options[value] : undefined
|
||||
|
||||
const removedInputs = remove(node.inputs, isInGroup)
|
||||
for (const widget of remove(node.widgets, isInGroup)) widget.onRemove?.()
|
||||
|
||||
if (!newSpec) return
|
||||
|
||||
const insertionPoint = node.widgets.findIndex((w) => w === widget) + 1
|
||||
const startingLength = node.widgets.length
|
||||
const startingInputLength = node.inputs.length
|
||||
|
||||
if (insertionPoint === 0)
|
||||
throw new Error("Dynamic widget doesn't exist on node")
|
||||
const inputTypes: (Record<string, InputSpec> | undefined)[] = [
|
||||
newSpec.required,
|
||||
newSpec.optional
|
||||
]
|
||||
inputTypes.forEach((inputType, idx) => {
|
||||
for (const key in inputType ?? {}) {
|
||||
const name = `${widget.name}.${key}`
|
||||
const specToAdd = transformInputSpecV1ToV2(inputType![key], {
|
||||
name,
|
||||
isOptional: idx !== 0
|
||||
})
|
||||
specToAdd.display_name = key
|
||||
addNodeInput(node, specToAdd)
|
||||
const newInputs = node.inputs
|
||||
.slice(startingInputLength)
|
||||
.filter((inp) => inp.name.startsWith(name))
|
||||
for (const newInput of newInputs) {
|
||||
if (INLINE_INPUTS && !newInput.widget)
|
||||
ensureWidgetForInput(node, newInput)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
const inputInsertionPoint =
|
||||
node.inputs.findIndex((i) => i.name === widget.name) + 1
|
||||
const addedWidgets = node.widgets.splice(startingLength)
|
||||
node.widgets.splice(insertionPoint, 0, ...addedWidgets)
|
||||
if (inputInsertionPoint === 0) {
|
||||
if (
|
||||
addedWidgets.length === 0 &&
|
||||
node.inputs.length !== startingInputLength
|
||||
)
|
||||
//input is inputOnly, but lacks an insertion point
|
||||
throw new Error('Failed to find input socket for ' + widget.name)
|
||||
return
|
||||
}
|
||||
const addedInputs = spliceInputs(node, startingInputLength).map(
|
||||
(addedInput) => {
|
||||
const existingInput = node.inputs.findIndex(
|
||||
(existingInput) => addedInput.name === existingInput.name
|
||||
)
|
||||
return existingInput === -1
|
||||
? addedInput
|
||||
: spliceInputs(node, existingInput, 1)[0]
|
||||
}
|
||||
)
|
||||
//assume existing inputs are in correct order
|
||||
spliceInputs(node, inputInsertionPoint, 0, ...addedInputs)
|
||||
|
||||
for (const input of removedInputs) {
|
||||
const inputIndex = node.inputs.findIndex((inp) => inp.name === input.name)
|
||||
if (inputIndex === -1) {
|
||||
node.inputs.push(input)
|
||||
node.removeInput(node.inputs.length - 1)
|
||||
} else {
|
||||
node.inputs[inputIndex].link = input.link
|
||||
if (!input.link) continue
|
||||
const link = node.graph?.links?.[input.link]
|
||||
if (!link) continue
|
||||
link.target_slot = inputIndex
|
||||
node.onConnectionsChange?.(
|
||||
LiteGraph.INPUT,
|
||||
inputIndex,
|
||||
true,
|
||||
link,
|
||||
node.inputs[inputIndex]
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
node.size[1] = node.computeSize([...node.size])[1]
|
||||
if (!node.graph) return
|
||||
node._setConcreteSlots()
|
||||
node.arrange()
|
||||
app.canvas?.setDirty(true, true)
|
||||
}
|
||||
//A little hacky, but onConfigure won't work.
|
||||
//It fires too late and is overly disruptive
|
||||
let widgetValue = widget.value
|
||||
Object.defineProperty(widget, 'value', {
|
||||
get() {
|
||||
return widgetValue
|
||||
},
|
||||
set(value) {
|
||||
widgetValue = value
|
||||
updateWidgets(value)
|
||||
}
|
||||
})
|
||||
widget.value = widgetValue
|
||||
return { widget, minWidth, minHeight }
|
||||
}
|
||||
|
||||
export const dynamicWidgets = { COMFY_DYNAMICCOMBO_V3: dynamicComboWidget }
|
||||
const dynamicInputs: Record<
|
||||
string,
|
||||
(node: LGraphNode, inputSpec: InputSpecV2) => void
|
||||
> = {
|
||||
COMFY_AUTOGROW_V3: applyAutogrow,
|
||||
COMFY_MATCHTYPE_V3: applyMatchType
|
||||
}
|
||||
|
||||
export function applyDynamicInputs(
|
||||
node: LGraphNode,
|
||||
inputSpec: InputSpecV2
|
||||
): boolean {
|
||||
if (!(inputSpec.type in dynamicInputs)) return false
|
||||
//TODO: move parsing/validation of inputSpec here?
|
||||
dynamicInputs[inputSpec.type](node, inputSpec)
|
||||
return true
|
||||
}
|
||||
function spliceInputs(
|
||||
node: LGraphNode,
|
||||
startIndex: number,
|
||||
deleteCount = -1,
|
||||
...toAdd: INodeInputSlot[]
|
||||
): INodeInputSlot[] {
|
||||
if (deleteCount < 0) return node.inputs.splice(startIndex)
|
||||
const ret = node.inputs.splice(startIndex, deleteCount, ...toAdd)
|
||||
node.inputs.slice(startIndex).forEach((input, index) => {
|
||||
const link = input.link && node.graph?.links?.get(input.link)
|
||||
if (link) link.target_slot = startIndex + index
|
||||
})
|
||||
return ret
|
||||
}
|
||||
|
||||
function changeOutputType(
|
||||
node: LGraphNode,
|
||||
output: INodeOutputSlot,
|
||||
combinedType: ISlotType
|
||||
) {
|
||||
if (output.type === combinedType) return
|
||||
output.type = combinedType
|
||||
|
||||
//check and potentially remove links
|
||||
if (!node.graph) return
|
||||
for (const link_id of output.links ?? []) {
|
||||
const link = node.graph.links[link_id]
|
||||
if (!link) continue
|
||||
const { input, inputNode, subgraphOutput } = link.resolve(node.graph)
|
||||
const inputType = (input ?? subgraphOutput)?.type
|
||||
if (!inputType) continue
|
||||
const keep = LiteGraph.isValidConnection(combinedType, inputType)
|
||||
if (!keep && subgraphOutput) subgraphOutput.disconnect()
|
||||
else if (!keep && inputNode) inputNode.disconnectInput(link.target_slot)
|
||||
if (input && inputNode?.onConnectionsChange)
|
||||
inputNode.onConnectionsChange(
|
||||
LiteGraph.INPUT,
|
||||
link.target_slot,
|
||||
keep,
|
||||
link,
|
||||
input
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
function withComfyMatchType(node: LGraphNode): asserts node is MatchTypeNode {
|
||||
if (node.comfyDynamic?.matchType) return
|
||||
node.comfyDynamic ??= {}
|
||||
node.comfyDynamic.matchType = {}
|
||||
|
||||
const outputGroups = node.constructor.nodeData?.output_matchtypes
|
||||
node.onConnectionsChange = useChainCallback(
|
||||
node.onConnectionsChange,
|
||||
function (
|
||||
this: MatchTypeNode,
|
||||
contype: ISlotType,
|
||||
slot: number,
|
||||
iscon: boolean,
|
||||
linf: LLink | null | undefined
|
||||
) {
|
||||
const input = this.inputs[slot]
|
||||
if (contype !== LiteGraph.INPUT || !this.graph || !input) return
|
||||
if (app.configuringGraph) return
|
||||
const [matchKey, matchGroup] = Object.entries(
|
||||
this.comfyDynamic.matchType
|
||||
).find(([, group]) => input.name in group) ?? ['', undefined]
|
||||
if (!matchGroup) return
|
||||
if (iscon && linf) {
|
||||
const { output, subgraphInput } = linf.resolve(this.graph)
|
||||
const connectingType = (output ?? subgraphInput)?.type
|
||||
if (connectingType) linf.type = connectingType
|
||||
}
|
||||
//NOTE: inputs contains input
|
||||
const groupInputs: INodeInputSlot[] = node.inputs.filter(
|
||||
(inp) => inp.name in matchGroup
|
||||
)
|
||||
const connectedTypes = groupInputs.map((inp) => {
|
||||
if (!inp.link) return '*'
|
||||
const link = this.graph!.links[inp.link]
|
||||
if (!link) return '*'
|
||||
const { output, subgraphInput } = link.resolve(this.graph!)
|
||||
return (output ?? subgraphInput)?.type ?? '*'
|
||||
})
|
||||
//An input slot can accept a connection that is
|
||||
// - Compatible with original type
|
||||
// - Compatible with all other input types
|
||||
//An output slot can output
|
||||
// - Only what every input can output
|
||||
groupInputs.forEach((input, idx) => {
|
||||
const otherConnected = [
|
||||
...connectedTypes.slice(0, idx),
|
||||
...connectedTypes.slice(idx + 1)
|
||||
]
|
||||
const combinedType = commonType(
|
||||
...otherConnected,
|
||||
matchGroup[input.name]
|
||||
)
|
||||
if (!combinedType) throw new Error('invalid connection')
|
||||
input.type = combinedType
|
||||
})
|
||||
const outputType = commonType(...connectedTypes)
|
||||
if (!outputType) throw new Error('invalid connection')
|
||||
this.outputs.forEach((output, idx) => {
|
||||
if (!(outputGroups?.[idx] == matchKey)) return
|
||||
changeOutputType(this, output, outputType)
|
||||
})
|
||||
app.canvas?.setDirty(true, true)
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
function applyMatchType(node: LGraphNode, inputSpec: InputSpecV2) {
|
||||
const { addNodeInput } = useLitegraphService()
|
||||
const name = inputSpec.name
|
||||
const { allowed_types, template_id } = (
|
||||
inputSpec as InputSpecV2 & {
|
||||
template: { allowed_types: string; template_id: string }
|
||||
}
|
||||
).template
|
||||
const typedSpec = { ...inputSpec, type: allowed_types }
|
||||
addNodeInput(node, typedSpec)
|
||||
withComfyMatchType(node)
|
||||
node.comfyDynamic.matchType[template_id] ??= {}
|
||||
node.comfyDynamic.matchType[template_id][name] = allowed_types
|
||||
|
||||
//TODO: instead apply on output add?
|
||||
//ensure outputs get updated
|
||||
const index = node.inputs.length - 1
|
||||
requestAnimationFrame(() => {
|
||||
const input = node.inputs[index]
|
||||
if (!input) return
|
||||
node.inputs[index] = shallowReactive(input)
|
||||
node.onConnectionsChange?.(
|
||||
LiteGraph.INPUT,
|
||||
index,
|
||||
!!input.link,
|
||||
input.link ? node.graph?.links?.[input.link] : undefined,
|
||||
input
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
function autogrowOrdinalToName(
|
||||
ordinal: number,
|
||||
key: string,
|
||||
groupName: string,
|
||||
node: AutogrowNode
|
||||
) {
|
||||
const {
|
||||
names,
|
||||
prefix = '',
|
||||
inputSpecs
|
||||
} = node.comfyDynamic.autogrow[groupName]
|
||||
const baseName = names
|
||||
? names[ordinal]
|
||||
: (inputSpecs.length == 1 ? prefix : key) + ordinal
|
||||
return { name: `${groupName}.${baseName}`, display_name: baseName }
|
||||
}
|
||||
|
||||
function addAutogrowGroup(
|
||||
ordinal: number,
|
||||
groupName: string,
|
||||
node: AutogrowNode
|
||||
) {
|
||||
const { addNodeInput } = useLitegraphService()
|
||||
const { max, min, inputSpecs } = node.comfyDynamic.autogrow[groupName]
|
||||
if (ordinal >= max) return
|
||||
|
||||
const namedSpecs = inputSpecs.map((input) => ({
|
||||
...input,
|
||||
isOptional: ordinal >= (min ?? 0) || input.isOptional,
|
||||
...autogrowOrdinalToName(ordinal, input.name, groupName, node)
|
||||
}))
|
||||
|
||||
const newInputs = namedSpecs.map((namedSpec) => {
|
||||
addNodeInput(node, namedSpec)
|
||||
const input = spliceInputs(node, node.inputs.length - 1, 1)[0]
|
||||
if (inputSpecs.length !== 1 || (INLINE_INPUTS && !input.widget))
|
||||
ensureWidgetForInput(node, input)
|
||||
return input
|
||||
})
|
||||
|
||||
for (const newInput of newInputs) {
|
||||
for (const existingInput of remove(
|
||||
node.inputs,
|
||||
(inp) => inp.name === newInput.name
|
||||
)) {
|
||||
//NOTE: link.target_slot is updated on spliceInputs call
|
||||
newInput.link ??= existingInput.link
|
||||
}
|
||||
}
|
||||
|
||||
const targetName = autogrowOrdinalToName(
|
||||
ordinal - 1,
|
||||
inputSpecs.at(-1)!.name,
|
||||
groupName,
|
||||
node
|
||||
).name
|
||||
const lastIndex = node.inputs.findLastIndex((inp) =>
|
||||
inp.name.startsWith(targetName)
|
||||
)
|
||||
const insertionIndex = lastIndex === -1 ? node.inputs.length : lastIndex + 1
|
||||
spliceInputs(node, insertionIndex, 0, ...newInputs)
|
||||
app.canvas?.setDirty(true, true)
|
||||
}
|
||||
|
||||
const ORDINAL_REGEX = /\d+$/
|
||||
function resolveAutogrowOrdinal(
|
||||
inputName: string,
|
||||
groupName: string,
|
||||
node: AutogrowNode
|
||||
): number | undefined {
|
||||
//TODO preslice groupname?
|
||||
const name = inputName.slice(groupName.length + 1)
|
||||
const { names } = node.comfyDynamic.autogrow[groupName]
|
||||
if (names) {
|
||||
const ordinal = names.findIndex((s) => s === name)
|
||||
return ordinal === -1 ? undefined : ordinal
|
||||
}
|
||||
const match = name.match(ORDINAL_REGEX)
|
||||
if (!match) return undefined
|
||||
const ordinal = parseInt(match[0])
|
||||
return ordinal !== ordinal ? undefined : ordinal
|
||||
}
|
||||
function autogrowInputConnected(index: number, node: AutogrowNode) {
|
||||
const input = node.inputs[index]
|
||||
const groupName = input.name.slice(0, input.name.lastIndexOf('.'))
|
||||
const lastInput = node.inputs.findLast((inp) =>
|
||||
inp.name.startsWith(groupName + '.')
|
||||
)
|
||||
const ordinal = resolveAutogrowOrdinal(input.name, groupName, node)
|
||||
if (
|
||||
!lastInput ||
|
||||
ordinal == undefined ||
|
||||
(ordinal !== resolveAutogrowOrdinal(lastInput.name, groupName, node) &&
|
||||
!app.configuringGraph)
|
||||
)
|
||||
return
|
||||
addAutogrowGroup(ordinal + 1, groupName, node)
|
||||
}
|
||||
function autogrowInputDisconnected(index: number, node: AutogrowNode) {
|
||||
const input = node.inputs[index]
|
||||
if (!input) return
|
||||
const groupName = input.name.slice(0, input.name.lastIndexOf('.'))
|
||||
const { min = 1, inputSpecs } = node.comfyDynamic.autogrow[groupName]
|
||||
const ordinal = resolveAutogrowOrdinal(input.name, groupName, node)
|
||||
if (ordinal == undefined || ordinal + 1 < min) return
|
||||
|
||||
//resolve all inputs in group
|
||||
const groupInputs = node.inputs.filter(
|
||||
(inp) =>
|
||||
inp.name.startsWith(groupName + '.') &&
|
||||
inp.name.lastIndexOf('.') === groupName.length
|
||||
)
|
||||
const stride = inputSpecs.length
|
||||
if (stride + index >= node.inputs.length) return
|
||||
if (groupInputs.length % stride !== 0) {
|
||||
console.error('Failed to group multi-input autogrow inputs')
|
||||
return
|
||||
}
|
||||
app.canvas?.setDirty(true, true)
|
||||
//groupBy would be nice here, but may not be supported
|
||||
for (let column = 0; column < stride; column++) {
|
||||
for (
|
||||
let bubbleOrdinal = ordinal * stride + column;
|
||||
bubbleOrdinal + stride < groupInputs.length;
|
||||
bubbleOrdinal += stride
|
||||
) {
|
||||
const curInput = groupInputs[bubbleOrdinal]
|
||||
curInput.link = groupInputs[bubbleOrdinal + stride].link
|
||||
if (!curInput.link) continue
|
||||
const link = node.graph?.links[curInput.link]
|
||||
if (!link) continue
|
||||
const curIndex = node.inputs.findIndex((inp) => inp === curInput)
|
||||
if (curIndex === -1) throw new Error('missing input')
|
||||
link.target_slot = curIndex
|
||||
node.onConnectionsChange?.(
|
||||
LiteGraph.INPUT,
|
||||
curIndex,
|
||||
true,
|
||||
link,
|
||||
curInput
|
||||
)
|
||||
}
|
||||
const lastInput = groupInputs.at(column - stride)
|
||||
if (!lastInput) continue
|
||||
lastInput.link = null
|
||||
node.onConnectionsChange?.(
|
||||
LiteGraph.INPUT,
|
||||
node.inputs.length + column - stride,
|
||||
false,
|
||||
null,
|
||||
lastInput
|
||||
)
|
||||
}
|
||||
const removalChecks = groupInputs.slice((min - 1) * stride)
|
||||
let i
|
||||
for (i = removalChecks.length - stride; i >= 0; i -= stride) {
|
||||
if (removalChecks.slice(i, i + stride).some((inp) => inp.link)) break
|
||||
}
|
||||
const toRemove = removalChecks.slice(i + stride * 2)
|
||||
remove(node.inputs, (inp) => toRemove.includes(inp))
|
||||
for (const input of toRemove) {
|
||||
const widgetName = input?.widget?.name
|
||||
if (!widgetName) continue
|
||||
for (const widget of remove(node.widgets, (w) => w.name === widgetName))
|
||||
widget.onRemove?.()
|
||||
}
|
||||
node.size[1] = node.computeSize([...node.size])[1]
|
||||
}
|
||||
|
||||
function withComfyAutogrow(node: LGraphNode): asserts node is AutogrowNode {
|
||||
if (node.comfyDynamic?.autogrow) return
|
||||
node.comfyDynamic ??= {}
|
||||
node.comfyDynamic.autogrow = {}
|
||||
|
||||
let pendingConnection: number | undefined
|
||||
let swappingConnection = false
|
||||
|
||||
const originalOnConnectInput = node.onConnectInput
|
||||
node.onConnectInput = function (slot: number, ...args) {
|
||||
pendingConnection = slot
|
||||
requestAnimationFrame(() => (pendingConnection = undefined))
|
||||
return originalOnConnectInput?.apply(this, [slot, ...args]) ?? true
|
||||
}
|
||||
|
||||
node.onConnectionsChange = useChainCallback(
|
||||
node.onConnectionsChange,
|
||||
function (
|
||||
this: AutogrowNode,
|
||||
contype: ISlotType,
|
||||
slot: number,
|
||||
iscon: boolean,
|
||||
linf: LLink | null | undefined
|
||||
) {
|
||||
const input = this.inputs[slot]
|
||||
if (contype !== LiteGraph.INPUT || !input) return
|
||||
//Return if input isn't known autogrow
|
||||
const key = input.name.slice(0, input.name.lastIndexOf('.'))
|
||||
const autogrowGroup = this.comfyDynamic.autogrow[key]
|
||||
if (!autogrowGroup) return
|
||||
if (app.configuringGraph && input.widget)
|
||||
ensureWidgetForInput(node, input)
|
||||
if (iscon) {
|
||||
if (swappingConnection || !linf) return
|
||||
autogrowInputConnected(slot, this)
|
||||
} else {
|
||||
if (pendingConnection === slot) {
|
||||
swappingConnection = true
|
||||
requestAnimationFrame(() => (swappingConnection = false))
|
||||
return
|
||||
}
|
||||
requestAnimationFrame(() => autogrowInputDisconnected(slot, this))
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
function applyAutogrow(node: LGraphNode, inputSpecV2: InputSpecV2) {
|
||||
withComfyAutogrow(node)
|
||||
|
||||
const parseResult = zAutogrowOptions.safeParse(inputSpecV2)
|
||||
if (!parseResult.success) throw new Error('invalid Autogrow spec')
|
||||
const inputSpec = parseResult.data
|
||||
const { input, min = 1, names, prefix, max = 100 } = inputSpec.template
|
||||
|
||||
const inputTypes: (Record<string, InputSpec> | undefined)[] = [
|
||||
input.required,
|
||||
input.optional
|
||||
]
|
||||
const inputsV2 = inputTypes.flatMap((inputType, index) =>
|
||||
Object.entries(inputType ?? {}).map(([name, v]) =>
|
||||
transformInputSpecV1ToV2(v, { name, isOptional: index === 1 })
|
||||
)
|
||||
)
|
||||
node.comfyDynamic.autogrow[inputSpecV2.name] = {
|
||||
names,
|
||||
min,
|
||||
max: names?.length ?? max,
|
||||
prefix,
|
||||
inputSpecs: inputsV2
|
||||
}
|
||||
for (let i = 0; i === 0 || i < min; i++)
|
||||
addAutogrowGroup(i, inputSpecV2.name, node)
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
import type { LGraphNode } from '@/lib/litegraph/src/LGraphNode'
|
||||
import { useExtensionService } from '@/services/extensionService'
|
||||
import { processDynamicPrompt } from '@/utils/formatUtil'
|
||||
|
||||
// Allows for simple dynamic prompt replacement
|
||||
// Inputs in the format {a|b} will have a random value of a or b chosen when the prompt is queued.
|
||||
|
||||
useExtensionService().registerExtension({
|
||||
name: 'Comfy.DynamicPrompts',
|
||||
nodeCreated(node: LGraphNode) {
|
||||
if (node.widgets) {
|
||||
// Locate dynamic prompt text widgets
|
||||
// Include any widgets with dynamicPrompts set to true, and customtext
|
||||
const widgets = node.widgets.filter((w) => w.dynamicPrompts)
|
||||
for (const widget of widgets) {
|
||||
// Override the serialization of the value to resolve dynamic prompts for all widgets supporting it in this node
|
||||
widget.serializeValue = (workflowNode, widgetIndex) => {
|
||||
if (typeof widget.value !== 'string') return widget.value
|
||||
|
||||
const prompt = processDynamicPrompt(widget.value)
|
||||
|
||||
// Overwrite the value in the serialized workflow pnginfo
|
||||
if (workflowNode?.widgets_values)
|
||||
workflowNode.widgets_values[widgetIndex] = prompt
|
||||
|
||||
return prompt
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,84 @@
|
||||
import { LGraphCanvas, LiteGraph } from '@/lib/litegraph/src/litegraph'
|
||||
import { LGraphNode } from '@/lib/litegraph/src/litegraph'
|
||||
|
||||
import { app } from '../../scripts/app'
|
||||
import { ComfyWidgets } from '../../scripts/widgets'
|
||||
|
||||
// Node that add notes to your project
|
||||
|
||||
app.registerExtension({
|
||||
name: 'Comfy.NoteNode',
|
||||
registerCustomNodes() {
|
||||
class NoteNode extends LGraphNode {
|
||||
static override category: string
|
||||
static collapsable: boolean
|
||||
static title_mode: number
|
||||
|
||||
groupcolor = LGraphCanvas.node_colors.yellow.groupcolor
|
||||
override isVirtualNode: boolean
|
||||
|
||||
constructor(title: string) {
|
||||
super(title)
|
||||
|
||||
this.color = LGraphCanvas.node_colors.yellow.color
|
||||
this.bgcolor = LGraphCanvas.node_colors.yellow.bgcolor
|
||||
|
||||
if (!this.properties) {
|
||||
this.properties = { text: '' }
|
||||
}
|
||||
ComfyWidgets.STRING(
|
||||
this,
|
||||
'text',
|
||||
['STRING', { default: this.properties.text, multiline: true }],
|
||||
app
|
||||
)
|
||||
|
||||
this.serialize_widgets = true
|
||||
this.isVirtualNode = true
|
||||
}
|
||||
}
|
||||
|
||||
// Load default visibility
|
||||
|
||||
LiteGraph.registerNodeType(
|
||||
'Note',
|
||||
Object.assign(NoteNode, {
|
||||
title_mode: LiteGraph.NORMAL_TITLE,
|
||||
title: 'Note',
|
||||
collapsable: true
|
||||
})
|
||||
)
|
||||
|
||||
NoteNode.category = 'utils'
|
||||
|
||||
/** Markdown variant of NoteNode */
|
||||
class MarkdownNoteNode extends LGraphNode {
|
||||
static override title = 'Markdown Note'
|
||||
|
||||
groupcolor = LGraphCanvas.node_colors.yellow.groupcolor
|
||||
|
||||
constructor(title: string) {
|
||||
super(title)
|
||||
|
||||
this.color = LGraphCanvas.node_colors.yellow.color
|
||||
this.bgcolor = LGraphCanvas.node_colors.yellow.bgcolor
|
||||
|
||||
if (!this.properties) {
|
||||
this.properties = { text: '' }
|
||||
}
|
||||
ComfyWidgets.MARKDOWN(
|
||||
this,
|
||||
'text',
|
||||
['STRING', { default: this.properties.text }],
|
||||
app
|
||||
)
|
||||
|
||||
this.serialize_widgets = true
|
||||
this.isVirtualNode = true
|
||||
}
|
||||
}
|
||||
|
||||
LiteGraph.registerNodeType('MarkdownNote', MarkdownNoteNode)
|
||||
MarkdownNoteNode.category = 'utils'
|
||||
}
|
||||
})
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
import type { LGraphNode } from '@/lib/litegraph/src/LGraphNode'
|
||||
import type { ComfyNodeDef } from '@/schemas/nodeDefSchema'
|
||||
import { applyTextReplacements } from '@/utils/searchAndReplace'
|
||||
|
||||
import { app } from '../../scripts/app'
|
||||
|
||||
const saveNodeTypes = new Set([
|
||||
'SaveImage',
|
||||
'SaveVideo',
|
||||
'SaveAnimatedWEBP',
|
||||
'SaveWEBM',
|
||||
'SaveAudio',
|
||||
'SaveGLB',
|
||||
'SaveAnimatedPNG',
|
||||
'CLIPSave',
|
||||
'VAESave',
|
||||
'ModelSave',
|
||||
'LoraSave',
|
||||
'SaveLatent'
|
||||
])
|
||||
|
||||
// Use widget values and dates in output filenames
|
||||
|
||||
app.registerExtension({
|
||||
name: 'Comfy.SaveImageExtraOutput',
|
||||
async beforeRegisterNodeDef(
|
||||
nodeType: typeof LGraphNode,
|
||||
nodeData: ComfyNodeDef
|
||||
) {
|
||||
if (saveNodeTypes.has(nodeData.name)) {
|
||||
const onNodeCreated = nodeType.prototype.onNodeCreated
|
||||
// When the SaveImage node is created we want to override the serialization of the output name widget to run our S&R
|
||||
nodeType.prototype.onNodeCreated = function () {
|
||||
const r = onNodeCreated
|
||||
? // @ts-expect-error fixme ts strict error
|
||||
onNodeCreated.apply(this, arguments)
|
||||
: undefined
|
||||
|
||||
// @ts-expect-error fixme ts strict error
|
||||
const widget = this.widgets.find((w) => w.name === 'filename_prefix')
|
||||
// @ts-expect-error fixme ts strict error
|
||||
widget.serializeValue = () => {
|
||||
// @ts-expect-error fixme ts strict error
|
||||
return applyTextReplacements(app.graph, widget.value)
|
||||
}
|
||||
|
||||
return r
|
||||
}
|
||||
} else {
|
||||
// When any other node is created add a property to alias the node
|
||||
const onNodeCreated = nodeType.prototype.onNodeCreated
|
||||
nodeType.prototype.onNodeCreated = function () {
|
||||
const r = onNodeCreated
|
||||
? // @ts-expect-error fixme ts strict error
|
||||
onNodeCreated.apply(this, arguments)
|
||||
: undefined
|
||||
|
||||
if (!this.properties || !('Node name for S&R' in this.properties)) {
|
||||
this.addProperty('Node name for S&R', this.constructor.type, 'string')
|
||||
}
|
||||
|
||||
return r
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,40 @@
|
||||
import type { LGraphNode } from '@/lib/litegraph/src/LGraphNode'
|
||||
import {
|
||||
type ComfyNodeDef,
|
||||
type InputSpec,
|
||||
isMediaUploadComboInput
|
||||
} from '@/schemas/nodeDefSchema'
|
||||
|
||||
import { app } from '../../scripts/app'
|
||||
|
||||
// Adds an upload button to the nodes
|
||||
|
||||
const createUploadInput = (
|
||||
imageInputName: string,
|
||||
imageInputOptions: InputSpec
|
||||
): InputSpec => [
|
||||
'IMAGEUPLOAD',
|
||||
{
|
||||
...imageInputOptions[1],
|
||||
imageInputName
|
||||
}
|
||||
]
|
||||
|
||||
app.registerExtension({
|
||||
name: 'Comfy.UploadImage',
|
||||
beforeRegisterNodeDef(_nodeType: typeof LGraphNode, nodeData: ComfyNodeDef) {
|
||||
const { input } = nodeData ?? {}
|
||||
const { required } = input ?? {}
|
||||
if (!required) return
|
||||
|
||||
const found = Object.entries(required).find(([_, input]) =>
|
||||
isMediaUploadComboInput(input)
|
||||
)
|
||||
|
||||
// If media combo input found, attach upload input
|
||||
if (found) {
|
||||
const [inputName, inputSpec] = found
|
||||
required.upload = createUploadInput(inputName, inputSpec)
|
||||
}
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,661 @@
|
||||
import { useChainCallback } from '@/composables/functional/useChainCallback'
|
||||
import { LGraphNode, LiteGraph } from '@/lib/litegraph/src/litegraph'
|
||||
import type {
|
||||
INodeInputSlot,
|
||||
INodeOutputSlot,
|
||||
ISlotType,
|
||||
LLink
|
||||
} from '@/lib/litegraph/src/litegraph'
|
||||
import { NodeSlot } from '@/lib/litegraph/src/node/NodeSlot'
|
||||
import type { CanvasPointerEvent } from '@/lib/litegraph/src/types/events'
|
||||
import type {
|
||||
IBaseWidget,
|
||||
TWidgetValue
|
||||
} from '@/lib/litegraph/src/types/widgets'
|
||||
import { assetService } from '@/platform/assets/services/assetService'
|
||||
import { createAssetWidget } from '@/platform/assets/utils/createAssetWidget'
|
||||
import type { ComfyNodeDef, InputSpec } from '@/schemas/nodeDefSchema'
|
||||
import { app } from '@/scripts/app'
|
||||
import {
|
||||
ComfyWidgets,
|
||||
addValueControlWidgets,
|
||||
isValidWidgetType
|
||||
} from '@/scripts/widgets'
|
||||
import { isPrimitiveNode } from '@/renderer/utils/nodeTypeGuards'
|
||||
import { CONFIG, GET_CONFIG } from '@/services/litegraphService'
|
||||
import { mergeInputSpec } from '@/utils/nodeDefUtil'
|
||||
import { applyTextReplacements } from '@/utils/searchAndReplace'
|
||||
|
||||
const replacePropertyName = 'Run widget replace on values'
|
||||
export class PrimitiveNode extends LGraphNode {
|
||||
controlValues?: TWidgetValue[]
|
||||
lastType?: string
|
||||
static override category: string
|
||||
constructor(title: string) {
|
||||
super(title)
|
||||
this.addOutput('connect to widget input', '*')
|
||||
this.serialize_widgets = true
|
||||
this.isVirtualNode = true
|
||||
|
||||
if (!this.properties || !(replacePropertyName in this.properties)) {
|
||||
this.addProperty(replacePropertyName, false, 'boolean')
|
||||
}
|
||||
}
|
||||
|
||||
override applyToGraph(extraLinks: LLink[] = []) {
|
||||
if (!this.outputs[0].links?.length || !this.graph) return
|
||||
|
||||
const links = [
|
||||
...this.outputs[0].links.map((l) => this.graph!.links[l]),
|
||||
...extraLinks
|
||||
]
|
||||
let v = this.widgets?.[0].value
|
||||
if (v && this.properties[replacePropertyName]) {
|
||||
v = applyTextReplacements(this.graph, v as string)
|
||||
}
|
||||
|
||||
// For each output link copy our value over the original widget value
|
||||
for (const linkInfo of links) {
|
||||
const node = this.graph?.getNodeById(linkInfo.target_id)
|
||||
const input = node?.inputs[linkInfo.target_slot]
|
||||
if (!input) {
|
||||
console.warn('Unable to resolve node or input for link', linkInfo)
|
||||
continue
|
||||
}
|
||||
|
||||
const widgetName = input.widget?.name
|
||||
if (!widgetName) {
|
||||
console.warn('Invalid widget or widget name', input.widget)
|
||||
continue
|
||||
}
|
||||
|
||||
const widget = node.widgets?.find((w) => w.name === widgetName)
|
||||
if (!widget) {
|
||||
console.warn(
|
||||
`Unable to find widget "${widgetName}" on node [${node.id}]`
|
||||
)
|
||||
continue
|
||||
}
|
||||
|
||||
widget.value = v
|
||||
widget.callback?.(
|
||||
widget.value,
|
||||
app.canvas,
|
||||
node,
|
||||
app.canvas.graph_mouse,
|
||||
{} as CanvasPointerEvent
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
override refreshComboInNode() {
|
||||
const widget = this.widgets?.[0]
|
||||
if (widget?.type === 'combo') {
|
||||
// @ts-expect-error fixme ts strict error
|
||||
widget.options.values = this.outputs[0].widget[GET_CONFIG]()[0]
|
||||
|
||||
// @ts-expect-error fixme ts strict error
|
||||
if (!widget.options.values.includes(widget.value as string)) {
|
||||
// @ts-expect-error fixme ts strict error
|
||||
widget.value = widget.options.values[0]
|
||||
;(widget.callback as Function)(widget.value)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override onAfterGraphConfigured() {
|
||||
if (this.outputs[0].links?.length && !this.widgets?.length) {
|
||||
this._onFirstConnection()
|
||||
|
||||
// Populate widget values from config data
|
||||
if (this.widgets && this.widgets_values) {
|
||||
for (let i = 0; i < this.widgets_values.length; i++) {
|
||||
const w = this.widgets[i]
|
||||
if (w) {
|
||||
w.value = this.widgets_values[i]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Merge values if required
|
||||
this._mergeWidgetConfig()
|
||||
}
|
||||
}
|
||||
|
||||
override onConnectionsChange(
|
||||
_type: ISlotType,
|
||||
_index: number,
|
||||
connected: boolean
|
||||
) {
|
||||
if (app.configuringGraph) {
|
||||
// Dont run while the graph is still setting up
|
||||
return
|
||||
}
|
||||
|
||||
const links = this.outputs[0].links
|
||||
if (connected) {
|
||||
if (links?.length && !this.widgets?.length) {
|
||||
this._onFirstConnection()
|
||||
}
|
||||
} else {
|
||||
// We may have removed a link that caused the constraints to change
|
||||
this._mergeWidgetConfig()
|
||||
|
||||
if (!links?.length) {
|
||||
this.onLastDisconnect()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override onConnectOutput(
|
||||
slot: number,
|
||||
_type: string,
|
||||
input: INodeInputSlot,
|
||||
target_node: LGraphNode,
|
||||
target_slot: number
|
||||
) {
|
||||
// Fires before the link is made allowing us to reject it if it isn't valid
|
||||
// No widget, we can't connect
|
||||
if (!input.widget && !(input.type in ComfyWidgets)) {
|
||||
return false
|
||||
}
|
||||
|
||||
if (this.outputs[slot].links?.length) {
|
||||
const valid = this._isValidConnection(input)
|
||||
if (valid) {
|
||||
// On connect of additional outputs, copy our value to their widget
|
||||
this.applyToGraph([{ target_id: target_node.id, target_slot } as LLink])
|
||||
}
|
||||
return valid
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
private _onFirstConnection(recreating?: boolean) {
|
||||
// First connection can fire before the graph is ready on initial load so random things can be missing
|
||||
if (!this.outputs[0].links || !this.graph) {
|
||||
this.onLastDisconnect()
|
||||
return
|
||||
}
|
||||
const linkId = this.outputs[0].links[0]
|
||||
const link = this.graph.links[linkId]
|
||||
if (!link) return
|
||||
|
||||
const theirNode = this.graph.getNodeById(link.target_id)
|
||||
if (!theirNode || !theirNode.inputs) return
|
||||
|
||||
const input = theirNode.inputs[link.target_slot]
|
||||
if (!input) return
|
||||
|
||||
let widget
|
||||
if (!input.widget) {
|
||||
if (!(input.type in ComfyWidgets)) return
|
||||
widget = { name: input.name, [GET_CONFIG]: () => [input.type, {}] } //fake widget
|
||||
} else {
|
||||
widget = input.widget
|
||||
}
|
||||
|
||||
// @ts-expect-error fixme ts strict error
|
||||
const config = widget[GET_CONFIG]?.()
|
||||
if (!config) return
|
||||
|
||||
const { type } = getWidgetType(config)
|
||||
// Update our output to restrict to the widget type
|
||||
this.outputs[0].type = type
|
||||
this.outputs[0].name = type
|
||||
this.outputs[0].widget = widget
|
||||
|
||||
this._createWidget(
|
||||
widget[CONFIG] ?? config,
|
||||
theirNode,
|
||||
widget.name,
|
||||
// @ts-expect-error fixme ts strict error
|
||||
recreating
|
||||
)
|
||||
}
|
||||
|
||||
private _createWidget(
|
||||
inputData: InputSpec,
|
||||
node: LGraphNode,
|
||||
widgetName: string,
|
||||
recreating: boolean
|
||||
) {
|
||||
let type = inputData[0]
|
||||
|
||||
if (type instanceof Array) {
|
||||
type = 'COMBO'
|
||||
}
|
||||
|
||||
// Store current size as addWidget resizes the node
|
||||
const [oldWidth, oldHeight] = this.size
|
||||
let widget: IBaseWidget
|
||||
|
||||
if (
|
||||
type === 'COMBO' &&
|
||||
assetService.shouldUseAssetBrowser(node.comfyClass, widgetName)
|
||||
) {
|
||||
widget = this._createAssetWidget(node, widgetName, inputData)
|
||||
const theirWidget = node.widgets?.find((w) => w.name === widgetName)
|
||||
if (theirWidget) widget.value = theirWidget.value
|
||||
this._finalizeWidget(widget, oldWidth, oldHeight, recreating)
|
||||
return
|
||||
}
|
||||
|
||||
if (isValidWidgetType(type)) {
|
||||
widget = (ComfyWidgets[type](this, 'value', inputData, app) || {}).widget
|
||||
} else {
|
||||
// @ts-expect-error InputSpec is not typed correctly
|
||||
widget = this.addWidget(type, 'value', null, () => {}, {})
|
||||
}
|
||||
|
||||
if (node?.widgets && widget) {
|
||||
const theirWidget = node.widgets.find((w) => w.name === widgetName)
|
||||
if (theirWidget) {
|
||||
widget.value = theirWidget.value
|
||||
}
|
||||
}
|
||||
|
||||
if (
|
||||
!inputData?.[1]?.control_after_generate &&
|
||||
(widget.type === 'number' || widget.type === 'combo')
|
||||
) {
|
||||
let control_value = this.widgets_values?.[1]
|
||||
if (!control_value) {
|
||||
control_value = 'fixed'
|
||||
}
|
||||
addValueControlWidgets(
|
||||
this,
|
||||
widget,
|
||||
control_value as string,
|
||||
undefined,
|
||||
inputData
|
||||
)
|
||||
if (this.widgets?.[1]) widget.linkedWidgets = [this.widgets[1]]
|
||||
|
||||
let filter = this.widgets_values?.[2]
|
||||
if (filter && this.widgets && this.widgets.length === 3) {
|
||||
this.widgets[2].value = filter
|
||||
}
|
||||
}
|
||||
|
||||
// Restore any saved control values
|
||||
const controlValues = this.controlValues
|
||||
if (
|
||||
this.widgets &&
|
||||
this.lastType === this.widgets[0]?.type &&
|
||||
controlValues?.length === this.widgets.length - 1
|
||||
) {
|
||||
for (let i = 0; i < controlValues.length; i++) {
|
||||
this.widgets[i + 1].value = controlValues[i]
|
||||
}
|
||||
}
|
||||
|
||||
this._finalizeWidget(widget, oldWidth, oldHeight, recreating)
|
||||
}
|
||||
|
||||
private _createAssetWidget(
|
||||
targetNode: LGraphNode,
|
||||
targetInputName: string,
|
||||
inputData: InputSpec
|
||||
): IBaseWidget {
|
||||
const defaultValue = inputData[1]?.default as string | undefined
|
||||
return createAssetWidget({
|
||||
node: this,
|
||||
widgetName: 'value',
|
||||
nodeTypeForBrowser: targetNode.comfyClass ?? '',
|
||||
inputNameForBrowser: targetInputName,
|
||||
defaultValue,
|
||||
onValueChange: (widget, newValue, oldValue) => {
|
||||
widget.callback?.(
|
||||
widget.value,
|
||||
app.canvas,
|
||||
this,
|
||||
app.canvas.graph_mouse,
|
||||
{} as CanvasPointerEvent
|
||||
)
|
||||
this.onWidgetChanged?.(widget.name, newValue, oldValue, widget)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
private _finalizeWidget(
|
||||
widget: IBaseWidget,
|
||||
oldWidth: number,
|
||||
oldHeight: number,
|
||||
recreating: boolean
|
||||
) {
|
||||
widget.callback = useChainCallback(widget.callback, () => {
|
||||
this.applyToGraph()
|
||||
})
|
||||
|
||||
this.setSize([
|
||||
Math.max(this.size[0], oldWidth),
|
||||
Math.max(this.size[1], oldHeight)
|
||||
])
|
||||
|
||||
if (!recreating) {
|
||||
const sz = this.computeSize()
|
||||
if (this.size[0] < sz[0]) {
|
||||
this.size[0] = sz[0]
|
||||
}
|
||||
if (this.size[1] < sz[1]) {
|
||||
this.size[1] = sz[1]
|
||||
}
|
||||
|
||||
requestAnimationFrame(() => {
|
||||
this.onResize?.(this.size)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
recreateWidget() {
|
||||
const values = this.widgets?.map((w) => w.value)
|
||||
this._removeWidgets()
|
||||
this._onFirstConnection(true)
|
||||
if (values?.length && this.widgets) {
|
||||
for (let i = 0; i < this.widgets.length; i++)
|
||||
this.widgets[i].value = values[i]
|
||||
}
|
||||
return this.widgets?.[0]
|
||||
}
|
||||
|
||||
private _mergeWidgetConfig() {
|
||||
// Merge widget configs if the node has multiple outputs
|
||||
const output = this.outputs[0]
|
||||
const links = output.links ?? []
|
||||
|
||||
const hasConfig = !!output.widget?.[CONFIG]
|
||||
if (hasConfig) {
|
||||
delete output.widget?.[CONFIG]
|
||||
}
|
||||
|
||||
if (links?.length < 2 && hasConfig) {
|
||||
// Copy the widget options from the source
|
||||
if (links.length) {
|
||||
this.recreateWidget()
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
const config1 = (output.widget?.[GET_CONFIG] as () => InputSpec)?.()
|
||||
if (!config1) return
|
||||
const isNumber = config1[0] === 'INT' || config1[0] === 'FLOAT'
|
||||
if (!isNumber || !this.graph) return
|
||||
|
||||
for (const linkId of links) {
|
||||
const link = this.graph.links[linkId]
|
||||
if (!link) continue // Can be null when removing a node
|
||||
|
||||
const theirNode = this.graph.getNodeById(link.target_id)
|
||||
if (!theirNode) continue
|
||||
const theirInput = theirNode.inputs[link.target_slot]
|
||||
|
||||
// Call is valid connection so it can merge the configs when validating
|
||||
this._isValidConnection(theirInput, hasConfig)
|
||||
}
|
||||
}
|
||||
|
||||
private _isValidConnection(input: INodeInputSlot, forceUpdate?: boolean) {
|
||||
// Only allow connections where the configs match
|
||||
const output = this.outputs?.[0]
|
||||
const config2 = (input.widget?.[GET_CONFIG] as () => InputSpec)?.()
|
||||
if (!config2) return false
|
||||
|
||||
return !!mergeIfValid.call(
|
||||
this,
|
||||
output,
|
||||
config2,
|
||||
forceUpdate,
|
||||
this.recreateWidget
|
||||
)
|
||||
}
|
||||
|
||||
private _removeWidgets() {
|
||||
if (this.widgets) {
|
||||
// Allow widgets to cleanup
|
||||
for (const w of this.widgets) {
|
||||
if (w.onRemove) {
|
||||
w.onRemove()
|
||||
}
|
||||
}
|
||||
|
||||
// Temporarily store the current values in case the node is being recreated
|
||||
// e.g. by group node conversion
|
||||
this.controlValues = []
|
||||
this.lastType = this.widgets[0]?.type
|
||||
for (let i = 1; i < this.widgets.length; i++) {
|
||||
this.controlValues.push(this.widgets[i].value)
|
||||
}
|
||||
setTimeout(() => {
|
||||
delete this.lastType
|
||||
delete this.controlValues
|
||||
}, 15)
|
||||
this.widgets.length = 0
|
||||
}
|
||||
}
|
||||
|
||||
onLastDisconnect() {
|
||||
// We can't remove + re-add the output here as if you drag a link over the same link
|
||||
// it removes, then re-adds, causing it to break
|
||||
this.outputs[0].type = '*'
|
||||
this.outputs[0].name = 'connect to widget input'
|
||||
delete this.outputs[0].widget
|
||||
|
||||
this._removeWidgets()
|
||||
}
|
||||
}
|
||||
|
||||
export function getWidgetConfig(
|
||||
slot: INodeInputSlot | INodeOutputSlot
|
||||
): InputSpec {
|
||||
return (slot.widget?.[CONFIG] ??
|
||||
(slot.widget?.[GET_CONFIG] as () => InputSpec)?.() ?? [
|
||||
'*',
|
||||
{}
|
||||
]) as InputSpec
|
||||
}
|
||||
|
||||
function getConfig(this: LGraphNode, widgetName: string) {
|
||||
const { nodeData } = this.constructor
|
||||
return (
|
||||
nodeData?.input?.required?.[widgetName] ??
|
||||
nodeData?.input?.optional?.[widgetName]
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert a widget to an input slot.
|
||||
* @deprecated Widget to socket conversion is no longer necessary, as they co-exist now.
|
||||
* @param node The node to convert the widget to an input slot for.
|
||||
* @param widget The widget to convert to an input slot.
|
||||
* @returns The input slot that was converted from the widget or undefined if the widget is not found.
|
||||
* @knipIgnoreUnusedButUsedByCustomNodes
|
||||
*/
|
||||
export function convertToInput(
|
||||
node: LGraphNode,
|
||||
widget: IBaseWidget
|
||||
): INodeInputSlot | undefined {
|
||||
console.warn(
|
||||
'Please remove call to convertToInput. Widget to socket conversion is no longer necessary, as they co-exist now.'
|
||||
)
|
||||
return node.inputs.find((slot) => slot.widget?.name === widget.name)
|
||||
}
|
||||
|
||||
function getWidgetType(config: InputSpec) {
|
||||
// Special handling for COMBO so we restrict links based on the entries
|
||||
let type = config[0]
|
||||
if (type instanceof Array) {
|
||||
type = 'COMBO'
|
||||
}
|
||||
return { type }
|
||||
}
|
||||
|
||||
export function setWidgetConfig(slot: INodeInputSlot, config?: InputSpec) {
|
||||
if (!slot.widget) return
|
||||
if (config) {
|
||||
slot.widget[GET_CONFIG] = () => config
|
||||
} else {
|
||||
delete slot.widget
|
||||
}
|
||||
|
||||
if (!(slot instanceof NodeSlot)) return
|
||||
const graph = slot.node.graph
|
||||
if (!graph) return
|
||||
const link = graph.links[slot.link ?? -1]
|
||||
if (!link) return
|
||||
const originNode = graph.getNodeById(link.origin_id)
|
||||
if (!originNode || !isPrimitiveNode(originNode)) return
|
||||
if (config) {
|
||||
originNode.recreateWidget()
|
||||
} else if (!app.configuringGraph) {
|
||||
originNode.disconnectOutput(0)
|
||||
originNode.onLastDisconnect()
|
||||
}
|
||||
}
|
||||
|
||||
export function mergeIfValid(
|
||||
output: INodeOutputSlot | INodeInputSlot,
|
||||
config2: InputSpec,
|
||||
forceUpdate?: boolean,
|
||||
recreateWidget?: () => void,
|
||||
config1?: InputSpec
|
||||
): { customConfig: InputSpec[1] } {
|
||||
if (!config1) {
|
||||
config1 = getWidgetConfig(output)
|
||||
}
|
||||
|
||||
const customSpec = mergeInputSpec(config1, config2)
|
||||
|
||||
if (customSpec || forceUpdate) {
|
||||
if (customSpec) {
|
||||
// @ts-expect-error fixme ts strict error
|
||||
output.widget[CONFIG] = customSpec
|
||||
}
|
||||
|
||||
// @ts-expect-error fixme ts strict error
|
||||
const widget = recreateWidget?.call(this)
|
||||
// When deleting a node this can be null
|
||||
if (widget) {
|
||||
// @ts-expect-error fixme ts strict error
|
||||
const min = widget.options.min
|
||||
// @ts-expect-error fixme ts strict error
|
||||
const max = widget.options.max
|
||||
// @ts-expect-error fixme ts strict error
|
||||
if (min != null && widget.value < min) widget.value = min
|
||||
// @ts-expect-error fixme ts strict error
|
||||
if (max != null && widget.value > max) widget.value = max
|
||||
// @ts-expect-error fixme ts strict error
|
||||
widget.callback(widget.value)
|
||||
}
|
||||
}
|
||||
|
||||
return { customConfig: customSpec?.[1] ?? {} }
|
||||
}
|
||||
|
||||
app.registerExtension({
|
||||
name: 'Comfy.WidgetInputs',
|
||||
async beforeRegisterNodeDef(
|
||||
nodeType: typeof LGraphNode,
|
||||
_nodeData: ComfyNodeDef
|
||||
) {
|
||||
// @ts-expect-error adding extra property
|
||||
nodeType.prototype.convertWidgetToInput = function (this: LGraphNode) {
|
||||
console.warn(
|
||||
'Please remove call to convertWidgetToInput. Widget to socket conversion is no longer necessary, as they co-exist now.'
|
||||
)
|
||||
return false
|
||||
}
|
||||
|
||||
nodeType.prototype.onGraphConfigured = useChainCallback(
|
||||
nodeType.prototype.onGraphConfigured,
|
||||
function (this: LGraphNode) {
|
||||
if (!this.inputs) return
|
||||
this.widgets ??= []
|
||||
|
||||
for (const input of this.inputs) {
|
||||
if (input.widget) {
|
||||
const name = input.widget.name
|
||||
if (!input.widget[GET_CONFIG]) {
|
||||
input.widget[GET_CONFIG] = () => getConfig.call(this, name)
|
||||
}
|
||||
|
||||
const w = this.widgets?.find((w) => w.name === name)
|
||||
if (!w) {
|
||||
this.removeInput(this.inputs.findIndex((i) => i === input))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
nodeType.prototype.onConfigure = useChainCallback(
|
||||
nodeType.prototype.onConfigure,
|
||||
function (this: LGraphNode) {
|
||||
if (!app.configuringGraph && this.inputs) {
|
||||
// On copy + paste of nodes, ensure that widget configs are set up
|
||||
for (const input of this.inputs) {
|
||||
if (input.widget && !input.widget[GET_CONFIG]) {
|
||||
const name = input.widget.name
|
||||
input.widget[GET_CONFIG] = () => getConfig.call(this, name)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
// Double click a widget input to automatically attach a primitive
|
||||
const origOnInputDblClick = nodeType.prototype.onInputDblClick
|
||||
nodeType.prototype.onInputDblClick = function (
|
||||
this: LGraphNode,
|
||||
...[slot, ...args]: Parameters<NonNullable<typeof origOnInputDblClick>>
|
||||
) {
|
||||
const r = origOnInputDblClick?.apply(this, [slot, ...args])
|
||||
|
||||
const input = this.inputs[slot]
|
||||
if (!input.widget) {
|
||||
// Not a widget input or already handled input
|
||||
if (
|
||||
!(input.type in ComfyWidgets) &&
|
||||
!(
|
||||
(
|
||||
input.widget?.[GET_CONFIG] as (() => InputSpec) | undefined
|
||||
)?.()?.[0] instanceof Array
|
||||
)
|
||||
) {
|
||||
return r //also Not a ComfyWidgets input or combo (do nothing)
|
||||
}
|
||||
}
|
||||
|
||||
// Create a primitive node
|
||||
const node = LiteGraph.createNode('PrimitiveNode')
|
||||
const graph = app.canvas.graph
|
||||
if (!node || !graph) return r
|
||||
|
||||
graph?.add(node)
|
||||
|
||||
// Calculate a position that won't directly overlap another node
|
||||
const pos: [number, number] = [
|
||||
this.pos[0] - node.size[0] - 30,
|
||||
this.pos[1]
|
||||
]
|
||||
while (graph.getNodeOnPos(pos[0], pos[1], graph.nodes))
|
||||
pos[1] += LiteGraph.NODE_TITLE_HEIGHT
|
||||
|
||||
node.pos = pos
|
||||
node.connect(0, this, slot)
|
||||
node.title = input.name
|
||||
|
||||
return r
|
||||
}
|
||||
},
|
||||
registerCustomNodes() {
|
||||
LiteGraph.registerNodeType(
|
||||
'PrimitiveNode',
|
||||
Object.assign(PrimitiveNode, {
|
||||
title: 'Primitive'
|
||||
})
|
||||
)
|
||||
PrimitiveNode.category = 'utils'
|
||||
}
|
||||
})
|
||||
+4282
File diff suppressed because it is too large
Load Diff
+411
@@ -0,0 +1,411 @@
|
||||
import type { LGraph } from '@/lib/litegraph/src/LGraph'
|
||||
import type { LGraphNode, NodeId } from '@/lib/litegraph/src/LGraphNode'
|
||||
import { InvalidLinkError } from '@/lib/litegraph/src/infrastructure/InvalidLinkError'
|
||||
import { NullGraphError } from '@/lib/litegraph/src/infrastructure/NullGraphError'
|
||||
import { RecursionError } from '@/lib/litegraph/src/infrastructure/RecursionError'
|
||||
import { SlotIndexError } from '@/lib/litegraph/src/infrastructure/SlotIndexError'
|
||||
import type { ISlotType } from '@/lib/litegraph/src/interfaces'
|
||||
import { LGraphEventMode, LiteGraph } from '@/lib/litegraph/src/litegraph'
|
||||
|
||||
import type { Subgraph } from './Subgraph'
|
||||
import type { SubgraphNode } from './SubgraphNode'
|
||||
|
||||
export type ExecutionId = string
|
||||
|
||||
/**
|
||||
* Interface describing the data transfer objects used when compiling a graph for execution.
|
||||
*/
|
||||
export type ExecutableLGraphNode = Omit<
|
||||
ExecutableNodeDTO,
|
||||
'graph' | 'node' | 'subgraphNode'
|
||||
>
|
||||
|
||||
/**
|
||||
* The end result of resolving a DTO input.
|
||||
* When a widget value is returned, {@link widgetInfo} is present and {@link origin_slot} is `-1`.
|
||||
*/
|
||||
type ResolvedInput = {
|
||||
/** DTO for the node that the link originates from. */
|
||||
node: ExecutableLGraphNode
|
||||
/** Full unique execution ID of the node that the link originates from. In the case of a widget value, this is the ID of the subgraph node. */
|
||||
origin_id: ExecutionId
|
||||
/** The slot index of the output on the node that the link originates from. `-1` when widget value is set. */
|
||||
origin_slot: number
|
||||
/** Boxed widget value (e.g. for widgets). If this box is `undefined`, then an input link is connected, and widget values from the subgraph node are ignored. */
|
||||
widgetInfo?: { value: unknown }
|
||||
}
|
||||
|
||||
/**
|
||||
* Concrete implementation of {@link ExecutableLGraphNode}.
|
||||
* @remarks This is the class that is used to create the data transfer objects for executable nodes.
|
||||
*/
|
||||
export class ExecutableNodeDTO implements ExecutableLGraphNode {
|
||||
applyToGraph?(
|
||||
...args: Parameters<NonNullable<typeof this.node.applyToGraph>>
|
||||
): ReturnType<NonNullable<typeof this.node.applyToGraph>>
|
||||
|
||||
/** The graph that this node is a part of. */
|
||||
readonly graph: LGraph | Subgraph
|
||||
|
||||
inputs: { linkId: number | null; name: string; type: ISlotType }[]
|
||||
|
||||
/** Backing field for {@link id}. */
|
||||
private _id: ExecutionId
|
||||
|
||||
/**
|
||||
* The path to the actual node through subgraph instances, represented as a list of all subgraph node IDs (instances),
|
||||
* followed by the actual original node ID within the subgraph. Each segment is separated by `:`.
|
||||
*
|
||||
* e.g. `1:2:3`:
|
||||
* - `1` is the node ID of the first subgraph node in the parent workflow
|
||||
* - `2` is the node ID of the second subgraph node in the first subgraph
|
||||
* - `3` is the node ID of the actual node in the subgraph definition
|
||||
*/
|
||||
get id() {
|
||||
return this._id
|
||||
}
|
||||
|
||||
get type() {
|
||||
return this.node.type
|
||||
}
|
||||
|
||||
get title() {
|
||||
return this.node.title
|
||||
}
|
||||
|
||||
get mode() {
|
||||
return this.node.mode
|
||||
}
|
||||
|
||||
get comfyClass() {
|
||||
return this.node.comfyClass
|
||||
}
|
||||
|
||||
get isVirtualNode() {
|
||||
return this.node.isVirtualNode
|
||||
}
|
||||
|
||||
get widgets() {
|
||||
return this.node.widgets
|
||||
}
|
||||
|
||||
get subgraphId() {
|
||||
return this.subgraphNode?.subgraph.id
|
||||
}
|
||||
|
||||
constructor(
|
||||
/** The actual node that this DTO wraps. */
|
||||
readonly node: LGraphNode | SubgraphNode,
|
||||
/** A list of subgraph instance node IDs from the root graph to the containing instance. @see {@link id} */
|
||||
readonly subgraphNodePath: readonly NodeId[],
|
||||
/** A flattened map of all DTOs in this node network. Subgraph instances have been expanded into their inner nodes. */
|
||||
readonly nodesByExecutionId: Map<ExecutionId, ExecutableLGraphNode>,
|
||||
/** The actual subgraph instance that contains this node, otherwise undefined. */
|
||||
readonly subgraphNode?: SubgraphNode
|
||||
) {
|
||||
if (!node.graph) throw new NullGraphError()
|
||||
|
||||
// Set the internal ID of the DTO
|
||||
this._id = [...this.subgraphNodePath, this.node.id].join(':')
|
||||
this.graph = node.graph
|
||||
this.inputs = this.node.inputs.map((x) => ({
|
||||
linkId: x.link,
|
||||
name: x.name,
|
||||
type: x.type
|
||||
}))
|
||||
|
||||
// Only create a wrapper if the node has an applyToGraph method
|
||||
if (this.node.applyToGraph) {
|
||||
this.applyToGraph = (...args) => this.node.applyToGraph?.(...args)
|
||||
}
|
||||
}
|
||||
|
||||
/** Returns either the DTO itself, or the DTOs of the inner nodes of the subgraph. */
|
||||
getInnerNodes(): ExecutableLGraphNode[] {
|
||||
return this.node.isSubgraphNode()
|
||||
? this.node.getInnerNodes(this.nodesByExecutionId, this.subgraphNodePath)
|
||||
: [this]
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves the executable node & link IDs for a given input slot.
|
||||
* @param slot The slot index of the input.
|
||||
* @param visited Leave empty unless overriding this method.
|
||||
* A set of unique IDs, used to guard against infinite recursion.
|
||||
* If overriding, ensure that the set is passed on all recursive calls.
|
||||
* @returns The node and the origin ID / slot index of the output.
|
||||
*/
|
||||
resolveInput(
|
||||
slot: number,
|
||||
visited = new Set<string>(),
|
||||
type?: ISlotType
|
||||
): ResolvedInput | undefined {
|
||||
const uniqueId = `${this.subgraphNode?.subgraph.id}:${this.node.id}[I]${slot}`
|
||||
if (visited.has(uniqueId)) {
|
||||
const nodeInfo = `${this.node.id}${this.node.title ? ` (${this.node.title})` : ''}`
|
||||
const pathInfo =
|
||||
this.subgraphNodePath.length > 0
|
||||
? ` at path ${this.subgraphNodePath.join(':')}`
|
||||
: ''
|
||||
throw new RecursionError(
|
||||
`Circular reference detected while resolving input ${slot} of node ${nodeInfo}${pathInfo}. ` +
|
||||
`This creates an infinite loop in link resolution. UniqueID: [${uniqueId}]`
|
||||
)
|
||||
}
|
||||
visited.add(uniqueId)
|
||||
|
||||
const input = this.inputs.at(slot)
|
||||
if (!input)
|
||||
throw new SlotIndexError(
|
||||
`No input found for flattened id [${this.id}] slot [${slot}]`
|
||||
)
|
||||
|
||||
// Nothing connected
|
||||
if (input.linkId == null) return
|
||||
|
||||
const link = this.graph.getLink(input.linkId)
|
||||
if (!link)
|
||||
throw new InvalidLinkError(
|
||||
`No link found in parent graph for id [${this.id}] slot [${slot}] ${input.name}`
|
||||
)
|
||||
|
||||
const { subgraphNode } = this
|
||||
|
||||
// Link goes up and out of this subgraph
|
||||
if (subgraphNode && link.originIsIoNode) {
|
||||
const subgraphNodeInput = subgraphNode.inputs.at(link.origin_slot)
|
||||
if (!subgraphNodeInput)
|
||||
throw new SlotIndexError(
|
||||
`No input found for slot [${link.origin_slot}] ${input.name}`
|
||||
)
|
||||
|
||||
// Nothing connected
|
||||
const linkId = subgraphNodeInput.link
|
||||
if (linkId == null) {
|
||||
const widget = subgraphNode.getWidgetFromSlot(subgraphNodeInput)
|
||||
if (!widget) return
|
||||
|
||||
// Special case: SubgraphNode widget.
|
||||
return {
|
||||
node: this,
|
||||
origin_id: this.id,
|
||||
origin_slot: -1,
|
||||
widgetInfo: { value: widget.value }
|
||||
}
|
||||
}
|
||||
|
||||
if (!subgraphNode.graph)
|
||||
throw new NullGraphError(
|
||||
`SubgraphNode ${subgraphNode.id} has no graph during input resolution`
|
||||
)
|
||||
const outerLink = subgraphNode.graph.getLink(linkId)
|
||||
if (!outerLink)
|
||||
throw new InvalidLinkError(
|
||||
`No outer link found for slot [${link.origin_slot}] ${input.name}`
|
||||
)
|
||||
|
||||
const subgraphNodeExecutionId = this.subgraphNodePath.join(':')
|
||||
const subgraphNodeDto = this.nodesByExecutionId.get(
|
||||
subgraphNodeExecutionId
|
||||
)
|
||||
if (!subgraphNodeDto)
|
||||
throw new Error(
|
||||
`No subgraph node DTO found for id [${subgraphNodeExecutionId}]`
|
||||
)
|
||||
|
||||
return subgraphNodeDto.resolveInput(outerLink.target_slot, visited)
|
||||
}
|
||||
|
||||
// Not part of a subgraph; use the original link
|
||||
const outputNode = this.graph.getNodeById(link.origin_id)
|
||||
if (!outputNode)
|
||||
throw new InvalidLinkError(
|
||||
`No input node found for id [${this.id}] slot [${slot}] ${input.name}`
|
||||
)
|
||||
|
||||
const outputNodeExecutionId = [
|
||||
...this.subgraphNodePath,
|
||||
outputNode.id
|
||||
].join(':')
|
||||
const outputNodeDto = this.nodesByExecutionId.get(outputNodeExecutionId)
|
||||
if (!outputNodeDto)
|
||||
throw new Error(
|
||||
`No output node DTO found for id [${outputNodeExecutionId}]`
|
||||
)
|
||||
|
||||
return outputNodeDto.resolveOutput(
|
||||
link.origin_slot,
|
||||
type ?? input.type,
|
||||
visited
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines whether this output is a valid endpoint for a link (non-virtual, non-bypass).
|
||||
* @param slot The slot index of the output.
|
||||
* @param type The type of the input
|
||||
* @param visited A set of unique IDs to guard against infinite recursion. See {@link resolveInput}.
|
||||
* @returns The node and the origin ID / slot index of the output.
|
||||
*/
|
||||
resolveOutput(
|
||||
slot: number,
|
||||
type: ISlotType,
|
||||
visited: Set<string>
|
||||
): ResolvedInput | undefined {
|
||||
const uniqueId = `${this.subgraphNode?.subgraph.id}:${this.node.id}[O]${slot}`
|
||||
if (visited.has(uniqueId)) {
|
||||
const nodeInfo = `${this.node.id}${this.node.title ? ` (${this.node.title})` : ''}`
|
||||
const pathInfo =
|
||||
this.subgraphNodePath.length > 0
|
||||
? ` at path ${this.subgraphNodePath.join(':')}`
|
||||
: ''
|
||||
throw new RecursionError(
|
||||
`Circular reference detected while resolving output ${slot} of node ${nodeInfo}${pathInfo}. ` +
|
||||
`This creates an infinite loop in link resolution. UniqueID: [${uniqueId}]`
|
||||
)
|
||||
}
|
||||
visited.add(uniqueId)
|
||||
|
||||
// Muted nodes produce no output
|
||||
if (this.mode === LGraphEventMode.NEVER) return
|
||||
|
||||
// Upstreamed: Bypass nodes are bypassed using the first input with matching type
|
||||
if (this.mode === LGraphEventMode.BYPASS) {
|
||||
// Bypass nodes by finding first input with matching type
|
||||
const matchingIndex = this._getBypassSlotIndex(slot, type)
|
||||
|
||||
// No input types match - bypass not possible
|
||||
if (matchingIndex === -1) {
|
||||
console.warn(
|
||||
`[ExecutableNodeDTO.resolveOutput] No input types match type [${type}] for id [${this.id}] slot [${slot}]`,
|
||||
this
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
return this.resolveInput(matchingIndex, visited)
|
||||
}
|
||||
|
||||
const { node } = this
|
||||
if (node.isSubgraphNode())
|
||||
return this._resolveSubgraphOutput(slot, type, visited)
|
||||
|
||||
if (node.isVirtualNode) {
|
||||
const virtualLink = this.node.getInputLink(slot)
|
||||
if (virtualLink) {
|
||||
const { inputNode } = virtualLink.resolve(this.graph)
|
||||
if (!inputNode)
|
||||
throw new InvalidLinkError(
|
||||
`Virtual node failed to resolve parent [${this.id}] slot [${slot}]`
|
||||
)
|
||||
|
||||
const inputNodeExecutionId = [
|
||||
...this.subgraphNodePath,
|
||||
inputNode.id
|
||||
].join(':')
|
||||
const inputNodeDto = this.nodesByExecutionId.get(inputNodeExecutionId)
|
||||
if (!inputNodeDto)
|
||||
throw new Error(`No input node DTO found for id [${inputNode.id}]`)
|
||||
|
||||
return inputNodeDto.resolveInput(virtualLink.target_slot, visited, type)
|
||||
}
|
||||
|
||||
// Virtual nodes without a matching input should be discarded.
|
||||
return
|
||||
}
|
||||
|
||||
return {
|
||||
node: this,
|
||||
origin_id: this.id,
|
||||
origin_slot: slot
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds the index of the input slot on this node that matches the given output {@link slot} index.
|
||||
* Used when bypassing nodes.
|
||||
* @param slot The output slot index on this node
|
||||
* @param type The type of the final target input (so type list matches are accurate)
|
||||
* @returns The index of the input slot on this node, otherwise `-1`.
|
||||
*/
|
||||
private _getBypassSlotIndex(slot: number, type: ISlotType) {
|
||||
const { inputs } = this
|
||||
const oppositeInput = inputs[slot]
|
||||
const outputType = this.node.outputs[slot].type
|
||||
|
||||
// Any type short circuit - match slot ID, fallback to first slot
|
||||
if (type === '*' || type === '') {
|
||||
return inputs.length > slot ? slot : 0
|
||||
}
|
||||
|
||||
// Prefer input with the same slot ID
|
||||
if (
|
||||
oppositeInput &&
|
||||
LiteGraph.isValidConnection(oppositeInput.type, outputType) &&
|
||||
LiteGraph.isValidConnection(oppositeInput.type, type)
|
||||
) {
|
||||
return slot
|
||||
}
|
||||
|
||||
// Preserve legacy behaviour; use exact match first.
|
||||
const exactMatch = inputs.findIndex((input) => input.type === type)
|
||||
if (exactMatch !== -1) return exactMatch
|
||||
|
||||
// Find first matching slot - prefer exact type
|
||||
return inputs.findIndex(
|
||||
(input) =>
|
||||
LiteGraph.isValidConnection(input.type, outputType) &&
|
||||
LiteGraph.isValidConnection(input.type, type)
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves the link inside a subgraph node, from the subgraph IO node to the node inside the subgraph.
|
||||
* @param slot The slot index of the output on the subgraph node.
|
||||
* @param visited A set of unique IDs to guard against infinite recursion. See {@link resolveInput}.
|
||||
* @returns A DTO for the node, and the origin ID / slot index of the output.
|
||||
*/
|
||||
private _resolveSubgraphOutput(
|
||||
slot: number,
|
||||
type: ISlotType,
|
||||
visited: Set<string>
|
||||
): ResolvedInput | undefined {
|
||||
const { node } = this
|
||||
const output = node.outputs.at(slot)
|
||||
|
||||
if (!output)
|
||||
throw new SlotIndexError(
|
||||
`No output found for flattened id [${this.id}] slot [${slot}]`
|
||||
)
|
||||
if (!node.isSubgraphNode())
|
||||
throw new TypeError(`Node is not a subgraph node: ${node.id}`)
|
||||
|
||||
// Link inside the subgraph
|
||||
const innerResolved = node.resolveSubgraphOutputLink(slot)
|
||||
if (!innerResolved) return
|
||||
|
||||
const innerNode = innerResolved.outputNode
|
||||
if (!innerNode)
|
||||
throw new Error(
|
||||
`No output node found for id [${this.id}] slot [${slot}] ${output.name}`
|
||||
)
|
||||
|
||||
// Recurse into the subgraph
|
||||
const innerNodeExecutionId = [
|
||||
...this.subgraphNodePath,
|
||||
node.id,
|
||||
innerNode.id
|
||||
].join(':')
|
||||
const innerNodeDto = this.nodesByExecutionId.get(innerNodeExecutionId)
|
||||
if (!innerNodeDto)
|
||||
throw new Error(
|
||||
`No inner node DTO found for id [${innerNodeExecutionId}]`
|
||||
)
|
||||
|
||||
return innerNodeDto.resolveOutput(
|
||||
innerResolved.link.origin_slot,
|
||||
type,
|
||||
visited
|
||||
)
|
||||
}
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
import type { LGraphNode } from '@/lib/litegraph/src/litegraph'
|
||||
import { isBooleanInputSpec } from '@/schemas/nodeDef/nodeDefSchemaV2'
|
||||
import type { InputSpec } from '@/schemas/nodeDef/nodeDefSchemaV2'
|
||||
import type { ComfyWidgetConstructorV2 } from '@/scripts/widgets'
|
||||
|
||||
export const useBooleanWidget = () => {
|
||||
const widgetConstructor: ComfyWidgetConstructorV2 = (
|
||||
node: LGraphNode,
|
||||
inputSpec: InputSpec
|
||||
) => {
|
||||
if (!isBooleanInputSpec(inputSpec)) {
|
||||
throw new Error(`Invalid input data: ${inputSpec}`)
|
||||
}
|
||||
|
||||
const defaultVal = inputSpec.default ?? false
|
||||
const options = {
|
||||
on: inputSpec.label_on,
|
||||
off: inputSpec.label_off
|
||||
}
|
||||
|
||||
return node.addWidget(
|
||||
'toggle',
|
||||
inputSpec.name,
|
||||
defaultVal,
|
||||
() => {},
|
||||
options
|
||||
)
|
||||
}
|
||||
|
||||
return widgetConstructor
|
||||
}
|
||||
+259
@@ -0,0 +1,259 @@
|
||||
import { ref } from 'vue'
|
||||
|
||||
import MultiSelectWidget from '@/components/graph/widgets/MultiSelectWidget.vue'
|
||||
import { t } from '@/i18n'
|
||||
import type { LGraphNode } from '@/lib/litegraph/src/litegraph'
|
||||
import { isComboWidget } from '@/lib/litegraph/src/litegraph'
|
||||
import type { IBaseWidget } from '@/lib/litegraph/src/types/widgets'
|
||||
import { assetService } from '@/platform/assets/services/assetService'
|
||||
import { createAssetWidget } from '@/platform/assets/utils/createAssetWidget'
|
||||
import { isCloud } from '@/platform/distribution/types'
|
||||
import type {
|
||||
ComboInputSpec,
|
||||
InputSpec
|
||||
} from '@/schemas/nodeDef/nodeDefSchemaV2'
|
||||
import { isComboInputSpec } from '@/schemas/nodeDef/nodeDefSchemaV2'
|
||||
import { transformInputSpecV2ToV1 } from '@/schemas/nodeDef/migration'
|
||||
import { ComponentWidgetImpl, addWidget } from '@/scripts/domWidget'
|
||||
import type { BaseDOMWidget } from '@/scripts/domWidget'
|
||||
import type { ComfyWidgetConstructorV2 } from '@/scripts/widgets'
|
||||
import { addValueControlWidgets } from '@/scripts/widgets'
|
||||
import { useAssetsStore } from '@/stores/assetsStore'
|
||||
import { getMediaTypeFromFilename } from '@/utils/formatUtil'
|
||||
|
||||
import { useRemoteWidget } from './useRemoteWidget'
|
||||
|
||||
const getDefaultValue = (inputSpec: ComboInputSpec) => {
|
||||
if (inputSpec.default) return inputSpec.default
|
||||
if (inputSpec.options?.length) return inputSpec.options[0]
|
||||
if (inputSpec.remote) return 'Loading...'
|
||||
return undefined
|
||||
}
|
||||
|
||||
// Map node types to expected media types
|
||||
const NODE_MEDIA_TYPE_MAP: Record<string, 'image' | 'video' | 'audio'> = {
|
||||
LoadImage: 'image',
|
||||
LoadVideo: 'video',
|
||||
LoadAudio: 'audio'
|
||||
}
|
||||
|
||||
// Map node types to placeholder i18n keys
|
||||
const NODE_PLACEHOLDER_MAP: Record<string, string> = {
|
||||
LoadImage: 'widgets.uploadSelect.placeholderImage',
|
||||
LoadVideo: 'widgets.uploadSelect.placeholderVideo',
|
||||
LoadAudio: 'widgets.uploadSelect.placeholderAudio'
|
||||
}
|
||||
|
||||
const addMultiSelectWidget = (
|
||||
node: LGraphNode,
|
||||
inputSpec: ComboInputSpec
|
||||
): IBaseWidget => {
|
||||
const widgetValue = ref<string[]>([])
|
||||
const widget = new ComponentWidgetImpl({
|
||||
node,
|
||||
name: inputSpec.name,
|
||||
component: MultiSelectWidget,
|
||||
inputSpec,
|
||||
options: {
|
||||
getValue: () => widgetValue.value,
|
||||
setValue: (value: string[]) => {
|
||||
widgetValue.value = value
|
||||
}
|
||||
}
|
||||
})
|
||||
addWidget(node, widget as BaseDOMWidget<object | string>)
|
||||
// TODO: Add remote support to multi-select widget
|
||||
// https://github.com/Comfy-Org/ComfyUI_frontend/issues/3003
|
||||
if (inputSpec.control_after_generate) {
|
||||
const defaultType =
|
||||
typeof inputSpec.control_after_generate === 'string'
|
||||
? inputSpec.control_after_generate
|
||||
: 'fixed'
|
||||
widget.linkedWidgets = addValueControlWidgets(
|
||||
node,
|
||||
widget,
|
||||
defaultType,
|
||||
undefined,
|
||||
transformInputSpecV2ToV1(inputSpec)
|
||||
)
|
||||
}
|
||||
|
||||
return widget
|
||||
}
|
||||
|
||||
function createAssetBrowserWidget(
|
||||
node: LGraphNode,
|
||||
inputSpec: ComboInputSpec,
|
||||
defaultValue: string | undefined
|
||||
): IBaseWidget {
|
||||
return createAssetWidget({
|
||||
node,
|
||||
widgetName: inputSpec.name,
|
||||
nodeTypeForBrowser: node.comfyClass ?? '',
|
||||
inputNameForBrowser: inputSpec.name,
|
||||
defaultValue,
|
||||
onValueChange: (widget, newValue, oldValue) => {
|
||||
node.onWidgetChanged?.(widget.name, newValue, oldValue, widget)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
const createInputMappingWidget = (
|
||||
node: LGraphNode,
|
||||
inputSpec: ComboInputSpec,
|
||||
defaultValue: string | undefined
|
||||
): IBaseWidget => {
|
||||
const assetsStore = useAssetsStore()
|
||||
|
||||
const widget = node.addWidget(
|
||||
'combo',
|
||||
inputSpec.name,
|
||||
defaultValue ?? '',
|
||||
() => {},
|
||||
{
|
||||
values: [],
|
||||
getOptionLabel: (value?: string | null) => {
|
||||
if (!value) {
|
||||
const placeholderKey =
|
||||
NODE_PLACEHOLDER_MAP[node.comfyClass ?? ''] ??
|
||||
'widgets.uploadSelect.placeholder'
|
||||
return t(placeholderKey)
|
||||
}
|
||||
return assetsStore.getInputName(value)
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
if (assetsStore.inputAssets.length === 0 && !assetsStore.inputLoading) {
|
||||
void assetsStore.updateInputs().then(() => {
|
||||
// edge for users using nodes with 0 prior inputs
|
||||
// force canvas refresh the first time they add an asset
|
||||
// so they see filenames instead of hashes.
|
||||
node.setDirtyCanvas(true, false)
|
||||
})
|
||||
}
|
||||
|
||||
const origOptions = widget.options
|
||||
widget.options = new Proxy(origOptions, {
|
||||
get(target, prop) {
|
||||
if (prop !== 'values') {
|
||||
return target[prop as keyof typeof target]
|
||||
}
|
||||
return assetsStore.inputAssets
|
||||
.filter(
|
||||
(asset) =>
|
||||
getMediaTypeFromFilename(asset.name) ===
|
||||
NODE_MEDIA_TYPE_MAP[node.comfyClass ?? '']
|
||||
)
|
||||
.map((asset) => asset.asset_hash)
|
||||
.filter((hash): hash is string => !!hash)
|
||||
}
|
||||
})
|
||||
|
||||
if (inputSpec.control_after_generate) {
|
||||
if (!isComboWidget(widget)) {
|
||||
throw new Error(`Expected combo widget but received ${widget.type}`)
|
||||
}
|
||||
const defaultType =
|
||||
typeof inputSpec.control_after_generate === 'string'
|
||||
? inputSpec.control_after_generate
|
||||
: 'randomize'
|
||||
widget.linkedWidgets = addValueControlWidgets(
|
||||
node,
|
||||
widget,
|
||||
defaultType,
|
||||
undefined,
|
||||
transformInputSpecV2ToV1(inputSpec)
|
||||
)
|
||||
}
|
||||
|
||||
return widget
|
||||
}
|
||||
|
||||
const addComboWidget = (
|
||||
node: LGraphNode,
|
||||
inputSpec: ComboInputSpec
|
||||
): IBaseWidget => {
|
||||
const defaultValue = getDefaultValue(inputSpec)
|
||||
|
||||
if (isCloud) {
|
||||
if (assetService.shouldUseAssetBrowser(node.comfyClass, inputSpec.name)) {
|
||||
return createAssetBrowserWidget(node, inputSpec, defaultValue)
|
||||
}
|
||||
|
||||
if (NODE_MEDIA_TYPE_MAP[node.comfyClass ?? '']) {
|
||||
return createInputMappingWidget(node, inputSpec, defaultValue)
|
||||
}
|
||||
}
|
||||
|
||||
// Standard combo widget
|
||||
const widget = node.addWidget(
|
||||
'combo',
|
||||
inputSpec.name,
|
||||
defaultValue,
|
||||
() => {},
|
||||
{
|
||||
values: inputSpec.options ?? []
|
||||
}
|
||||
)
|
||||
|
||||
if (inputSpec.remote) {
|
||||
if (!isComboWidget(widget)) {
|
||||
throw new Error(`Expected combo widget but received ${widget.type}`)
|
||||
}
|
||||
|
||||
const remoteWidget = useRemoteWidget({
|
||||
remoteConfig: inputSpec.remote,
|
||||
defaultValue,
|
||||
node,
|
||||
widget
|
||||
})
|
||||
if (inputSpec.remote.refresh_button) remoteWidget.addRefreshButton()
|
||||
|
||||
const origOptions = widget.options
|
||||
widget.options = new Proxy(origOptions, {
|
||||
get(target, prop) {
|
||||
// Assertion: Proxy handler passthrough
|
||||
return prop !== 'values'
|
||||
? target[prop as keyof typeof target]
|
||||
: remoteWidget.getValue()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
if (inputSpec.control_after_generate) {
|
||||
if (!isComboWidget(widget)) {
|
||||
throw new Error(`Expected combo widget but received ${widget.type}`)
|
||||
}
|
||||
|
||||
const defaultType =
|
||||
typeof inputSpec.control_after_generate === 'string'
|
||||
? inputSpec.control_after_generate
|
||||
: 'randomize'
|
||||
widget.linkedWidgets = addValueControlWidgets(
|
||||
node,
|
||||
widget,
|
||||
defaultType,
|
||||
undefined,
|
||||
transformInputSpecV2ToV1(inputSpec)
|
||||
)
|
||||
}
|
||||
|
||||
return widget
|
||||
}
|
||||
|
||||
export const useComboWidget = () => {
|
||||
const widgetConstructor: ComfyWidgetConstructorV2 = (
|
||||
node: LGraphNode,
|
||||
inputSpec: InputSpec
|
||||
) => {
|
||||
if (!isComboInputSpec(inputSpec)) {
|
||||
throw new Error(`Invalid input data: ${inputSpec}`)
|
||||
}
|
||||
return inputSpec.multi_select
|
||||
? addMultiSelectWidget(node, inputSpec)
|
||||
: addComboWidget(node, inputSpec)
|
||||
}
|
||||
|
||||
return widgetConstructor
|
||||
}
|
||||
+127
@@ -0,0 +1,127 @@
|
||||
import { useNodeImage, useNodeVideo } from '@/composables/node/useNodeImage'
|
||||
import { useNodeImageUpload } from '@/composables/node/useNodeImageUpload'
|
||||
import { t } from '@/i18n'
|
||||
import type { LGraphNode } from '@/lib/litegraph/src/litegraph'
|
||||
import type { IComboWidget } from '@/lib/litegraph/src/types/widgets'
|
||||
import type { ResultItemType } from '@/schemas/apiSchema'
|
||||
import type { InputSpec } from '@/schemas/nodeDefSchema'
|
||||
import type { ComfyWidgetConstructor } from '@/scripts/widgets'
|
||||
import { useNodeOutputStore } from '@/stores/nodeOutputStore'
|
||||
import { isImageUploadInput } from '@/types/nodeDefAugmentation'
|
||||
import { createAnnotatedPath } from '@/utils/createAnnotatedPath'
|
||||
import { addToComboValues } from '@/utils/litegraphUtil'
|
||||
|
||||
const ACCEPTED_IMAGE_TYPES = 'image/png,image/jpeg,image/webp'
|
||||
const ACCEPTED_VIDEO_TYPES = 'video/webm,video/mp4'
|
||||
|
||||
const isImageFile = (file: File) => file.type.startsWith('image/')
|
||||
const isVideoFile = (file: File) => file.type.startsWith('video/')
|
||||
|
||||
const findFileComboWidget = (
|
||||
node: LGraphNode,
|
||||
inputName: string
|
||||
): IComboWidget | undefined =>
|
||||
node.widgets?.find((w): w is IComboWidget => w.name === inputName)
|
||||
|
||||
export const useImageUploadWidget = () => {
|
||||
const widgetConstructor: ComfyWidgetConstructor = (
|
||||
node: LGraphNode,
|
||||
inputName: string,
|
||||
inputData: InputSpec
|
||||
) => {
|
||||
if (!isImageUploadInput(inputData)) {
|
||||
throw new Error(
|
||||
'Image upload widget requires imageInputName augmentation'
|
||||
)
|
||||
}
|
||||
|
||||
const inputOptions = inputData[1]
|
||||
const { imageInputName, allow_batch, image_folder = 'input' } = inputOptions
|
||||
const folder: ResultItemType | undefined = image_folder
|
||||
const nodeOutputStore = useNodeOutputStore()
|
||||
|
||||
const isAnimated = !!inputOptions.animated_image_upload
|
||||
const isVideo = !!inputOptions.video_upload
|
||||
const accept = isVideo ? ACCEPTED_VIDEO_TYPES : ACCEPTED_IMAGE_TYPES
|
||||
const { showPreview } = isVideo ? useNodeVideo(node) : useNodeImage(node)
|
||||
|
||||
const fileFilter = isVideo ? isVideoFile : isImageFile
|
||||
const fileComboWidget = findFileComboWidget(node, imageInputName)
|
||||
if (!fileComboWidget) {
|
||||
throw new Error(`Widget "${imageInputName}" not found on node`)
|
||||
}
|
||||
const formatPath = (value: string) =>
|
||||
createAnnotatedPath(value, { rootFolder: image_folder })
|
||||
|
||||
// Setup file upload handling
|
||||
let rollback: (() => void) | undefined
|
||||
const { openFileSelection } = useNodeImageUpload(node, {
|
||||
allow_batch,
|
||||
fileFilter,
|
||||
accept,
|
||||
folder,
|
||||
onUploadStart: (files) => {
|
||||
if (files.length > 0) {
|
||||
const prev = fileComboWidget.value
|
||||
fileComboWidget.value = files[0].name
|
||||
rollback = () => {
|
||||
fileComboWidget.value = prev
|
||||
}
|
||||
}
|
||||
},
|
||||
onUploadError: () => {
|
||||
rollback?.()
|
||||
rollback = undefined
|
||||
},
|
||||
onUploadComplete: (output) => {
|
||||
rollback = undefined
|
||||
const annotated = output.map(formatPath)
|
||||
annotated.forEach((path) => {
|
||||
addToComboValues(fileComboWidget, path)
|
||||
})
|
||||
|
||||
const newValue = allow_batch ? annotated : annotated[0]
|
||||
|
||||
// @ts-expect-error litegraph combo value type does not support arrays yet
|
||||
fileComboWidget.value = newValue
|
||||
fileComboWidget.callback?.(newValue)
|
||||
}
|
||||
})
|
||||
|
||||
// Create the button widget for selecting the files
|
||||
const uploadWidget = node.addWidget(
|
||||
'button',
|
||||
inputName,
|
||||
'image',
|
||||
() => openFileSelection(),
|
||||
{
|
||||
serialize: false,
|
||||
canvasOnly: true
|
||||
}
|
||||
)
|
||||
uploadWidget.label = t('g.choose_file_to_upload')
|
||||
|
||||
// Add our own callback to the combo widget to render an image when it changes
|
||||
fileComboWidget.callback = function () {
|
||||
node.imgs = undefined
|
||||
nodeOutputStore.setNodeOutputs(node, String(fileComboWidget.value), {
|
||||
isAnimated
|
||||
})
|
||||
node.graph?.setDirtyCanvas(true)
|
||||
}
|
||||
|
||||
// On load if we have a value then render the image
|
||||
// The value isn't set immediately so we need to wait a moment
|
||||
// No change callbacks seem to be fired on initial setting of the value
|
||||
requestAnimationFrame(() => {
|
||||
nodeOutputStore.setNodeOutputs(node, String(fileComboWidget.value), {
|
||||
isAnimated
|
||||
})
|
||||
showPreview({ block: false })
|
||||
})
|
||||
|
||||
return { widget: uploadWidget }
|
||||
}
|
||||
|
||||
return widgetConstructor
|
||||
}
|
||||
+93
@@ -0,0 +1,93 @@
|
||||
import type { LGraphNode } from '@/lib/litegraph/src/litegraph'
|
||||
import type { INumericWidget } from '@/lib/litegraph/src/types/widgets'
|
||||
import { useSettingStore } from '@/platform/settings/settingStore'
|
||||
import type { InputSpec } from '@/schemas/nodeDef/nodeDefSchemaV2'
|
||||
import { isIntInputSpec } from '@/schemas/nodeDef/nodeDefSchemaV2'
|
||||
import type { ComfyWidgetConstructorV2 } from '@/scripts/widgets'
|
||||
import { addValueControlWidget } from '@/scripts/widgets'
|
||||
import { transformInputSpecV2ToV1 } from '@/schemas/nodeDef/migration'
|
||||
|
||||
function onValueChange(this: INumericWidget, v: number) {
|
||||
// For integers, always round to the nearest step
|
||||
// step === 0 is invalid, assign 1 if options.step is 0
|
||||
const step = this.options.step2 || 1
|
||||
|
||||
if (step === 1) {
|
||||
// Simple case: round to nearest integer
|
||||
this.value = Math.round(v)
|
||||
} else {
|
||||
// Round to nearest multiple of step
|
||||
// First, determine if min value creates an offset
|
||||
const min = this.options.min ?? 0
|
||||
const offset = min % step
|
||||
|
||||
// Round to nearest step, accounting for offset
|
||||
this.value = Math.round((v - offset) / step) * step + offset
|
||||
}
|
||||
}
|
||||
|
||||
export const _for_testing = {
|
||||
onValueChange
|
||||
}
|
||||
|
||||
export const useIntWidget = () => {
|
||||
const widgetConstructor: ComfyWidgetConstructorV2 = (
|
||||
node: LGraphNode,
|
||||
inputSpec: InputSpec
|
||||
) => {
|
||||
if (!isIntInputSpec(inputSpec)) {
|
||||
throw new Error(`Invalid input data: ${inputSpec}`)
|
||||
}
|
||||
|
||||
const settingStore = useSettingStore()
|
||||
const sliderEnabled = !settingStore.get('Comfy.DisableSliders')
|
||||
const display_type = inputSpec.display
|
||||
const widgetType =
|
||||
sliderEnabled && display_type == 'slider'
|
||||
? 'slider'
|
||||
: display_type == 'knob'
|
||||
? 'knob'
|
||||
: 'number'
|
||||
|
||||
const step = inputSpec.step ?? 1
|
||||
/** Assertion {@link inputSpec.default} */
|
||||
const defaultValue = (inputSpec.default as number | undefined) ?? 0
|
||||
const widget = node.addWidget(
|
||||
widgetType,
|
||||
inputSpec.name,
|
||||
defaultValue,
|
||||
onValueChange,
|
||||
{
|
||||
min: inputSpec.min ?? 0,
|
||||
max: inputSpec.max ?? 2048,
|
||||
/** @deprecated Use step2 instead. The 10x value is a legacy implementation. */
|
||||
step: step * 10,
|
||||
step2: step,
|
||||
precision: 0
|
||||
}
|
||||
)
|
||||
|
||||
const controlAfterGenerate =
|
||||
inputSpec.control_after_generate ??
|
||||
['seed', 'noise_seed'].includes(inputSpec.name)
|
||||
|
||||
if (controlAfterGenerate) {
|
||||
const defaultType =
|
||||
typeof inputSpec.control_after_generate === 'string'
|
||||
? inputSpec.control_after_generate
|
||||
: 'randomize'
|
||||
const controlWidget = addValueControlWidget(
|
||||
node,
|
||||
widget,
|
||||
defaultType,
|
||||
undefined,
|
||||
undefined,
|
||||
transformInputSpecV2ToV1(inputSpec)
|
||||
)
|
||||
widget.linkedWidgets = [controlWidget]
|
||||
}
|
||||
|
||||
return widget
|
||||
}
|
||||
return widgetConstructor
|
||||
}
|
||||
+153
@@ -0,0 +1,153 @@
|
||||
import type { LGraphNode } from '@/lib/litegraph/src/litegraph'
|
||||
import { resolveNodeRootGraphId } from '@/lib/litegraph/src/litegraph'
|
||||
import { useSettingStore } from '@/platform/settings/settingStore'
|
||||
import { isStringInputSpec } from '@/schemas/nodeDef/nodeDefSchemaV2'
|
||||
import type { InputSpec } from '@/schemas/nodeDef/nodeDefSchemaV2'
|
||||
import { app } from '@/scripts/app'
|
||||
import type { ComfyWidgetConstructorV2 } from '@/scripts/widgets'
|
||||
import { useWidgetValueStore } from '@/stores/widgetValueStore'
|
||||
|
||||
const TRACKPAD_DETECTION_THRESHOLD = 50
|
||||
|
||||
// TODO: This widget manually syncs with widgetValueStore via getValue/setValue.
|
||||
// Consolidate with useMarkdownWidget into shared helpers (domWidgetHelpers.ts).
|
||||
function addMultilineWidget(
|
||||
node: LGraphNode,
|
||||
name: string,
|
||||
opts: { defaultVal: string; placeholder?: string }
|
||||
) {
|
||||
const widgetStore = useWidgetValueStore()
|
||||
const inputEl = document.createElement('textarea')
|
||||
inputEl.className = 'comfy-multiline-input'
|
||||
inputEl.dataset.testid = 'dom-widget-textarea'
|
||||
inputEl.value = opts.defaultVal
|
||||
inputEl.placeholder = opts.placeholder || name
|
||||
inputEl.spellcheck = useSettingStore().get('Comfy.TextareaWidget.Spellcheck')
|
||||
|
||||
const widget = node.addDOMWidget(name, 'customtext', inputEl, {
|
||||
getValue(): string {
|
||||
const graphId = resolveNodeRootGraphId(node, app.rootGraph.id)
|
||||
const widgetState = widgetStore.getWidget(graphId, node.id, name)
|
||||
|
||||
return (widgetState?.value as string) ?? inputEl.value
|
||||
},
|
||||
setValue(v: string) {
|
||||
inputEl.value = v
|
||||
const graphId = resolveNodeRootGraphId(node, app.rootGraph.id)
|
||||
const widgetState = widgetStore.getWidget(graphId, node.id, name)
|
||||
if (widgetState) widgetState.value = v
|
||||
}
|
||||
})
|
||||
|
||||
widget.element = inputEl
|
||||
widget.inputEl = inputEl
|
||||
widget.options.minNodeSize = [400, 200]
|
||||
|
||||
inputEl.addEventListener('input', (event) => {
|
||||
if (event.target instanceof HTMLTextAreaElement) {
|
||||
widget.value = event.target.value
|
||||
}
|
||||
widget.callback?.(widget.value)
|
||||
})
|
||||
|
||||
// Allow middle mouse button panning
|
||||
inputEl.addEventListener('pointerdown', (event: PointerEvent) => {
|
||||
if (event.button === 1) {
|
||||
app.canvas.processMouseDown(event)
|
||||
}
|
||||
})
|
||||
|
||||
inputEl.addEventListener('pointermove', (event: PointerEvent) => {
|
||||
if ((event.buttons & 4) === 4) {
|
||||
app.canvas.processMouseMove(event)
|
||||
}
|
||||
})
|
||||
|
||||
inputEl.addEventListener('pointerup', (event: PointerEvent) => {
|
||||
if (event.button === 1) {
|
||||
app.canvas.processMouseUp(event)
|
||||
}
|
||||
})
|
||||
|
||||
inputEl.addEventListener('wheel', (event: WheelEvent) => {
|
||||
const gesturesEnabled = useSettingStore().get(
|
||||
'LiteGraph.Pointer.TrackpadGestures'
|
||||
)
|
||||
const deltaX = event.deltaX
|
||||
const deltaY = event.deltaY
|
||||
|
||||
const canScrollY = inputEl.scrollHeight > inputEl.clientHeight
|
||||
const isHorizontal = Math.abs(deltaX) > Math.abs(deltaY)
|
||||
|
||||
// Prevent pinch zoom from zooming the page
|
||||
if (event.ctrlKey) {
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
app.canvas.processMouseWheel(event)
|
||||
return
|
||||
}
|
||||
|
||||
// Detect if this is likely a trackpad gesture vs mouse wheel
|
||||
// Trackpads usually have deltaX or smaller deltaY values (< TRACKPAD_DETECTION_THRESHOLD)
|
||||
// Mouse wheels typically have larger discrete deltaY values (>= TRACKPAD_DETECTION_THRESHOLD)
|
||||
const isLikelyTrackpad =
|
||||
Math.abs(deltaX) > 0 || Math.abs(deltaY) < TRACKPAD_DETECTION_THRESHOLD
|
||||
|
||||
// Trackpad gestures: when enabled, trackpad panning goes to canvas
|
||||
if (gesturesEnabled && isLikelyTrackpad) {
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
app.canvas.processMouseWheel(event)
|
||||
return
|
||||
}
|
||||
|
||||
// When gestures disabled: horizontal always goes to canvas (no horizontal scroll in textarea)
|
||||
if (isHorizontal) {
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
app.canvas.processMouseWheel(event)
|
||||
return
|
||||
}
|
||||
|
||||
// Vertical scrolling when gestures disabled: let textarea scroll if scrollable
|
||||
if (canScrollY) {
|
||||
event.stopPropagation()
|
||||
return
|
||||
}
|
||||
|
||||
// If textarea can't scroll vertically, pass to canvas
|
||||
event.preventDefault()
|
||||
app.canvas.processMouseWheel(event)
|
||||
})
|
||||
|
||||
return widget
|
||||
}
|
||||
|
||||
export const useStringWidget = () => {
|
||||
const widgetConstructor: ComfyWidgetConstructorV2 = (
|
||||
node: LGraphNode,
|
||||
inputSpec: InputSpec
|
||||
) => {
|
||||
if (!isStringInputSpec(inputSpec)) {
|
||||
throw new Error(`Invalid input data: ${inputSpec}`)
|
||||
}
|
||||
|
||||
const defaultVal = inputSpec.default ?? ''
|
||||
const multiline = inputSpec.multiline
|
||||
|
||||
const widget = multiline
|
||||
? addMultilineWidget(node, inputSpec.name, {
|
||||
defaultVal,
|
||||
placeholder: inputSpec.placeholder
|
||||
})
|
||||
: node.addWidget('text', inputSpec.name, defaultVal, () => {}, {})
|
||||
|
||||
if (typeof inputSpec.dynamicPrompts === 'boolean') {
|
||||
widget.dynamicPrompts = inputSpec.dynamicPrompts
|
||||
}
|
||||
|
||||
return widget
|
||||
}
|
||||
|
||||
return widgetConstructor
|
||||
}
|
||||
@@ -0,0 +1,372 @@
|
||||
import { z } from 'zod'
|
||||
import { fromZodError } from 'zod-validation-error'
|
||||
|
||||
import { resultItemType } from '@/schemas/apiSchema'
|
||||
import { CONTROL_OPTIONS } from '@/types/simplifiedWidget'
|
||||
|
||||
const zComboOption = z.union([z.string(), z.number()])
|
||||
const zRemoteWidgetConfig = z.object({
|
||||
route: z.string().url().or(z.string().startsWith('/')),
|
||||
refresh: z.number().gte(128).safe().or(z.number().lte(0).safe()).optional(),
|
||||
response_key: z.string().optional(),
|
||||
query_params: z.record(z.string(), z.string()).optional(),
|
||||
refresh_button: z.boolean().optional(),
|
||||
control_after_refresh: z.enum(['first', 'last']).optional(),
|
||||
timeout: z.number().gte(0).optional(),
|
||||
max_retries: z.number().gte(0).optional()
|
||||
})
|
||||
const zMultiSelectOption = z.object({
|
||||
placeholder: z.string().optional(),
|
||||
chip: z.boolean().optional()
|
||||
})
|
||||
|
||||
export const zBaseInputOptions = z
|
||||
.object({
|
||||
default: z.any().optional(),
|
||||
defaultInput: z.boolean().optional(),
|
||||
display_name: z.string().optional(),
|
||||
forceInput: z.boolean().optional(),
|
||||
tooltip: z.string().optional(),
|
||||
socketless: z.boolean().optional(),
|
||||
hidden: z.boolean().optional(),
|
||||
advanced: z.boolean().optional(),
|
||||
widgetType: z.string().optional(),
|
||||
/** Backend-only properties. */
|
||||
rawLink: z.boolean().optional(),
|
||||
lazy: z.boolean().optional()
|
||||
})
|
||||
.passthrough()
|
||||
|
||||
const zNumericInputOptions = zBaseInputOptions.extend({
|
||||
min: z.number().optional(),
|
||||
max: z.number().optional(),
|
||||
step: z.number().optional(),
|
||||
/** Note: Many node authors are using INT/FLOAT to pass list of INT/FLOAT. */
|
||||
default: z.union([z.number(), z.array(z.number())]).optional(),
|
||||
display: z.enum(['slider', 'number', 'knob', 'gradientslider']).optional()
|
||||
})
|
||||
|
||||
export const zIntInputOptions = zNumericInputOptions.extend({
|
||||
/**
|
||||
* If true, a linked widget will be added to the node to select the mode
|
||||
* of `control_after_generate`.
|
||||
*/
|
||||
control_after_generate: z
|
||||
.union([z.boolean(), z.enum(CONTROL_OPTIONS)])
|
||||
.optional()
|
||||
})
|
||||
|
||||
export const zFloatInputOptions = zNumericInputOptions.extend({
|
||||
round: z.union([z.number(), z.literal(false)]).optional(),
|
||||
gradient_stops: z
|
||||
.array(
|
||||
z.object({
|
||||
offset: z.number(),
|
||||
color: z.tuple([z.number(), z.number(), z.number()])
|
||||
})
|
||||
)
|
||||
.optional()
|
||||
})
|
||||
|
||||
export const zBooleanInputOptions = zBaseInputOptions.extend({
|
||||
label_on: z.string().optional(),
|
||||
label_off: z.string().optional(),
|
||||
default: z.boolean().optional()
|
||||
})
|
||||
|
||||
export const zStringInputOptions = zBaseInputOptions.extend({
|
||||
default: z.string().optional(),
|
||||
multiline: z.boolean().optional(),
|
||||
dynamicPrompts: z.boolean().optional(),
|
||||
|
||||
// Multiline-only fields
|
||||
defaultVal: z.string().optional(),
|
||||
placeholder: z.string().optional()
|
||||
})
|
||||
|
||||
export const zComboInputOptions = zBaseInputOptions.extend({
|
||||
control_after_generate: z
|
||||
.union([z.boolean(), z.enum(CONTROL_OPTIONS)])
|
||||
.optional(),
|
||||
image_upload: z.boolean().optional(),
|
||||
image_folder: resultItemType.optional(),
|
||||
allow_batch: z.boolean().optional(),
|
||||
video_upload: z.boolean().optional(),
|
||||
audio_upload: z.boolean().optional(),
|
||||
mesh_upload: z.boolean().optional(),
|
||||
upload_subfolder: z.string().optional(),
|
||||
animated_image_upload: z.boolean().optional(),
|
||||
options: z.array(zComboOption).optional(),
|
||||
remote: zRemoteWidgetConfig.optional(),
|
||||
/** Whether the widget is a multi-select widget. */
|
||||
multi_select: zMultiSelectOption.optional()
|
||||
})
|
||||
|
||||
const zIntInputSpec = z.tuple([z.literal('INT'), zIntInputOptions.optional()])
|
||||
const zFloatInputSpec = z.tuple([
|
||||
z.literal('FLOAT'),
|
||||
zFloatInputOptions.optional()
|
||||
])
|
||||
const zBooleanInputSpec = z.tuple([
|
||||
z.literal('BOOLEAN'),
|
||||
zBooleanInputOptions.optional()
|
||||
])
|
||||
const zStringInputSpec = z.tuple([
|
||||
z.literal('STRING'),
|
||||
zStringInputOptions.optional()
|
||||
])
|
||||
/**
|
||||
* Legacy combo syntax.
|
||||
* @deprecated Use `zComboInputSpecV2` instead.
|
||||
*/
|
||||
const zComboInputSpec = z.tuple([
|
||||
z.array(zComboOption),
|
||||
zComboInputOptions.optional()
|
||||
])
|
||||
const zComboInputSpecV2 = z.tuple([
|
||||
z.literal('COMBO'),
|
||||
zComboInputOptions.optional()
|
||||
])
|
||||
|
||||
export function isComboInputSpecV1(
|
||||
inputSpec: InputSpec
|
||||
): inputSpec is ComboInputSpec {
|
||||
return Array.isArray(inputSpec[0])
|
||||
}
|
||||
|
||||
export function isIntInputSpec(
|
||||
inputSpec: InputSpec
|
||||
): inputSpec is IntInputSpec {
|
||||
return inputSpec[0] === 'INT'
|
||||
}
|
||||
|
||||
export function isFloatInputSpec(
|
||||
inputSpec: InputSpec
|
||||
): inputSpec is FloatInputSpec {
|
||||
return inputSpec[0] === 'FLOAT'
|
||||
}
|
||||
|
||||
export function isComboInputSpecV2(
|
||||
inputSpec: InputSpec
|
||||
): inputSpec is ComboInputSpecV2 {
|
||||
return inputSpec[0] === 'COMBO'
|
||||
}
|
||||
|
||||
export function isComboInputSpec(
|
||||
inputSpec: InputSpec
|
||||
): inputSpec is ComboInputSpec | ComboInputSpecV2 {
|
||||
return isComboInputSpecV1(inputSpec) || isComboInputSpecV2(inputSpec)
|
||||
}
|
||||
|
||||
export function isMediaUploadComboInput(inputSpec: InputSpec): boolean {
|
||||
const [inputName, inputOptions] = inputSpec
|
||||
if (!inputOptions) return false
|
||||
|
||||
const isUploadInput =
|
||||
inputOptions['image_upload'] === true ||
|
||||
inputOptions['video_upload'] === true ||
|
||||
inputOptions['animated_image_upload'] === true
|
||||
|
||||
return (
|
||||
isUploadInput && (isComboInputSpecV1(inputSpec) || inputName === 'COMBO')
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the type of an input spec.
|
||||
*
|
||||
* @param inputSpec - The input spec to get the type of.
|
||||
* @returns The type of the input spec.
|
||||
*/
|
||||
export function getInputSpecType(inputSpec: InputSpec): string {
|
||||
return isComboInputSpec(inputSpec) ? 'COMBO' : inputSpec[0]
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the combo options from a combo input spec.
|
||||
*
|
||||
* @param inputSpec - The input spec to get the combo options from.
|
||||
* @returns The combo options.
|
||||
*/
|
||||
export function getComboSpecComboOptions(
|
||||
inputSpec: ComboInputSpec | ComboInputSpecV2
|
||||
): (number | string)[] {
|
||||
return (
|
||||
(isComboInputSpecV2(inputSpec) ? inputSpec[1]?.options : inputSpec[0]) ?? []
|
||||
)
|
||||
}
|
||||
|
||||
const excludedLiterals = new Set(['INT', 'FLOAT', 'BOOLEAN', 'STRING', 'COMBO'])
|
||||
const zCustomInputSpec = z.tuple([
|
||||
z.string().refine((value) => !excludedLiterals.has(value)),
|
||||
zBaseInputOptions.optional()
|
||||
])
|
||||
|
||||
const zInputSpec = z.union([
|
||||
zIntInputSpec,
|
||||
zFloatInputSpec,
|
||||
zBooleanInputSpec,
|
||||
zStringInputSpec,
|
||||
zComboInputSpec,
|
||||
zComboInputSpecV2,
|
||||
zCustomInputSpec
|
||||
])
|
||||
|
||||
const zComfyInputsSpec = z.object({
|
||||
required: z.record(zInputSpec).optional(),
|
||||
optional: z.record(zInputSpec).optional(),
|
||||
// Frontend repo is not using it, but some custom nodes are using the
|
||||
// hidden field to pass various values.
|
||||
hidden: z.record(z.any()).optional()
|
||||
})
|
||||
|
||||
const zComfyNodeDataType = z.string()
|
||||
const zComfyComboOutput = z.array(zComboOption)
|
||||
const zComfyOutputTypesSpec = z.array(
|
||||
z.union([zComfyNodeDataType, zComfyComboOutput])
|
||||
)
|
||||
|
||||
/**
|
||||
* Widget dependency with type information.
|
||||
* Provides strong type enforcement for JSONata evaluation context.
|
||||
*/
|
||||
const zWidgetDependency = z.object({
|
||||
name: z.string(),
|
||||
type: z.string()
|
||||
})
|
||||
|
||||
export type WidgetDependency = z.infer<typeof zWidgetDependency>
|
||||
|
||||
/**
|
||||
* Schema for price badge depends_on field.
|
||||
* Specifies which widgets and inputs the pricing expression depends on.
|
||||
* Widgets must be specified as objects with name and type.
|
||||
*/
|
||||
const zPriceBadgeDepends = z.object({
|
||||
widgets: z.array(zWidgetDependency).optional().default([]),
|
||||
inputs: z.array(z.string()).optional().default([]),
|
||||
/**
|
||||
* Autogrow input group names to track.
|
||||
* For each group, the count of connected inputs will be available in the
|
||||
* JSONata context as `g.<groupName>`.
|
||||
* Example: `input_groups: ["reference_videos"]` makes `g.reference_videos`
|
||||
* available with the count of connected inputs like `reference_videos.character1`, etc.
|
||||
*/
|
||||
input_groups: z.array(z.string()).optional().default([])
|
||||
})
|
||||
|
||||
/**
|
||||
* Schema for price badge definition.
|
||||
* Used to calculate and display pricing information for API nodes.
|
||||
* The `expr` field contains a JSONata expression that returns a PricingResult.
|
||||
*/
|
||||
const zPriceBadge = z.object({
|
||||
engine: z.literal('jsonata').optional().default('jsonata'),
|
||||
depends_on: zPriceBadgeDepends
|
||||
.optional()
|
||||
.default({ widgets: [], inputs: [], input_groups: [] }),
|
||||
expr: z.string()
|
||||
})
|
||||
|
||||
export type PriceBadge = z.infer<typeof zPriceBadge>
|
||||
|
||||
export const zComfyNodeDef = z.object({
|
||||
input: zComfyInputsSpec.optional(),
|
||||
output: zComfyOutputTypesSpec.optional(),
|
||||
output_is_list: z.array(z.boolean()).optional(),
|
||||
output_name: z.array(z.string()).optional(),
|
||||
output_tooltips: z.array(z.string()).optional(),
|
||||
output_matchtypes: z.array(z.string().optional()).optional(),
|
||||
name: z.string(),
|
||||
display_name: z.string(),
|
||||
description: z.string(),
|
||||
help: z.string().optional(),
|
||||
category: z.string(),
|
||||
main_category: z.string().optional(),
|
||||
output_node: z.boolean(),
|
||||
python_module: z.string(),
|
||||
deprecated: z.boolean().optional(),
|
||||
experimental: z.boolean().optional(),
|
||||
dev_only: z.boolean().optional(),
|
||||
/**
|
||||
* Whether the node is an API node. Running API nodes requires login to
|
||||
* Comfy Org account.
|
||||
* https://docs.comfy.org/tutorials/api-nodes/overview
|
||||
*/
|
||||
api_node: z.boolean().optional(),
|
||||
/**
|
||||
* Specifies the order of inputs for each input category.
|
||||
* Used to ensure consistent widget ordering regardless of JSON serialization.
|
||||
* Keys are 'required', 'optional', etc., values are arrays of input names.
|
||||
*/
|
||||
input_order: z.record(z.array(z.string())).optional(),
|
||||
/**
|
||||
* Alternative names for search. Useful for synonyms, abbreviations,
|
||||
* or old names after renaming a node.
|
||||
*/
|
||||
search_aliases: z.array(z.string()).optional(),
|
||||
/**
|
||||
* Price badge definition for API nodes.
|
||||
* Contains a JSONata expression to calculate pricing based on widget values
|
||||
* and input connectivity.
|
||||
*/
|
||||
price_badge: zPriceBadge.optional(),
|
||||
/** Category for the Essentials tab. If set, the node appears in Essentials. */
|
||||
essentials_category: z.string().optional(),
|
||||
/** Whether the blueprint is a global/installed blueprint (not user-created). */
|
||||
isGlobal: z.boolean().optional()
|
||||
})
|
||||
|
||||
export const zAutogrowOptions = z.object({
|
||||
...zBaseInputOptions.shape,
|
||||
template: z.object({
|
||||
input: zComfyInputsSpec,
|
||||
names: z.array(z.string()).optional(),
|
||||
max: z.number().optional(),
|
||||
//Backend defines as mandatory with min 1, Frontend is more forgiving
|
||||
min: z.number().optional(),
|
||||
prefix: z.string().optional()
|
||||
})
|
||||
})
|
||||
|
||||
export const zDynamicComboInputSpec = z.tuple([
|
||||
z.literal('COMFY_DYNAMICCOMBO_V3'),
|
||||
zBaseInputOptions.extend({
|
||||
options: z.array(
|
||||
z.object({
|
||||
inputs: zComfyInputsSpec,
|
||||
key: z.string()
|
||||
})
|
||||
)
|
||||
})
|
||||
])
|
||||
|
||||
// `/object_info`
|
||||
export type ComfyInputsSpec = z.infer<typeof zComfyInputsSpec>
|
||||
export type ComfyOutputTypesSpec = z.infer<typeof zComfyOutputTypesSpec>
|
||||
export type ComfyNodeDef = z.infer<typeof zComfyNodeDef>
|
||||
export type RemoteWidgetConfig = z.infer<typeof zRemoteWidgetConfig>
|
||||
|
||||
export type ComboInputOptions = z.infer<typeof zComboInputOptions>
|
||||
export type NumericInputOptions = z.infer<typeof zNumericInputOptions>
|
||||
|
||||
export type IntInputSpec = z.infer<typeof zIntInputSpec>
|
||||
export type FloatInputSpec = z.infer<typeof zFloatInputSpec>
|
||||
export type ComboInputSpec = z.infer<typeof zComboInputSpec>
|
||||
export type ComboInputSpecV2 = z.infer<typeof zComboInputSpecV2>
|
||||
export type InputSpec = z.infer<typeof zInputSpec>
|
||||
|
||||
export function validateComfyNodeDef(
|
||||
data: unknown,
|
||||
onError: (error: string) => void = console.warn
|
||||
): ComfyNodeDef | null {
|
||||
const result = zComfyNodeDef.safeParse(data)
|
||||
if (!result.success) {
|
||||
const zodError = fromZodError(result.error)
|
||||
onError(
|
||||
`Invalid ComfyNodeDef: ${JSON.stringify(data)}\n${zodError.message}`
|
||||
)
|
||||
return null
|
||||
}
|
||||
return result.data
|
||||
}
|
||||
@@ -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<string, InputSpecV2> = {}
|
||||
|
||||
// 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]
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,320 @@
|
||||
import { t } from '@/i18n'
|
||||
import { type LGraphNode, isComboWidget } from '@/lib/litegraph/src/litegraph'
|
||||
import type {
|
||||
IBaseWidget,
|
||||
IComboWidget,
|
||||
IStringWidget
|
||||
} from '@/lib/litegraph/src/types/widgets'
|
||||
import { useSettingStore } from '@/platform/settings/settingStore'
|
||||
import { dynamicWidgets } from '@/core/graph/widgets/dynamicWidgets'
|
||||
import { useBooleanWidget } from '@/renderer/extensions/vueNodes/widgets/composables/useBooleanWidget'
|
||||
import { useBoundingBoxWidget } from '@/renderer/extensions/vueNodes/widgets/composables/useBoundingBoxWidget'
|
||||
import { useCurveWidget } from '@/renderer/extensions/vueNodes/widgets/composables/useCurveWidget'
|
||||
import { useChartWidget } from '@/renderer/extensions/vueNodes/widgets/composables/useChartWidget'
|
||||
import { useColorWidget } from '@/renderer/extensions/vueNodes/widgets/composables/useColorWidget'
|
||||
import { useComboWidget } from '@/renderer/extensions/vueNodes/widgets/composables/useComboWidget'
|
||||
import { useFloatWidget } from '@/renderer/extensions/vueNodes/widgets/composables/useFloatWidget'
|
||||
import { useGalleriaWidget } from '@/renderer/extensions/vueNodes/widgets/composables/useGalleriaWidget'
|
||||
import { useImageCompareWidget } from '@/renderer/extensions/vueNodes/widgets/composables/useImageCompareWidget'
|
||||
import { useImageUploadWidget } from '@/renderer/extensions/vueNodes/widgets/composables/useImageUploadWidget'
|
||||
import { useIntWidget } from '@/renderer/extensions/vueNodes/widgets/composables/useIntWidget'
|
||||
import { useMarkdownWidget } from '@/renderer/extensions/vueNodes/widgets/composables/useMarkdownWidget'
|
||||
import { usePainterWidget } from '@/renderer/extensions/vueNodes/widgets/composables/usePainterWidget'
|
||||
import { useStringWidget } from '@/renderer/extensions/vueNodes/widgets/composables/useStringWidget'
|
||||
import { useTextareaWidget } from '@/renderer/extensions/vueNodes/widgets/composables/useTextareaWidget'
|
||||
import { transformInputSpecV1ToV2 } from '@/schemas/nodeDef/migration'
|
||||
import type { InputSpec as InputSpecV2 } from '@/schemas/nodeDef/nodeDefSchemaV2'
|
||||
import type { InputSpec } from '@/schemas/nodeDefSchema'
|
||||
|
||||
import type { ComfyApp } from './app'
|
||||
import './domWidget'
|
||||
import './errorNodeWidgets'
|
||||
|
||||
export type ComfyWidgetConstructorV2 = (
|
||||
node: LGraphNode,
|
||||
inputSpec: InputSpecV2
|
||||
) => IBaseWidget
|
||||
|
||||
export type ComfyWidgetConstructor = (
|
||||
node: LGraphNode,
|
||||
inputName: string,
|
||||
inputData: InputSpec,
|
||||
app: ComfyApp,
|
||||
widgetName?: string
|
||||
) => { widget: IBaseWidget; minWidth?: number; minHeight?: number }
|
||||
|
||||
/**
|
||||
* Transforms a V2 widget constructor to a V1 widget constructor.
|
||||
* @param widgetConstructorV2 The V2 widget constructor to transform.
|
||||
* @returns The transformed V1 widget constructor.
|
||||
*/
|
||||
const transformWidgetConstructorV2ToV1 = (
|
||||
widgetConstructorV2: ComfyWidgetConstructorV2
|
||||
): ComfyWidgetConstructor => {
|
||||
return (node, inputName, inputData) => {
|
||||
const inputSpec = transformInputSpecV1ToV2(inputData, {
|
||||
name: inputName
|
||||
})
|
||||
const widget = widgetConstructorV2(node, inputSpec)
|
||||
return {
|
||||
widget,
|
||||
minWidth: widget.options.minNodeSize?.[0],
|
||||
minHeight: widget.options.minNodeSize?.[1]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function controlValueRunBefore() {
|
||||
return useSettingStore().get('Comfy.WidgetControlMode') === 'before'
|
||||
}
|
||||
|
||||
export function updateControlWidgetLabel(widget: IBaseWidget) {
|
||||
if (controlValueRunBefore()) {
|
||||
widget.label = t('g.control_before_generate')
|
||||
} else {
|
||||
widget.label = t('g.control_after_generate')
|
||||
}
|
||||
}
|
||||
|
||||
export const IS_CONTROL_WIDGET = Symbol()
|
||||
const HAS_EXECUTED = Symbol()
|
||||
|
||||
export function addValueControlWidget(
|
||||
node: LGraphNode,
|
||||
targetWidget: IBaseWidget,
|
||||
defaultValue?: string,
|
||||
_values?: unknown,
|
||||
widgetName?: string,
|
||||
inputData?: InputSpec
|
||||
): IComboWidget {
|
||||
let name = inputData?.[1]?.control_after_generate
|
||||
if (typeof name !== 'string') {
|
||||
name = widgetName
|
||||
}
|
||||
const widgets = addValueControlWidgets(
|
||||
node,
|
||||
targetWidget,
|
||||
defaultValue ?? 'randomize',
|
||||
{
|
||||
addFilterList: false,
|
||||
controlAfterGenerateName: name
|
||||
},
|
||||
inputData
|
||||
)
|
||||
return widgets[0]
|
||||
}
|
||||
|
||||
export function addValueControlWidgets(
|
||||
node: LGraphNode,
|
||||
targetWidget: IBaseWidget,
|
||||
defaultValue?: string,
|
||||
options?: Record<string, any>,
|
||||
inputData?: InputSpec
|
||||
): [IComboWidget, ...IStringWidget[]] {
|
||||
if (!defaultValue) defaultValue = 'randomize'
|
||||
if (!options) options = {}
|
||||
|
||||
const getName = (defaultName: string, optionName: string) => {
|
||||
let name = defaultName
|
||||
if (options[optionName]) {
|
||||
name = options[optionName]
|
||||
} else if (typeof inputData?.[1]?.[defaultName] === 'string') {
|
||||
name = inputData?.[1]?.[defaultName]
|
||||
} else if (inputData?.[1]?.control_prefix) {
|
||||
name = inputData?.[1]?.control_prefix + ' ' + name
|
||||
}
|
||||
return name
|
||||
}
|
||||
|
||||
const valueControl = node.addWidget(
|
||||
'combo',
|
||||
getName('control_after_generate', 'controlAfterGenerateName'),
|
||||
defaultValue,
|
||||
function () {},
|
||||
{
|
||||
values: ['fixed', 'increment', 'decrement', 'randomize'],
|
||||
serialize: false, // Don't include this in prompt.
|
||||
canvasOnly: true
|
||||
}
|
||||
) as IComboWidget
|
||||
|
||||
valueControl.tooltip =
|
||||
'Allows the linked widget to be changed automatically, for example randomizing the noise seed.'
|
||||
valueControl[IS_CONTROL_WIDGET] = true
|
||||
updateControlWidgetLabel(valueControl)
|
||||
Object.defineProperty(valueControl, 'disabled', {
|
||||
get: () => targetWidget.computedDisabled
|
||||
})
|
||||
const widgets: [IComboWidget, ...IStringWidget[]] = [valueControl]
|
||||
|
||||
const isCombo = isComboWidget(targetWidget)
|
||||
let comboFilter: IStringWidget
|
||||
if (isCombo && valueControl.options.values) {
|
||||
// @ts-expect-error Combo widget values may be a dictionary or legacy function type
|
||||
valueControl.options.values.push('increment-wrap')
|
||||
}
|
||||
if (isCombo && options.addFilterList !== false) {
|
||||
comboFilter = node.addWidget(
|
||||
'string',
|
||||
getName('control_filter_list', 'controlFilterListName'),
|
||||
'',
|
||||
function () {},
|
||||
{
|
||||
serialize: false // Don't include this in prompt.
|
||||
}
|
||||
) as IStringWidget
|
||||
updateControlWidgetLabel(comboFilter)
|
||||
comboFilter.tooltip =
|
||||
"Allows for filtering the list of values when changing the value via the control generate mode. Allows for RegEx matches in the format /abc/ to only filter to values containing 'abc'."
|
||||
Object.defineProperty(comboFilter, 'disabled', {
|
||||
get: () => targetWidget.computedDisabled
|
||||
})
|
||||
|
||||
widgets.push(comboFilter)
|
||||
}
|
||||
|
||||
const applyWidgetControl = () => {
|
||||
var v = valueControl.value
|
||||
|
||||
if (isCombo && v !== 'fixed') {
|
||||
let values = targetWidget.options.values ?? []
|
||||
const filter = comboFilter?.value
|
||||
if (filter) {
|
||||
let check
|
||||
if (filter.startsWith('/') && filter.endsWith('/')) {
|
||||
try {
|
||||
const regex = new RegExp(filter.substring(1, filter.length - 1))
|
||||
check = (item: string) => regex.test(item)
|
||||
} catch (error) {
|
||||
console.error(
|
||||
'Error constructing RegExp filter for node ' + node.id,
|
||||
filter,
|
||||
error
|
||||
)
|
||||
}
|
||||
}
|
||||
if (!check) {
|
||||
const lower = filter.toLocaleLowerCase()
|
||||
check = (item: string) => item.toLocaleLowerCase().includes(lower)
|
||||
}
|
||||
// @ts-expect-error Combo widget values may be a dictionary or legacy function type
|
||||
values = values.filter((item: string) => check(item))
|
||||
if (!values.length && targetWidget.options.values?.length) {
|
||||
console.warn(
|
||||
'Filter for node ' + node.id + ' has filtered out all items',
|
||||
filter
|
||||
)
|
||||
}
|
||||
}
|
||||
// @ts-expect-error targetWidget.value can be number or string
|
||||
let current_index = values.indexOf(targetWidget.value)
|
||||
let current_length = values.length
|
||||
|
||||
switch (v) {
|
||||
case 'increment':
|
||||
current_index += 1
|
||||
break
|
||||
case 'increment-wrap':
|
||||
current_index += 1
|
||||
if (current_index >= current_length) {
|
||||
current_index = 0
|
||||
}
|
||||
break
|
||||
case 'decrement':
|
||||
current_index -= 1
|
||||
break
|
||||
case 'randomize':
|
||||
// @ts-expect-error Combo widget values may be a dictionary or legacy function type
|
||||
current_index = Math.floor(Math.random() * current_length)
|
||||
break
|
||||
default:
|
||||
break
|
||||
}
|
||||
current_index = Math.max(0, current_index)
|
||||
// @ts-expect-error Combo widget values may be a dictionary or legacy function type
|
||||
current_index = Math.min(current_length - 1, current_index)
|
||||
if (current_index >= 0) {
|
||||
// @ts-expect-error Combo widget values may be a dictionary or legacy function type
|
||||
let value = values[current_index]
|
||||
targetWidget.value = value
|
||||
targetWidget.callback?.(value)
|
||||
}
|
||||
} else {
|
||||
//number
|
||||
let { min = 0, max = 1, step2 = 1 } = targetWidget.options
|
||||
// limit to something that javascript can handle
|
||||
max = Math.min(1125899906842624, max)
|
||||
min = Math.max(-1125899906842624, min)
|
||||
let range = (max - min) / step2
|
||||
|
||||
//adjust values based on valueControl Behaviour
|
||||
switch (v) {
|
||||
case 'fixed':
|
||||
break
|
||||
case 'increment':
|
||||
// @ts-expect-error targetWidget.value can be number or string
|
||||
targetWidget.value += step2
|
||||
break
|
||||
case 'decrement':
|
||||
// @ts-expect-error targetWidget.value can be number or string
|
||||
targetWidget.value -= step2
|
||||
break
|
||||
case 'randomize':
|
||||
targetWidget.value = Math.floor(Math.random() * range) * step2 + min
|
||||
break
|
||||
default:
|
||||
break
|
||||
}
|
||||
/*check if values are over or under their respective
|
||||
* ranges and set them to min or max.*/
|
||||
// @ts-expect-error targetWidget.value can be number or string
|
||||
if (targetWidget.value < min) targetWidget.value = min
|
||||
// @ts-expect-error targetWidget.value can be number or string
|
||||
if (targetWidget.value > max) targetWidget.value = max
|
||||
targetWidget.callback?.(targetWidget.value)
|
||||
}
|
||||
}
|
||||
|
||||
valueControl.beforeQueued = ({ isPartialExecution } = {}) => {
|
||||
if (!isPartialExecution && controlValueRunBefore()) {
|
||||
// Don't run on first execution
|
||||
if (valueControl[HAS_EXECUTED]) {
|
||||
applyWidgetControl()
|
||||
}
|
||||
}
|
||||
valueControl[HAS_EXECUTED] = true
|
||||
}
|
||||
|
||||
valueControl.afterQueued = ({ isPartialExecution } = {}) => {
|
||||
if (!isPartialExecution && !controlValueRunBefore()) {
|
||||
applyWidgetControl()
|
||||
}
|
||||
}
|
||||
|
||||
return widgets
|
||||
}
|
||||
|
||||
export const ComfyWidgets = {
|
||||
INT: transformWidgetConstructorV2ToV1(useIntWidget()),
|
||||
FLOAT: transformWidgetConstructorV2ToV1(useFloatWidget()),
|
||||
BOOLEAN: transformWidgetConstructorV2ToV1(useBooleanWidget()),
|
||||
STRING: transformWidgetConstructorV2ToV1(useStringWidget()),
|
||||
MARKDOWN: transformWidgetConstructorV2ToV1(useMarkdownWidget()),
|
||||
COMBO: transformWidgetConstructorV2ToV1(useComboWidget()),
|
||||
IMAGEUPLOAD: useImageUploadWidget(),
|
||||
COLOR: transformWidgetConstructorV2ToV1(useColorWidget()),
|
||||
IMAGECOMPARE: transformWidgetConstructorV2ToV1(useImageCompareWidget()),
|
||||
BOUNDING_BOX: transformWidgetConstructorV2ToV1(useBoundingBoxWidget()),
|
||||
CHART: transformWidgetConstructorV2ToV1(useChartWidget()),
|
||||
GALLERIA: transformWidgetConstructorV2ToV1(useGalleriaWidget()),
|
||||
PAINTER: transformWidgetConstructorV2ToV1(usePainterWidget()),
|
||||
TEXTAREA: transformWidgetConstructorV2ToV1(useTextareaWidget()),
|
||||
CURVE: transformWidgetConstructorV2ToV1(useCurveWidget()),
|
||||
...dynamicWidgets
|
||||
} as const
|
||||
|
||||
export function isValidWidgetType(
|
||||
key: unknown
|
||||
): key is keyof typeof ComfyWidgets {
|
||||
return ComfyWidgets[key as keyof typeof ComfyWidgets] !== undefined
|
||||
}
|
||||
@@ -0,0 +1,985 @@
|
||||
import _ from 'es-toolkit/compat'
|
||||
|
||||
import { downloadFile, openFileInNewTab } from '@/base/common/downloadUtil'
|
||||
import { useSelectedLiteGraphItems } from '@/composables/canvas/useSelectedLiteGraphItems'
|
||||
import { useSubgraphOperations } from '@/composables/graph/useSubgraphOperations'
|
||||
import { useNodeAnimatedImage } from '@/composables/node/useNodeAnimatedImage'
|
||||
import { useNodeCanvasImagePreview } from '@/composables/node/useNodeCanvasImagePreview'
|
||||
import { useNodeImage, useNodeVideo } from '@/composables/node/useNodeImage'
|
||||
import {
|
||||
addWidgetPromotionOptions,
|
||||
isPreviewPseudoWidget
|
||||
} from '@/core/graph/subgraph/promotionUtils'
|
||||
import { applyDynamicInputs } from '@/core/graph/widgets/dynamicWidgets'
|
||||
import { st, t } from '@/i18n'
|
||||
import {
|
||||
LGraphCanvas,
|
||||
LGraphEventMode,
|
||||
LGraphNode,
|
||||
LiteGraph,
|
||||
RenderShape,
|
||||
SubgraphNode,
|
||||
createBounds
|
||||
} from '@/lib/litegraph/src/litegraph'
|
||||
import type {
|
||||
CreateNodeOptions,
|
||||
GraphAddOptions,
|
||||
IContextMenuValue,
|
||||
Point,
|
||||
Subgraph
|
||||
} from '@/lib/litegraph/src/litegraph'
|
||||
import type {
|
||||
ExportedSubgraphInstance,
|
||||
ISerialisableNodeInput,
|
||||
ISerialisableNodeOutput,
|
||||
ISerialisedNode
|
||||
} from '@/lib/litegraph/src/types/serialisation'
|
||||
import type { IBaseWidget } from '@/lib/litegraph/src/types/widgets'
|
||||
import { useSettingStore } from '@/platform/settings/settingStore'
|
||||
import { useToastStore } from '@/platform/updates/common/toastStore'
|
||||
import { useWorkflowStore } from '@/platform/workflow/management/stores/workflowStore'
|
||||
import type { NodeId } from '@/platform/workflow/validation/schemas/workflowSchema'
|
||||
import { useCanvasStore } from '@/renderer/core/canvas/canvasStore'
|
||||
import { useDialogService } from '@/services/dialogService'
|
||||
import { resolveSubgraphPseudoWidgetCache } from '@/services/subgraphPseudoWidgetCache'
|
||||
import type { SubgraphPseudoWidgetCache } from '@/services/subgraphPseudoWidgetCache'
|
||||
import { transformInputSpecV2ToV1 } from '@/schemas/nodeDef/migration'
|
||||
import type {
|
||||
ComfyNodeDef as ComfyNodeDefV2,
|
||||
InputSpec,
|
||||
OutputSpec
|
||||
} from '@/schemas/nodeDef/nodeDefSchemaV2'
|
||||
import type { ComfyNodeDef as ComfyNodeDefV1 } from '@/schemas/nodeDefSchema'
|
||||
import { ComfyApp, app } from '@/scripts/app'
|
||||
import { isComponentWidget, isDOMWidget } from '@/scripts/domWidget'
|
||||
import { $el } from '@/scripts/ui'
|
||||
import { useDomWidgetStore } from '@/stores/domWidgetStore'
|
||||
import { useExecutionStore } from '@/stores/executionStore'
|
||||
import { useNodeOutputStore } from '@/stores/nodeOutputStore'
|
||||
import { ComfyNodeDefImpl } from '@/stores/nodeDefStore'
|
||||
import { usePromotionStore } from '@/stores/promotionStore'
|
||||
import { useSubgraphStore } from '@/stores/subgraphStore'
|
||||
import { useFavoritedWidgetsStore } from '@/stores/workspace/favoritedWidgetsStore'
|
||||
import { useRightSidePanelStore } from '@/stores/workspace/rightSidePanelStore'
|
||||
import { useWidgetStore } from '@/stores/widgetStore'
|
||||
import { normalizeI18nKey } from '@/utils/formatUtil'
|
||||
import {
|
||||
isAnimatedOutput,
|
||||
isImageNode,
|
||||
isVideoNode,
|
||||
isVideoOutput,
|
||||
migrateWidgetsValues
|
||||
} from '@/utils/litegraphUtil'
|
||||
import { getOrderedInputSpecs } from '@/workbench/utils/nodeDefOrderingUtil'
|
||||
|
||||
import { useExtensionService } from './extensionService'
|
||||
import { useMaskEditor } from '@/composables/maskeditor/useMaskEditor'
|
||||
|
||||
export interface HasInitialMinSize {
|
||||
_initialMinSize: { width: number; height: number }
|
||||
}
|
||||
|
||||
export const CONFIG = Symbol()
|
||||
export const GET_CONFIG = Symbol()
|
||||
|
||||
export function getExtraOptionsForWidget(
|
||||
node: LGraphNode,
|
||||
widget: IBaseWidget
|
||||
) {
|
||||
const options: IContextMenuValue[] = []
|
||||
const input = node.inputs.find((inp) => inp.widget?.name === widget.name)
|
||||
|
||||
if (input) {
|
||||
options.unshift({
|
||||
content: `${t('contextMenu.RenameWidget')}: ${widget.label ?? widget.name}`,
|
||||
callback: async () => {
|
||||
const newLabel = await useDialogService().prompt({
|
||||
title: t('g.rename'),
|
||||
message: t('g.enterNewNamePrompt'),
|
||||
defaultValue: widget.label,
|
||||
placeholder: widget.name
|
||||
})
|
||||
if (newLabel === null) return
|
||||
widget.label = newLabel || undefined
|
||||
input.label = newLabel || undefined
|
||||
widget.callback?.(widget.value)
|
||||
useCanvasStore().canvas?.setDirty(true)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
const favoritedWidgetsStore = useFavoritedWidgetsStore()
|
||||
const isFavorited = favoritedWidgetsStore.isFavorited(node, widget.name)
|
||||
options.unshift({
|
||||
content: isFavorited
|
||||
? `${t('contextMenu.UnfavoriteWidget')}: ${widget.label ?? widget.name}`
|
||||
: `${t('contextMenu.FavoriteWidget')}: ${widget.label ?? widget.name}`,
|
||||
callback: () => {
|
||||
favoritedWidgetsStore.toggleFavorite(node, widget.name)
|
||||
}
|
||||
})
|
||||
|
||||
if (node.graph && !node.graph.isRootGraph) {
|
||||
addWidgetPromotionOptions(options, widget, node)
|
||||
}
|
||||
return options
|
||||
}
|
||||
|
||||
/**
|
||||
* Service that augments litegraph with ComfyUI specific functionality.
|
||||
*/
|
||||
export const useLitegraphService = () => {
|
||||
const extensionService = useExtensionService()
|
||||
const toastStore = useToastStore()
|
||||
const widgetStore = useWidgetStore()
|
||||
const canvasStore = useCanvasStore()
|
||||
const { toggleSelectedNodesMode } = useSelectedLiteGraphItems()
|
||||
const subgraphPseudoWidgetCache = new WeakMap<
|
||||
SubgraphNode,
|
||||
SubgraphPseudoWidgetCache<LGraphNode, IBaseWidget>
|
||||
>()
|
||||
|
||||
function invalidateSubgraphPseudoWidgetCache(node: SubgraphNode) {
|
||||
subgraphPseudoWidgetCache.delete(node)
|
||||
}
|
||||
|
||||
function getPseudoWidgetPreviewTargets(node: SubgraphNode): LGraphNode[] {
|
||||
const promotionStore = usePromotionStore()
|
||||
const promotions = promotionStore.getPromotionsRef(
|
||||
node.rootGraph.id,
|
||||
node.id
|
||||
)
|
||||
const resolved = resolveSubgraphPseudoWidgetCache({
|
||||
cache: subgraphPseudoWidgetCache.get(node) ?? null,
|
||||
promotions,
|
||||
getNodeById: (nodeId) => node.subgraph.getNodeById(nodeId) ?? undefined,
|
||||
isPreviewPseudoWidget
|
||||
})
|
||||
subgraphPseudoWidgetCache.set(node, resolved.cache)
|
||||
return resolved.nodes
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal The key for the node definition in the i18n file.
|
||||
*/
|
||||
function nodeKey(node: LGraphNode): string {
|
||||
return `nodeDefs.${normalizeI18nKey(node.constructor.nodeData!.name)}`
|
||||
}
|
||||
/**
|
||||
* @internal Add input sockets to the node. (No widget)
|
||||
*/
|
||||
function addInputSocket(node: LGraphNode, inputSpec: InputSpec) {
|
||||
const inputName = inputSpec.name
|
||||
const nameKey = `${nodeKey(node)}.inputs.${normalizeI18nKey(inputName)}.name`
|
||||
const widgetConstructor = widgetStore.widgets.get(
|
||||
inputSpec.widgetType ?? inputSpec.type
|
||||
)
|
||||
if (
|
||||
(widgetConstructor && !inputSpec.forceInput) ||
|
||||
applyDynamicInputs(node, inputSpec)
|
||||
)
|
||||
return
|
||||
|
||||
const input = node.addInput(inputName, inputSpec.type, {
|
||||
shape: inputSpec.isOptional ? RenderShape.HollowCircle : undefined,
|
||||
localized_name: st(nameKey, inputName)
|
||||
})
|
||||
input.label ??= inputSpec.display_name
|
||||
}
|
||||
/**
|
||||
* @internal Setup stroke styles for the node under various conditions.
|
||||
*/
|
||||
function setupStrokeStyles(node: LGraphNode) {
|
||||
node.strokeStyles['running'] = function (this: LGraphNode) {
|
||||
const nodeId = String(this.id)
|
||||
const nodeLocatorId = useWorkflowStore().nodeIdToNodeLocatorId(nodeId)
|
||||
const state =
|
||||
useExecutionStore().nodeLocationProgressStates[nodeLocatorId]?.state
|
||||
if (state === 'running') {
|
||||
return { color: '#0f0', lineWidth: 3 }
|
||||
}
|
||||
}
|
||||
node.strokeStyles['dragOver'] = function (this: LGraphNode) {
|
||||
if (app.dragOverNode?.id == this.id) {
|
||||
return { color: 'dodgerblue' }
|
||||
}
|
||||
}
|
||||
node.strokeStyles['executionError'] = function (this: LGraphNode) {
|
||||
if (app.lastExecutionError?.node_id == this.id) {
|
||||
return { color: '#f0f', lineWidth: 3 }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Utility function. Implemented for use with dynamic widgets
|
||||
*/
|
||||
function addNodeInput(node: LGraphNode, inputSpec: InputSpec) {
|
||||
addInputSocket(node, inputSpec)
|
||||
addInputWidget(node, inputSpec)
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal Add a widget to the node. For both primitive types and custom widgets
|
||||
* (unless `socketless`), an input socket is also added.
|
||||
*/
|
||||
function addInputWidget(node: LGraphNode, inputSpec: InputSpec) {
|
||||
const widgetInputSpec = { ...inputSpec }
|
||||
if (inputSpec.widgetType) {
|
||||
widgetInputSpec.type = inputSpec.widgetType
|
||||
}
|
||||
const inputName = inputSpec.name
|
||||
const nameKey = `${nodeKey(node)}.inputs.${normalizeI18nKey(inputName)}.name`
|
||||
const widgetConstructor = widgetStore.widgets.get(widgetInputSpec.type)
|
||||
if (!widgetConstructor || inputSpec.forceInput) return
|
||||
|
||||
const {
|
||||
widget,
|
||||
minWidth = 1,
|
||||
minHeight = 1
|
||||
} = widgetConstructor(
|
||||
node,
|
||||
inputName,
|
||||
transformInputSpecV2ToV1(widgetInputSpec),
|
||||
app
|
||||
) ?? {}
|
||||
|
||||
if (widget) {
|
||||
widget.label = st(
|
||||
nameKey,
|
||||
widget.label ?? widgetInputSpec.display_name ?? inputName
|
||||
)
|
||||
widget.options ??= {}
|
||||
Object.assign(widget.options, {
|
||||
advanced: inputSpec.advanced,
|
||||
hidden: inputSpec.hidden
|
||||
})
|
||||
}
|
||||
|
||||
if (!widget?.options?.socketless) {
|
||||
const inputSpecV1 = transformInputSpecV2ToV1(widgetInputSpec)
|
||||
node.addInput(inputName, inputSpec.type, {
|
||||
shape: inputSpec.isOptional ? RenderShape.HollowCircle : undefined,
|
||||
localized_name: st(nameKey, inputName),
|
||||
widget: { name: inputName, [GET_CONFIG]: () => inputSpecV1 }
|
||||
})
|
||||
}
|
||||
const castedNode = node as LGraphNode & HasInitialMinSize
|
||||
castedNode._initialMinSize.width = Math.max(
|
||||
castedNode._initialMinSize.width,
|
||||
minWidth
|
||||
)
|
||||
castedNode._initialMinSize.height = Math.max(
|
||||
castedNode._initialMinSize.height,
|
||||
minHeight
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal Add inputs to the node.
|
||||
*/
|
||||
function addInputs(node: LGraphNode, inputs: Record<string, InputSpec>) {
|
||||
// Use input_order if available to ensure consistent widget ordering
|
||||
//@ts-expect-error was ComfyNode.nodeData as ComfyNodeDefImpl
|
||||
const nodeDefImpl = node.constructor.nodeData as ComfyNodeDefImpl
|
||||
const orderedInputSpecs = getOrderedInputSpecs(nodeDefImpl, inputs)
|
||||
|
||||
// Create sockets and widgets in the determined order
|
||||
for (const inputSpec of orderedInputSpecs) addInputSocket(node, inputSpec)
|
||||
for (const inputSpec of orderedInputSpecs) addInputWidget(node, inputSpec)
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal Add outputs to the node.
|
||||
*/
|
||||
function addOutputs(node: LGraphNode, outputs: OutputSpec[]) {
|
||||
for (const output of outputs) {
|
||||
const { name, is_list } = output
|
||||
// TODO: Fix the typing at the node spec level
|
||||
const type = output.type === 'COMFY_MATCHTYPE_V3' ? '*' : output.type
|
||||
const shapeOptions = is_list ? { shape: LiteGraph.GRID_SHAPE } : {}
|
||||
const nameKey = `${nodeKey(node)}.outputs.${output.index}.name`
|
||||
const typeKey = `dataTypes.${normalizeI18nKey(type)}`
|
||||
const outputOptions = {
|
||||
...shapeOptions,
|
||||
// If the output name is different from the output type, use the output name.
|
||||
// e.g.
|
||||
// - type ("INT"); name ("Positive") => translate name
|
||||
// - type ("FLOAT"); name ("FLOAT") => translate type
|
||||
localized_name: type !== name ? st(nameKey, name) : st(typeKey, name)
|
||||
}
|
||||
node.addOutput(name, type, outputOptions)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal Set the initial size of the node.
|
||||
*/
|
||||
function setInitialSize(node: LGraphNode) {
|
||||
const s = node.computeSize()
|
||||
// Expand the width a little to fit widget values on screen.
|
||||
const pad =
|
||||
node.widgets?.length &&
|
||||
!useSettingStore().get('LiteGraph.Node.DefaultPadding')
|
||||
const castedNode = node as LGraphNode & HasInitialMinSize
|
||||
s[0] = Math.max(castedNode._initialMinSize.width, s[0] + (pad ? 60 : 0))
|
||||
s[1] = Math.max(castedNode._initialMinSize.height, s[1])
|
||||
node.setSize(s)
|
||||
}
|
||||
|
||||
function registerSubgraphNodeDef(
|
||||
nodeDefV1: ComfyNodeDefV1,
|
||||
subgraph: Subgraph,
|
||||
instanceData: ExportedSubgraphInstance
|
||||
) {
|
||||
const node = class ComfyNode
|
||||
extends SubgraphNode
|
||||
implements HasInitialMinSize
|
||||
{
|
||||
static comfyClass: string
|
||||
static override title: string
|
||||
static override category: string
|
||||
static override nodeData: ComfyNodeDefV1 & ComfyNodeDefV2
|
||||
|
||||
_initialMinSize = { width: 1, height: 1 }
|
||||
|
||||
constructor() {
|
||||
super(app.rootGraph, subgraph, instanceData)
|
||||
|
||||
// Set up event listener for promoted widget registration
|
||||
subgraph.events.addEventListener('widget-promoted', (event) => {
|
||||
invalidateSubgraphPseudoWidgetCache(this)
|
||||
const { widget } = event.detail
|
||||
// Only handle DOM widgets
|
||||
if (!isDOMWidget(widget) && !isComponentWidget(widget)) return
|
||||
|
||||
const domWidgetStore = useDomWidgetStore()
|
||||
if (!domWidgetStore.widgetStates.has(widget.id)) {
|
||||
domWidgetStore.registerWidget(widget)
|
||||
// Set initial visibility based on whether the widget's node is in the current graph
|
||||
const widgetState = domWidgetStore.widgetStates.get(widget.id)
|
||||
if (widgetState) {
|
||||
const currentGraph = canvasStore.getCanvas().graph
|
||||
widgetState.visible =
|
||||
currentGraph?.nodes.includes(widget.node) ?? false
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
// Set up event listener for promoted widget removal
|
||||
subgraph.events.addEventListener('widget-demoted', (event) => {
|
||||
invalidateSubgraphPseudoWidgetCache(this)
|
||||
const { widget } = event.detail
|
||||
// Only handle DOM widgets
|
||||
if (!isDOMWidget(widget) && !isComponentWidget(widget)) return
|
||||
|
||||
const domWidgetStore = useDomWidgetStore()
|
||||
if (domWidgetStore.widgetStates.has(widget.id)) {
|
||||
domWidgetStore.unregisterWidget(widget.id)
|
||||
}
|
||||
})
|
||||
|
||||
setupStrokeStyles(this)
|
||||
addInputs(this, ComfyNode.nodeData.inputs)
|
||||
addOutputs(this, ComfyNode.nodeData.outputs)
|
||||
setInitialSize(this)
|
||||
this.serialize_widgets = true
|
||||
void extensionService.invokeExtensionsAsync('nodeCreated', this)
|
||||
}
|
||||
|
||||
/**
|
||||
* Configure the node from a serialised node. Keep 'name', 'type', 'shape',
|
||||
* and 'localized_name' information from the original node definition.
|
||||
*/
|
||||
override configure(data: ISerialisedNode): void {
|
||||
const RESERVED_KEYS = ['name', 'type', 'shape', 'localized_name']
|
||||
|
||||
// Note: input name is unique in a node definition, so we can lookup
|
||||
// input by name.
|
||||
const inputByName = new Map<string, ISerialisableNodeInput>(
|
||||
data.inputs?.map((input) => [input.name, input]) ?? []
|
||||
)
|
||||
// Inputs defined by the node definition.
|
||||
const definedInputNames = new Set(
|
||||
this.inputs.map((input) => input.name)
|
||||
)
|
||||
const definedInputs = this.inputs.map((input) => {
|
||||
const inputData = inputByName.get(input.name)
|
||||
return inputData
|
||||
? {
|
||||
...inputData,
|
||||
// Whether the input has associated widget follows the
|
||||
// original node definition.
|
||||
..._.pick(input, RESERVED_KEYS.concat('widget'))
|
||||
}
|
||||
: input
|
||||
})
|
||||
// Extra inputs that potentially dynamically added by custom js logic.
|
||||
const extraInputs = data.inputs?.filter(
|
||||
(input) => !definedInputNames.has(input.name)
|
||||
)
|
||||
data.inputs = [...definedInputs, ...(extraInputs ?? [])]
|
||||
|
||||
// Note: output name is not unique, so we cannot lookup output by name.
|
||||
// Use index instead.
|
||||
data.outputs = _.zip(this.outputs, data.outputs).map(
|
||||
([output, outputData]) => {
|
||||
// If there are extra outputs in the serialised node, use them directly.
|
||||
// There are currently custom nodes that dynamically add outputs via
|
||||
// js logic.
|
||||
if (!output) return outputData as ISerialisableNodeOutput
|
||||
|
||||
return outputData
|
||||
? {
|
||||
...outputData,
|
||||
..._.pick(output, RESERVED_KEYS)
|
||||
}
|
||||
: output
|
||||
}
|
||||
)
|
||||
|
||||
data.widgets_values = migrateWidgetsValues(
|
||||
ComfyNode.nodeData.inputs,
|
||||
this.widgets ?? [],
|
||||
data.widgets_values ?? []
|
||||
)
|
||||
|
||||
super.configure(data)
|
||||
}
|
||||
}
|
||||
|
||||
addNodeContextMenuHandler(node)
|
||||
addDrawBackgroundHandler(node)
|
||||
addNodeKeyHandler(node)
|
||||
// Note: Some extensions expects node.comfyClass to be set in
|
||||
// `beforeRegisterNodeDef`.
|
||||
node.prototype.comfyClass = nodeDefV1.name
|
||||
node.comfyClass = nodeDefV1.name
|
||||
|
||||
const nodeDef = new ComfyNodeDefImpl(nodeDefV1)
|
||||
node.nodeData = nodeDef
|
||||
LiteGraph.registerNodeType(subgraph.id, node)
|
||||
// Note: Do not following assignments before `LiteGraph.registerNodeType`
|
||||
// because `registerNodeType` will overwrite the assignments.
|
||||
node.category = nodeDef.category
|
||||
node.skip_list = true
|
||||
node.title = nodeDef.display_name || nodeDef.name
|
||||
}
|
||||
|
||||
async function registerNodeDef(nodeId: string, nodeDefV1: ComfyNodeDefV1) {
|
||||
const node = class ComfyNode
|
||||
extends LGraphNode
|
||||
implements HasInitialMinSize
|
||||
{
|
||||
static comfyClass: string
|
||||
static override title: string
|
||||
static override category: string
|
||||
static override nodeData: ComfyNodeDefV1 & ComfyNodeDefV2
|
||||
|
||||
_initialMinSize = { width: 1, height: 1 }
|
||||
|
||||
constructor(title: string) {
|
||||
super(title)
|
||||
setupStrokeStyles(this)
|
||||
addInputs(this, ComfyNode.nodeData.inputs)
|
||||
addOutputs(this, ComfyNode.nodeData.outputs)
|
||||
setInitialSize(this)
|
||||
this.serialize_widgets = true
|
||||
|
||||
// Mark API Nodes yellow by default to distinguish with other nodes.
|
||||
if (ComfyNode.nodeData.api_node) {
|
||||
this.color = LGraphCanvas.node_colors.yellow.color
|
||||
this.bgcolor = LGraphCanvas.node_colors.yellow.bgcolor
|
||||
}
|
||||
|
||||
void extensionService.invokeExtensionsAsync('nodeCreated', this)
|
||||
}
|
||||
|
||||
/**
|
||||
* Configure the node from a serialised node. Keep 'name', 'type', 'shape',
|
||||
* and 'localized_name' information from the original node definition.
|
||||
*/
|
||||
override configure(data: ISerialisedNode): void {
|
||||
const RESERVED_KEYS = ['name', 'type', 'shape', 'localized_name']
|
||||
|
||||
// Note: input name is unique in a node definition, so we can lookup
|
||||
// input by name.
|
||||
const inputByName = new Map<string, ISerialisableNodeInput>(
|
||||
data.inputs?.map((input) => [input.name, input]) ?? []
|
||||
)
|
||||
// Inputs defined by the node definition.
|
||||
const definedInputNames = new Set(
|
||||
this.inputs.map((input) => input.name)
|
||||
)
|
||||
const definedInputs = this.inputs.map((input) => {
|
||||
const inputData = inputByName.get(input.name)
|
||||
return inputData
|
||||
? {
|
||||
...inputData,
|
||||
// Whether the input has associated widget follows the
|
||||
// original node definition.
|
||||
..._.pick(input, RESERVED_KEYS.concat('widget'))
|
||||
}
|
||||
: input
|
||||
})
|
||||
// Extra inputs that potentially dynamically added by custom js logic.
|
||||
const extraInputs = data.inputs?.filter(
|
||||
(input) => !definedInputNames.has(input.name)
|
||||
)
|
||||
data.inputs = [...definedInputs, ...(extraInputs ?? [])]
|
||||
|
||||
// Note: output name is not unique, so we cannot lookup output by name.
|
||||
// Use index instead.
|
||||
data.outputs = _.zip(this.outputs, data.outputs).map(
|
||||
([output, outputData]) => {
|
||||
// If there are extra outputs in the serialised node, use them directly.
|
||||
// There are currently custom nodes that dynamically add outputs via
|
||||
// js logic.
|
||||
if (!output) return outputData as ISerialisableNodeOutput
|
||||
|
||||
return outputData
|
||||
? {
|
||||
...outputData,
|
||||
..._.pick(output, RESERVED_KEYS)
|
||||
}
|
||||
: output
|
||||
}
|
||||
)
|
||||
|
||||
data.widgets_values = migrateWidgetsValues(
|
||||
ComfyNode.nodeData.inputs,
|
||||
this.widgets ?? [],
|
||||
data.widgets_values ?? []
|
||||
)
|
||||
|
||||
super.configure(data)
|
||||
}
|
||||
}
|
||||
|
||||
addNodeContextMenuHandler(node)
|
||||
addDrawBackgroundHandler(node)
|
||||
addNodeKeyHandler(node)
|
||||
// Note: Some extensions expects node.comfyClass to be set in
|
||||
// `beforeRegisterNodeDef`.
|
||||
node.prototype.comfyClass = nodeDefV1.name
|
||||
node.comfyClass = nodeDefV1.name
|
||||
await extensionService.invokeExtensionsAsync(
|
||||
'beforeRegisterNodeDef',
|
||||
node,
|
||||
nodeDefV1 // Receives V1 NodeDef, and potentially make modifications to it
|
||||
)
|
||||
|
||||
const nodeDef = new ComfyNodeDefImpl(nodeDefV1)
|
||||
node.nodeData = nodeDef
|
||||
LiteGraph.registerNodeType(nodeId, node)
|
||||
// Note: Do not following assignments before `LiteGraph.registerNodeType`
|
||||
// because `registerNodeType` will overwrite the assignments.
|
||||
node.category = nodeDef.category
|
||||
node.title = nodeDef.display_name || nodeDef.name
|
||||
|
||||
// Set skip_list for dev-only nodes based on current DevMode setting
|
||||
// This ensures nodes registered after initial load respect the current setting
|
||||
if (nodeDef.dev_only) {
|
||||
const settingStore = useSettingStore()
|
||||
node.skip_list = !settingStore.get('Comfy.DevMode')
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds special context menu handling for nodes
|
||||
* e.g. this adds Open Image functionality for nodes that show images
|
||||
* @param {*} node The node to add the menu handler
|
||||
*/
|
||||
function addNodeContextMenuHandler(node: typeof LGraphNode) {
|
||||
function getCopyImageOption(img: HTMLImageElement): IContextMenuValue[] {
|
||||
if (typeof window.ClipboardItem === 'undefined') return []
|
||||
return [
|
||||
{
|
||||
content: 'Copy Image',
|
||||
callback: async () => {
|
||||
const url = new URL(img.src)
|
||||
url.searchParams.delete('preview')
|
||||
|
||||
// @ts-expect-error fixme ts strict error
|
||||
const writeImage = async (blob) => {
|
||||
await navigator.clipboard.write([
|
||||
new ClipboardItem({
|
||||
[blob.type]: blob
|
||||
})
|
||||
])
|
||||
}
|
||||
|
||||
try {
|
||||
const data = await fetch(url)
|
||||
const blob = await data.blob()
|
||||
try {
|
||||
await writeImage(blob)
|
||||
} catch (error) {
|
||||
// Chrome seems to only support PNG on write, convert and try again
|
||||
if (blob.type !== 'image/png') {
|
||||
const canvas = $el('canvas', {
|
||||
width: img.naturalWidth,
|
||||
height: img.naturalHeight
|
||||
}) as HTMLCanvasElement
|
||||
const ctx = canvas.getContext('2d')
|
||||
// @ts-expect-error fixme ts strict error
|
||||
let image
|
||||
if (typeof window.createImageBitmap === 'undefined') {
|
||||
image = new Image()
|
||||
const p = new Promise((resolve, reject) => {
|
||||
// @ts-expect-error fixme ts strict error
|
||||
image.onload = resolve
|
||||
// @ts-expect-error fixme ts strict error
|
||||
image.onerror = reject
|
||||
}).finally(() => {
|
||||
// @ts-expect-error fixme ts strict error
|
||||
URL.revokeObjectURL(image.src)
|
||||
})
|
||||
image.src = URL.createObjectURL(blob)
|
||||
await p
|
||||
} else {
|
||||
image = await createImageBitmap(blob)
|
||||
}
|
||||
try {
|
||||
// @ts-expect-error fixme ts strict error
|
||||
ctx.drawImage(image, 0, 0)
|
||||
canvas.toBlob(writeImage, 'image/png')
|
||||
} finally {
|
||||
// @ts-expect-error fixme ts strict error
|
||||
if (typeof image.close === 'function') {
|
||||
// @ts-expect-error fixme ts strict error
|
||||
image.close()
|
||||
}
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
throw error
|
||||
}
|
||||
} catch (error) {
|
||||
toastStore.addAlert(
|
||||
t('toastMessages.errorCopyImage', {
|
||||
// @ts-expect-error fixme ts strict error
|
||||
error: error.message ?? error
|
||||
})
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
node.prototype.getExtraMenuOptions = function (canvas, options) {
|
||||
if (this.imgs) {
|
||||
// If this node has images then we add an open in new tab item
|
||||
let img
|
||||
if (this.imageIndex != null) {
|
||||
// An image is selected so select that
|
||||
img = this.imgs[this.imageIndex]
|
||||
} else if (this.overIndex != null) {
|
||||
// No image is selected but one is hovered
|
||||
img = this.imgs[this.overIndex]
|
||||
}
|
||||
if (img) {
|
||||
options.unshift(
|
||||
{
|
||||
content: 'Open Image',
|
||||
callback: () => {
|
||||
const url = new URL(img.src)
|
||||
url.searchParams.delete('preview')
|
||||
void openFileInNewTab(url.toString())
|
||||
}
|
||||
},
|
||||
...getCopyImageOption(img),
|
||||
{
|
||||
content: 'Save Image',
|
||||
callback: () => {
|
||||
const url = new URL(img.src)
|
||||
url.searchParams.delete('preview')
|
||||
const filename = new URLSearchParams(url.search).get('filename')
|
||||
downloadFile(url.toString(), filename ?? undefined)
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
options.push({
|
||||
content: 'Bypass',
|
||||
callback: () => {
|
||||
toggleSelectedNodesMode(LGraphEventMode.BYPASS)
|
||||
canvas.setDirty(true, true)
|
||||
}
|
||||
})
|
||||
|
||||
// prevent conflict of clipspace content
|
||||
if (!ComfyApp.clipspace_return_node) {
|
||||
options.push({
|
||||
content: 'Copy (Clipspace)',
|
||||
callback: () => {
|
||||
ComfyApp.copyToClipspace(this)
|
||||
}
|
||||
})
|
||||
|
||||
if (ComfyApp.clipspace != null) {
|
||||
options.push({
|
||||
content: 'Paste (Clipspace)',
|
||||
callback: () => {
|
||||
ComfyApp.pasteFromClipspace(this)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
if (isImageNode(this)) {
|
||||
options.push({
|
||||
content: 'Open in MaskEditor | Image Canvas',
|
||||
callback: () => {
|
||||
useMaskEditor().openMaskEditor(this)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
if (this instanceof SubgraphNode) {
|
||||
options.unshift(
|
||||
{
|
||||
content: 'Edit Subgraph Widgets',
|
||||
callback: () => {
|
||||
useRightSidePanelStore().openPanel('subgraph')
|
||||
}
|
||||
},
|
||||
{
|
||||
content: 'Unpack Subgraph',
|
||||
callback: () => {
|
||||
const { unpackSubgraph } = useSubgraphOperations()
|
||||
unpackSubgraph()
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
const [x, y] = canvas.graph_mouse
|
||||
const overWidget = this.getWidgetOnPos(x, y, true)
|
||||
if (overWidget)
|
||||
options.unshift(...getExtraOptionsForWidget(this, overWidget))
|
||||
return []
|
||||
}
|
||||
}
|
||||
function updatePreviews(node: LGraphNode, callback?: () => void) {
|
||||
try {
|
||||
unsafeUpdatePreviews.call(node, callback)
|
||||
} catch (error) {
|
||||
console.error('Error drawing node background', error)
|
||||
}
|
||||
}
|
||||
function unsafeUpdatePreviews(this: LGraphNode, callback?: () => void) {
|
||||
if (this.flags.collapsed) return
|
||||
|
||||
const nodeOutputStore = useNodeOutputStore()
|
||||
const { showAnimatedPreview, removeAnimatedPreview } =
|
||||
useNodeAnimatedImage()
|
||||
const { showCanvasImagePreview, removeCanvasImagePreview } =
|
||||
useNodeCanvasImagePreview()
|
||||
|
||||
const output = nodeOutputStore.getNodeOutputs(this)
|
||||
const preview = nodeOutputStore.getNodePreviews(this)
|
||||
|
||||
const isNewOutput = output && this.images !== output.images
|
||||
const isNewPreview = preview && this.preview !== preview
|
||||
|
||||
if (isNewPreview) this.preview = preview
|
||||
if (isNewOutput) this.images = output.images
|
||||
|
||||
if (isNewOutput || isNewPreview) {
|
||||
this.animatedImages = isAnimatedOutput(output)
|
||||
|
||||
const isVideo = isVideoOutput(output) || isVideoNode(this)
|
||||
if (isVideo) {
|
||||
useNodeVideo(this, callback).showPreview()
|
||||
} else {
|
||||
useNodeImage(this, callback).showPreview()
|
||||
}
|
||||
}
|
||||
|
||||
// Nothing to do
|
||||
if (!this.imgs?.length) return
|
||||
|
||||
if (this.animatedImages) {
|
||||
removeCanvasImagePreview(this)
|
||||
showAnimatedPreview(this)
|
||||
} else {
|
||||
removeAnimatedPreview(this)
|
||||
showCanvasImagePreview(this)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds Custom drawing logic for nodes
|
||||
* e.g. Draws images and handles thumbnail navigation on nodes that output images
|
||||
* @param {*} node The node to add the draw handler
|
||||
*/
|
||||
function addDrawBackgroundHandler(node: typeof LGraphNode) {
|
||||
/**
|
||||
* @deprecated No longer needed as we use {@link useImagePreviewWidget}
|
||||
*/
|
||||
node.prototype.setSizeForImage = function (this: LGraphNode) {
|
||||
console.warn(
|
||||
'node.setSizeForImage is deprecated. Now it has no effect. Please remove the call to it.'
|
||||
)
|
||||
}
|
||||
node.prototype.onDrawBackground = function () {
|
||||
updatePreviews(this)
|
||||
|
||||
if (this instanceof SubgraphNode) {
|
||||
const parentGraph = this.graph
|
||||
for (const interiorNode of getPseudoWidgetPreviewTargets(this)) {
|
||||
updatePreviews(interiorNode, () => {
|
||||
parentGraph?.setDirtyCanvas(true)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function addNodeKeyHandler(node: typeof LGraphNode) {
|
||||
const origNodeOnKeyDown = node.prototype.onKeyDown
|
||||
|
||||
node.prototype.onKeyDown = function (e) {
|
||||
// @ts-expect-error fixme ts strict error
|
||||
if (origNodeOnKeyDown && origNodeOnKeyDown.apply(this, e) === false) {
|
||||
return false
|
||||
}
|
||||
|
||||
if (this.flags.collapsed || !this.imgs || this.imageIndex === null) {
|
||||
return
|
||||
}
|
||||
|
||||
let handled = false
|
||||
|
||||
if (e.key === 'ArrowLeft' || e.key === 'ArrowRight') {
|
||||
if (e.key === 'ArrowLeft') {
|
||||
// @ts-expect-error fixme ts strict error
|
||||
this.imageIndex -= 1
|
||||
} else if (e.key === 'ArrowRight') {
|
||||
// @ts-expect-error fixme ts strict error
|
||||
this.imageIndex += 1
|
||||
}
|
||||
// @ts-expect-error fixme ts strict error
|
||||
this.imageIndex %= this.imgs.length
|
||||
|
||||
// @ts-expect-error fixme ts strict error
|
||||
if (this.imageIndex < 0) {
|
||||
// @ts-expect-error fixme ts strict error
|
||||
this.imageIndex = this.imgs.length + this.imageIndex
|
||||
}
|
||||
handled = true
|
||||
} else if (e.key === 'Escape') {
|
||||
this.imageIndex = null
|
||||
handled = true
|
||||
}
|
||||
|
||||
if (handled === true) {
|
||||
e.preventDefault()
|
||||
e.stopImmediatePropagation()
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function addNodeOnGraph(
|
||||
nodeDef: ComfyNodeDefV1 | ComfyNodeDefV2,
|
||||
options: CreateNodeOptions = {},
|
||||
addOptions?: GraphAddOptions
|
||||
): LGraphNode | null {
|
||||
options.pos ??= getCanvasCenter()
|
||||
|
||||
if (nodeDef.name.startsWith(useSubgraphStore().typePrefix)) {
|
||||
const canvas = canvasStore.getCanvas()
|
||||
const bp = useSubgraphStore().getBlueprint(nodeDef.name)
|
||||
const items: object = {
|
||||
nodes: bp.nodes,
|
||||
subgraphs: bp.definitions?.subgraphs
|
||||
}
|
||||
const results = canvas._deserializeItems(items, {
|
||||
position: options.pos
|
||||
})
|
||||
if (!results) throw new Error('Failed to add subgraph blueprint')
|
||||
const node = results.nodes.values().next().value
|
||||
if (!node)
|
||||
throw new Error(
|
||||
'Subgraph blueprint was added, but failed to resolve a subgraph Node'
|
||||
)
|
||||
return node
|
||||
}
|
||||
|
||||
const node = LiteGraph.createNode(
|
||||
nodeDef.name,
|
||||
nodeDef.display_name,
|
||||
options
|
||||
)
|
||||
|
||||
const graph = useWorkflowStore().activeSubgraph ?? app.graph
|
||||
if (!graph || !node) return null
|
||||
|
||||
graph.add(node, addOptions)
|
||||
return node
|
||||
}
|
||||
|
||||
function getCanvasCenter(): Point {
|
||||
const dpi = Math.max(window.devicePixelRatio ?? 1, 1)
|
||||
const visibleArea = app.canvas?.ds?.visible_area
|
||||
if (!visibleArea) {
|
||||
return [0, 0]
|
||||
}
|
||||
const [x, y, w, h] = visibleArea
|
||||
return [x + w / dpi / 2, y + h / dpi / 2]
|
||||
}
|
||||
|
||||
function goToNode(nodeId: NodeId) {
|
||||
const graphNode = app.canvas.graph?.getNodeById(nodeId)
|
||||
if (!graphNode) return
|
||||
app.canvas.animateToBounds(graphNode.boundingRect)
|
||||
}
|
||||
|
||||
function ensureBounds(nodes: LGraphNode[]) {
|
||||
for (const node of nodes) {
|
||||
if (!node.boundingRect.every((i) => i === 0)) continue
|
||||
node.updateArea()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Resets the canvas view to the default
|
||||
*/
|
||||
function resetView() {
|
||||
const canvas = canvasStore.canvas
|
||||
if (!canvas) return
|
||||
|
||||
canvas.ds.scale = 1
|
||||
canvas.ds.offset = [0, 0]
|
||||
canvas.setDirty(true, true)
|
||||
}
|
||||
|
||||
function fitView() {
|
||||
const canvas = canvasStore.getCanvas()
|
||||
const nodes = canvas.graph?.nodes
|
||||
if (!nodes) return
|
||||
ensureBounds(nodes)
|
||||
const bounds = createBounds(nodes)
|
||||
if (!bounds) return
|
||||
|
||||
canvas.ds.fitToBounds(bounds)
|
||||
canvas.setDirty(true, true)
|
||||
}
|
||||
|
||||
return {
|
||||
registerNodeDef,
|
||||
registerSubgraphNodeDef,
|
||||
addNodeOnGraph,
|
||||
addNodeInput,
|
||||
getCanvasCenter,
|
||||
getExtraOptionsForWidget,
|
||||
goToNode,
|
||||
resetView,
|
||||
fitView,
|
||||
updatePreviews
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
import type {
|
||||
ExecutableLGraphNode,
|
||||
ExecutionId,
|
||||
LGraph
|
||||
} from '@/lib/litegraph/src/litegraph'
|
||||
import {
|
||||
ExecutableNodeDTO,
|
||||
LGraphEventMode
|
||||
} from '@/lib/litegraph/src/litegraph'
|
||||
import type {
|
||||
ComfyApiWorkflow,
|
||||
ComfyWorkflowJSON
|
||||
} from '@/platform/workflow/validation/schemas/workflowSchema'
|
||||
|
||||
import { ExecutableGroupNodeDTO, isGroupNode } from './executableGroupNodeDto'
|
||||
import { compressWidgetInputSlots } from './litegraphUtil'
|
||||
|
||||
/**
|
||||
* Converts the current graph workflow for sending to the API.
|
||||
* @note Node widgets are updated before serialization to prepare queueing.
|
||||
*
|
||||
* @param graph The graph to convert.
|
||||
* @param options The options for the conversion.
|
||||
* - `sortNodes`: Whether to sort the nodes by execution order.
|
||||
* @returns The workflow and node links
|
||||
*/
|
||||
export const graphToPrompt = async (
|
||||
graph: LGraph,
|
||||
options: { sortNodes?: boolean } = {}
|
||||
): Promise<{ workflow: ComfyWorkflowJSON; output: ComfyApiWorkflow }> => {
|
||||
const { sortNodes = false } = options
|
||||
|
||||
for (const node of graph.computeExecutionOrder(false)) {
|
||||
const innerNodes = node.getInnerNodes
|
||||
? node.getInnerNodes(new Map())
|
||||
: [node]
|
||||
for (const innerNode of innerNodes) {
|
||||
if (innerNode.isVirtualNode) {
|
||||
innerNode.applyToGraph?.()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const workflow = graph.serialize({ sortNodes })
|
||||
|
||||
// Remove localized_name from the workflow
|
||||
for (const node of workflow.nodes) {
|
||||
for (const slot of node.inputs ?? []) {
|
||||
delete slot.localized_name
|
||||
}
|
||||
for (const slot of node.outputs ?? []) {
|
||||
delete slot.localized_name
|
||||
}
|
||||
}
|
||||
|
||||
compressWidgetInputSlots(workflow)
|
||||
workflow.extra ??= {}
|
||||
workflow.extra.frontendVersion = __COMFYUI_FRONTEND_VERSION__
|
||||
|
||||
const nodeDtoMap = new Map<ExecutionId, ExecutableLGraphNode>()
|
||||
for (const node of graph.computeExecutionOrder(false)) {
|
||||
const dto: ExecutableLGraphNode = isGroupNode(node)
|
||||
? new ExecutableGroupNodeDTO(node, [], nodeDtoMap)
|
||||
: new ExecutableNodeDTO(node, [], nodeDtoMap)
|
||||
|
||||
nodeDtoMap.set(dto.id, dto)
|
||||
|
||||
if (
|
||||
node.mode === LGraphEventMode.NEVER ||
|
||||
node.mode === LGraphEventMode.BYPASS
|
||||
) {
|
||||
continue
|
||||
}
|
||||
|
||||
for (const innerNode of dto.getInnerNodes()) {
|
||||
nodeDtoMap.set(innerNode.id, innerNode)
|
||||
}
|
||||
}
|
||||
|
||||
const output: ComfyApiWorkflow = {}
|
||||
// Process nodes in order of execution
|
||||
for (const node of nodeDtoMap.values()) {
|
||||
// Don't serialize muted nodes
|
||||
if (
|
||||
node.isVirtualNode ||
|
||||
node.mode === LGraphEventMode.NEVER ||
|
||||
node.mode === LGraphEventMode.BYPASS
|
||||
) {
|
||||
continue
|
||||
}
|
||||
|
||||
const inputs: ComfyApiWorkflow[string]['inputs'] = {}
|
||||
const { widgets } = node
|
||||
|
||||
// Store all widget values in the API prompt.
|
||||
// Note: widget.options.serialize controls prompt inclusion (checked here).
|
||||
// widget.serialize controls workflow persistence (checked by LGraphNode).
|
||||
if (widgets) {
|
||||
for (const [i, widget] of widgets.entries()) {
|
||||
if (!widget.name || widget.options?.serialize === false) continue
|
||||
|
||||
const widgetValue = widget.serializeValue
|
||||
? await widget.serializeValue(node, i)
|
||||
: widget.value
|
||||
// By default, Array values are reserved to represent node connections.
|
||||
// We need to wrap the array as an object to avoid the misinterpretation
|
||||
// of the array as a node connection.
|
||||
// The backend automatically unwraps the object to an array during
|
||||
// execution.
|
||||
inputs[widget.name] = Array.isArray(widgetValue)
|
||||
? widget.type === 'curve'
|
||||
? { __type__: 'CURVE', __value__: widgetValue }
|
||||
: { __value__: widgetValue }
|
||||
: widgetValue
|
||||
}
|
||||
}
|
||||
|
||||
// Store all node links
|
||||
for (const [i, input] of node.inputs.entries()) {
|
||||
const resolvedInput = node.resolveInput(i)
|
||||
if (!resolvedInput) continue
|
||||
|
||||
// Resolved to an actual widget value rather than a node connection
|
||||
if (resolvedInput.widgetInfo) {
|
||||
const { value } = resolvedInput.widgetInfo
|
||||
inputs[input.name] = Array.isArray(value) ? { __value__: value } : value
|
||||
continue
|
||||
}
|
||||
|
||||
inputs[input.name] = [
|
||||
String(resolvedInput.origin_id),
|
||||
// @ts-expect-error link.origin_slot is already number.
|
||||
parseInt(resolvedInput.origin_slot)
|
||||
]
|
||||
}
|
||||
|
||||
output[String(node.id)] = {
|
||||
inputs,
|
||||
// TODO(huchenlei): Filter out all nodes that cannot be mapped to a
|
||||
// comfyClass.
|
||||
class_type: node.comfyClass!,
|
||||
// Ignored by the backend.
|
||||
_meta: {
|
||||
title: node.title
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Remove inputs connected to removed nodes
|
||||
for (const { inputs } of Object.values(output)) {
|
||||
for (const [i, input] of Object.entries(inputs)) {
|
||||
if (Array.isArray(input) && input.length === 2 && !output[input[0]]) {
|
||||
delete inputs[i]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return { workflow: workflow as ComfyWorkflowJSON, output }
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
import type { LGraph, Subgraph } from '@/lib/litegraph/src/litegraph'
|
||||
import { formatDate } from '@/utils/formatUtil'
|
||||
import { collectAllNodes } from '@/utils/graphTraversalUtil'
|
||||
|
||||
export function applyTextReplacements(
|
||||
graph: LGraph | Subgraph,
|
||||
value: string
|
||||
): string {
|
||||
const allNodes = collectAllNodes(graph)
|
||||
|
||||
return value.replace(/%([^%]+)%/g, function (match, text) {
|
||||
const split = text.split('.')
|
||||
if (split.length !== 2) {
|
||||
// Special handling for dates
|
||||
if (split[0].startsWith('date:')) {
|
||||
return formatDate(split[0].substring(5), new Date())
|
||||
}
|
||||
|
||||
if (text !== 'width' && text !== 'height') {
|
||||
// Dont warn on standard replacements
|
||||
console.warn('Invalid replacement pattern', text)
|
||||
}
|
||||
return match
|
||||
}
|
||||
|
||||
// Find node with matching S&R property name
|
||||
let nodes = allNodes.filter(
|
||||
(n) => n.properties?.['Node name for S&R'] === split[0]
|
||||
)
|
||||
// If we can't, see if there is a node with that title
|
||||
if (!nodes.length) {
|
||||
nodes = allNodes.filter((n) => n.title === split[0])
|
||||
}
|
||||
if (!nodes.length) {
|
||||
console.warn('Unable to find node', split[0])
|
||||
return match
|
||||
}
|
||||
|
||||
if (nodes.length > 1) {
|
||||
console.warn('Multiple nodes matched', split[0], 'using first match')
|
||||
}
|
||||
|
||||
const node = nodes[0]
|
||||
|
||||
const widget = node.widgets?.find((w) => w.name === split[1])
|
||||
if (!widget) {
|
||||
console.warn('Unable to find widget', split[1], 'on node', split[0], node)
|
||||
return match
|
||||
}
|
||||
|
||||
return ((widget.value ?? '') + '').replaceAll(
|
||||
// eslint-disable-next-line no-control-regex
|
||||
/[/?<>\\:*|"\x00-\x1F\x7F]/g,
|
||||
'_'
|
||||
)
|
||||
})
|
||||
}
|
||||
+108
@@ -0,0 +1,108 @@
|
||||
import type { TWidgetValue } from '@/lib/litegraph/src/litegraph'
|
||||
import type { InputSpec } from '@/schemas/nodeDef/nodeDefSchemaV2'
|
||||
import type { ComfyNodeDefImpl } from '@/stores/nodeDefStore'
|
||||
|
||||
/**
|
||||
* Gets an ordered array of InputSpec objects based on input_order.
|
||||
* This is designed to work with V2 format used by litegraphService.
|
||||
*
|
||||
* @param nodeDefImpl - The ComfyNodeDefImpl containing both V1 and V2 formats
|
||||
* @param inputs - The V2 format inputs (flat Record<string, InputSpec>)
|
||||
* @returns Array of InputSpec objects in the correct order
|
||||
*/
|
||||
export function getOrderedInputSpecs(
|
||||
nodeDefImpl: ComfyNodeDefImpl,
|
||||
inputs: Record<string, InputSpec>
|
||||
): InputSpec[] {
|
||||
const orderedInputSpecs: InputSpec[] = []
|
||||
|
||||
// If no input_order, return default Object.values order
|
||||
if (!nodeDefImpl.input_order) {
|
||||
return Object.values(inputs)
|
||||
}
|
||||
|
||||
// Process required inputs in specified order
|
||||
if (nodeDefImpl.input_order.required) {
|
||||
for (const name of nodeDefImpl.input_order.required) {
|
||||
const inputSpec = inputs[name]
|
||||
if (inputSpec && !inputSpec.isOptional) {
|
||||
orderedInputSpecs.push(inputSpec)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Process optional inputs in specified order
|
||||
if (nodeDefImpl.input_order.optional) {
|
||||
for (const name of nodeDefImpl.input_order.optional) {
|
||||
const inputSpec = inputs[name]
|
||||
if (inputSpec && inputSpec.isOptional) {
|
||||
orderedInputSpecs.push(inputSpec)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Add any remaining inputs not specified in input_order
|
||||
const processedNames = new Set(orderedInputSpecs.map((spec) => spec.name))
|
||||
for (const inputSpec of Object.values(inputs)) {
|
||||
if (!processedNames.has(inputSpec.name)) {
|
||||
orderedInputSpecs.push(inputSpec)
|
||||
}
|
||||
}
|
||||
|
||||
return orderedInputSpecs
|
||||
}
|
||||
|
||||
/**
|
||||
* Reorders widget values based on the input_order to match expected widget order.
|
||||
* This is used when widgets were created in a different order than input_order specifies.
|
||||
*
|
||||
* @param widgetValues - The current widget values array
|
||||
* @param currentWidgetOrder - The current order of widget names
|
||||
* @param inputOrder - The desired order from input_order
|
||||
* @returns Reordered widget values array
|
||||
*/
|
||||
export function sortWidgetValuesByInputOrder(
|
||||
widgetValues: TWidgetValue[],
|
||||
currentWidgetOrder: string[],
|
||||
inputOrder: string[]
|
||||
): TWidgetValue[] {
|
||||
if (!inputOrder || inputOrder.length === 0) {
|
||||
return widgetValues
|
||||
}
|
||||
|
||||
// Create a map of widget name to value
|
||||
const valueMap = new Map<string, TWidgetValue>()
|
||||
currentWidgetOrder.forEach((name, index) => {
|
||||
if (index < widgetValues.length) {
|
||||
valueMap.set(name, widgetValues[index])
|
||||
}
|
||||
})
|
||||
|
||||
// Reorder based on input_order
|
||||
const reordered: TWidgetValue[] = []
|
||||
const usedNames = new Set<string>()
|
||||
|
||||
// First, add values in the order specified by input_order
|
||||
for (const name of inputOrder) {
|
||||
if (valueMap.has(name)) {
|
||||
reordered.push(valueMap.get(name))
|
||||
usedNames.add(name)
|
||||
}
|
||||
}
|
||||
|
||||
// Then add any remaining values not in input_order
|
||||
for (const [name, value] of valueMap.entries()) {
|
||||
if (!usedNames.has(name)) {
|
||||
reordered.push(value)
|
||||
}
|
||||
}
|
||||
|
||||
// If there are extra values not in the map, append them
|
||||
if (widgetValues.length > currentWidgetOrder.length) {
|
||||
for (let i = currentWidgetOrder.length; i < widgetValues.length; i++) {
|
||||
reordered.push(widgetValues[i])
|
||||
}
|
||||
}
|
||||
|
||||
return reordered
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
{"sha":"63d1bbdb407c69370d407ce5ced6ca3f917528a8","node_id":"C_kwDOIygeJtoAKDYzZDFiYmRiNDA3YzY5MzcwZDQwN2NlNWNlZDZjYTNmOTE3NTI4YTg","commit":{"author":{"name":"comfyanonymous","email":"comfyanonymous@protonmail.com","date":"2026-03-13T00:41:48Z"},"committer":{"name":"comfyanonymous","email":"comfyanonymous@protonmail.com","date":"2026-03-13T00:44:22Z"},"message":"ComfyUI v0.17.0","tree":{"sha":"0307c85e63955f4d813304d2f62ac05d695ec696","url":"https://api.github.com/repos/Comfy-Org/ComfyUI/git/trees/0307c85e63955f4d813304d2f62ac05d695ec696"},"url":"https://api.github.com/repos/Comfy-Org/ComfyUI/git/commits/63d1bbdb407c69370d407ce5ced6ca3f917528a8","comment_count":0,"verification":{"verified":false,"reason":"unsigned","signature":null,"payload":null,"verified_at":null}},"url":"https://api.github.com/repos/Comfy-Org/ComfyUI/commits/63d1bbdb407c69370d407ce5ced6ca3f917528a8","html_url":"https://github.com/Comfy-Org/ComfyUI/commit/63d1bbdb407c69370d407ce5ced6ca3f917528a8","comments_url":"https://api.github.com/repos/Comfy-Org/ComfyUI/commits/63d1bbdb407c69370d407ce5ced6ca3f917528a8/comments","author":{"login":"comfyanonymous","id":121283862,"node_id":"U_kgDOBzqlFg","avatar_url":"https://avatars.githubusercontent.com/u/121283862?v=4","gravatar_id":"","url":"https://api.github.com/users/comfyanonymous","html_url":"https://github.com/comfyanonymous","followers_url":"https://api.github.com/users/comfyanonymous/followers","following_url":"https://api.github.com/users/comfyanonymous/following{/other_user}","gists_url":"https://api.github.com/users/comfyanonymous/gists{/gist_id}","starred_url":"https://api.github.com/users/comfyanonymous/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/comfyanonymous/subscriptions","organizations_url":"https://api.github.com/users/comfyanonymous/orgs","repos_url":"https://api.github.com/users/comfyanonymous/repos","events_url":"https://api.github.com/users/comfyanonymous/events{/privacy}","received_events_url":"https://api.github.com/users/comfyanonymous/received_events","type":"User","user_view_type":"public","site_admin":false},"committer":{"login":"comfyanonymous","id":121283862,"node_id":"U_kgDOBzqlFg","avatar_url":"https://avatars.githubusercontent.com/u/121283862?v=4","gravatar_id":"","url":"https://api.github.com/users/comfyanonymous","html_url":"https://github.com/comfyanonymous","followers_url":"https://api.github.com/users/comfyanonymous/followers","following_url":"https://api.github.com/users/comfyanonymous/following{/other_user}","gists_url":"https://api.github.com/users/comfyanonymous/gists{/gist_id}","starred_url":"https://api.github.com/users/comfyanonymous/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/comfyanonymous/subscriptions","organizations_url":"https://api.github.com/users/comfyanonymous/orgs","repos_url":"https://api.github.com/users/comfyanonymous/repos","events_url":"https://api.github.com/users/comfyanonymous/events{/privacy}","received_events_url":"https://api.github.com/users/comfyanonymous/received_events","type":"User","user_view_type":"public","site_admin":false},"parents":[{"sha":"5df1427124f6ceb70166326ee257d52076adea37","url":"https://api.github.com/repos/Comfy-Org/ComfyUI/commits/5df1427124f6ceb70166326ee257d52076adea37","html_url":"https://github.com/Comfy-Org/ComfyUI/commit/5df1427124f6ceb70166326ee257d52076adea37"}],"stats":{"total":4,"additions":2,"deletions":2},"files":[{"sha":"701f4d66a042949e96d2a61f8b36b800eb4f1080","filename":"comfyui_version.py","status":"modified","additions":1,"deletions":1,"changes":2,"blob_url":"https://github.com/Comfy-Org/ComfyUI/blob/63d1bbdb407c69370d407ce5ced6ca3f917528a8/comfyui_version.py","raw_url":"https://github.com/Comfy-Org/ComfyUI/raw/63d1bbdb407c69370d407ce5ced6ca3f917528a8/comfyui_version.py","contents_url":"https://api.github.com/repos/Comfy-Org/ComfyUI/contents/comfyui_version.py?ref=63d1bbdb407c69370d407ce5ced6ca3f917528a8","patch":"@@ -1,3 +1,3 @@\n # This file is automatically generated by the build process when version is\n # updated in pyproject.toml.\n-__version__ = \"0.16.4\"\n+__version__ = \"0.17.0\""},{"sha":"e2ca79be7882c7279069f20842e9e67fee44f4bf","filename":"pyproject.toml","status":"modified","additions":1,"deletions":1,"changes":2,"blob_url":"https://github.com/Comfy-Org/ComfyUI/blob/63d1bbdb407c69370d407ce5ced6ca3f917528a8/pyproject.toml","raw_url":"https://github.com/Comfy-Org/ComfyUI/raw/63d1bbdb407c69370d407ce5ced6ca3f917528a8/pyproject.toml","contents_url":"https://api.github.com/repos/Comfy-Org/ComfyUI/contents/pyproject.toml?ref=63d1bbdb407c69370d407ce5ced6ca3f917528a8","patch":"@@ -1,6 +1,6 @@\n [project]\n name = \"ComfyUI\"\n-version = \"0.16.4\"\n+version = \"0.17.0\"\n readme = \"README.md\"\n license = { file = \"LICENSE\" }\n requires-python = \">=3.10\""}]}
|
||||
@@ -0,0 +1 @@
|
||||
{"ref":"refs/tags/v0.17.0","node_id":"REF_kwDOIygeJrFyZWZzL3RhZ3MvdjAuMTcuMA","url":"https://api.github.com/repos/Comfy-Org/ComfyUI/git/refs/tags/v0.17.0","object":{"sha":"63d1bbdb407c69370d407ce5ced6ca3f917528a8","type":"commit","url":"https://api.github.com/repos/Comfy-Org/ComfyUI/git/commits/63d1bbdb407c69370d407ce5ced6ca3f917528a8"}}
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
|
||||
{"ref":"refs/tags/v1.41.20","node_id":"REF_kwDOMIrOxrJyZWZzL3RhZ3MvdjEuNDEuMjA","url":"https://api.github.com/repos/Comfy-Org/ComfyUI_frontend/git/refs/tags/v1.41.20","object":{"sha":"f2254852b2a575b30cc1cde46742a89afbfac252","type":"commit","url":"https://api.github.com/repos/Comfy-Org/ComfyUI_frontend/git/commits/f2254852b2a575b30cc1cde46742a89afbfac252"}}
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
|
||||
{"frontend": "f2254852b2a575b30cc1cde46742a89afbfac252", "core": "63d1bbdb407c69370d407ce5ced6ca3f917528a8"}
|
||||
@@ -0,0 +1,220 @@
|
||||
{
|
||||
"number": 25,
|
||||
"state": "open",
|
||||
"merged": false,
|
||||
"head": {
|
||||
"label": "agent/agent/a64a969a6a44",
|
||||
"ref": "agent/agent/a64a969a6a44",
|
||||
"sha": "0609341afaab955755b2f17d64e449727f65784c",
|
||||
"repo_id": 41,
|
||||
"repo": {
|
||||
"id": 41,
|
||||
"owner": {
|
||||
"id": 1,
|
||||
"login": "leefer",
|
||||
"login_name": "",
|
||||
"source_id": 0,
|
||||
"full_name": "\u767d\u6816\u77e5",
|
||||
"email": "2298888111@qq.com",
|
||||
"avatar_url": "http://gitea.xbay.cc/avatars/91b54124de25997159e246521e39a411c269d223991e40f108233dd43810b64c",
|
||||
"html_url": "http://gitea.xbay.cc/leefer",
|
||||
"language": "",
|
||||
"is_admin": false,
|
||||
"last_login": "0001-01-01T00:00:00Z",
|
||||
"created": "2026-07-21T22:34:43+08:00",
|
||||
"restricted": false,
|
||||
"active": false,
|
||||
"prohibit_login": false,
|
||||
"location": "",
|
||||
"website": "",
|
||||
"description": "",
|
||||
"visibility": "public",
|
||||
"followers_count": 0,
|
||||
"following_count": 0,
|
||||
"starred_repos_count": 1,
|
||||
"username": "leefer"
|
||||
},
|
||||
"name": "aigc-home",
|
||||
"full_name": "leefer/aigc-home",
|
||||
"description": "AIGC\u5de5\u4f5c\u53f0",
|
||||
"empty": false,
|
||||
"private": false,
|
||||
"fork": false,
|
||||
"template": false,
|
||||
"mirror": false,
|
||||
"size": 39577,
|
||||
"language": "",
|
||||
"languages_url": "https://gitea.xbay.cc/api/v1/repos/leefer/aigc-home/languages",
|
||||
"html_url": "http://gitea.xbay.cc/leefer/aigc-home",
|
||||
"url": "https://gitea.xbay.cc/api/v1/repos/leefer/aigc-home",
|
||||
"link": "",
|
||||
"ssh_url": "ssh://git@192.168.200.36:222/leefer/aigc-home.git",
|
||||
"clone_url": "http://gitea.xbay.cc/leefer/aigc-home.git",
|
||||
"original_url": "",
|
||||
"website": "",
|
||||
"stars_count": 0,
|
||||
"forks_count": 0,
|
||||
"watchers_count": 1,
|
||||
"branch_count": 84,
|
||||
"open_issues_count": 0,
|
||||
"open_pr_counter": 11,
|
||||
"release_counter": 0,
|
||||
"default_branch": "main",
|
||||
"archived": false,
|
||||
"created_at": "2026-09-27T15:54:10+08:00",
|
||||
"updated_at": "2026-10-30T05:50:17+08:00",
|
||||
"archived_at": "1970-01-01T08:00:00+08:00",
|
||||
"permissions": {
|
||||
"admin": false,
|
||||
"push": false,
|
||||
"pull": true
|
||||
},
|
||||
"has_code": true,
|
||||
"has_issues": true,
|
||||
"internal_tracker": {
|
||||
"enable_time_tracker": true,
|
||||
"allow_only_contributors_to_track_time": true,
|
||||
"enable_issue_dependencies": true
|
||||
},
|
||||
"has_wiki": true,
|
||||
"has_pull_requests": true,
|
||||
"has_projects": true,
|
||||
"projects_mode": "all",
|
||||
"has_releases": true,
|
||||
"has_packages": true,
|
||||
"has_actions": true,
|
||||
"ignore_whitespace_conflicts": false,
|
||||
"allow_merge_commits": true,
|
||||
"allow_rebase": true,
|
||||
"allow_rebase_explicit": true,
|
||||
"allow_squash_merge": true,
|
||||
"allow_fast_forward_only_merge": true,
|
||||
"allow_merge_update": true,
|
||||
"allow_rebase_update": true,
|
||||
"allow_manual_merge": false,
|
||||
"autodetect_manual_merge": false,
|
||||
"default_delete_branch_after_merge": false,
|
||||
"default_merge_style": "merge",
|
||||
"default_update_style": "merge",
|
||||
"default_allow_maintainer_edit": true,
|
||||
"avatar_url": "",
|
||||
"internal": false,
|
||||
"mirror_interval": "",
|
||||
"object_format_name": "sha1",
|
||||
"mirror_updated": "0001-01-01T00:00:00Z",
|
||||
"mirror_last_sync_at": "0001-01-01T00:00:00Z",
|
||||
"topics": [],
|
||||
"licenses": [
|
||||
"MIT"
|
||||
]
|
||||
}
|
||||
},
|
||||
"base": {
|
||||
"label": "main",
|
||||
"ref": "main",
|
||||
"sha": "1fc8bdb8bb2a88ccace6f21a507fd77bcf22f532",
|
||||
"repo_id": 41,
|
||||
"repo": {
|
||||
"id": 41,
|
||||
"owner": {
|
||||
"id": 1,
|
||||
"login": "leefer",
|
||||
"login_name": "",
|
||||
"source_id": 0,
|
||||
"full_name": "\u767d\u6816\u77e5",
|
||||
"email": "2298888111@qq.com",
|
||||
"avatar_url": "http://gitea.xbay.cc/avatars/91b54124de25997159e246521e39a411c269d223991e40f108233dd43810b64c",
|
||||
"html_url": "http://gitea.xbay.cc/leefer",
|
||||
"language": "",
|
||||
"is_admin": false,
|
||||
"last_login": "0001-01-01T00:00:00Z",
|
||||
"created": "2026-07-21T22:34:43+08:00",
|
||||
"restricted": false,
|
||||
"active": false,
|
||||
"prohibit_login": false,
|
||||
"location": "",
|
||||
"website": "",
|
||||
"description": "",
|
||||
"visibility": "public",
|
||||
"followers_count": 0,
|
||||
"following_count": 0,
|
||||
"starred_repos_count": 1,
|
||||
"username": "leefer"
|
||||
},
|
||||
"name": "aigc-home",
|
||||
"full_name": "leefer/aigc-home",
|
||||
"description": "AIGC\u5de5\u4f5c\u53f0",
|
||||
"empty": false,
|
||||
"private": false,
|
||||
"fork": false,
|
||||
"template": false,
|
||||
"mirror": false,
|
||||
"size": 39577,
|
||||
"language": "",
|
||||
"languages_url": "https://gitea.xbay.cc/api/v1/repos/leefer/aigc-home/languages",
|
||||
"html_url": "http://gitea.xbay.cc/leefer/aigc-home",
|
||||
"url": "https://gitea.xbay.cc/api/v1/repos/leefer/aigc-home",
|
||||
"link": "",
|
||||
"ssh_url": "ssh://git@192.168.200.36:222/leefer/aigc-home.git",
|
||||
"clone_url": "http://gitea.xbay.cc/leefer/aigc-home.git",
|
||||
"original_url": "",
|
||||
"website": "",
|
||||
"stars_count": 0,
|
||||
"forks_count": 0,
|
||||
"watchers_count": 1,
|
||||
"branch_count": 84,
|
||||
"open_issues_count": 0,
|
||||
"open_pr_counter": 11,
|
||||
"release_counter": 0,
|
||||
"default_branch": "main",
|
||||
"archived": false,
|
||||
"created_at": "2026-09-27T15:54:10+08:00",
|
||||
"updated_at": "2026-10-30T05:50:17+08:00",
|
||||
"archived_at": "1970-01-01T08:00:00+08:00",
|
||||
"permissions": {
|
||||
"admin": false,
|
||||
"push": false,
|
||||
"pull": true
|
||||
},
|
||||
"has_code": true,
|
||||
"has_issues": true,
|
||||
"internal_tracker": {
|
||||
"enable_time_tracker": true,
|
||||
"allow_only_contributors_to_track_time": true,
|
||||
"enable_issue_dependencies": true
|
||||
},
|
||||
"has_wiki": true,
|
||||
"has_pull_requests": true,
|
||||
"has_projects": true,
|
||||
"projects_mode": "all",
|
||||
"has_releases": true,
|
||||
"has_packages": true,
|
||||
"has_actions": true,
|
||||
"ignore_whitespace_conflicts": false,
|
||||
"allow_merge_commits": true,
|
||||
"allow_rebase": true,
|
||||
"allow_rebase_explicit": true,
|
||||
"allow_squash_merge": true,
|
||||
"allow_fast_forward_only_merge": true,
|
||||
"allow_merge_update": true,
|
||||
"allow_rebase_update": true,
|
||||
"allow_manual_merge": false,
|
||||
"autodetect_manual_merge": false,
|
||||
"default_delete_branch_after_merge": false,
|
||||
"default_merge_style": "merge",
|
||||
"default_update_style": "merge",
|
||||
"default_allow_maintainer_edit": true,
|
||||
"avatar_url": "",
|
||||
"internal": false,
|
||||
"mirror_interval": "",
|
||||
"object_format_name": "sha1",
|
||||
"mirror_updated": "0001-01-01T00:00:00Z",
|
||||
"mirror_last_sync_at": "0001-01-01T00:00:00Z",
|
||||
"topics": [],
|
||||
"licenses": [
|
||||
"MIT"
|
||||
]
|
||||
}
|
||||
},
|
||||
"html_url": "http://gitea.xbay.cc/leefer/aigc-home/pulls/25"
|
||||
}
|
||||
@@ -0,0 +1,854 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"authority": "public_reference_only_not_object_info",
|
||||
"sources": [
|
||||
{
|
||||
"id": "ComfyUI_frontend:LICENSE",
|
||||
"repository": "https://github.com/Comfy-Org/ComfyUI_frontend",
|
||||
"commit": "f2254852b2a575b30cc1cde46742a89afbfac252",
|
||||
"tag": "v1.41.20",
|
||||
"file": "LICENSE",
|
||||
"lines": [
|
||||
[
|
||||
1,
|
||||
674
|
||||
]
|
||||
],
|
||||
"raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/f2254852b2a575b30cc1cde46742a89afbfac252/LICENSE",
|
||||
"url": "https://github.com/Comfy-Org/ComfyUI_frontend/blob/f2254852b2a575b30cc1cde46742a89afbfac252/LICENSE",
|
||||
"sha256": "3972dc9744f6499f0f9b2dbf76696f2ae7ad8af9b23dde66d6af86c9dfb36986",
|
||||
"retrieved_at": "2026-10-29T22:07:09.058456+00:00",
|
||||
"local_file": "ComfyUI_frontend__LICENSE",
|
||||
"target_version_match": "unknown"
|
||||
},
|
||||
{
|
||||
"id": "ComfyUI_frontend:src/scripts/widgets.ts",
|
||||
"repository": "https://github.com/Comfy-Org/ComfyUI_frontend",
|
||||
"commit": "f2254852b2a575b30cc1cde46742a89afbfac252",
|
||||
"tag": "v1.41.20",
|
||||
"file": "src/scripts/widgets.ts",
|
||||
"lines": [
|
||||
[
|
||||
1,
|
||||
320
|
||||
]
|
||||
],
|
||||
"raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/f2254852b2a575b30cc1cde46742a89afbfac252/src/scripts/widgets.ts",
|
||||
"url": "https://github.com/Comfy-Org/ComfyUI_frontend/blob/f2254852b2a575b30cc1cde46742a89afbfac252/src/scripts/widgets.ts",
|
||||
"sha256": "43e1551ebcf9753e8a3ee47afc0b647eacbecebd2303bab7f155dd3f311c820d",
|
||||
"retrieved_at": "2026-10-29T22:07:09.463692+00:00",
|
||||
"local_file": "ComfyUI_frontend__src__scripts__widgets.ts",
|
||||
"target_version_match": "unknown"
|
||||
},
|
||||
{
|
||||
"id": "ComfyUI_frontend:src/services/litegraphService.ts",
|
||||
"repository": "https://github.com/Comfy-Org/ComfyUI_frontend",
|
||||
"commit": "f2254852b2a575b30cc1cde46742a89afbfac252",
|
||||
"tag": "v1.41.20",
|
||||
"file": "src/services/litegraphService.ts",
|
||||
"lines": [
|
||||
[
|
||||
1,
|
||||
985
|
||||
]
|
||||
],
|
||||
"raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/f2254852b2a575b30cc1cde46742a89afbfac252/src/services/litegraphService.ts",
|
||||
"url": "https://github.com/Comfy-Org/ComfyUI_frontend/blob/f2254852b2a575b30cc1cde46742a89afbfac252/src/services/litegraphService.ts",
|
||||
"sha256": "67bac0f8cd590a5674a6633f256e97d03d561444e6e6c0a5e66fa7380de7592a",
|
||||
"retrieved_at": "2026-10-29T22:07:09.906613+00:00",
|
||||
"local_file": "ComfyUI_frontend__src__services__litegraphService.ts",
|
||||
"target_version_match": "unknown",
|
||||
"rule_locations": {
|
||||
"dynamic_add_input": [
|
||||
217,
|
||||
220
|
||||
],
|
||||
"widgets_and_named_socket_construction": [
|
||||
226,
|
||||
277
|
||||
],
|
||||
"ordered_inputs": [
|
||||
281,
|
||||
289
|
||||
],
|
||||
"constructor_and_persistence": [
|
||||
480,
|
||||
495
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "ComfyUI_frontend:src/lib/litegraph/src/LGraphNode.ts",
|
||||
"repository": "https://github.com/Comfy-Org/ComfyUI_frontend",
|
||||
"commit": "f2254852b2a575b30cc1cde46742a89afbfac252",
|
||||
"tag": "v1.41.20",
|
||||
"file": "src/lib/litegraph/src/LGraphNode.ts",
|
||||
"lines": [
|
||||
[
|
||||
1,
|
||||
4282
|
||||
]
|
||||
],
|
||||
"raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/f2254852b2a575b30cc1cde46742a89afbfac252/src/lib/litegraph/src/LGraphNode.ts",
|
||||
"url": "https://github.com/Comfy-Org/ComfyUI_frontend/blob/f2254852b2a575b30cc1cde46742a89afbfac252/src/lib/litegraph/src/LGraphNode.ts",
|
||||
"sha256": "7ed927f0a8c0fa3c5e13fa457269c41bf86a693bf26dbbb4c1cf76a86360c367",
|
||||
"retrieved_at": "2026-10-29T22:07:10.389982+00:00",
|
||||
"local_file": "ComfyUI_frontend__src__lib__litegraph__src__LGraphNode.ts",
|
||||
"target_version_match": "unknown",
|
||||
"rule_locations": {
|
||||
"saved_restore_live_iterator": [
|
||||
894,
|
||||
918
|
||||
],
|
||||
"persist_widget_values": [
|
||||
958,
|
||||
977
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "ComfyUI_frontend:src/utils/executionUtil.ts",
|
||||
"repository": "https://github.com/Comfy-Org/ComfyUI_frontend",
|
||||
"commit": "f2254852b2a575b30cc1cde46742a89afbfac252",
|
||||
"tag": "v1.41.20",
|
||||
"file": "src/utils/executionUtil.ts",
|
||||
"lines": [
|
||||
[
|
||||
1,
|
||||
159
|
||||
]
|
||||
],
|
||||
"raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/f2254852b2a575b30cc1cde46742a89afbfac252/src/utils/executionUtil.ts",
|
||||
"url": "https://github.com/Comfy-Org/ComfyUI_frontend/blob/f2254852b2a575b30cc1cde46742a89afbfac252/src/utils/executionUtil.ts",
|
||||
"sha256": "67bbc3d626a5092f0093e45d2df2308a2bf5cd69a85c26f81cb6fa143fda2d33",
|
||||
"retrieved_at": "2026-10-29T22:07:10.782754+00:00",
|
||||
"local_file": "ComfyUI_frontend__src__utils__executionUtil.ts",
|
||||
"target_version_match": "unknown",
|
||||
"rule_locations": {
|
||||
"exclude_virtual_nodes": [
|
||||
80,
|
||||
91
|
||||
],
|
||||
"serialize_widgets_before_links": [
|
||||
94,
|
||||
135
|
||||
],
|
||||
"metadata": [
|
||||
136,
|
||||
145
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "ComfyUI_frontend:src/extensions/core/uploadImage.ts",
|
||||
"repository": "https://github.com/Comfy-Org/ComfyUI_frontend",
|
||||
"commit": "f2254852b2a575b30cc1cde46742a89afbfac252",
|
||||
"tag": "v1.41.20",
|
||||
"file": "src/extensions/core/uploadImage.ts",
|
||||
"lines": [
|
||||
[
|
||||
1,
|
||||
40
|
||||
]
|
||||
],
|
||||
"raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/f2254852b2a575b30cc1cde46742a89afbfac252/src/extensions/core/uploadImage.ts",
|
||||
"url": "https://github.com/Comfy-Org/ComfyUI_frontend/blob/f2254852b2a575b30cc1cde46742a89afbfac252/src/extensions/core/uploadImage.ts",
|
||||
"sha256": "48d062c2ee95bd77c537c539e6c8f8bc03bd71dcec94c5b82487c014ea3e9c06",
|
||||
"retrieved_at": "2026-10-29T22:07:11.167790+00:00",
|
||||
"local_file": "ComfyUI_frontend__src__extensions__core__uploadImage.ts",
|
||||
"target_version_match": "unknown"
|
||||
},
|
||||
{
|
||||
"id": "ComfyUI_frontend:src/extensions/core/dynamicPrompts.ts",
|
||||
"repository": "https://github.com/Comfy-Org/ComfyUI_frontend",
|
||||
"commit": "f2254852b2a575b30cc1cde46742a89afbfac252",
|
||||
"tag": "v1.41.20",
|
||||
"file": "src/extensions/core/dynamicPrompts.ts",
|
||||
"lines": [
|
||||
[
|
||||
1,
|
||||
31
|
||||
]
|
||||
],
|
||||
"raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/f2254852b2a575b30cc1cde46742a89afbfac252/src/extensions/core/dynamicPrompts.ts",
|
||||
"url": "https://github.com/Comfy-Org/ComfyUI_frontend/blob/f2254852b2a575b30cc1cde46742a89afbfac252/src/extensions/core/dynamicPrompts.ts",
|
||||
"sha256": "31004dc7ba9b8ea5c8caa92ab3a15a0e63af8a822f57cb487079aad84d06f4bd",
|
||||
"retrieved_at": "2026-10-29T22:07:11.569562+00:00",
|
||||
"local_file": "ComfyUI_frontend__src__extensions__core__dynamicPrompts.ts",
|
||||
"target_version_match": "unknown"
|
||||
},
|
||||
{
|
||||
"id": "ComfyUI_frontend:src/lib/litegraph/src/subgraph/ExecutableNodeDTO.ts",
|
||||
"repository": "https://github.com/Comfy-Org/ComfyUI_frontend",
|
||||
"commit": "f2254852b2a575b30cc1cde46742a89afbfac252",
|
||||
"tag": "v1.41.20",
|
||||
"file": "src/lib/litegraph/src/subgraph/ExecutableNodeDTO.ts",
|
||||
"lines": [
|
||||
[
|
||||
1,
|
||||
411
|
||||
]
|
||||
],
|
||||
"raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/f2254852b2a575b30cc1cde46742a89afbfac252/src/lib/litegraph/src/subgraph/ExecutableNodeDTO.ts",
|
||||
"url": "https://github.com/Comfy-Org/ComfyUI_frontend/blob/f2254852b2a575b30cc1cde46742a89afbfac252/src/lib/litegraph/src/subgraph/ExecutableNodeDTO.ts",
|
||||
"sha256": "b8dd5ebf3ccec49bb74d927fee1acf7c38bad482c33779fd6a2ba84018b1d989",
|
||||
"retrieved_at": "2026-10-29T22:07:11.959360+00:00",
|
||||
"local_file": "ComfyUI_frontend__src__lib__litegraph__src__subgraph__ExecutableNodeDTO.ts",
|
||||
"target_version_match": "unknown",
|
||||
"rule_locations": {
|
||||
"root_link_resolution": [
|
||||
219,
|
||||
241
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "ComfyUI:LICENSE",
|
||||
"repository": "https://github.com/Comfy-Org/ComfyUI",
|
||||
"commit": "63d1bbdb407c69370d407ce5ced6ca3f917528a8",
|
||||
"tag": "v0.17.0",
|
||||
"file": "LICENSE",
|
||||
"lines": [
|
||||
[
|
||||
1,
|
||||
674
|
||||
]
|
||||
],
|
||||
"raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI/63d1bbdb407c69370d407ce5ced6ca3f917528a8/LICENSE",
|
||||
"url": "https://github.com/Comfy-Org/ComfyUI/blob/63d1bbdb407c69370d407ce5ced6ca3f917528a8/LICENSE",
|
||||
"sha256": "3972dc9744f6499f0f9b2dbf76696f2ae7ad8af9b23dde66d6af86c9dfb36986",
|
||||
"retrieved_at": "2026-10-29T22:07:12.390880+00:00",
|
||||
"local_file": "ComfyUI__LICENSE",
|
||||
"target_version_match": "unknown"
|
||||
},
|
||||
{
|
||||
"id": "ComfyUI:nodes.py",
|
||||
"repository": "https://github.com/Comfy-Org/ComfyUI",
|
||||
"commit": "63d1bbdb407c69370d407ce5ced6ca3f917528a8",
|
||||
"tag": "v0.17.0",
|
||||
"file": "nodes.py",
|
||||
"lines": [
|
||||
[
|
||||
1,
|
||||
2519
|
||||
]
|
||||
],
|
||||
"raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI/63d1bbdb407c69370d407ce5ced6ca3f917528a8/nodes.py",
|
||||
"url": "https://github.com/Comfy-Org/ComfyUI/blob/63d1bbdb407c69370d407ce5ced6ca3f917528a8/nodes.py",
|
||||
"sha256": "dae541f8bec1483d923d75d7c74bdd166a03d361e913adb5b766f3da42965166",
|
||||
"retrieved_at": "2026-10-29T22:07:12.841541+00:00",
|
||||
"local_file": "ComfyUI__nodes.py",
|
||||
"target_version_match": "unknown",
|
||||
"rule_locations": {
|
||||
"resolution_limit": [
|
||||
57,
|
||||
57
|
||||
],
|
||||
"save_image_schema": [
|
||||
1629,
|
||||
1653
|
||||
],
|
||||
"load_image_schema": [
|
||||
1702,
|
||||
1717
|
||||
],
|
||||
"core_registration": [
|
||||
2051,
|
||||
2053
|
||||
],
|
||||
"postprocessing_registration": [
|
||||
2361,
|
||||
2361
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "ComfyUI:comfy_extras/nodes_images.py",
|
||||
"repository": "https://github.com/Comfy-Org/ComfyUI",
|
||||
"commit": "63d1bbdb407c69370d407ce5ced6ca3f917528a8",
|
||||
"tag": "v0.17.0",
|
||||
"file": "comfy_extras/nodes_images.py",
|
||||
"lines": [
|
||||
[
|
||||
1,
|
||||
849
|
||||
]
|
||||
],
|
||||
"raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI/63d1bbdb407c69370d407ce5ced6ca3f917528a8/comfy_extras/nodes_images.py",
|
||||
"url": "https://github.com/Comfy-Org/ComfyUI/blob/63d1bbdb407c69370d407ce5ced6ca3f917528a8/comfy_extras/nodes_images.py",
|
||||
"sha256": "40f22183dcbc9f871030145ca33d52f3dd9d8f64b21ceb071c2fdf6cd49ff501",
|
||||
"retrieved_at": "2026-10-29T22:07:13.278745+00:00",
|
||||
"local_file": "ComfyUI__comfy_extras__nodes_images.py",
|
||||
"target_version_match": "unknown",
|
||||
"rule_locations": {
|
||||
"stitch_schema": [
|
||||
253,
|
||||
275
|
||||
],
|
||||
"stitch_registration": [
|
||||
832,
|
||||
849
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "ComfyUI:comfy_api/latest/_io.py",
|
||||
"repository": "https://github.com/Comfy-Org/ComfyUI",
|
||||
"commit": "63d1bbdb407c69370d407ce5ced6ca3f917528a8",
|
||||
"tag": "v0.17.0",
|
||||
"file": "comfy_api/latest/_io.py",
|
||||
"lines": [
|
||||
[
|
||||
1,
|
||||
2244
|
||||
]
|
||||
],
|
||||
"raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI/63d1bbdb407c69370d407ce5ced6ca3f917528a8/comfy_api/latest/_io.py",
|
||||
"url": "https://github.com/Comfy-Org/ComfyUI/blob/63d1bbdb407c69370d407ce5ced6ca3f917528a8/comfy_api/latest/_io.py",
|
||||
"sha256": "7a2af992330d562fad6ef6d7acb15a41e7f934b11e45c6ade01636b6cea275e9",
|
||||
"retrieved_at": "2026-10-29T22:07:13.823589+00:00",
|
||||
"local_file": "ComfyUI__comfy_api__latest___io.py",
|
||||
"target_version_match": "unknown",
|
||||
"rule_locations": {
|
||||
"dynamic_combo_schema_and_expansion": [
|
||||
1090,
|
||||
1140
|
||||
],
|
||||
"schema_input_order": [
|
||||
1565,
|
||||
1578
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "ComfyUI_frontend:src/core/graph/widgets/dynamicWidgets.ts",
|
||||
"repository": "https://github.com/Comfy-Org/ComfyUI_frontend",
|
||||
"commit": "f2254852b2a575b30cc1cde46742a89afbfac252",
|
||||
"tag": "v1.41.20",
|
||||
"file": "src/core/graph/widgets/dynamicWidgets.ts",
|
||||
"lines": [
|
||||
[
|
||||
1,
|
||||
601
|
||||
]
|
||||
],
|
||||
"raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/f2254852b2a575b30cc1cde46742a89afbfac252/src/core/graph/widgets/dynamicWidgets.ts",
|
||||
"url": "https://github.com/Comfy-Org/ComfyUI_frontend/blob/f2254852b2a575b30cc1cde46742a89afbfac252/src/core/graph/widgets/dynamicWidgets.ts",
|
||||
"sha256": "c51c658cc04b1017390c63cd4fd44c16646c28244f11154f8f3926cf9104d51f",
|
||||
"retrieved_at": "2026-10-29T22:07:26.964993+00:00",
|
||||
"local_file": "ComfyUI_frontend__src__core__graph__widgets__dynamicWidgets.ts",
|
||||
"target_version_match": "unknown",
|
||||
"rule_locations": {
|
||||
"dynamic_combo_validation_and_selector": [
|
||||
74,
|
||||
102
|
||||
],
|
||||
"remove_old_group_and_build_qualified_inputs": [
|
||||
103,
|
||||
140
|
||||
],
|
||||
"insert_children_after_selector_and_preserve_links": [
|
||||
142,
|
||||
187
|
||||
],
|
||||
"live_setter_runs_during_configure": [
|
||||
194,
|
||||
212
|
||||
],
|
||||
"matchtype_concrete_propagation": [
|
||||
287,
|
||||
390
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "ComfyUI_frontend:src/core/graph/widgets/dynamicWidgets.test.ts",
|
||||
"repository": "https://github.com/Comfy-Org/ComfyUI_frontend",
|
||||
"commit": "f2254852b2a575b30cc1cde46742a89afbfac252",
|
||||
"tag": "v1.41.20",
|
||||
"file": "src/core/graph/widgets/dynamicWidgets.test.ts",
|
||||
"lines": [
|
||||
[
|
||||
1,
|
||||
206
|
||||
]
|
||||
],
|
||||
"raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/f2254852b2a575b30cc1cde46742a89afbfac252/src/core/graph/widgets/dynamicWidgets.test.ts",
|
||||
"url": "https://github.com/Comfy-Org/ComfyUI_frontend/blob/f2254852b2a575b30cc1cde46742a89afbfac252/src/core/graph/widgets/dynamicWidgets.test.ts",
|
||||
"sha256": "e296ae3e983f2df56c4a1e43ccefae5e8071f250bcbb70ba9b01ed938d2582fa",
|
||||
"retrieved_at": "2026-10-29T22:07:27.345318+00:00",
|
||||
"local_file": "ComfyUI_frontend__src__core__graph__widgets__dynamicWidgets.test.ts",
|
||||
"target_version_match": "unknown"
|
||||
},
|
||||
{
|
||||
"id": "ComfyUI_frontend:src/schemas/nodeDef/migration.ts",
|
||||
"repository": "https://github.com/Comfy-Org/ComfyUI_frontend",
|
||||
"commit": "f2254852b2a575b30cc1cde46742a89afbfac252",
|
||||
"tag": "v1.41.20",
|
||||
"file": "src/schemas/nodeDef/migration.ts",
|
||||
"lines": [
|
||||
[
|
||||
1,
|
||||
143
|
||||
]
|
||||
],
|
||||
"raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/f2254852b2a575b30cc1cde46742a89afbfac252/src/schemas/nodeDef/migration.ts",
|
||||
"url": "https://github.com/Comfy-Org/ComfyUI_frontend/blob/f2254852b2a575b30cc1cde46742a89afbfac252/src/schemas/nodeDef/migration.ts",
|
||||
"sha256": "ae357da184625b93c492c0b73ce9bd2f3b49d158ca19a2944c6500f924a7a533",
|
||||
"retrieved_at": "2026-10-29T22:07:27.743976+00:00",
|
||||
"local_file": "ComfyUI_frontend__src__schemas__nodeDef__migration.ts",
|
||||
"target_version_match": "unknown"
|
||||
},
|
||||
{
|
||||
"id": "ComfyUI_frontend:src/schemas/nodeDefSchema.ts",
|
||||
"repository": "https://github.com/Comfy-Org/ComfyUI_frontend",
|
||||
"commit": "f2254852b2a575b30cc1cde46742a89afbfac252",
|
||||
"tag": "v1.41.20",
|
||||
"file": "src/schemas/nodeDefSchema.ts",
|
||||
"lines": [
|
||||
[
|
||||
1,
|
||||
372
|
||||
]
|
||||
],
|
||||
"raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/f2254852b2a575b30cc1cde46742a89afbfac252/src/schemas/nodeDefSchema.ts",
|
||||
"url": "https://github.com/Comfy-Org/ComfyUI_frontend/blob/f2254852b2a575b30cc1cde46742a89afbfac252/src/schemas/nodeDefSchema.ts",
|
||||
"sha256": "670298367ae9d62fd4d285554c41aa8e3e0fe7e8794e8ef3e27b24fd4a2d9305",
|
||||
"retrieved_at": "2026-10-29T22:07:28.145277+00:00",
|
||||
"local_file": "ComfyUI_frontend__src__schemas__nodeDefSchema.ts",
|
||||
"target_version_match": "unknown"
|
||||
},
|
||||
{
|
||||
"id": "ComfyUI_frontend:src/extensions/core/widgetInputs.ts",
|
||||
"repository": "https://github.com/Comfy-Org/ComfyUI_frontend",
|
||||
"commit": "f2254852b2a575b30cc1cde46742a89afbfac252",
|
||||
"tag": "v1.41.20",
|
||||
"file": "src/extensions/core/widgetInputs.ts",
|
||||
"lines": [
|
||||
[
|
||||
1,
|
||||
661
|
||||
]
|
||||
],
|
||||
"raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/f2254852b2a575b30cc1cde46742a89afbfac252/src/extensions/core/widgetInputs.ts",
|
||||
"url": "https://github.com/Comfy-Org/ComfyUI_frontend/blob/f2254852b2a575b30cc1cde46742a89afbfac252/src/extensions/core/widgetInputs.ts",
|
||||
"sha256": "e37bdb998b863483f51d07d31ae193dc2aa1657d4c450cc3b1640af51be5caea",
|
||||
"retrieved_at": "2026-10-29T22:07:28.533528+00:00",
|
||||
"local_file": "ComfyUI_frontend__src__extensions__core__widgetInputs.ts",
|
||||
"target_version_match": "unknown"
|
||||
},
|
||||
{
|
||||
"id": "ComfyUI_frontend:src/scripts/app.ts",
|
||||
"repository": "https://github.com/Comfy-Org/ComfyUI_frontend",
|
||||
"commit": "f2254852b2a575b30cc1cde46742a89afbfac252",
|
||||
"tag": "v1.41.20",
|
||||
"file": "src/scripts/app.ts",
|
||||
"lines": [
|
||||
[
|
||||
1,
|
||||
2035
|
||||
]
|
||||
],
|
||||
"raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/f2254852b2a575b30cc1cde46742a89afbfac252/src/scripts/app.ts",
|
||||
"url": "https://github.com/Comfy-Org/ComfyUI_frontend/blob/f2254852b2a575b30cc1cde46742a89afbfac252/src/scripts/app.ts",
|
||||
"sha256": "3446354983eea9803e13d200c8c26534f1703ac445462eee8c2940623b58f6e8",
|
||||
"retrieved_at": "2026-10-29T22:07:28.950745+00:00",
|
||||
"local_file": "ComfyUI_frontend__src__scripts__app.ts",
|
||||
"target_version_match": "unknown"
|
||||
},
|
||||
{
|
||||
"id": "ComfyUI:comfy_extras/nodes_post_processing.py",
|
||||
"repository": "https://github.com/Comfy-Org/ComfyUI",
|
||||
"commit": "63d1bbdb407c69370d407ce5ced6ca3f917528a8",
|
||||
"tag": "v0.17.0",
|
||||
"file": "comfy_extras/nodes_post_processing.py",
|
||||
"lines": [
|
||||
[
|
||||
1,
|
||||
679
|
||||
]
|
||||
],
|
||||
"raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI/63d1bbdb407c69370d407ce5ced6ca3f917528a8/comfy_extras/nodes_post_processing.py",
|
||||
"url": "https://github.com/Comfy-Org/ComfyUI/blob/63d1bbdb407c69370d407ce5ced6ca3f917528a8/comfy_extras/nodes_post_processing.py",
|
||||
"sha256": "e262de1a82890723ade27ebb8b7616e26320140480f8c874f64eb38355a11249",
|
||||
"retrieved_at": "2026-10-29T22:07:29.385812+00:00",
|
||||
"local_file": "ComfyUI__comfy_extras__nodes_post_processing.py",
|
||||
"target_version_match": "unknown",
|
||||
"rule_locations": {
|
||||
"resize_enum": [
|
||||
250,
|
||||
260
|
||||
],
|
||||
"resize_schema_and_branches": [
|
||||
406,
|
||||
484
|
||||
],
|
||||
"resize_execution_dict": [
|
||||
486,
|
||||
505
|
||||
],
|
||||
"resize_registration": [
|
||||
662,
|
||||
679
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "ComfyUI:comfy_api/latest/_io.py",
|
||||
"repository": "https://github.com/Comfy-Org/ComfyUI",
|
||||
"commit": "63d1bbdb407c69370d407ce5ced6ca3f917528a8",
|
||||
"tag": "v0.17.0",
|
||||
"file": "comfy_api/latest/_io.py",
|
||||
"lines": [
|
||||
[
|
||||
1,
|
||||
2244
|
||||
]
|
||||
],
|
||||
"raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI/63d1bbdb407c69370d407ce5ced6ca3f917528a8/comfy_api/latest/_io.py",
|
||||
"url": "https://github.com/Comfy-Org/ComfyUI/blob/63d1bbdb407c69370d407ce5ced6ca3f917528a8/comfy_api/latest/_io.py",
|
||||
"sha256": "7a2af992330d562fad6ef6d7acb15a41e7f934b11e45c6ade01636b6cea275e9",
|
||||
"retrieved_at": "2026-10-29T22:07:29.594947+00:00",
|
||||
"local_file": "ComfyUI__comfy_api__latest___io.py",
|
||||
"target_version_match": "unknown",
|
||||
"rule_locations": {
|
||||
"dynamic_combo_schema_and_expansion": [
|
||||
1090,
|
||||
1140
|
||||
],
|
||||
"schema_input_order": [
|
||||
1565,
|
||||
1578
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "ComfyUI:comfy_api/latest/_io_public.py",
|
||||
"repository": "https://github.com/Comfy-Org/ComfyUI",
|
||||
"commit": "63d1bbdb407c69370d407ce5ced6ca3f917528a8",
|
||||
"tag": "v0.17.0",
|
||||
"file": "comfy_api/latest/_io_public.py",
|
||||
"lines": [
|
||||
[
|
||||
1,
|
||||
1
|
||||
]
|
||||
],
|
||||
"raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI/63d1bbdb407c69370d407ce5ced6ca3f917528a8/comfy_api/latest/_io_public.py",
|
||||
"url": "https://github.com/Comfy-Org/ComfyUI/blob/63d1bbdb407c69370d407ce5ced6ca3f917528a8/comfy_api/latest/_io_public.py",
|
||||
"sha256": "c805d754d61aba1ea72ed2d9d5c371de35be9affa5305d35426fb298fcb7c046",
|
||||
"retrieved_at": "2026-10-29T22:07:30.002180+00:00",
|
||||
"local_file": "ComfyUI__comfy_api__latest___io_public.py",
|
||||
"target_version_match": "unknown"
|
||||
},
|
||||
{
|
||||
"id": "ComfyUI_frontend:src/renderer/extensions/vueNodes/widgets/composables/useImageUploadWidget.ts",
|
||||
"repository": "https://github.com/Comfy-Org/ComfyUI_frontend",
|
||||
"commit": "f2254852b2a575b30cc1cde46742a89afbfac252",
|
||||
"tag": "v1.41.20",
|
||||
"file": "src/renderer/extensions/vueNodes/widgets/composables/useImageUploadWidget.ts",
|
||||
"lines": [
|
||||
[
|
||||
1,
|
||||
127
|
||||
]
|
||||
],
|
||||
"raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/f2254852b2a575b30cc1cde46742a89afbfac252/src/renderer/extensions/vueNodes/widgets/composables/useImageUploadWidget.ts",
|
||||
"url": "https://github.com/Comfy-Org/ComfyUI_frontend/blob/f2254852b2a575b30cc1cde46742a89afbfac252/src/renderer/extensions/vueNodes/widgets/composables/useImageUploadWidget.ts",
|
||||
"sha256": "318c8134c2499a4ee33d07bb8aff029b5d02f503b6e217f874e5dc0f5d9b69bc",
|
||||
"retrieved_at": "2026-10-29T22:08:19.384086+00:00",
|
||||
"local_file": "ComfyUI_frontend__src__renderer__extensions__vueNodes__widgets__composables__useImageUploadWidget.ts",
|
||||
"target_version_match": "unknown",
|
||||
"rule_locations": {
|
||||
"upload_ui_options": [
|
||||
91,
|
||||
103
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "ComfyUI_frontend:src/renderer/extensions/vueNodes/widgets/composables/useIntWidget.ts",
|
||||
"repository": "https://github.com/Comfy-Org/ComfyUI_frontend",
|
||||
"commit": "f2254852b2a575b30cc1cde46742a89afbfac252",
|
||||
"tag": "v1.41.20",
|
||||
"file": "src/renderer/extensions/vueNodes/widgets/composables/useIntWidget.ts",
|
||||
"lines": [
|
||||
[
|
||||
1,
|
||||
93
|
||||
]
|
||||
],
|
||||
"raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/f2254852b2a575b30cc1cde46742a89afbfac252/src/renderer/extensions/vueNodes/widgets/composables/useIntWidget.ts",
|
||||
"url": "https://github.com/Comfy-Org/ComfyUI_frontend/blob/f2254852b2a575b30cc1cde46742a89afbfac252/src/renderer/extensions/vueNodes/widgets/composables/useIntWidget.ts",
|
||||
"sha256": "8720d5a8194c9987eddbb42d0e925bcbb20e96e94f52c5f21750ba90b2113e02",
|
||||
"retrieved_at": "2026-10-29T22:08:19.852221+00:00",
|
||||
"local_file": "ComfyUI_frontend__src__renderer__extensions__vueNodes__widgets__composables__useIntWidget.ts",
|
||||
"target_version_match": "unknown",
|
||||
"rule_locations": {
|
||||
"step_invariant": [
|
||||
10,
|
||||
28
|
||||
],
|
||||
"int_constructor": [
|
||||
50,
|
||||
68
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "ComfyUI_frontend:src/renderer/extensions/vueNodes/widgets/composables/useComboWidget.ts",
|
||||
"repository": "https://github.com/Comfy-Org/ComfyUI_frontend",
|
||||
"commit": "f2254852b2a575b30cc1cde46742a89afbfac252",
|
||||
"tag": "v1.41.20",
|
||||
"file": "src/renderer/extensions/vueNodes/widgets/composables/useComboWidget.ts",
|
||||
"lines": [
|
||||
[
|
||||
1,
|
||||
259
|
||||
]
|
||||
],
|
||||
"raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/f2254852b2a575b30cc1cde46742a89afbfac252/src/renderer/extensions/vueNodes/widgets/composables/useComboWidget.ts",
|
||||
"url": "https://github.com/Comfy-Org/ComfyUI_frontend/blob/f2254852b2a575b30cc1cde46742a89afbfac252/src/renderer/extensions/vueNodes/widgets/composables/useComboWidget.ts",
|
||||
"sha256": "c10f95e716c00592d59b73baec92a71eedbc3ff90d18bd55e0c308308369632d",
|
||||
"retrieved_at": "2026-10-29T22:08:20.241890+00:00",
|
||||
"local_file": "ComfyUI_frontend__src__renderer__extensions__vueNodes__widgets__composables__useComboWidget.ts",
|
||||
"target_version_match": "unknown"
|
||||
},
|
||||
{
|
||||
"id": "ComfyUI_frontend:src/renderer/extensions/vueNodes/widgets/composables/useBooleanWidget.ts",
|
||||
"repository": "https://github.com/Comfy-Org/ComfyUI_frontend",
|
||||
"commit": "f2254852b2a575b30cc1cde46742a89afbfac252",
|
||||
"tag": "v1.41.20",
|
||||
"file": "src/renderer/extensions/vueNodes/widgets/composables/useBooleanWidget.ts",
|
||||
"lines": [
|
||||
[
|
||||
1,
|
||||
31
|
||||
]
|
||||
],
|
||||
"raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/f2254852b2a575b30cc1cde46742a89afbfac252/src/renderer/extensions/vueNodes/widgets/composables/useBooleanWidget.ts",
|
||||
"url": "https://github.com/Comfy-Org/ComfyUI_frontend/blob/f2254852b2a575b30cc1cde46742a89afbfac252/src/renderer/extensions/vueNodes/widgets/composables/useBooleanWidget.ts",
|
||||
"sha256": "36f477f75561e0c7bfc2c6757906724f8ff2c8660ace26759f3f07493877fece",
|
||||
"retrieved_at": "2026-10-29T22:08:20.650172+00:00",
|
||||
"local_file": "ComfyUI_frontend__src__renderer__extensions__vueNodes__widgets__composables__useBooleanWidget.ts",
|
||||
"target_version_match": "unknown"
|
||||
},
|
||||
{
|
||||
"id": "ComfyUI_frontend:src/renderer/extensions/vueNodes/widgets/composables/useStringWidget.ts",
|
||||
"repository": "https://github.com/Comfy-Org/ComfyUI_frontend",
|
||||
"commit": "f2254852b2a575b30cc1cde46742a89afbfac252",
|
||||
"tag": "v1.41.20",
|
||||
"file": "src/renderer/extensions/vueNodes/widgets/composables/useStringWidget.ts",
|
||||
"lines": [
|
||||
[
|
||||
1,
|
||||
153
|
||||
]
|
||||
],
|
||||
"raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/f2254852b2a575b30cc1cde46742a89afbfac252/src/renderer/extensions/vueNodes/widgets/composables/useStringWidget.ts",
|
||||
"url": "https://github.com/Comfy-Org/ComfyUI_frontend/blob/f2254852b2a575b30cc1cde46742a89afbfac252/src/renderer/extensions/vueNodes/widgets/composables/useStringWidget.ts",
|
||||
"sha256": "d6c7d090149d2fe5181128b8b38942f5ed9a7ec2f752ff5fe2ef7b1b4505e00a",
|
||||
"retrieved_at": "2026-10-29T22:08:21.067465+00:00",
|
||||
"local_file": "ComfyUI_frontend__src__renderer__extensions__vueNodes__widgets__composables__useStringWidget.ts",
|
||||
"target_version_match": "unknown"
|
||||
},
|
||||
{
|
||||
"id": "ComfyUI_frontend:src/workbench/utils/nodeDefOrderingUtil.ts",
|
||||
"repository": "https://github.com/Comfy-Org/ComfyUI_frontend",
|
||||
"commit": "f2254852b2a575b30cc1cde46742a89afbfac252",
|
||||
"tag": "v1.41.20",
|
||||
"file": "src/workbench/utils/nodeDefOrderingUtil.ts",
|
||||
"lines": [
|
||||
[
|
||||
1,
|
||||
108
|
||||
]
|
||||
],
|
||||
"raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/f2254852b2a575b30cc1cde46742a89afbfac252/src/workbench/utils/nodeDefOrderingUtil.ts",
|
||||
"url": "https://github.com/Comfy-Org/ComfyUI_frontend/blob/f2254852b2a575b30cc1cde46742a89afbfac252/src/workbench/utils/nodeDefOrderingUtil.ts",
|
||||
"sha256": "27e98379fef3cb7158b2968d1b920ff16db662e4e0c5252ed62c7c7edc6f2227",
|
||||
"retrieved_at": "2026-10-29T22:08:21.461286+00:00",
|
||||
"local_file": "ComfyUI_frontend__src__workbench__utils__nodeDefOrderingUtil.ts",
|
||||
"target_version_match": "unknown",
|
||||
"rule_locations": {
|
||||
"required_optional_order": [
|
||||
13,
|
||||
55
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "ComfyUI_frontend:src/extensions/core/noteNode.ts",
|
||||
"repository": "https://github.com/Comfy-Org/ComfyUI_frontend",
|
||||
"commit": "f2254852b2a575b30cc1cde46742a89afbfac252",
|
||||
"tag": "v1.41.20",
|
||||
"file": "src/extensions/core/noteNode.ts",
|
||||
"lines": [
|
||||
[
|
||||
1,
|
||||
84
|
||||
]
|
||||
],
|
||||
"raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/f2254852b2a575b30cc1cde46742a89afbfac252/src/extensions/core/noteNode.ts",
|
||||
"url": "https://github.com/Comfy-Org/ComfyUI_frontend/blob/f2254852b2a575b30cc1cde46742a89afbfac252/src/extensions/core/noteNode.ts",
|
||||
"sha256": "1014f719e3d67d9c5183a5e8631d4c2d6581dfe67083f32eb23774ec3074bef2",
|
||||
"retrieved_at": "2026-10-29T22:08:21.846561+00:00",
|
||||
"local_file": "ComfyUI_frontend__src__extensions__core__noteNode.ts",
|
||||
"target_version_match": "unknown",
|
||||
"rule_locations": {
|
||||
"markdown_virtual_registration": [
|
||||
54,
|
||||
82
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "ComfyUI_frontend:src/extensions/core/saveImageExtraOutput.ts",
|
||||
"repository": "https://github.com/Comfy-Org/ComfyUI_frontend",
|
||||
"commit": "f2254852b2a575b30cc1cde46742a89afbfac252",
|
||||
"tag": "v1.41.20",
|
||||
"file": "src/extensions/core/saveImageExtraOutput.ts",
|
||||
"lines": [
|
||||
[
|
||||
1,
|
||||
66
|
||||
]
|
||||
],
|
||||
"raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/f2254852b2a575b30cc1cde46742a89afbfac252/src/extensions/core/saveImageExtraOutput.ts",
|
||||
"url": "https://github.com/Comfy-Org/ComfyUI_frontend/blob/f2254852b2a575b30cc1cde46742a89afbfac252/src/extensions/core/saveImageExtraOutput.ts",
|
||||
"sha256": "ec67f928b92c418678619840041ab8d9d6c43945e1d237704dbea15e8ee5b6e3",
|
||||
"retrieved_at": "2026-10-29T22:08:22.243427+00:00",
|
||||
"local_file": "ComfyUI_frontend__src__extensions__core__saveImageExtraOutput.ts",
|
||||
"target_version_match": "unknown",
|
||||
"rule_locations": {
|
||||
"save_prefix_serializer_override": [
|
||||
25,
|
||||
46
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "ComfyUI_frontend:src/utils/searchAndReplace.ts",
|
||||
"repository": "https://github.com/Comfy-Org/ComfyUI_frontend",
|
||||
"commit": "f2254852b2a575b30cc1cde46742a89afbfac252",
|
||||
"tag": "v1.41.20",
|
||||
"file": "src/utils/searchAndReplace.ts",
|
||||
"lines": [
|
||||
[
|
||||
1,
|
||||
57
|
||||
]
|
||||
],
|
||||
"raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/f2254852b2a575b30cc1cde46742a89afbfac252/src/utils/searchAndReplace.ts",
|
||||
"url": "https://github.com/Comfy-Org/ComfyUI_frontend/blob/f2254852b2a575b30cc1cde46742a89afbfac252/src/utils/searchAndReplace.ts",
|
||||
"sha256": "c7462edebf266b8b8cc62954a371ca3ec3fd1ee4c188e1b80a675003b49887d4",
|
||||
"retrieved_at": "2026-10-29T22:12:03.563960+00:00",
|
||||
"local_file": "ComfyUI_frontend__src__utils__searchAndReplace.ts",
|
||||
"target_version_match": "unknown",
|
||||
"rule_locations": {
|
||||
"regex_contextual_replacement": [
|
||||
5,
|
||||
57
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "ComfyUI_frontend:frontend-tag",
|
||||
"repository": "https://github.com/Comfy-Org/ComfyUI_frontend",
|
||||
"commit": "f2254852b2a575b30cc1cde46742a89afbfac252",
|
||||
"tag": "v1.41.20",
|
||||
"file": "git/ref/tags/v1.41.20",
|
||||
"lines": [
|
||||
[
|
||||
1,
|
||||
1
|
||||
]
|
||||
],
|
||||
"raw_url": "https://api.github.com/repos/Comfy-Org/ComfyUI_frontend/git/ref/tags/v1.41.20",
|
||||
"url": "https://api.github.com/repos/Comfy-Org/ComfyUI_frontend/git/ref/tags/v1.41.20",
|
||||
"sha256": "4a09cdcf5a33520eec6b02114986eb22619a2538f2b0f8ba84132468555b15bb",
|
||||
"retrieved_at": "2026-10-29T22:14:22.810044+00:00",
|
||||
"local_file": "frontend-tag.json",
|
||||
"target_version_match": "unknown"
|
||||
},
|
||||
{
|
||||
"id": "ComfyUI_frontend:frontend-tree",
|
||||
"repository": "https://github.com/Comfy-Org/ComfyUI_frontend",
|
||||
"commit": "f2254852b2a575b30cc1cde46742a89afbfac252",
|
||||
"tag": "v1.41.20",
|
||||
"file": "git/trees/f2254852b2a575b30cc1cde46742a89afbfac252?recursive=1",
|
||||
"lines": [
|
||||
[
|
||||
1,
|
||||
1
|
||||
]
|
||||
],
|
||||
"raw_url": "https://api.github.com/repos/Comfy-Org/ComfyUI_frontend/git/trees/f2254852b2a575b30cc1cde46742a89afbfac252?recursive=1",
|
||||
"url": "https://api.github.com/repos/Comfy-Org/ComfyUI_frontend/git/trees/f2254852b2a575b30cc1cde46742a89afbfac252?recursive=1",
|
||||
"sha256": "faef0c10b4d92026465c36b076e37fc31988301f050ca87aabb6a0e8a0b7aeb2",
|
||||
"retrieved_at": "2026-10-29T22:14:22.811026+00:00",
|
||||
"local_file": "frontend-tree.json",
|
||||
"target_version_match": "unknown"
|
||||
},
|
||||
{
|
||||
"id": "ComfyUI_frontend:frontend-commit",
|
||||
"repository": "https://github.com/Comfy-Org/ComfyUI_frontend",
|
||||
"commit": "f2254852b2a575b30cc1cde46742a89afbfac252",
|
||||
"tag": "v1.41.20",
|
||||
"file": "commits/f2254852b2a575b30cc1cde46742a89afbfac252",
|
||||
"lines": [
|
||||
[
|
||||
1,
|
||||
1
|
||||
]
|
||||
],
|
||||
"raw_url": "https://api.github.com/repos/Comfy-Org/ComfyUI_frontend/commits/f2254852b2a575b30cc1cde46742a89afbfac252",
|
||||
"url": "https://api.github.com/repos/Comfy-Org/ComfyUI_frontend/commits/f2254852b2a575b30cc1cde46742a89afbfac252",
|
||||
"sha256": "71e2c5f21fa45cfe8aeb89ed1983116aefedc6cf48e312e10c0f028f0437a3d6",
|
||||
"retrieved_at": "2026-10-29T22:14:22.811070+00:00",
|
||||
"local_file": "frontend-commit.json",
|
||||
"target_version_match": "unknown"
|
||||
},
|
||||
{
|
||||
"id": "ComfyUI:core-tag",
|
||||
"repository": "https://github.com/Comfy-Org/ComfyUI",
|
||||
"commit": "63d1bbdb407c69370d407ce5ced6ca3f917528a8",
|
||||
"tag": "v0.17.0",
|
||||
"file": "git/ref/tags/v0.17.0",
|
||||
"lines": [
|
||||
[
|
||||
1,
|
||||
1
|
||||
]
|
||||
],
|
||||
"raw_url": "https://api.github.com/repos/Comfy-Org/ComfyUI/git/ref/tags/v0.17.0",
|
||||
"url": "https://api.github.com/repos/Comfy-Org/ComfyUI/git/ref/tags/v0.17.0",
|
||||
"sha256": "528c78d14feafed7806b7dfce1c49cf03a212d1b7328db61a4825720d4acbed2",
|
||||
"retrieved_at": "2026-10-29T22:14:22.811083+00:00",
|
||||
"local_file": "core-tag.json",
|
||||
"target_version_match": "unknown"
|
||||
},
|
||||
{
|
||||
"id": "ComfyUI:core-commit",
|
||||
"repository": "https://github.com/Comfy-Org/ComfyUI",
|
||||
"commit": "63d1bbdb407c69370d407ce5ced6ca3f917528a8",
|
||||
"tag": "v0.17.0",
|
||||
"file": "commits/63d1bbdb407c69370d407ce5ced6ca3f917528a8",
|
||||
"lines": [
|
||||
[
|
||||
1,
|
||||
1
|
||||
]
|
||||
],
|
||||
"raw_url": "https://api.github.com/repos/Comfy-Org/ComfyUI/commits/63d1bbdb407c69370d407ce5ced6ca3f917528a8",
|
||||
"url": "https://api.github.com/repos/Comfy-Org/ComfyUI/commits/63d1bbdb407c69370d407ce5ced6ca3f917528a8",
|
||||
"sha256": "9383ff99f29430f1a24606c9a79ff84d66bf2d466d9bf4139c6d70ab55528013",
|
||||
"retrieved_at": "2026-10-29T22:14:22.811098+00:00",
|
||||
"local_file": "core-commit.json",
|
||||
"target_version_match": "unknown"
|
||||
}
|
||||
],
|
||||
"profile": "comfy-frontend-1.41.20-core-0.17.0-grid-reference",
|
||||
"target_version_match": "unknown",
|
||||
"license_boundary": "Unmodified upstream source bytes retained with each GPL-3.0 LICENSE for review; never imported, installed or executed. No target installation or release artifact provenance asserted."
|
||||
}
|
||||
Reference in New Issue
Block a user