HEL-892: add bounded UI widget serialization and Reroute reference conversion
Co-authored-by: multica-agent <github@multica.ai>
This commit is contained in:
@@ -0,0 +1,134 @@
|
||||
"""Compare bounded public-reference behavior to six supplied APIs, never mark ready.
|
||||
|
||||
PYTHONPATH=src python scripts/audit_reference_conversion.py --repo .. --output report.json
|
||||
The report intentionally includes only supported fields/legacy links, alongside
|
||||
whole-graph blockers. It is not a substitute for compare_frontend_exports.py's
|
||||
source/version binding checks or a target node snapshot.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
from compare_frontend_exports import differences
|
||||
|
||||
from calliope.comfyui.companions import load_companions
|
||||
from calliope.comfyui.delivery_scope import exclusion_for
|
||||
from calliope.comfyui.serialization_reference import (
|
||||
PROFILE,
|
||||
resolve_reference_link,
|
||||
serialize_reference_widgets,
|
||||
)
|
||||
from calliope.comfyui.ui2api import convert, convert_reference
|
||||
|
||||
|
||||
def audit(repo: Path) -> dict:
|
||||
rows = []
|
||||
records = load_companions(repo / "docs/hel-892/supplied-api/manifest.json")
|
||||
for path, record in records.items():
|
||||
binding = record["binding"]
|
||||
if exclusion_for(path):
|
||||
continue
|
||||
raw = (repo / path).read_bytes()
|
||||
assert hashlib.sha1(raw).hexdigest() == binding["source_sha"]
|
||||
assert hashlib.sha256(raw).hexdigest() == binding["source_sha256"]
|
||||
source, api = json.loads(raw), json.loads(record["raw"])
|
||||
assert convert(api).prompt is not None
|
||||
nodes = {str(n["id"]): n for n in source["nodes"]}
|
||||
links = {str(link[0]): link for link in source.get("links", [])}
|
||||
fields, edges, unsupported = [], [], []
|
||||
for nid, node in nodes.items():
|
||||
if node.get("type") in ("Reroute", "Note", "MarkdownNote"):
|
||||
continue
|
||||
try:
|
||||
values = serialize_reference_widgets(node)
|
||||
except ValueError as exc:
|
||||
unsupported.append({"node_id": nid, "type": node["type"], "reason": str(exc)})
|
||||
else:
|
||||
for name, value in values.items():
|
||||
expected = api.get(nid, {}).get("inputs", {}).get(name)
|
||||
fields.append(
|
||||
{
|
||||
"node_id": nid,
|
||||
"field": name,
|
||||
"source_reference": value,
|
||||
"api": expected,
|
||||
"differences": differences(expected, value),
|
||||
}
|
||||
)
|
||||
for socket in node.get("inputs", []):
|
||||
lid = socket.get("link")
|
||||
if lid is None:
|
||||
continue
|
||||
try:
|
||||
endpoint = resolve_reference_link(nodes, links, lid)
|
||||
except (ValueError, KeyError, TypeError, AttributeError) as exc:
|
||||
edges.append(
|
||||
{
|
||||
"node_id": nid,
|
||||
"input": socket["name"],
|
||||
"status": "unsupported",
|
||||
"reason": str(exc),
|
||||
}
|
||||
)
|
||||
continue
|
||||
expected = api.get(nid, {}).get("inputs", {}).get(socket["name"])
|
||||
edges.append(
|
||||
{
|
||||
"node_id": nid,
|
||||
"input": socket["name"],
|
||||
"via_reroute": nodes[str(links[str(lid)][1])]["type"] == "Reroute",
|
||||
"source_reference": endpoint,
|
||||
"api": expected,
|
||||
"differences": differences(expected, endpoint),
|
||||
}
|
||||
)
|
||||
candidate = convert_reference(source)
|
||||
rows.append(
|
||||
{
|
||||
"id": binding["id"],
|
||||
"source_path": path,
|
||||
"source_sha256": binding["source_sha256"],
|
||||
"api_sha256": binding["export_sha256"],
|
||||
"source_frontend_version": source.get("extra", {}).get("frontendVersion"),
|
||||
"export_frontend_version": binding["frontend_version"],
|
||||
"whole_prompt_available": candidate.prompt is not None,
|
||||
"whole_prompt_differences": differences(api, candidate.prompt)
|
||||
if candidate.prompt is not None
|
||||
else None,
|
||||
"whole_prompt_issues": candidate.issues,
|
||||
"production_prompt_available": convert(source).prompt is not None,
|
||||
"serialized_fields": fields,
|
||||
"topology_edges": edges,
|
||||
"unsupported_widget_nodes": unsupported,
|
||||
"executable": False,
|
||||
"execution_verified": False,
|
||||
}
|
||||
)
|
||||
return {
|
||||
"profile": PROFILE,
|
||||
"authority": "public_reference_only_not_object_info",
|
||||
"comparison_scope": "supported root scalar widgets and legacy root link endpoints only",
|
||||
"target_version_match": "unknown",
|
||||
"whole_source_equivalence_verified": False,
|
||||
"execution_verified": False,
|
||||
"cases": rows,
|
||||
}
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--repo", type=Path, required=True)
|
||||
parser.add_argument("--output", type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
report = audit(args.repo)
|
||||
args.output.parent.mkdir(parents=True, exist_ok=True)
|
||||
args.output.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n")
|
||||
print(json.dumps({"reference_only": True, "active_cases": len(report["cases"])}))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,51 @@
|
||||
"""Verify pinned frontend/core source bytes; never import or execute upstream code."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
from urllib.request import urlopen
|
||||
|
||||
|
||||
def verify(directory: Path, fetch: bool = False) -> dict:
|
||||
manifest = json.loads((directory / "sources.json").read_text())
|
||||
verified = []
|
||||
for source in manifest["sources"]:
|
||||
path = directory / source["local_file"]
|
||||
if fetch:
|
||||
with urlopen(source["raw_url"], timeout=30) as response:
|
||||
raw = response.read()
|
||||
else:
|
||||
raw = path.read_bytes()
|
||||
if hashlib.sha256(raw).hexdigest() != source["sha256"]:
|
||||
raise ValueError(f"哈希不一致:{source['id']}")
|
||||
lines = raw.decode("utf-8").splitlines()
|
||||
for start, end in source["lines"]:
|
||||
if not 1 <= start <= end <= len(lines):
|
||||
raise ValueError(f"行号越界:{source['id']}")
|
||||
if fetch:
|
||||
path.write_bytes(raw)
|
||||
verified.append({"id": source["id"], "sha256": source["sha256"]})
|
||||
return {
|
||||
"authority": "public_reference_only",
|
||||
"sources_verified": verified,
|
||||
"upstream_code_executed": False,
|
||||
"target_version_match": "unknown",
|
||||
}
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--source-dir", type=Path, required=True)
|
||||
parser.add_argument("--fetch", action="store_true")
|
||||
parser.add_argument("--output", type=Path, required=True)
|
||||
args = parser.parse_args()
|
||||
report = verify(args.source_dir, args.fetch)
|
||||
args.output.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n")
|
||||
print(f"verified {len(report['sources_verified'])} sources; no upstream execution")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,143 @@
|
||||
"""Small, explicit public-reference contract, never a target object_info snapshot.
|
||||
|
||||
Sources and limits: docs/hel-892/serialization-evidence/sources.json.
|
||||
Only unmodified scalar core widgets are covered. No plugin, dynamic prompt,
|
||||
seed controller, subgraph, bypass or custom serializeValue is inferred.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
PROFILE = "comfy-frontend-1.37.11-core-reference"
|
||||
|
||||
# Widget construction order, including workflow-only upload button. A None type
|
||||
# is a workflow-persisted widget with options.serialize=false in graphToPrompt.
|
||||
_LAYOUTS = {
|
||||
"Canny": (("low_threshold", float), ("high_threshold", float)),
|
||||
"ImageStitch": (
|
||||
("direction", str),
|
||||
("match_image_size", bool),
|
||||
("spacing_width", int),
|
||||
("spacing_color", str),
|
||||
),
|
||||
"LoadImage": (("image", str), ("upload", None)),
|
||||
"PreviewImage": (),
|
||||
}
|
||||
|
||||
|
||||
def reference_definitions() -> dict[str, Any]:
|
||||
"""Only public core reference schemas; no model/file availability assertion."""
|
||||
|
||||
def spec(required, outputs, optional=None):
|
||||
return {
|
||||
"input": {
|
||||
"required": {k: [v] for k, v in required.items()},
|
||||
"optional": {k: [v] for k, v in (optional or {}).items()},
|
||||
},
|
||||
"output": outputs,
|
||||
}
|
||||
|
||||
return {
|
||||
"Canny": spec(
|
||||
{"image": "IMAGE", "low_threshold": "FLOAT", "high_threshold": "FLOAT"}, ["IMAGE"]
|
||||
),
|
||||
"ImageStitch": spec(
|
||||
{
|
||||
"image1": "IMAGE",
|
||||
"direction": "COMBO",
|
||||
"match_image_size": "BOOLEAN",
|
||||
"spacing_width": "INT",
|
||||
"spacing_color": "COMBO",
|
||||
},
|
||||
["IMAGE"],
|
||||
{"image2": "IMAGE"},
|
||||
),
|
||||
"LoadImage": spec({"image": "COMBO"}, ["IMAGE", "MASK"]),
|
||||
"PreviewImage": spec({"images": "IMAGE"}, []),
|
||||
}
|
||||
|
||||
|
||||
def serialize_reference_widgets(node: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Apply only the pinned identity serializers; reject any extra/missing value."""
|
||||
if node.get("mode", 0) != 0:
|
||||
raise ValueError("静音/旁路不在序列化参考契约内")
|
||||
properties = node.get("properties") or {}
|
||||
expected_version = "0.17.0" if node.get("type") == "ImageStitch" else "0.21.1"
|
||||
if (
|
||||
properties.get("cnr_id", "comfy-core") != "comfy-core"
|
||||
or properties.get("ver", expected_version) != expected_version
|
||||
):
|
||||
raise ValueError("源节点声明与固定核心参考版本不符")
|
||||
layout = _LAYOUTS.get(node.get("type"))
|
||||
values = node.get("widgets_values", [])
|
||||
if layout is None or not isinstance(values, list) or len(values) != len(layout):
|
||||
raise ValueError("控件数量/形式或节点类型不在固定参考契约内")
|
||||
result = {}
|
||||
for (name, kind), value in zip(layout, values):
|
||||
if kind is None:
|
||||
if value != "image":
|
||||
raise ValueError("upload 不是已知的前端按钮占位值")
|
||||
continue
|
||||
if (kind is float and type(value) not in (int, float)) or (
|
||||
kind is not float and type(value) is not kind
|
||||
):
|
||||
raise ValueError(f"{name} 的类型不符合固定标量契约")
|
||||
result[name] = value
|
||||
return result
|
||||
|
||||
|
||||
def validate_reroute(node: dict[str, Any]) -> None:
|
||||
if (
|
||||
node.get("mode", 0) != 0
|
||||
or node.get("widgets_values") not in (None, [])
|
||||
or len(node.get("inputs", [])) != 1
|
||||
or len(node.get("outputs", [])) != 1
|
||||
or node["inputs"][0].get("name") != ""
|
||||
):
|
||||
raise ValueError("Reroute 必须是无控件、单入口/出口、非旁路的固定参考形式")
|
||||
|
||||
|
||||
def resolve_reference_link(nodes, links, link_id) -> list[Any]:
|
||||
"""Trace legacy six-field links through slot 0 of Reroute, preserving source slot.
|
||||
|
||||
Validate reciprocal endpoints at every hop. Fail instead of the frontend's
|
||||
optional discard of dangling links. This helper is also usable to compare
|
||||
topology alone when unsupported third-party widgets block the whole prompt.
|
||||
It makes no assertion about those third-party nodes' input/output types.
|
||||
"""
|
||||
seen = set()
|
||||
while True:
|
||||
key = str(link_id)
|
||||
if key in seen:
|
||||
raise ValueError("Reroute 链路循环")
|
||||
seen.add(key)
|
||||
link = links.get(key)
|
||||
if not isinstance(link, list) or len(link) != 6:
|
||||
raise ValueError("缺失连线或非六字段旧式连线")
|
||||
_, origin, output_slot, target, input_slot, _ = link
|
||||
upstream, downstream = nodes.get(str(origin)), nodes.get(str(target))
|
||||
if not upstream or not downstream:
|
||||
raise ValueError("悬空节点")
|
||||
for slot, sockets in (
|
||||
(output_slot, upstream.get("outputs", [])),
|
||||
(input_slot, downstream.get("inputs", [])),
|
||||
):
|
||||
if type(slot) is not int or not 0 <= slot < len(sockets):
|
||||
raise ValueError("连线槽无效")
|
||||
outgoing = upstream["outputs"][output_slot].get("links") or []
|
||||
if (
|
||||
sum(str(x) == key for x in outgoing) != 1
|
||||
or str(downstream["inputs"][input_slot].get("link")) != key
|
||||
):
|
||||
raise ValueError("连线与入口/出口记录不互相对应")
|
||||
if upstream.get("mode", 0) != 0 or downstream.get("mode", 0) != 0:
|
||||
raise ValueError("静音/旁路不在追线参考契约内")
|
||||
if upstream.get("type") != "Reroute":
|
||||
return [str(origin), output_slot]
|
||||
validate_reroute(upstream)
|
||||
if output_slot != 0:
|
||||
raise ValueError("Reroute 出口必须为零槽")
|
||||
link_id = upstream["inputs"][0].get("link")
|
||||
if link_id is None:
|
||||
raise ValueError("Reroute 无上游连线")
|
||||
@@ -2,7 +2,9 @@
|
||||
|
||||
object_info does not define custom frontend widget serialization. Only named
|
||||
widgets pass. Even input_order cannot prove arbitrary frontend serialization.
|
||||
Subgraphs, virtual nodes, seed extra controls, mute and bypass need API exports.
|
||||
The separate convert_reference entry point supports a bounded public-source
|
||||
profile for offline comparison only; it never changes production eligibility.
|
||||
Subgraphs, seed extra controls, mute and bypass remain unsupported.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -10,14 +12,47 @@ from __future__ import annotations
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any
|
||||
|
||||
from .serialization_reference import (
|
||||
PROFILE,
|
||||
reference_definitions,
|
||||
resolve_reference_link,
|
||||
serialize_reference_widgets,
|
||||
validate_reroute,
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class Conversion:
|
||||
prompt: dict[str, Any] | None
|
||||
issues: list[dict[str, Any]] = field(default_factory=list)
|
||||
reference_only: bool = False
|
||||
|
||||
|
||||
def convert(source: Any, object_info: dict[str, Any] | None = None) -> Conversion:
|
||||
return _convert(source, object_info)
|
||||
|
||||
|
||||
def convert_reference(source: Any, profile: str = PROFILE) -> Conversion:
|
||||
"""Offline candidate only. Never consumed by production library import.
|
||||
|
||||
An unknown profile is rejected, not interpreted as a widget-order contract.
|
||||
Public reference definitions cannot establish target execution eligibility.
|
||||
"""
|
||||
if profile != PROFILE or not isinstance(source, dict) or "nodes" not in source:
|
||||
return Conversion(
|
||||
None,
|
||||
[{"code": "invalid_reference_contract", "message": "未知参考版本或不是 UI 图"}],
|
||||
True,
|
||||
)
|
||||
try:
|
||||
result = _convert(source, reference_definitions(), reference=True)
|
||||
except (ValueError, TypeError, KeyError, AttributeError, IndexError) as exc:
|
||||
return Conversion(None, [{"code": "invalid_reference_contract", "message": str(exc)}], True)
|
||||
result.reference_only = True
|
||||
return result
|
||||
|
||||
|
||||
def _convert(source, object_info=None, *, reference=False) -> Conversion:
|
||||
issues: list[dict[str, Any]] = []
|
||||
|
||||
def fail(code: str, message: str, node_id: Any = "") -> None:
|
||||
@@ -65,6 +100,29 @@ def convert(source: Any, object_info: dict[str, Any] | None = None) -> Conversio
|
||||
if str(link[0]) in links:
|
||||
fail("duplicate_link", "连线 ID 重复")
|
||||
links[str(link[0])] = link
|
||||
if reference:
|
||||
frontend_version = (source.get("extra") or {}).get("frontendVersion")
|
||||
if frontend_version is not None and frontend_version != "1.37.11":
|
||||
fail("reference_frontend_mismatch", "源图声明的前端版本与固定参考不一致")
|
||||
# Validate every stored link, even unused branches: never silently drop
|
||||
# an unsupported connection to obtain a partial candidate.
|
||||
for node in nodes.values():
|
||||
for slot, socket in enumerate(node.get("inputs", [])):
|
||||
lid = socket.get("link")
|
||||
if lid is not None:
|
||||
link = links.get(str(lid))
|
||||
if not link or str(link[3]) != str(node["id"]) or link[4] != slot:
|
||||
fail("reference_link_invalid", "输入与连线目标记录不对应", node["id"])
|
||||
for slot, socket in enumerate(node.get("outputs", [])):
|
||||
for lid in socket.get("links") or []:
|
||||
link = links.get(str(lid))
|
||||
if not link or str(link[1]) != str(node["id"]) or link[2] != slot:
|
||||
fail("reference_link_invalid", "输出与连线来源记录不对应", node["id"])
|
||||
for lid in links:
|
||||
try:
|
||||
resolve_reference_link(nodes, links, lid)
|
||||
except (ValueError, TypeError, KeyError, AttributeError) as exc:
|
||||
fail("reference_link_invalid", str(exc))
|
||||
prompt = {}
|
||||
for nid, node in nodes.items():
|
||||
ct = node.get("type", "")
|
||||
@@ -73,9 +131,19 @@ def convert(source: Any, object_info: dict[str, Any] | None = None) -> Conversio
|
||||
if node.get("mode", 0) != 0:
|
||||
fail("mode_requires_export", f"{ct} 包含静音/旁路状态,需 API 导出核对", nid)
|
||||
continue
|
||||
if reference and ct == "Reroute":
|
||||
try:
|
||||
validate_reroute(node)
|
||||
resolve_reference_link(nodes, links, node["inputs"][0].get("link"))
|
||||
except (ValueError, TypeError, KeyError, AttributeError) as exc:
|
||||
fail("reference_link_invalid", str(exc), nid)
|
||||
continue
|
||||
spec = info.get(ct)
|
||||
if not isinstance(spec, dict):
|
||||
fail("node_definition_unavailable", f"待提供目标机节点定义:{ct}", nid)
|
||||
if reference:
|
||||
fail("reference_node_unsupported", f"固定参考契约未覆盖节点:{ct}", nid)
|
||||
else:
|
||||
fail("node_definition_unavailable", f"待提供目标机节点定义:{ct}", nid)
|
||||
continue
|
||||
declared = {
|
||||
**spec.get("input", {}).get("required", {}),
|
||||
@@ -84,7 +152,19 @@ def convert(source: Any, object_info: dict[str, Any] | None = None) -> Conversio
|
||||
sockets = {s["name"]: s for s in node.get("inputs", []) if "name" in s}
|
||||
widgets = node.get("widgets_values") or []
|
||||
inputs = {}
|
||||
if isinstance(widgets, dict):
|
||||
if reference:
|
||||
try:
|
||||
inputs.update(serialize_reference_widgets(node))
|
||||
if [s.get("type") for s in node.get("outputs", [])] != spec["output"]:
|
||||
raise ValueError("源输出槽不符合固定参考契约")
|
||||
names = [s.get("name") for s in node.get("inputs", [])]
|
||||
allowed = set(declared) | ({"upload"} if ct == "LoadImage" else set())
|
||||
if len(names) != len(set(names)) or set(names) - allowed:
|
||||
raise ValueError("额外或重复输入槽不在固定参考契约内")
|
||||
except (ValueError, TypeError, AttributeError) as exc:
|
||||
fail("reference_widget_unverified", str(exc), nid)
|
||||
continue
|
||||
elif isinstance(widgets, dict):
|
||||
if set(widgets) - set(declared):
|
||||
fail("unknown_widget", f"{ct} 存在节点定义以外的具名控件", nid)
|
||||
inputs.update({k: v for k, v in widgets.items() if k in declared})
|
||||
@@ -111,6 +191,13 @@ def convert(source: Any, object_info: dict[str, Any] | None = None) -> Conversio
|
||||
if node["inputs"][link[4]].get("name") != name or name not in declared:
|
||||
fail("invalid_socket", f"输入 {name} 的目标槽不匹配", nid)
|
||||
continue
|
||||
if reference:
|
||||
try:
|
||||
resolved = resolve_reference_link(nodes, links, lid)
|
||||
link = [link[0], resolved[0], resolved[1], *link[3:]]
|
||||
except (ValueError, TypeError, KeyError, AttributeError) as exc:
|
||||
fail("reference_link_invalid", str(exc), nid)
|
||||
continue
|
||||
upstream = nodes.get(str(link[1]))
|
||||
outputs = info.get((upstream or {}).get("type"), {}).get("output", [])
|
||||
if not upstream or not isinstance(link[2], int) or not 0 <= link[2] < len(outputs):
|
||||
|
||||
@@ -0,0 +1,235 @@
|
||||
"""Synthetic contract tests and bounded real-source comparison; no execution proof."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import copy
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from calliope.comfyui.serialization_reference import (
|
||||
reference_definitions,
|
||||
resolve_reference_link,
|
||||
serialize_reference_widgets,
|
||||
)
|
||||
from calliope.comfyui.ui2api import convert, convert_reference
|
||||
|
||||
REPO = Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
def synthetic_graph():
|
||||
return {
|
||||
"nodes": [
|
||||
{
|
||||
"id": 1,
|
||||
"type": "LoadImage",
|
||||
"widgets_values": ["测试.png", "image"],
|
||||
"outputs": [{"type": "IMAGE", "links": [10]}, {"type": "MASK", "links": []}],
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"type": "Reroute",
|
||||
"inputs": [{"name": "", "link": 10}],
|
||||
"outputs": [{"type": "IMAGE", "links": [11]}],
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"type": "Reroute",
|
||||
"inputs": [{"name": "", "link": 11}],
|
||||
"outputs": [{"type": "IMAGE", "links": [12]}],
|
||||
},
|
||||
{
|
||||
"id": 4,
|
||||
"type": "Canny",
|
||||
"widgets_values": [0.23, 0.91],
|
||||
"inputs": [{"name": "image", "link": 12}],
|
||||
"outputs": [{"type": "IMAGE", "links": [13]}],
|
||||
},
|
||||
{
|
||||
"id": 5,
|
||||
"type": "PreviewImage",
|
||||
"widgets_values": [],
|
||||
"inputs": [{"name": "images", "link": 13}],
|
||||
"outputs": [],
|
||||
},
|
||||
],
|
||||
"links": [
|
||||
[10, 1, 0, 2, 0, "IMAGE"],
|
||||
[11, 2, 0, 3, 0, "IMAGE"],
|
||||
[12, 3, 0, 4, 0, "IMAGE"],
|
||||
[13, 4, 0, 5, 0, "IMAGE"],
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def test_identity_widgets_upload_omission_and_reroute_chain():
|
||||
graph = synthetic_graph()
|
||||
before = copy.deepcopy(graph)
|
||||
result = convert_reference(graph)
|
||||
assert result.reference_only and not result.issues
|
||||
assert set(result.prompt) == {"1", "4", "5"}
|
||||
assert result.prompt["1"]["inputs"] == {"image": "测试.png"}
|
||||
assert result.prompt["4"]["inputs"] == {
|
||||
"image": ["1", 0],
|
||||
"low_threshold": 0.23,
|
||||
"high_threshold": 0.91,
|
||||
}
|
||||
assert result.prompt["5"]["inputs"] == {"images": ["4", 0]}
|
||||
assert graph == before
|
||||
assert convert(graph).prompt is None
|
||||
assert not convert(graph).reference_only
|
||||
# Even a matching input_order does not opt production into public contracts.
|
||||
definitions = reference_definitions()
|
||||
for spec in definitions.values():
|
||||
spec["input_order"] = {"required": list(spec["input"]["required"])}
|
||||
assert convert(graph, definitions).prompt is None
|
||||
|
||||
|
||||
def test_nonzero_original_source_slot_is_preserved_but_type_mismatch_rejected():
|
||||
graph = synthetic_graph()
|
||||
graph["nodes"][0]["outputs"][0]["links"] = []
|
||||
graph["nodes"][0]["outputs"][1]["links"] = [10]
|
||||
graph["links"][0][2] = 1
|
||||
assert resolve_reference_link(
|
||||
{str(n["id"]): n for n in graph["nodes"]},
|
||||
{str(link[0]): link for link in graph["links"]},
|
||||
12,
|
||||
) == ["1", 1]
|
||||
result = convert_reference(graph)
|
||||
assert result.prompt is None
|
||||
assert "link_type_unverified" in {i["code"] for i in result.issues}
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"change",
|
||||
[
|
||||
"cycle",
|
||||
"missing_link",
|
||||
"missing_node",
|
||||
"negative_slot",
|
||||
"bool_slot",
|
||||
"wrong_target",
|
||||
"output_disagrees",
|
||||
"duplicate_link",
|
||||
"missing_output_link",
|
||||
"extra_reroute_input",
|
||||
"reroute_widgets",
|
||||
"bypass",
|
||||
"subgraph",
|
||||
"extra_widget",
|
||||
"missing_widget",
|
||||
"bool_numeric",
|
||||
"dynamic_value",
|
||||
"extra_input",
|
||||
"ambiguous_output",
|
||||
"node_version",
|
||||
"node_provider",
|
||||
"frontend_version",
|
||||
],
|
||||
)
|
||||
def test_unsupported_graph_never_returns_partial_prompt(change):
|
||||
graph = synthetic_graph()
|
||||
if change == "cycle":
|
||||
graph["links"][0][1:3] = [3, 0]
|
||||
graph["nodes"][2]["outputs"][0]["links"].append(10)
|
||||
elif change == "missing_link":
|
||||
graph["links"].pop(0)
|
||||
elif change == "missing_node":
|
||||
graph["nodes"].pop(0)
|
||||
elif change in ("negative_slot", "bool_slot"):
|
||||
graph["links"][0][2] = -1 if change == "negative_slot" else False
|
||||
elif change == "wrong_target":
|
||||
graph["links"][0][4] = 1
|
||||
elif change == "output_disagrees":
|
||||
graph["nodes"][0]["outputs"][0]["links"] = []
|
||||
elif change == "duplicate_link":
|
||||
graph["links"].append(graph["links"][0])
|
||||
elif change == "missing_output_link":
|
||||
graph["nodes"][0]["outputs"][0]["links"].append(999)
|
||||
elif change == "extra_reroute_input":
|
||||
graph["nodes"][1]["inputs"].append({"name": "", "link": None})
|
||||
elif change == "reroute_widgets":
|
||||
graph["nodes"][1]["widgets_values"] = [123]
|
||||
elif change == "bypass":
|
||||
graph["nodes"][1]["mode"] = 4
|
||||
elif change == "subgraph":
|
||||
graph["definitions"] = {"subgraphs": [{"id": "unsupported"}]}
|
||||
elif change == "extra_widget":
|
||||
graph["nodes"][3]["widgets_values"].append("randomize")
|
||||
elif change == "missing_widget":
|
||||
graph["nodes"][3]["widgets_values"].pop()
|
||||
elif change in ("bool_numeric", "dynamic_value"):
|
||||
graph["nodes"][3]["widgets_values"][0] = True if change == "bool_numeric" else {"x": 1}
|
||||
elif change == "node_version":
|
||||
graph["nodes"][3]["properties"] = {"cnr_id": "comfy-core", "ver": "9.9.9"}
|
||||
elif change == "node_provider":
|
||||
graph["nodes"][3]["properties"] = {"cnr_id": "unknown-plugin"}
|
||||
elif change == "frontend_version":
|
||||
graph["extra"] = {"frontendVersion": "9.9.9"}
|
||||
elif change == "ambiguous_output":
|
||||
graph["nodes"][0]["outputs"][1]["links"] = [10]
|
||||
elif change == "extra_input":
|
||||
graph["nodes"][3]["inputs"].append({"name": "custom", "link": None})
|
||||
result = convert_reference(graph)
|
||||
assert result.prompt is None and result.issues and result.reference_only
|
||||
if change == "cycle":
|
||||
assert any("循环" in issue["message"] for issue in result.issues)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"source,profile",
|
||||
[
|
||||
(synthetic_graph(), "input_order_is_not_a_contract"),
|
||||
({"nodes": "malformed"}, None),
|
||||
({"nodes": [{"id": 1, "type": "LoadImage", "inputs": None}]}, None),
|
||||
],
|
||||
)
|
||||
def test_bad_contracts_rejected(source, profile):
|
||||
result = convert_reference(source, profile) if profile else convert_reference(source)
|
||||
assert result.prompt is None and result.issues and result.reference_only
|
||||
|
||||
|
||||
def test_seed_and_custom_serializers_are_not_inferred():
|
||||
with pytest.raises(ValueError):
|
||||
serialize_reference_widgets({"type": "KSampler", "widgets_values": [12, "fixed"]})
|
||||
with pytest.raises(ValueError):
|
||||
serialize_reference_widgets({"type": "Canny", "widgets_values": {"low_threshold": 0.4}})
|
||||
|
||||
|
||||
def test_real_case01_edges_and_supported_fields_match_supplied_export():
|
||||
record = json.loads((REPO / "docs/hel-892/supplied-api/manifest.json").read_text())["cases"][0]
|
||||
raw = (REPO / record["source_path"]).read_bytes()
|
||||
assert hashlib.sha256(raw).hexdigest() == record["source_sha256"]
|
||||
api_raw = (REPO / "docs/hel-892/supplied-api" / record["export_file"]).read_bytes()
|
||||
assert hashlib.sha256(api_raw).hexdigest() == record["export_sha256"]
|
||||
source, api = json.loads(raw), json.loads(api_raw)
|
||||
before = copy.deepcopy(source)
|
||||
nodes = {str(n["id"]): n for n in source["nodes"]}
|
||||
links = {str(link[0]): link for link in source["links"]}
|
||||
fields = edges = rerouted = 0
|
||||
for nid, node in nodes.items():
|
||||
if node["type"] == "Reroute":
|
||||
continue
|
||||
try:
|
||||
values = serialize_reference_widgets(node)
|
||||
except ValueError:
|
||||
pass
|
||||
else:
|
||||
for name, value in values.items():
|
||||
assert type(value) is type(api[nid]["inputs"][name])
|
||||
assert value == api[nid]["inputs"][name]
|
||||
fields += 1
|
||||
for socket in node.get("inputs", []):
|
||||
if socket.get("link") is None:
|
||||
continue
|
||||
lid = socket["link"]
|
||||
assert resolve_reference_link(nodes, links, lid) == api[nid]["inputs"][socket["name"]]
|
||||
edges += 1
|
||||
rerouted += nodes[str(links[str(lid)][1])]["type"] == "Reroute"
|
||||
assert (fields, edges, rerouted) == (16, 23, 9)
|
||||
result = convert_reference(source)
|
||||
assert result.prompt is None
|
||||
assert "reference_node_unsupported" in {i["code"] for i in result.issues}
|
||||
assert source == before
|
||||
@@ -1,3 +1,5 @@
|
||||
> 当前 UI 转换增量:见 `UI序列化与Reroute参考转换.md` 与 `serialization-evidence/`。case01 的16项核心标量、23条输入端点(9条经转接)已由固定官方参考算法对齐;整图仍因第三方契约关闭。参考不改变生产导入资格,全量目标未完成。
|
||||
|
||||
> 当前输出协议增量:见 `输出协议固定参考与兼容验证.md`、`protocol-evidence/` 与后台 `protocol_references.json`。case02/03及case04/07的同协议预览已补公开固定版本参考与实际说明;目标版本/history仍未验证,配套保持停用,全量目标未完成。
|
||||
|
||||
> 当前范围:源文件156 / 本次目标155 / 用户明确排除case06共1份。落实策略、协调恢复与证据见 `155份范围落地与协调恢复.md`、`scope-evidence/`;当前145份UI通用转换未证明,6份采用API配套、139份尚无配套,完整定稿/实跑为0。下面156/146及7份收件数字保留为历史范围。
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
# HEL-892 UI 序列化与 Reroute 参考转换
|
||||
|
||||
本轮新增可执行的离线转换算法,并保留生产导入关闭策略。未重做第七批输出协议、源审校或非阻塞建议。继续原 PR #25、分支 `agent/agent/a64a969a6a44`,目标 `main`。增量基点为 `f62786f4a0c2eed48c22da7164e248d473be0d83`;开工通过 Gitea PR API 核对 head/base,PR 未合并。Multica PR 链接表为空,因此以直接 PR API 和 Git 远端引用核对,未盲改链接或另开 PR。
|
||||
|
||||
## 实际算法与接口
|
||||
|
||||
- `calliope-backend/src/calliope/comfyui/ui2api.py`:复用原转换器的节点、输入、类型检查和全图失败返回逻辑;新增 `convert_reference(source, profile)` 离线入口,结果一律 `reference_only=True`。原 `convert(source, object_info)` 签名与生产行为保留,库导入没有调用参考入口。不是另造执行器,不返回任何包含未支持节点的部分 prompt。
|
||||
- `serialization_reference.py`:固定 profile `comfy-frontend-1.37.11-core-reference`,仅覆盖未被扩展修改的本地核心 Canny、ImageStitch、LoadImage、PreviewImage 标量控件。按具体构造契约取值,严格核对数量和类型;LoadImage 的 upload 按钮占位在 workflow 中保留、在 prompt 中排除。没有按 `input_order` 自动推断任意第三方布局;不支持 seed/noise_seed 控制、任意数组值、动态提示、云端/远程 combo 或未知 `serializeValue`。
|
||||
- 同模块 `resolve_reference_link`:沿旧式六字段连线,从 Reroute 的输出零槽追到输入零槽,保留最终实体源节点 ID 和原始输出槽。每跳核对输入/输出相互引用、槽范围、循环、悬空、模式;全图额外校验所有存储连线和槽的对应关系。Reroute 本身不出现在候选 prompt 中。额外入口/出口、控件、坏连线、多义对应、静音/旁路继续拒绝。
|
||||
- `audit_reference_conversion.py`:复用既有 `load_companions` 的来源/哈希与 `compare_frontend_exports.differences` 的严格类型差分;读取六份现存 API,对照受支持字段及根图连线端点,并保留完整候选的阻塞。它不绕过旧工具的原始前端导出声明/版本绑定要求,不标 equal/可执行。
|
||||
- `verify_frontend_sources.py`:只核对固定来源全文 SHA256 和行号范围,可显式重新下载复验;不导入或执行上游代码。
|
||||
- `test_reference_serialization.py`:实际源图与 API 的受限对照,以及明确标为合成的算法验证。源码原件、来源、差分、回归和隔离审计均在 `serialization-evidence/`;本说明和 README 是唯一文字入口更新,没有批量修改未知说明。
|
||||
|
||||
调用方式:
|
||||
|
||||
```python
|
||||
from calliope.comfyui.ui2api import convert_reference
|
||||
result = convert_reference(source)
|
||||
assert result.reference_only # 不是运行资格
|
||||
# 有任何不支持项则 result.prompt is None;不得提取局部候选交执行队列。
|
||||
```
|
||||
|
||||
未知 profile 直接拒绝。源图若声明非 1.37.11 前端则记录不匹配;已声明核心提供方/版本与固定契约不同也拒绝相应节点。缺声明只允许在显式参考模式做假设比较,绝不当版本已匹配。输入顺序即使一致,也不能使生产入口消费位置数组。
|
||||
|
||||
## 固定官方依据
|
||||
|
||||
case01 没有 `extra.frontendVersion`,不能确认原前端。选择已有 case02 源图声明的官方 `v1.37.11` 作为明确的公开参考,commit `4bf6a1960028cc5cda57d48f9fb01a74dfaade43`。case01 核心节点声明 Canny/LoadImage/PreviewImage `0.21.1`、ImageStitch `0.17.0`,分别取得官方 tag commit `26515acd23fa291a8f5ab53c5997258598de0701`、`63d1bbdb407c69370d407ce5ced6ca3f917528a8`。这些是源图声明与公开代码,均不是用户实际导出版本或目标 object_info。
|
||||
|
||||
来源完整记录在 `serialization-evidence/sources.json`:19 个全文原件(18 份代码、1 份许可证),逐个包含 tag/完整 commit、仓库、原文件、固定 URL、行号、获取时间和 SHA256。未安装、导入任何节点包或插件。主要证据:
|
||||
|
||||
- [graphToPrompt](https://github.com/Comfy-Org/ComfyUI_frontend/blob/4bf6a1960028cc5cda57d48f9fb01a74dfaade43/src/utils/executionUtil.ts#L74):74–145 行处理虚拟/静音/旁路、`options.serialize`、`serializeValue` 与链接覆盖。数组包装虽有源码,本轮没有未经节点契约证明就放行任意数组。
|
||||
- [Reroute](https://github.com/Comfy-Org/ComfyUI_frontend/blob/4bf6a1960028cc5cda57d48f9fb01a74dfaade43/src/extensions/core/rerouteNode.ts#L21):21–38 行创建单入口/出口并标记虚拟;[ExecutableNodeDTO](https://github.com/Comfy-Org/ComfyUI_frontend/blob/4bf6a1960028cc5cda57d48f9fb01a74dfaade43/src/lib/litegraph/src/subgraph/ExecutableNodeDTO.ts#L250) 250–320 行检查访问环并经同槽输入递归追线,最终保留源槽。本轮只实现普通 Reroute 子集;不照搬可丢弃悬空输入的行为,保守拒绝坏图。
|
||||
- [LGraphNode](https://github.com/Comfy-Org/ComfyUI_frontend/blob/4bf6a1960028cc5cda57d48f9fb01a74dfaade43/src/lib/litegraph/src/LGraphNode.ts#L866):866–875、913–922 行区分 workflow 控件读取/写入和 widget.serialize。`litegraphService.ts` 202–212、`nodeDefOrderingUtil.ts` 14–60、具体 float/int/boolean/combo 构造器,连同官方核心 schema,组成顺序契约。没有把单独的 input_order 当完整证明。
|
||||
- [上传按钮](https://github.com/Comfy-Org/ComfyUI_frontend/blob/4bf6a1960028cc5cda57d48f9fb01a74dfaade43/src/renderer/extensions/vueNodes/widgets/composables/useImageUploadWidget.ts#L104):104–120 行默认按钮值 image、`options.serialize=false`;`uploadImage.ts` 给图片 combo 加入 upload 控件。字符串路径原样取源值,不猜实际文件是否存在。
|
||||
- [Canny](https://github.com/Comfy-Org/ComfyUI/blob/26515acd23fa291a8f5ab53c5997258598de0701/comfy_extras/nodes_canny.py#L9)、[ImageStitch](https://github.com/Comfy-Org/ComfyUI/blob/63d1bbdb407c69370d407ce5ced6ca3f917528a8/comfy_extras/nodes_images.py#L253)、[LoadImage/PreviewImage](https://github.com/Comfy-Org/ComfyUI/blob/26515acd23fa291a8f5ab53c5997258598de0701/nodes.py#L1665):具名 schema/顺序/输出槽及类注册依据。`widgets.ts` 的额外 seed 控制、`litegraphUtil.ts` 的旧 forceInput 控件迁移和 `dynamicPrompts.ts` 的自定义序列化是保留关闭的具体边界。
|
||||
|
||||
原图还含 UE 扩展版本属性,实际扩展是否改变构造/序列化未证实。参考只说明在上述官方原实现条件下算法的结果;即使值对齐也不把扩展或目标环境判为一致。上游 GPL 原件保留,许可证随附。
|
||||
|
||||
## 实际 case01 覆盖
|
||||
|
||||
源路径 `example_ComfyUI_workflows/0-基础处理:图像合并-音频分离-视频截取合并-图像视频放大/ControlNet_aux_常用样例.json`;源 SHA256 `8898689d777330c4749a079cd762f573bb12a278c47a2fefbd066ffbdc122b6b`,API SHA256 `0ed76e088a23af43d6fecbf273fc0a983d7112e2b046d347f715afffac56d57e`,均与既有收件 manifest 一致,未改字节。
|
||||
|
||||
新算法实际追过 4 个 Reroute:24、31、32、35。23 条非虚拟节点输入连线全部与 API 端点相同,其中 9 条经过转接:
|
||||
|
||||
- 24 → 18/19/20/21 的 image,最终均为 `['2', 0]`;
|
||||
- 31 → 10/12 的 image,最终均为 `['2', 0]`;
|
||||
- 32 → 4/1 的 image,最终均为 `['2', 0]`;
|
||||
- 35 → 33 的 image,最终为 `['2', 0]`。
|
||||
|
||||
这解决旧逐原始连线比对中的 9 项转接端点差异,**仅在本轮明确的参考拓扑范围内**。既有配套比较/审批状态并未因此清除 link_difference 或 companion_unverified。
|
||||
|
||||
具名序列化实际覆盖节点 10 的 2 项 Canny 值、28/29/30 的 12 项 ImageStitch 值、2/38 的 2 个 LoadImage 字符串,共 16 项,与 API 类型和值全部一致。2 个 upload 按钮占位按源码排除;3/5/11/13/22/36/37 共 7 个 PreviewImage 无标量控件。共覆盖 13 个核心节点的控件布局,另 4 个转接节点只负责连线。
|
||||
|
||||
**整张 case01 仍返回 prompt=None**:8 个 AIO_Preprocessor(1/12/18/19/20/21/33/34)和 1 个 DepthAnythingPreprocessor(4)的前端契约未纳入本轮固定核心 profile,其相关类型检查也继续阻塞。没有从整图裁掉它们再宣称完成。非零源槽在合成链路中另测:LoadImage MASK 槽 1 经多级转接保持 1;后续 MASK→IMAGE 类型不符仍拒绝。
|
||||
|
||||
## 六份原导出对照
|
||||
|
||||
`serialization-evidence/six-case-comparison.json` 逐项列原值/端点与严格差分。仅根图层,不展开子图、Primitive、循环或第三方动态输入;未覆盖标量不计 equal,元数据/种子/其他路径差异不忽略。
|
||||
|
||||
|case|受支持标量一致|根图连线端点一致|端点不同|追线拒绝|整图候选|
|
||||
|---|---:|---:|---:|---:|---|
|
||||
|01|16|23|0|0|关闭:第三方控件/节点|
|
||||
|02|0|5|1|0|关闭:Primitive/字幕等未覆盖|
|
||||
|03|0|0|1|0|关闭:子图、版本及高级音频未覆盖|
|
||||
|04|0|0|4|0|关闭:子图、版本与动态输入未覆盖|
|
||||
|05|0|18|0|0|关闭:其他核心/第三方控件、版本未覆盖|
|
||||
|07|0|4|33|2|关闭:子图/循环、静音分支、版本等|
|
||||
|
||||
02 的 hints 仍是源节点7连线与 API 内联文本之间的差异,未实现 Primitive 折叠;03 的 `37` vs `37:43`、04 的 `459` vs `459:457` 等仍是子图边界;07 的 33 项差异和 2 项拒绝原样记录。07 的 LoadImage 声明 0.31.1,与固定 0.21.1 不同,故不消费其控件。05 的根图连线相同仍不能证明节点参数或全图等价。其它种子、媒体路径、版本等原有差异继续留在配套审计中,未改写已有证据。
|
||||
|
||||
## 本次验证与复现
|
||||
|
||||
在 `calliope-backend` 目录,用已安装依赖的 Python 3.11 环境执行,显式 `PYTHONPATH=src`,并核实 ui2api 导入的是本 checkout,未安装新依赖。实际命令:
|
||||
|
||||
```bash
|
||||
PYTHONPATH=src python -m pytest tests/test_reference_serialization.py \
|
||||
tests/test_ui2api_differential.py tests/test_frontend_export_comparison.py \
|
||||
tests/test_workflow_library.py tests/test_supplied_companions.py tests/test_delivery_scope.py -q
|
||||
PYTHONPATH=src python scripts/audit_reference_conversion.py --repo .. \
|
||||
--output ../docs/hel-892/serialization-evidence/six-case-comparison.json
|
||||
python scripts/verify_frontend_sources.py \
|
||||
--source-dir ../docs/hel-892/serialization-evidence \
|
||||
--output ../docs/hel-892/serialization-evidence/source-verification.json
|
||||
# 可添加 --fetch,重新读取19份固定URL并核验全文哈希;不执行源码。
|
||||
uv build --offline --out-dir ../.local-evidence/serialization-build
|
||||
```
|
||||
|
||||
本次受影响回归 **91 通过**;所有失败关闭场景、版本/提供方不符、原 API 字段保留、重导、用户整行保护、源变化失效和 case06 精确排除均包含在内。只有已安装 Starlette 的弃用警告。已改/新增 5 个 Python 文件 Ruff 通过,diff 检查通过;wheel/sdist 构建与 wheel 内新模块/既有保护资源检查通过。没有重跑共享下载、worker、前端或全后台,因本轮未修改这些路径。历史全后台 865 通过/5 个既有失败/6 跳过、历史 259 项回归仅沿用,绝非本次结果。
|
||||
|
||||
隔离库按原生产导入入口执行首导/重导,并调用既有 `audit_library_documents.py` 与 `audit_supplied_api.py`。结果见 import/reimport/document/companion/protection 摘要:源156 / 目标155 / 排除1;16 pending_check / 139 needs_conversion;全部停用,重导155 skipped;1217 源具名值、3660 位置控件节点、294 配套具名值保留,说明完成0、实跑0,完成/实跑时间戳为空。原始7份附件、156份源文件无改动。
|
||||
|
||||
## 剩余阶段
|
||||
|
||||
本轮只完成核心标量与普通 Reroute 的参考算法;145 份 UI 通用可靠转换、155 份完整说明定稿与必要实跑仍未完成。case06 继续精确排除,不再索要材料。
|
||||
|
||||
下一阶段可按具体节点逐类扩充有版本依据的前端构造/序列化契约,优先 case01 的 AIO_Preprocessor 和 DepthAnythingPreprocessor;再另做 Primitive、子图/循环等独立语义。每段都要保留完整图失败关闭与真实导出差分。真正目标版本/扩展、模型/文件、history/编码与必要实跑仍按以后批准的阶段协调,不要求现在提供材料或开放机器。
|
||||
|
||||
未连接目标机、停止 TTS、启动 ComfyUI、提交 prompt、下载模型、调用付费服务、写在线库、修改界面、合并或部署。由总管交 HEL-893 审核本轮实际增量。
|
||||
@@ -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>.
|
||||
@@ -0,0 +1,4 @@
|
||||
Building source distribution...
|
||||
Building wheel from source distribution...
|
||||
Successfully built ../.local-evidence/serialization-build/calliope-1.5.8.tar.gz
|
||||
Successfully built ../.local-evidence/serialization-build/calliope-1.5.8-py3-none-any.whl
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"adopted": 6,
|
||||
"user_excluded": 1,
|
||||
"source_files": 156,
|
||||
"target_files": 155,
|
||||
"general_conversion_verified": 0,
|
||||
"execution_verified": 0,
|
||||
"new_api_literal_params": 294
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"v0.21.1": "26515acd23fa291a8f5ab53c5997258598de0701",
|
||||
"v0.17.0": "63d1bbdb407c69370d407ce5ced6ca3f917528a8"
|
||||
}
|
||||
@@ -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,45 @@
|
||||
from kornia.filters import canny
|
||||
from typing_extensions import override
|
||||
|
||||
import comfy.model_management
|
||||
from comfy_api.latest import ComfyExtension, io
|
||||
import torch
|
||||
|
||||
|
||||
class Canny(io.ComfyNode):
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
return io.Schema(
|
||||
node_id="Canny",
|
||||
display_name="Canny",
|
||||
search_aliases=["edge detection", "outline", "contour detection", "line art"],
|
||||
category="image/preprocessors",
|
||||
essentials_category="Image Tools",
|
||||
inputs=[
|
||||
io.Image.Input("image"),
|
||||
io.Float.Input("low_threshold", default=0.4, min=0.01, max=0.99, step=0.01),
|
||||
io.Float.Input("high_threshold", default=0.8, min=0.01, max=0.99, step=0.01),
|
||||
],
|
||||
outputs=[io.Image.Output()],
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def detect_edge(cls, image, low_threshold, high_threshold):
|
||||
# Deprecated: use the V3 schema's `execute` method instead of this.
|
||||
return cls.execute(image, low_threshold, high_threshold)
|
||||
|
||||
@classmethod
|
||||
def execute(cls, image, low_threshold, high_threshold) -> io.NodeOutput:
|
||||
output = canny(image.to(device=comfy.model_management.get_torch_device(), dtype=torch.float32).movedim(-1, 1), low_threshold, high_threshold)
|
||||
img_out = output[1].to(device=comfy.model_management.intermediate_device(), dtype=comfy.model_management.intermediate_dtype()).repeat(1, 3, 1, 1).movedim(1, -1)
|
||||
return io.NodeOutput(img_out)
|
||||
|
||||
|
||||
class CannyExtension(ComfyExtension):
|
||||
@override
|
||||
async def get_node_list(self) -> list[type[io.ComfyNode]]:
|
||||
return [Canny]
|
||||
|
||||
|
||||
async def comfy_entrypoint() -> CannyExtension:
|
||||
return CannyExtension()
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"total": 155,
|
||||
"audit_scope": "current_delivery",
|
||||
"source_files": 156,
|
||||
"target_files": 155,
|
||||
"user_excluded": 1,
|
||||
"source_structure_purpose_partially_reviewed": 155,
|
||||
"full_documents_completed": 0,
|
||||
"files_with_selected_named_fields_reviewed": 41,
|
||||
"selected_named_fields_reviewed": 1217,
|
||||
"real_executions": 0,
|
||||
"states": {
|
||||
"pending_check": 16,
|
||||
"needs_conversion": 139
|
||||
},
|
||||
"named_values_preserved": 1217,
|
||||
"unnamed_widget_nodes": 3660,
|
||||
"semantic_batch_files": 139,
|
||||
"semantic_batch_without_named_fields": 114,
|
||||
"semantic_batch_named_fields": 490,
|
||||
"named_values_without_manual_field_review": 0,
|
||||
"named_values_without_verified_units_ranges_effects": 1217,
|
||||
"scope_limit": "人工结论与机械原值清单分开;源语义局部审校非完整说明定稿"
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
{"tag": "v1.37.11", "commit": "4bf6a1960028cc5cda57d48f9fb01a74dfaade43"}
|
||||
@@ -0,0 +1 @@
|
||||
{"batch_id": "87586f61-6a4e-4227-8ee3-32c7c4f6f204", "source_commit": "f62786f4a0c2eed48c22da7164e248d473be0d83", "counts": {"imported": 155, "user_excluded": 1}, "states": {"pending_check": 16, "needs_conversion": 139}, "source_total": 156, "excluded_total": 1, "target_total": 155, "total": 156, "doc_completed": 0, "exec_verified": 0}
|
||||
@@ -0,0 +1 @@
|
||||
All checks passed!
|
||||
@@ -0,0 +1 @@
|
||||
wheel contains current ui2api and serialization_reference modules and existing protocol/scope resources; source bytes match.
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"rows": 155,
|
||||
"enabled": 0,
|
||||
"doc_completed": 0,
|
||||
"exec_verified": 0,
|
||||
"source_files_unchanged": true,
|
||||
"user_row_protection": "test_workflow_library.py and test_supplied_companions.py regression"
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
........................................................................ [ 79%]
|
||||
................... [100%]
|
||||
=============================== warnings summary ===============================
|
||||
../../../../hel-892-830870af070f/workdir/aigc-home/calliope-backend/.venv/lib/python3.11/site-packages/starlette/testclient.py:53
|
||||
/home/xiaomo/multica_workspaces/hello-af23464d222e/hel-892-830870af070f/workdir/aigc-home/calliope-backend/.venv/lib/python3.11/site-packages/starlette/testclient.py:53: DeprecationWarning: The anyio.abc.BlockingPortal alias is deprecated, use anyio.from_thread.BlockingPortal instead.
|
||||
_PortalFactoryType = Callable[[], AbstractContextManager[anyio.abc.BlockingPortal]]
|
||||
|
||||
-- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html
|
||||
91 passed, 1 warning in 8.01s
|
||||
@@ -0,0 +1 @@
|
||||
{"batch_id": "a9d14faa-e859-4c9e-bde6-d1f85d33821d", "source_commit": "f62786f4a0c2eed48c22da7164e248d473be0d83", "counts": {"skipped": 155, "user_excluded": 1}, "states": {"pending_check": 16, "needs_conversion": 139}, "source_total": 156, "excluded_total": 1, "target_total": 155, "total": 156, "doc_completed": 0, "exec_verified": 0}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,83 @@
|
||||
{
|
||||
"authority": "public_reference_only",
|
||||
"sources_verified": [
|
||||
{
|
||||
"id": "ComfyUI_frontend:LICENSE",
|
||||
"sha256": "3972dc9744f6499f0f9b2dbf76696f2ae7ad8af9b23dde66d6af86c9dfb36986"
|
||||
},
|
||||
{
|
||||
"id": "ComfyUI:comfy_extras/nodes_images.py",
|
||||
"sha256": "40f22183dcbc9f871030145ca33d52f3dd9d8f64b21ceb071c2fdf6cd49ff501"
|
||||
},
|
||||
{
|
||||
"id": "ComfyUI:comfy_extras/nodes_canny.py",
|
||||
"sha256": "c69f945190aaeb02fd3e81bbe21f5bf2dd70395a3bf17cbe8726261739146fff"
|
||||
},
|
||||
{
|
||||
"id": "ComfyUI:nodes.py",
|
||||
"sha256": "e09534d2c275b2bd389ba7d28677a24d86ce174cdb2419f3d424ff5e50b5d62a"
|
||||
},
|
||||
{
|
||||
"id": "ComfyUI_frontend:src/extensions/core/dynamicPrompts.ts",
|
||||
"sha256": "d190ef52ad9ca6d0351a8e08881773baf1dac49cd2eed71c2cceb20d90838216"
|
||||
},
|
||||
{
|
||||
"id": "ComfyUI_frontend:src/extensions/core/rerouteNode.ts",
|
||||
"sha256": "53abe69665c97427faa7e41d4d0b9b33c8c1415fff84f582ed51862bdf7bfcd8"
|
||||
},
|
||||
{
|
||||
"id": "ComfyUI_frontend:src/extensions/core/uploadImage.ts",
|
||||
"sha256": "935687284bebc3bbb49616976ccaf83c31998dd7abba231e5c8eaab0e8aa9e04"
|
||||
},
|
||||
{
|
||||
"id": "ComfyUI_frontend:src/lib/litegraph/src/LGraphNode.ts",
|
||||
"sha256": "706225a8a06cd7929f9e04fe2388bcdb8f158cdac756c65c45657c020ab7b319"
|
||||
},
|
||||
{
|
||||
"id": "ComfyUI_frontend:src/lib/litegraph/src/subgraph/ExecutableNodeDTO.ts",
|
||||
"sha256": "fd2e19a6b8f4369e6e97d79f407cc1bec130feec9d6d3c979cc03b0a556f249f"
|
||||
},
|
||||
{
|
||||
"id": "ComfyUI_frontend:src/renderer/extensions/vueNodes/widgets/composables/useBooleanWidget.ts",
|
||||
"sha256": "36f477f75561e0c7bfc2c6757906724f8ff2c8660ace26759f3f07493877fece"
|
||||
},
|
||||
{
|
||||
"id": "ComfyUI_frontend:src/renderer/extensions/vueNodes/widgets/composables/useComboWidget.ts",
|
||||
"sha256": "578955db305e760d317b394d0c155caa6aa1e60a235a076e14aadadbd25222d4"
|
||||
},
|
||||
{
|
||||
"id": "ComfyUI_frontend:src/renderer/extensions/vueNodes/widgets/composables/useFloatWidget.ts",
|
||||
"sha256": "a6536de10db2ee4dca8f858f1b2ee68077e9313393e3657e9c22a49c408629e5"
|
||||
},
|
||||
{
|
||||
"id": "ComfyUI_frontend:src/renderer/extensions/vueNodes/widgets/composables/useImageUploadWidget.ts",
|
||||
"sha256": "77d0603c9cb4397cdb33bcbee5721a3690b63f28e82eb11e79a356f0306e149d"
|
||||
},
|
||||
{
|
||||
"id": "ComfyUI_frontend:src/renderer/extensions/vueNodes/widgets/composables/useIntWidget.ts",
|
||||
"sha256": "68cb754c9c9ba48da2031981d65eca244d66c611314fc5690e96fdb941a0e8ff"
|
||||
},
|
||||
{
|
||||
"id": "ComfyUI_frontend:src/scripts/widgets.ts",
|
||||
"sha256": "e8bb428cbf69635015de43a4ebc89817b3443f876cbed52eeafe67d26f2398d8"
|
||||
},
|
||||
{
|
||||
"id": "ComfyUI_frontend:src/services/litegraphService.ts",
|
||||
"sha256": "ccd4b316a41b6e090716e6243f50135f87b209ff1531a4c3d6e29d99e4392041"
|
||||
},
|
||||
{
|
||||
"id": "ComfyUI_frontend:src/utils/executionUtil.ts",
|
||||
"sha256": "4e51bc54e35cb7ac9bb7cba418a74ccdd5974f640b9b088aa4ae7668f746ab36"
|
||||
},
|
||||
{
|
||||
"id": "ComfyUI_frontend:src/utils/litegraphUtil.ts",
|
||||
"sha256": "816d80ceb6a42abb61090f97172345e53827ab8ba1993817108ec6f8abc61505"
|
||||
},
|
||||
{
|
||||
"id": "ComfyUI_frontend:src/workbench/utils/nodeDefOrderingUtil.ts",
|
||||
"sha256": "27e98379fef3cb7158b2968d1b920ff16db662e4e0c5252ed62c7c7edc6f2227"
|
||||
}
|
||||
],
|
||||
"upstream_code_executed": false,
|
||||
"target_version_match": "unknown"
|
||||
}
|
||||
@@ -0,0 +1,433 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"authority": "public_reference_only_not_object_info",
|
||||
"profile": "comfy-frontend-1.37.11-core-reference",
|
||||
"source_frontend_version": null,
|
||||
"source_frontend_version_basis": "case01未声明;选择case02声明的1.37.11为公开参考,绝不推定case01或真实导出匹配",
|
||||
"core_schema_basis": "case01源节点属性:Canny/LoadImage 0.21.1、ImageStitch 0.17.0;PreviewImage沿用0.21.1参考,目标未知",
|
||||
"scope": "unmodified local scalar widgets; no cloud, remote combo, custom extension, dynamic serializer or array value",
|
||||
"target_version_match": "unknown",
|
||||
"sources": [
|
||||
{
|
||||
"id": "ComfyUI_frontend:LICENSE",
|
||||
"repository": "https://github.com/Comfy-Org/ComfyUI_frontend",
|
||||
"commit": "4bf6a1960028cc5cda57d48f9fb01a74dfaade43",
|
||||
"tag": "v1.37.11",
|
||||
"file": "LICENSE",
|
||||
"lines": [
|
||||
[
|
||||
1,
|
||||
10
|
||||
]
|
||||
],
|
||||
"url": "https://github.com/Comfy-Org/ComfyUI_frontend/blob/4bf6a1960028cc5cda57d48f9fb01a74dfaade43/LICENSE",
|
||||
"raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/4bf6a1960028cc5cda57d48f9fb01a74dfaade43/LICENSE",
|
||||
"sha256": "3972dc9744f6499f0f9b2dbf76696f2ae7ad8af9b23dde66d6af86c9dfb36986",
|
||||
"retrieved_at": "2026-10-29T15:18:59.361315+00:00",
|
||||
"local_file": "LICENSE",
|
||||
"target_version_match": "unknown"
|
||||
},
|
||||
{
|
||||
"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": [
|
||||
[
|
||||
253,
|
||||
277
|
||||
],
|
||||
[
|
||||
832,
|
||||
841
|
||||
]
|
||||
],
|
||||
"url": "https://github.com/Comfy-Org/ComfyUI/blob/63d1bbdb407c69370d407ce5ced6ca3f917528a8/comfy_extras/nodes_images.py",
|
||||
"raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI/63d1bbdb407c69370d407ce5ced6ca3f917528a8/comfy_extras/nodes_images.py",
|
||||
"sha256": "40f22183dcbc9f871030145ca33d52f3dd9d8f64b21ceb071c2fdf6cd49ff501",
|
||||
"retrieved_at": "2026-10-29T15:20:32.983124+00:00",
|
||||
"local_file": "corev0.17.0__comfy_extras__nodes_images.py",
|
||||
"target_version_match": "unknown"
|
||||
},
|
||||
{
|
||||
"id": "ComfyUI:comfy_extras/nodes_canny.py",
|
||||
"repository": "https://github.com/Comfy-Org/ComfyUI",
|
||||
"commit": "26515acd23fa291a8f5ab53c5997258598de0701",
|
||||
"tag": "v0.21.1",
|
||||
"file": "comfy_extras/nodes_canny.py",
|
||||
"lines": [
|
||||
[
|
||||
9,
|
||||
44
|
||||
]
|
||||
],
|
||||
"url": "https://github.com/Comfy-Org/ComfyUI/blob/26515acd23fa291a8f5ab53c5997258598de0701/comfy_extras/nodes_canny.py",
|
||||
"raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI/26515acd23fa291a8f5ab53c5997258598de0701/comfy_extras/nodes_canny.py",
|
||||
"sha256": "c69f945190aaeb02fd3e81bbe21f5bf2dd70395a3bf17cbe8726261739146fff",
|
||||
"retrieved_at": "2026-10-29T15:20:30.921972+00:00",
|
||||
"local_file": "corev0.21.1__comfy_extras__nodes_canny.py",
|
||||
"target_version_match": "unknown"
|
||||
},
|
||||
{
|
||||
"id": "ComfyUI:nodes.py",
|
||||
"repository": "https://github.com/Comfy-Org/ComfyUI",
|
||||
"commit": "26515acd23fa291a8f5ab53c5997258598de0701",
|
||||
"tag": "v0.21.1",
|
||||
"file": "nodes.py",
|
||||
"lines": [
|
||||
[
|
||||
1620,
|
||||
1633
|
||||
],
|
||||
[
|
||||
1665,
|
||||
1697
|
||||
],
|
||||
[
|
||||
2020,
|
||||
2026
|
||||
]
|
||||
],
|
||||
"url": "https://github.com/Comfy-Org/ComfyUI/blob/26515acd23fa291a8f5ab53c5997258598de0701/nodes.py",
|
||||
"raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI/26515acd23fa291a8f5ab53c5997258598de0701/nodes.py",
|
||||
"sha256": "e09534d2c275b2bd389ba7d28677a24d86ce174cdb2419f3d424ff5e50b5d62a",
|
||||
"retrieved_at": "2026-10-29T15:20:30.344472+00:00",
|
||||
"local_file": "corev0.21.1__nodes.py",
|
||||
"target_version_match": "unknown"
|
||||
},
|
||||
{
|
||||
"id": "ComfyUI_frontend:src/extensions/core/dynamicPrompts.ts",
|
||||
"repository": "https://github.com/Comfy-Org/ComfyUI_frontend",
|
||||
"commit": "4bf6a1960028cc5cda57d48f9fb01a74dfaade43",
|
||||
"tag": "v1.37.11",
|
||||
"file": "src/extensions/core/dynamicPrompts.ts",
|
||||
"lines": [
|
||||
[
|
||||
1,
|
||||
30
|
||||
]
|
||||
],
|
||||
"url": "https://github.com/Comfy-Org/ComfyUI_frontend/blob/4bf6a1960028cc5cda57d48f9fb01a74dfaade43/src/extensions/core/dynamicPrompts.ts",
|
||||
"raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/4bf6a1960028cc5cda57d48f9fb01a74dfaade43/src/extensions/core/dynamicPrompts.ts",
|
||||
"sha256": "d190ef52ad9ca6d0351a8e08881773baf1dac49cd2eed71c2cceb20d90838216",
|
||||
"retrieved_at": "2026-10-29T15:18:58.033161+00:00",
|
||||
"local_file": "src__extensions__core__dynamicPrompts.ts",
|
||||
"target_version_match": "unknown"
|
||||
},
|
||||
{
|
||||
"id": "ComfyUI_frontend:src/extensions/core/rerouteNode.ts",
|
||||
"repository": "https://github.com/Comfy-Org/ComfyUI_frontend",
|
||||
"commit": "4bf6a1960028cc5cda57d48f9fb01a74dfaade43",
|
||||
"tag": "v1.37.11",
|
||||
"file": "src/extensions/core/rerouteNode.ts",
|
||||
"lines": [
|
||||
[
|
||||
21,
|
||||
38
|
||||
],
|
||||
[
|
||||
80,
|
||||
113
|
||||
],
|
||||
[
|
||||
280,
|
||||
293
|
||||
]
|
||||
],
|
||||
"url": "https://github.com/Comfy-Org/ComfyUI_frontend/blob/4bf6a1960028cc5cda57d48f9fb01a74dfaade43/src/extensions/core/rerouteNode.ts",
|
||||
"raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/4bf6a1960028cc5cda57d48f9fb01a74dfaade43/src/extensions/core/rerouteNode.ts",
|
||||
"sha256": "53abe69665c97427faa7e41d4d0b9b33c8c1415fff84f582ed51862bdf7bfcd8",
|
||||
"retrieved_at": "2026-10-29T15:12:31.976041+00:00",
|
||||
"local_file": "src__extensions__core__rerouteNode.ts",
|
||||
"target_version_match": "unknown"
|
||||
},
|
||||
{
|
||||
"id": "ComfyUI_frontend:src/extensions/core/uploadImage.ts",
|
||||
"repository": "https://github.com/Comfy-Org/ComfyUI_frontend",
|
||||
"commit": "4bf6a1960028cc5cda57d48f9fb01a74dfaade43",
|
||||
"tag": "v1.37.11",
|
||||
"file": "src/extensions/core/uploadImage.ts",
|
||||
"lines": [
|
||||
[
|
||||
25,
|
||||
53
|
||||
]
|
||||
],
|
||||
"url": "https://github.com/Comfy-Org/ComfyUI_frontend/blob/4bf6a1960028cc5cda57d48f9fb01a74dfaade43/src/extensions/core/uploadImage.ts",
|
||||
"raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/4bf6a1960028cc5cda57d48f9fb01a74dfaade43/src/extensions/core/uploadImage.ts",
|
||||
"sha256": "935687284bebc3bbb49616976ccaf83c31998dd7abba231e5c8eaab0e8aa9e04",
|
||||
"retrieved_at": "2026-10-29T15:12:44.918839+00:00",
|
||||
"local_file": "src__extensions__core__uploadImage.ts",
|
||||
"target_version_match": "unknown"
|
||||
},
|
||||
{
|
||||
"id": "ComfyUI_frontend:src/lib/litegraph/src/LGraphNode.ts",
|
||||
"repository": "https://github.com/Comfy-Org/ComfyUI_frontend",
|
||||
"commit": "4bf6a1960028cc5cda57d48f9fb01a74dfaade43",
|
||||
"tag": "v1.37.11",
|
||||
"file": "src/lib/litegraph/src/LGraphNode.ts",
|
||||
"lines": [
|
||||
[
|
||||
866,
|
||||
875
|
||||
],
|
||||
[
|
||||
913,
|
||||
922
|
||||
]
|
||||
],
|
||||
"url": "https://github.com/Comfy-Org/ComfyUI_frontend/blob/4bf6a1960028cc5cda57d48f9fb01a74dfaade43/src/lib/litegraph/src/LGraphNode.ts",
|
||||
"raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/4bf6a1960028cc5cda57d48f9fb01a74dfaade43/src/lib/litegraph/src/LGraphNode.ts",
|
||||
"sha256": "706225a8a06cd7929f9e04fe2388bcdb8f158cdac756c65c45657c020ab7b319",
|
||||
"retrieved_at": "2026-10-29T15:12:44.050396+00:00",
|
||||
"local_file": "src__lib__litegraph__src__LGraphNode.ts",
|
||||
"target_version_match": "unknown"
|
||||
},
|
||||
{
|
||||
"id": "ComfyUI_frontend:src/lib/litegraph/src/subgraph/ExecutableNodeDTO.ts",
|
||||
"repository": "https://github.com/Comfy-Org/ComfyUI_frontend",
|
||||
"commit": "4bf6a1960028cc5cda57d48f9fb01a74dfaade43",
|
||||
"tag": "v1.37.11",
|
||||
"file": "src/lib/litegraph/src/subgraph/ExecutableNodeDTO.ts",
|
||||
"lines": [
|
||||
[
|
||||
142,
|
||||
170
|
||||
],
|
||||
[
|
||||
220,
|
||||
240
|
||||
],
|
||||
[
|
||||
250,
|
||||
320
|
||||
]
|
||||
],
|
||||
"url": "https://github.com/Comfy-Org/ComfyUI_frontend/blob/4bf6a1960028cc5cda57d48f9fb01a74dfaade43/src/lib/litegraph/src/subgraph/ExecutableNodeDTO.ts",
|
||||
"raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/4bf6a1960028cc5cda57d48f9fb01a74dfaade43/src/lib/litegraph/src/subgraph/ExecutableNodeDTO.ts",
|
||||
"sha256": "fd2e19a6b8f4369e6e97d79f407cc1bec130feec9d6d3c979cc03b0a556f249f",
|
||||
"retrieved_at": "2026-10-29T15:14:28.683258+00:00",
|
||||
"local_file": "src__lib__litegraph__src__subgraph__ExecutableNodeDTO.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": "4bf6a1960028cc5cda57d48f9fb01a74dfaade43",
|
||||
"tag": "v1.37.11",
|
||||
"file": "src/renderer/extensions/vueNodes/widgets/composables/useBooleanWidget.ts",
|
||||
"lines": [
|
||||
[
|
||||
6,
|
||||
31
|
||||
]
|
||||
],
|
||||
"url": "https://github.com/Comfy-Org/ComfyUI_frontend/blob/4bf6a1960028cc5cda57d48f9fb01a74dfaade43/src/renderer/extensions/vueNodes/widgets/composables/useBooleanWidget.ts",
|
||||
"raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/4bf6a1960028cc5cda57d48f9fb01a74dfaade43/src/renderer/extensions/vueNodes/widgets/composables/useBooleanWidget.ts",
|
||||
"sha256": "36f477f75561e0c7bfc2c6757906724f8ff2c8660ace26759f3f07493877fece",
|
||||
"retrieved_at": "2026-10-29T15:13:55.060959+00:00",
|
||||
"local_file": "src__renderer__extensions__vueNodes__widgets__composables__useBooleanWidget.ts",
|
||||
"target_version_match": "unknown"
|
||||
},
|
||||
{
|
||||
"id": "ComfyUI_frontend:src/renderer/extensions/vueNodes/widgets/composables/useComboWidget.ts",
|
||||
"repository": "https://github.com/Comfy-Org/ComfyUI_frontend",
|
||||
"commit": "4bf6a1960028cc5cda57d48f9fb01a74dfaade43",
|
||||
"tag": "v1.37.11",
|
||||
"file": "src/renderer/extensions/vueNodes/widgets/composables/useComboWidget.ts",
|
||||
"lines": [
|
||||
[
|
||||
215,
|
||||
252
|
||||
],
|
||||
[
|
||||
291,
|
||||
305
|
||||
]
|
||||
],
|
||||
"url": "https://github.com/Comfy-Org/ComfyUI_frontend/blob/4bf6a1960028cc5cda57d48f9fb01a74dfaade43/src/renderer/extensions/vueNodes/widgets/composables/useComboWidget.ts",
|
||||
"raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/4bf6a1960028cc5cda57d48f9fb01a74dfaade43/src/renderer/extensions/vueNodes/widgets/composables/useComboWidget.ts",
|
||||
"sha256": "578955db305e760d317b394d0c155caa6aa1e60a235a076e14aadadbd25222d4",
|
||||
"retrieved_at": "2026-10-29T15:13:53.606321+00:00",
|
||||
"local_file": "src__renderer__extensions__vueNodes__widgets__composables__useComboWidget.ts",
|
||||
"target_version_match": "unknown"
|
||||
},
|
||||
{
|
||||
"id": "ComfyUI_frontend:src/renderer/extensions/vueNodes/widgets/composables/useFloatWidget.ts",
|
||||
"repository": "https://github.com/Comfy-Org/ComfyUI_frontend",
|
||||
"commit": "4bf6a1960028cc5cda57d48f9fb01a74dfaade43",
|
||||
"tag": "v1.37.11",
|
||||
"file": "src/renderer/extensions/vueNodes/widgets/composables/useFloatWidget.ts",
|
||||
"lines": [
|
||||
[
|
||||
58,
|
||||
95
|
||||
]
|
||||
],
|
||||
"url": "https://github.com/Comfy-Org/ComfyUI_frontend/blob/4bf6a1960028cc5cda57d48f9fb01a74dfaade43/src/renderer/extensions/vueNodes/widgets/composables/useFloatWidget.ts",
|
||||
"raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/4bf6a1960028cc5cda57d48f9fb01a74dfaade43/src/renderer/extensions/vueNodes/widgets/composables/useFloatWidget.ts",
|
||||
"sha256": "a6536de10db2ee4dca8f858f1b2ee68077e9313393e3657e9c22a49c408629e5",
|
||||
"retrieved_at": "2026-10-29T15:13:50.435623+00:00",
|
||||
"local_file": "src__renderer__extensions__vueNodes__widgets__composables__useFloatWidget.ts",
|
||||
"target_version_match": "unknown"
|
||||
},
|
||||
{
|
||||
"id": "ComfyUI_frontend:src/renderer/extensions/vueNodes/widgets/composables/useImageUploadWidget.ts",
|
||||
"repository": "https://github.com/Comfy-Org/ComfyUI_frontend",
|
||||
"commit": "4bf6a1960028cc5cda57d48f9fb01a74dfaade43",
|
||||
"tag": "v1.37.11",
|
||||
"file": "src/renderer/extensions/vueNodes/widgets/composables/useImageUploadWidget.ts",
|
||||
"lines": [
|
||||
[
|
||||
35,
|
||||
80
|
||||
],
|
||||
[
|
||||
104,
|
||||
120
|
||||
]
|
||||
],
|
||||
"url": "https://github.com/Comfy-Org/ComfyUI_frontend/blob/4bf6a1960028cc5cda57d48f9fb01a74dfaade43/src/renderer/extensions/vueNodes/widgets/composables/useImageUploadWidget.ts",
|
||||
"raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/4bf6a1960028cc5cda57d48f9fb01a74dfaade43/src/renderer/extensions/vueNodes/widgets/composables/useImageUploadWidget.ts",
|
||||
"sha256": "77d0603c9cb4397cdb33bcbee5721a3690b63f28e82eb11e79a356f0306e149d",
|
||||
"retrieved_at": "2026-10-29T15:13:49.563730+00:00",
|
||||
"local_file": "src__renderer__extensions__vueNodes__widgets__composables__useImageUploadWidget.ts",
|
||||
"target_version_match": "unknown"
|
||||
},
|
||||
{
|
||||
"id": "ComfyUI_frontend:src/renderer/extensions/vueNodes/widgets/composables/useIntWidget.ts",
|
||||
"repository": "https://github.com/Comfy-Org/ComfyUI_frontend",
|
||||
"commit": "4bf6a1960028cc5cda57d48f9fb01a74dfaade43",
|
||||
"tag": "v1.37.11",
|
||||
"file": "src/renderer/extensions/vueNodes/widgets/composables/useIntWidget.ts",
|
||||
"lines": [
|
||||
[
|
||||
45,
|
||||
89
|
||||
]
|
||||
],
|
||||
"url": "https://github.com/Comfy-Org/ComfyUI_frontend/blob/4bf6a1960028cc5cda57d48f9fb01a74dfaade43/src/renderer/extensions/vueNodes/widgets/composables/useIntWidget.ts",
|
||||
"raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/4bf6a1960028cc5cda57d48f9fb01a74dfaade43/src/renderer/extensions/vueNodes/widgets/composables/useIntWidget.ts",
|
||||
"sha256": "68cb754c9c9ba48da2031981d65eca244d66c611314fc5690e96fdb941a0e8ff",
|
||||
"retrieved_at": "2026-10-29T15:13:52.076416+00:00",
|
||||
"local_file": "src__renderer__extensions__vueNodes__widgets__composables__useIntWidget.ts",
|
||||
"target_version_match": "unknown"
|
||||
},
|
||||
{
|
||||
"id": "ComfyUI_frontend:src/scripts/widgets.ts",
|
||||
"repository": "https://github.com/Comfy-Org/ComfyUI_frontend",
|
||||
"commit": "4bf6a1960028cc5cda57d48f9fb01a74dfaade43",
|
||||
"tag": "v1.37.11",
|
||||
"file": "src/scripts/widgets.ts",
|
||||
"lines": [
|
||||
[
|
||||
80,
|
||||
91
|
||||
],
|
||||
[
|
||||
126,
|
||||
161
|
||||
],
|
||||
[
|
||||
283,
|
||||
305
|
||||
]
|
||||
],
|
||||
"url": "https://github.com/Comfy-Org/ComfyUI_frontend/blob/4bf6a1960028cc5cda57d48f9fb01a74dfaade43/src/scripts/widgets.ts",
|
||||
"raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/4bf6a1960028cc5cda57d48f9fb01a74dfaade43/src/scripts/widgets.ts",
|
||||
"sha256": "e8bb428cbf69635015de43a4ebc89817b3443f876cbed52eeafe67d26f2398d8",
|
||||
"retrieved_at": "2026-10-29T15:12:34.877619+00:00",
|
||||
"local_file": "src__scripts__widgets.ts",
|
||||
"target_version_match": "unknown"
|
||||
},
|
||||
{
|
||||
"id": "ComfyUI_frontend:src/services/litegraphService.ts",
|
||||
"repository": "https://github.com/Comfy-Org/ComfyUI_frontend",
|
||||
"commit": "4bf6a1960028cc5cda57d48f9fb01a74dfaade43",
|
||||
"tag": "v1.37.11",
|
||||
"file": "src/services/litegraphService.ts",
|
||||
"lines": [
|
||||
[
|
||||
90,
|
||||
106
|
||||
],
|
||||
[
|
||||
144,
|
||||
195
|
||||
],
|
||||
[
|
||||
202,
|
||||
212
|
||||
],
|
||||
[
|
||||
350,
|
||||
367
|
||||
]
|
||||
],
|
||||
"url": "https://github.com/Comfy-Org/ComfyUI_frontend/blob/4bf6a1960028cc5cda57d48f9fb01a74dfaade43/src/services/litegraphService.ts",
|
||||
"raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/4bf6a1960028cc5cda57d48f9fb01a74dfaade43/src/services/litegraphService.ts",
|
||||
"sha256": "ccd4b316a41b6e090716e6243f50135f87b209ff1531a4c3d6e29d99e4392041",
|
||||
"retrieved_at": "2026-10-29T15:13:48.652249+00:00",
|
||||
"local_file": "src__services__litegraphService.ts",
|
||||
"target_version_match": "unknown"
|
||||
},
|
||||
{
|
||||
"id": "ComfyUI_frontend:src/utils/executionUtil.ts",
|
||||
"repository": "https://github.com/Comfy-Org/ComfyUI_frontend",
|
||||
"commit": "4bf6a1960028cc5cda57d48f9fb01a74dfaade43",
|
||||
"tag": "v1.37.11",
|
||||
"file": "src/utils/executionUtil.ts",
|
||||
"lines": [
|
||||
[
|
||||
74,
|
||||
145
|
||||
]
|
||||
],
|
||||
"url": "https://github.com/Comfy-Org/ComfyUI_frontend/blob/4bf6a1960028cc5cda57d48f9fb01a74dfaade43/src/utils/executionUtil.ts",
|
||||
"raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/4bf6a1960028cc5cda57d48f9fb01a74dfaade43/src/utils/executionUtil.ts",
|
||||
"sha256": "4e51bc54e35cb7ac9bb7cba418a74ccdd5974f640b9b088aa4ae7668f746ab36",
|
||||
"retrieved_at": "2026-10-29T15:12:29.674745+00:00",
|
||||
"local_file": "src__utils__executionUtil.ts",
|
||||
"target_version_match": "unknown"
|
||||
},
|
||||
{
|
||||
"id": "ComfyUI_frontend:src/utils/litegraphUtil.ts",
|
||||
"repository": "https://github.com/Comfy-Org/ComfyUI_frontend",
|
||||
"commit": "4bf6a1960028cc5cda57d48f9fb01a74dfaade43",
|
||||
"tag": "v1.37.11",
|
||||
"file": "src/utils/litegraphUtil.ts",
|
||||
"lines": [
|
||||
[
|
||||
95,
|
||||
137
|
||||
]
|
||||
],
|
||||
"url": "https://github.com/Comfy-Org/ComfyUI_frontend/blob/4bf6a1960028cc5cda57d48f9fb01a74dfaade43/src/utils/litegraphUtil.ts",
|
||||
"raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/4bf6a1960028cc5cda57d48f9fb01a74dfaade43/src/utils/litegraphUtil.ts",
|
||||
"sha256": "816d80ceb6a42abb61090f97172345e53827ab8ba1993817108ec6f8abc61505",
|
||||
"retrieved_at": "2026-10-29T15:18:57.413086+00:00",
|
||||
"local_file": "src__utils__litegraphUtil.ts",
|
||||
"target_version_match": "unknown"
|
||||
},
|
||||
{
|
||||
"id": "ComfyUI_frontend:src/workbench/utils/nodeDefOrderingUtil.ts",
|
||||
"repository": "https://github.com/Comfy-Org/ComfyUI_frontend",
|
||||
"commit": "4bf6a1960028cc5cda57d48f9fb01a74dfaade43",
|
||||
"tag": "v1.37.11",
|
||||
"file": "src/workbench/utils/nodeDefOrderingUtil.ts",
|
||||
"lines": [
|
||||
[
|
||||
14,
|
||||
60
|
||||
]
|
||||
],
|
||||
"url": "https://github.com/Comfy-Org/ComfyUI_frontend/blob/4bf6a1960028cc5cda57d48f9fb01a74dfaade43/src/workbench/utils/nodeDefOrderingUtil.ts",
|
||||
"raw_url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/4bf6a1960028cc5cda57d48f9fb01a74dfaade43/src/workbench/utils/nodeDefOrderingUtil.ts",
|
||||
"sha256": "27e98379fef3cb7158b2968d1b920ff16db662e4e0c5252ed62c7c7edc6f2227",
|
||||
"retrieved_at": "2026-10-29T15:15:05.285092+00:00",
|
||||
"local_file": "src__workbench__utils__nodeDefOrderingUtil.ts",
|
||||
"target_version_match": "unknown"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
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) {
|
||||
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,295 @@
|
||||
import type { IContextMenuValue } from '@/lib/litegraph/src/litegraph'
|
||||
import {
|
||||
LGraphCanvas,
|
||||
LGraphNode,
|
||||
LiteGraph
|
||||
} from '@/lib/litegraph/src/litegraph'
|
||||
import type { ISlotType } from '@/lib/litegraph/src/interfaces'
|
||||
|
||||
import { app } from '../../scripts/app'
|
||||
import { getWidgetConfig, mergeIfValid, setWidgetConfig } from './widgetInputs'
|
||||
|
||||
// Node that allows you to redirect connections for cleaner graphs
|
||||
|
||||
app.registerExtension({
|
||||
name: 'Comfy.RerouteNode',
|
||||
registerCustomNodes(app) {
|
||||
interface RerouteNode extends LGraphNode {
|
||||
__outputType?: string | number
|
||||
}
|
||||
|
||||
class RerouteNode extends LGraphNode {
|
||||
static override category: string | undefined
|
||||
static defaultVisibility = false
|
||||
|
||||
constructor(title?: string) {
|
||||
super(title ?? '')
|
||||
if (!this.properties) {
|
||||
this.properties = {}
|
||||
}
|
||||
this.properties.showOutputText = RerouteNode.defaultVisibility
|
||||
this.properties.horizontal = false
|
||||
|
||||
this.addInput('', '*')
|
||||
this.addOutput(this.properties.showOutputText ? '*' : '', '*')
|
||||
|
||||
// This node is purely frontend and does not impact the resulting prompt so should not be serialized
|
||||
this.isVirtualNode = true
|
||||
}
|
||||
override onAfterGraphConfigured() {
|
||||
requestAnimationFrame(() => {
|
||||
this.onConnectionsChange(LiteGraph.INPUT, undefined, true)
|
||||
})
|
||||
}
|
||||
override clone(): LGraphNode | null {
|
||||
const cloned = super.clone()
|
||||
if (!cloned) return cloned
|
||||
cloned.removeOutput(0)
|
||||
cloned.addOutput(this.properties.showOutputText ? '*' : '', '*')
|
||||
cloned.setSize(cloned.computeSize())
|
||||
return cloned
|
||||
}
|
||||
override onConnectionsChange(
|
||||
type: ISlotType,
|
||||
_index: number | undefined,
|
||||
connected: boolean
|
||||
) {
|
||||
const { graph } = this
|
||||
if (!graph) return
|
||||
if (app.configuringGraph) return
|
||||
|
||||
// Prevent multiple connections to different types when we have no input
|
||||
if (connected && type === LiteGraph.OUTPUT) {
|
||||
// Ignore wildcard nodes as these will be updated to real types
|
||||
const types = new Set(
|
||||
this.outputs[0].links
|
||||
?.map((l) => graph.links[l]?.type)
|
||||
?.filter((t) => t && t !== '*') ?? []
|
||||
)
|
||||
if (types.size > 1) {
|
||||
const linksToDisconnect = []
|
||||
for (const linkId of this.outputs[0].links ?? []) {
|
||||
const link = graph.links[linkId]
|
||||
linksToDisconnect.push(link)
|
||||
}
|
||||
linksToDisconnect.pop()
|
||||
for (const link of linksToDisconnect) {
|
||||
const node = graph.getNodeById(link.target_id)
|
||||
node?.disconnectInput(link.target_slot)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Find root input
|
||||
let currentNode: RerouteNode | null = this
|
||||
let updateNodes: RerouteNode[] = []
|
||||
let inputType = null
|
||||
let inputNode = null
|
||||
while (currentNode) {
|
||||
updateNodes.unshift(currentNode)
|
||||
const linkId = currentNode.inputs[0].link
|
||||
if (linkId !== null) {
|
||||
const link = graph.links[linkId]
|
||||
if (!link) return
|
||||
const node = graph.getNodeById(link.origin_id)
|
||||
if (!node) return
|
||||
if (node instanceof RerouteNode) {
|
||||
if (node === this) {
|
||||
// We've found a circle
|
||||
currentNode.disconnectInput(link.target_slot)
|
||||
currentNode = null
|
||||
} else {
|
||||
// Move the previous node
|
||||
currentNode = node
|
||||
}
|
||||
} else {
|
||||
// We've found the end
|
||||
inputNode = currentNode
|
||||
inputType = node.outputs[link.origin_slot]?.type ?? null
|
||||
break
|
||||
}
|
||||
} else {
|
||||
// This path has no input node
|
||||
currentNode = null
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// Find all outputs
|
||||
const nodes: RerouteNode[] = [this]
|
||||
let outputType = null
|
||||
while (nodes.length) {
|
||||
currentNode = nodes.pop()!
|
||||
const outputs = currentNode.outputs?.[0]?.links ?? []
|
||||
for (const linkId of outputs) {
|
||||
const link = graph.links[linkId]
|
||||
|
||||
// When disconnecting sometimes the link is still registered
|
||||
if (!link) continue
|
||||
|
||||
const node = graph.getNodeById(link.target_id)
|
||||
if (!node) continue
|
||||
if (node instanceof RerouteNode) {
|
||||
// Follow reroute nodes
|
||||
nodes.push(node)
|
||||
updateNodes.push(node)
|
||||
} else {
|
||||
// We've found an output
|
||||
const nodeInput = node.inputs[link.target_slot]
|
||||
const nodeOutType = nodeInput.type
|
||||
const keep =
|
||||
!inputType ||
|
||||
!nodeOutType ||
|
||||
LiteGraph.isValidConnection(inputType, nodeOutType)
|
||||
if (!keep) {
|
||||
// The output doesnt match our input so disconnect it
|
||||
node.disconnectInput(link.target_slot)
|
||||
continue
|
||||
}
|
||||
node.onConnectionsChange?.(
|
||||
LiteGraph.INPUT,
|
||||
link.target_slot,
|
||||
keep,
|
||||
link,
|
||||
nodeInput
|
||||
)
|
||||
outputType = node.inputs[link.target_slot].type
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const displayType = inputType || outputType || '*'
|
||||
const color = LGraphCanvas.link_type_colors[displayType]
|
||||
|
||||
let widgetConfig
|
||||
let widgetType
|
||||
// Update the types of each node
|
||||
for (const node of updateNodes) {
|
||||
// If we dont have an input type we are always wildcard but we'll show the output type
|
||||
// This lets you change the output link to a different type and all nodes will update
|
||||
node.outputs[0].type = inputType || '*'
|
||||
node.__outputType = displayType
|
||||
node.outputs[0].name = node.properties.showOutputText
|
||||
? `${displayType}`
|
||||
: ''
|
||||
node.setSize(node.computeSize())
|
||||
|
||||
for (const l of node.outputs[0].links || []) {
|
||||
const link = graph.links[l]
|
||||
if (!link) continue
|
||||
link.color = color
|
||||
|
||||
if (app.configuringGraph) continue
|
||||
const targetNode = graph.getNodeById(link.target_id)
|
||||
if (!targetNode) continue
|
||||
const targetInput = targetNode.inputs?.[link.target_slot]
|
||||
if (targetInput?.widget) {
|
||||
const config = getWidgetConfig(targetInput)
|
||||
if (!widgetConfig) {
|
||||
widgetConfig = config[1] ?? {}
|
||||
widgetType = config[0]
|
||||
}
|
||||
|
||||
const merged = mergeIfValid(targetInput, [
|
||||
config[0],
|
||||
widgetConfig
|
||||
])
|
||||
if (merged.customConfig) {
|
||||
widgetConfig = merged.customConfig
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (const node of updateNodes) {
|
||||
if (widgetConfig && outputType) {
|
||||
node.inputs[0].widget = { name: 'value' }
|
||||
setWidgetConfig(node.inputs[0], [
|
||||
widgetType ?? `${displayType}`,
|
||||
widgetConfig
|
||||
])
|
||||
} else {
|
||||
setWidgetConfig(node.inputs[0], undefined)
|
||||
}
|
||||
}
|
||||
|
||||
if (inputNode?.inputs?.[0]?.link) {
|
||||
const link = graph.links[inputNode.inputs[0].link]
|
||||
if (link) {
|
||||
link.color = color
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override getExtraMenuOptions(
|
||||
_: unknown,
|
||||
options: (IContextMenuValue | null)[]
|
||||
): IContextMenuValue[] {
|
||||
options.unshift(
|
||||
{
|
||||
content:
|
||||
(this.properties.showOutputText ? 'Hide' : 'Show') + ' Type',
|
||||
callback: () => {
|
||||
this.properties.showOutputText = !this.properties.showOutputText
|
||||
if (this.properties.showOutputText) {
|
||||
this.outputs[0].name = `${this.__outputType || this.outputs[0].type}`
|
||||
} else {
|
||||
this.outputs[0].name = ''
|
||||
}
|
||||
this.setSize(this.computeSize())
|
||||
app.canvas.setDirty(true, true)
|
||||
}
|
||||
},
|
||||
{
|
||||
content:
|
||||
(RerouteNode.defaultVisibility ? 'Hide' : 'Show') +
|
||||
' Type By Default',
|
||||
callback: () => {
|
||||
RerouteNode.setDefaultTextVisibility(
|
||||
!RerouteNode.defaultVisibility
|
||||
)
|
||||
}
|
||||
}
|
||||
)
|
||||
return []
|
||||
}
|
||||
override computeSize(): [number, number] {
|
||||
return [
|
||||
this.properties.showOutputText && this.outputs && this.outputs.length
|
||||
? Math.max(
|
||||
75,
|
||||
LiteGraph.NODE_TEXT_SIZE * this.outputs[0].name.length * 0.6 +
|
||||
40
|
||||
)
|
||||
: 75,
|
||||
26
|
||||
]
|
||||
}
|
||||
|
||||
static setDefaultTextVisibility(visible: boolean) {
|
||||
RerouteNode.defaultVisibility = visible
|
||||
if (visible) {
|
||||
localStorage['Comfy.RerouteNode.DefaultVisibility'] = 'true'
|
||||
} else {
|
||||
delete localStorage['Comfy.RerouteNode.DefaultVisibility']
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Load default visibility
|
||||
RerouteNode.setDefaultTextVisibility(
|
||||
!!localStorage['Comfy.RerouteNode.DefaultVisibility']
|
||||
)
|
||||
|
||||
LiteGraph.registerNodeType(
|
||||
'Reroute',
|
||||
Object.assign(RerouteNode, {
|
||||
title_mode: LiteGraph.NO_TITLE,
|
||||
title: 'Reroute',
|
||||
collapsable: false
|
||||
})
|
||||
)
|
||||
|
||||
RerouteNode.category = 'utils'
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,53 @@
|
||||
import {
|
||||
type ComfyNodeDef,
|
||||
type InputSpec,
|
||||
isComboInputSpecV1
|
||||
} from '@/schemas/nodeDefSchema'
|
||||
|
||||
import { app } from '../../scripts/app'
|
||||
|
||||
// Adds an upload button to the nodes
|
||||
|
||||
const isMediaUploadComboInput = (inputSpec: InputSpec) => {
|
||||
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')
|
||||
)
|
||||
}
|
||||
|
||||
const createUploadInput = (
|
||||
imageInputName: string,
|
||||
imageInputOptions: InputSpec
|
||||
): InputSpec => [
|
||||
'IMAGEUPLOAD',
|
||||
{
|
||||
...imageInputOptions[1],
|
||||
imageInputName
|
||||
}
|
||||
]
|
||||
|
||||
app.registerExtension({
|
||||
name: 'Comfy.UploadImage',
|
||||
beforeRegisterNodeDef(_nodeType, 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)
|
||||
}
|
||||
}
|
||||
})
|
||||
File diff suppressed because it is too large
Load Diff
+408
@@ -0,0 +1,408 @@
|
||||
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 {
|
||||
CallbackParams,
|
||||
CallbackReturn,
|
||||
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: CallbackParams<typeof this.node.applyToGraph>
|
||||
): CallbackReturn<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}. */
|
||||
#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 }
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
|
||||
// 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`.
|
||||
*/
|
||||
#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.
|
||||
*/
|
||||
#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
|
||||
}
|
||||
+305
@@ -0,0 +1,305 @@
|
||||
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 { isAssetWidget, isComboWidget } from '@/lib/litegraph/src/litegraph'
|
||||
import type { IBaseWidget } from '@/lib/litegraph/src/types/widgets'
|
||||
import { useAssetBrowserDialog } from '@/platform/assets/composables/useAssetBrowserDialog'
|
||||
import {
|
||||
assetFilenameSchema,
|
||||
assetItemSchema
|
||||
} from '@/platform/assets/schemas/assetSchema'
|
||||
import { assetService } from '@/platform/assets/services/assetService'
|
||||
import { isCloud } from '@/platform/distribution/types'
|
||||
import { useSettingStore } from '@/platform/settings/settingStore'
|
||||
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) {
|
||||
widget.linkedWidgets = addValueControlWidgets(
|
||||
node,
|
||||
widget,
|
||||
'fixed',
|
||||
undefined,
|
||||
transformInputSpecV2ToV1(inputSpec)
|
||||
)
|
||||
}
|
||||
|
||||
return widget
|
||||
}
|
||||
|
||||
const createAssetBrowserWidget = (
|
||||
node: LGraphNode,
|
||||
inputSpec: ComboInputSpec,
|
||||
defaultValue: string | undefined
|
||||
): IBaseWidget => {
|
||||
const currentValue = defaultValue
|
||||
const displayLabel = currentValue ?? t('widgets.selectModel')
|
||||
const assetBrowserDialog = useAssetBrowserDialog()
|
||||
|
||||
const widget = node.addWidget(
|
||||
'asset',
|
||||
inputSpec.name,
|
||||
displayLabel,
|
||||
async function (this: IBaseWidget) {
|
||||
if (!isAssetWidget(widget)) {
|
||||
throw new Error(`Expected asset widget but received ${widget.type}`)
|
||||
}
|
||||
await assetBrowserDialog.show({
|
||||
nodeType: node.comfyClass || '',
|
||||
inputName: inputSpec.name,
|
||||
currentValue: widget.value,
|
||||
onAssetSelected: (asset) => {
|
||||
const validatedAsset = assetItemSchema.safeParse(asset)
|
||||
|
||||
if (!validatedAsset.success) {
|
||||
console.error(
|
||||
'Invalid asset item:',
|
||||
validatedAsset.error.errors,
|
||||
'Received:',
|
||||
asset
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
const filename = validatedAsset.data.user_metadata?.filename
|
||||
const validatedFilename = assetFilenameSchema.safeParse(filename)
|
||||
|
||||
if (!validatedFilename.success) {
|
||||
console.error(
|
||||
'Invalid asset filename:',
|
||||
validatedFilename.error.errors,
|
||||
'for asset:',
|
||||
validatedAsset.data.id
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
const oldValue = widget.value
|
||||
this.value = validatedFilename.data
|
||||
node.onWidgetChanged?.(
|
||||
widget.name,
|
||||
validatedFilename.data,
|
||||
oldValue,
|
||||
widget
|
||||
)
|
||||
}
|
||||
})
|
||||
}
|
||||
)
|
||||
|
||||
return 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}`)
|
||||
}
|
||||
widget.linkedWidgets = addValueControlWidgets(
|
||||
node,
|
||||
widget,
|
||||
undefined,
|
||||
undefined,
|
||||
transformInputSpecV2ToV1(inputSpec)
|
||||
)
|
||||
}
|
||||
|
||||
return widget
|
||||
}
|
||||
|
||||
const addComboWidget = (
|
||||
node: LGraphNode,
|
||||
inputSpec: ComboInputSpec
|
||||
): IBaseWidget => {
|
||||
const defaultValue = getDefaultValue(inputSpec)
|
||||
|
||||
if (isCloud) {
|
||||
const settingStore = useSettingStore()
|
||||
const isUsingAssetAPI = settingStore.get('Comfy.Assets.UseAssetAPI')
|
||||
const isEligible = assetService.isAssetBrowserEligible(
|
||||
node.comfyClass,
|
||||
inputSpec.name
|
||||
)
|
||||
|
||||
if (isUsingAssetAPI && isEligible) {
|
||||
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}`)
|
||||
}
|
||||
|
||||
widget.linkedWidgets = addValueControlWidgets(
|
||||
node,
|
||||
widget,
|
||||
undefined,
|
||||
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
|
||||
}
|
||||
+95
@@ -0,0 +1,95 @@
|
||||
import { clamp } from 'es-toolkit/compat'
|
||||
|
||||
import type { LGraphNode } from '@/lib/litegraph/src/litegraph'
|
||||
import type { INumericWidget } from '@/lib/litegraph/src/types/widgets'
|
||||
import { useSettingStore } from '@/platform/settings/settingStore'
|
||||
import { isFloatInputSpec } from '@/schemas/nodeDef/nodeDefSchemaV2'
|
||||
import type { InputSpec } from '@/schemas/nodeDef/nodeDefSchemaV2'
|
||||
import type { ComfyWidgetConstructorV2 } from '@/scripts/widgets'
|
||||
import { addValueControlWidget } from '@/scripts/widgets'
|
||||
import { transformInputSpecV2ToV1 } from '@/schemas/nodeDef/migration'
|
||||
|
||||
function onFloatValueChange(this: INumericWidget, v: number) {
|
||||
const round = this.options.round
|
||||
if (round) {
|
||||
const precision =
|
||||
this.options.precision ?? Math.max(0, -Math.floor(Math.log10(round)))
|
||||
const rounded = Math.round(v / round) * round
|
||||
this.value = clamp(
|
||||
Number(rounded.toFixed(precision)),
|
||||
this.options.min ?? -Infinity,
|
||||
this.options.max ?? Infinity
|
||||
)
|
||||
} else {
|
||||
this.value = v
|
||||
}
|
||||
}
|
||||
|
||||
export const _for_testing = {
|
||||
onFloatValueChange
|
||||
}
|
||||
|
||||
export const useFloatWidget = () => {
|
||||
const widgetConstructor: ComfyWidgetConstructorV2 = (
|
||||
node: LGraphNode,
|
||||
inputSpec: InputSpec
|
||||
) => {
|
||||
if (!isFloatInputSpec(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 ?? 0.5
|
||||
const precision =
|
||||
settingStore.get('Comfy.FloatRoundingPrecision') ||
|
||||
Math.max(0, -Math.floor(Math.log10(step)))
|
||||
const enableRounding = !settingStore.get('Comfy.DisableFloatRounding')
|
||||
|
||||
/** Assertion {@link inputSpec.default} */
|
||||
const defaultValue = (inputSpec.default as number | undefined) ?? 0
|
||||
const widget = node.addWidget(
|
||||
widgetType,
|
||||
inputSpec.name,
|
||||
defaultValue,
|
||||
onFloatValueChange,
|
||||
{
|
||||
min: inputSpec.min ?? 0,
|
||||
max: inputSpec.max ?? 2048,
|
||||
round:
|
||||
enableRounding && precision && !inputSpec.round
|
||||
? Math.pow(10, -precision)
|
||||
: (inputSpec.round as number),
|
||||
/** @deprecated Use step2 instead. The 10x value is a legacy implementation. */
|
||||
step: step * 10.0,
|
||||
step2: step,
|
||||
precision
|
||||
}
|
||||
)
|
||||
|
||||
if (inputSpec.control_after_generate) {
|
||||
const controlWidget = addValueControlWidget(
|
||||
node,
|
||||
widget,
|
||||
'fixed',
|
||||
undefined,
|
||||
undefined,
|
||||
transformInputSpecV2ToV1(inputSpec)
|
||||
)
|
||||
widget.linkedWidgets = [controlWidget]
|
||||
}
|
||||
|
||||
return widget
|
||||
}
|
||||
|
||||
return widgetConstructor
|
||||
}
|
||||
+126
@@ -0,0 +1,126 @@
|
||||
import { useNodeImage, useNodeVideo } from '@/composables/node/useNodeImage'
|
||||
import { useNodeImageUpload } from '@/composables/node/useNodeImageUpload'
|
||||
import { useValueTransform } from '@/composables/useValueTransform'
|
||||
import { t } from '@/i18n'
|
||||
import type { LGraphNode } from '@/lib/litegraph/src/litegraph'
|
||||
import type { IComboWidget } from '@/lib/litegraph/src/types/widgets'
|
||||
import type { ResultItem, ResultItemType } from '@/schemas/apiSchema'
|
||||
import type { InputSpec } from '@/schemas/nodeDefSchema'
|
||||
import type { ComfyWidgetConstructor } from '@/scripts/widgets'
|
||||
import { useNodeOutputStore } from '@/stores/imagePreviewStore'
|
||||
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'
|
||||
|
||||
type InternalFile = string | ResultItem
|
||||
type InternalValue = InternalFile | InternalFile[]
|
||||
type ExposedValue = string | string[]
|
||||
|
||||
const isImageFile = (file: File) => file.type.startsWith('image/')
|
||||
const isVideoFile = (file: File) => file.type.startsWith('video/')
|
||||
|
||||
const findFileComboWidget = (node: LGraphNode, inputName: string) =>
|
||||
node.widgets!.find((w) => w.name === inputName) as IComboWidget & {
|
||||
value: ExposedValue
|
||||
}
|
||||
|
||||
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)
|
||||
const initialFile = `${fileComboWidget.value}`
|
||||
const formatPath = (value: InternalFile) =>
|
||||
createAnnotatedPath(value, { rootFolder: image_folder })
|
||||
|
||||
const transform = (internalValue: InternalValue): ExposedValue => {
|
||||
if (!internalValue) return initialFile
|
||||
if (Array.isArray(internalValue))
|
||||
return allow_batch
|
||||
? internalValue.map(formatPath)
|
||||
: formatPath(internalValue[0])
|
||||
return formatPath(internalValue)
|
||||
}
|
||||
|
||||
Object.defineProperty(
|
||||
fileComboWidget,
|
||||
'value',
|
||||
useValueTransform(transform, initialFile)
|
||||
)
|
||||
|
||||
// Setup file upload handling
|
||||
const { openFileSelection } = useNodeImageUpload(node, {
|
||||
allow_batch,
|
||||
fileFilter,
|
||||
accept,
|
||||
folder,
|
||||
onUploadComplete: (output) => {
|
||||
output.forEach((path) => addToComboValues(fileComboWidget, path))
|
||||
|
||||
// Create a NEW array to ensure Vue reactivity detects the change
|
||||
const newValue = allow_batch ? [...output] : output[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 () {
|
||||
nodeOutputStore.setNodeOutputs(node, 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, fileComboWidget.value, {
|
||||
isAnimated
|
||||
})
|
||||
showPreview({ block: false })
|
||||
})
|
||||
|
||||
return { widget: uploadWidget }
|
||||
}
|
||||
|
||||
return widgetConstructor
|
||||
}
|
||||
+89
@@ -0,0 +1,89 @@
|
||||
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 controlWidget = addValueControlWidget(
|
||||
node,
|
||||
widget,
|
||||
'randomize',
|
||||
undefined,
|
||||
undefined,
|
||||
transformInputSpecV2ToV1(inputSpec)
|
||||
)
|
||||
widget.linkedWidgets = [controlWidget]
|
||||
}
|
||||
|
||||
return widget
|
||||
}
|
||||
return widgetConstructor
|
||||
}
|
||||
@@ -0,0 +1,308 @@
|
||||
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 { 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 { 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)
|
||||
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'."
|
||||
|
||||
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 = () => {
|
||||
if (controlValueRunBefore()) {
|
||||
// Don't run on first execution
|
||||
if (valueControl[HAS_EXECUTED]) {
|
||||
applyWidgetControl()
|
||||
}
|
||||
}
|
||||
valueControl[HAS_EXECUTED] = true
|
||||
}
|
||||
|
||||
valueControl.afterQueued = () => {
|
||||
if (!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()),
|
||||
CHART: transformWidgetConstructorV2ToV1(useChartWidget()),
|
||||
GALLERIA: transformWidgetConstructorV2ToV1(useGalleriaWidget()),
|
||||
TEXTAREA: transformWidgetConstructorV2ToV1(useTextareaWidget()),
|
||||
...dynamicWidgets
|
||||
} as const
|
||||
|
||||
export function isValidWidgetType(
|
||||
key: unknown
|
||||
): key is keyof typeof ComfyWidgets {
|
||||
return ComfyWidgets[key as keyof typeof ComfyWidgets] !== undefined
|
||||
}
|
||||
@@ -0,0 +1,913 @@
|
||||
import _ from 'es-toolkit/compat'
|
||||
|
||||
import { downloadFile } 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 } from '@/core/graph/subgraph/proxyWidgetUtils'
|
||||
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 {
|
||||
IContextMenuValue,
|
||||
Point,
|
||||
Subgraph
|
||||
} from '@/lib/litegraph/src/litegraph'
|
||||
import type {
|
||||
ExportedSubgraphInstance,
|
||||
ISerialisableNodeInput,
|
||||
ISerialisableNodeOutput,
|
||||
ISerialisedNode
|
||||
} from '@/lib/litegraph/src/types/serialisation'
|
||||
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 { 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/imagePreviewStore'
|
||||
import { ComfyNodeDefImpl } from '@/stores/nodeDefStore'
|
||||
import { useSubgraphStore } from '@/stores/subgraphStore'
|
||||
import { useRightSidePanelStore } from '@/stores/workspace/rightSidePanelStore'
|
||||
import { useWidgetStore } from '@/stores/widgetStore'
|
||||
import { normalizeI18nKey } from '@/utils/formatUtil'
|
||||
import {
|
||||
isImageNode,
|
||||
isVideoNode,
|
||||
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()
|
||||
|
||||
/**
|
||||
* 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()
|
||||
|
||||
/**
|
||||
* @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' }
|
||||
}
|
||||
}
|
||||
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: 2 }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 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) => {
|
||||
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) => {
|
||||
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 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
|
||||
}
|
||||
|
||||
/**
|
||||
* 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')
|
||||
window.open(url, '_blank')
|
||||
}
|
||||
},
|
||||
...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) {
|
||||
const input = this.inputs.find(
|
||||
(inp) => inp.widget?.name === overWidget.name
|
||||
)
|
||||
if (input)
|
||||
options.unshift({
|
||||
content: `${t('contextMenu.RenameWidget')}: ${overWidget.label ?? overWidget.name}`,
|
||||
callback: async () => {
|
||||
const newLabel = await useDialogService().prompt({
|
||||
title: t('g.rename'),
|
||||
message: t('g.enterNewName') + ':',
|
||||
defaultValue: overWidget.label,
|
||||
placeholder: overWidget.name
|
||||
})
|
||||
if (newLabel === null) return
|
||||
overWidget.label = newLabel || undefined
|
||||
input.label = newLabel || undefined
|
||||
useCanvasStore().canvas?.setDirty(true)
|
||||
}
|
||||
})
|
||||
if (this.graph && !this.graph.isRootGraph) {
|
||||
addWidgetPromotionOptions(options, overWidget, this)
|
||||
}
|
||||
}
|
||||
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 = output?.animated?.find(Boolean)
|
||||
|
||||
const isAnimatedWebp =
|
||||
this.animatedImages &&
|
||||
output?.images?.some((img) => img.filename?.includes('webp'))
|
||||
const isAnimatedPng =
|
||||
this.animatedImages &&
|
||||
output?.images?.some((img) => img.filename?.includes('png'))
|
||||
const isVideo =
|
||||
(this.animatedImages && !isAnimatedWebp && !isAnimatedPng) ||
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
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: Record<string, any> = {}
|
||||
): LGraphNode {
|
||||
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
|
||||
|
||||
// @ts-expect-error fixme ts strict error
|
||||
graph.add(node)
|
||||
// @ts-expect-error fixme ts strict error
|
||||
return node
|
||||
}
|
||||
|
||||
function getCanvasCenter(): Point {
|
||||
const dpi = Math.max(window.devicePixelRatio ?? 1, 1)
|
||||
const [x, y, w, h] = app.canvas.ds.visible_area
|
||||
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,
|
||||
goToNode,
|
||||
resetView,
|
||||
fitView,
|
||||
updatePreviews
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
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)
|
||||
|
||||
for (const innerNode of dto.getInnerNodes()) {
|
||||
nodeDtoMap.set(innerNode.id, innerNode)
|
||||
}
|
||||
|
||||
nodeDtoMap.set(dto.id, dto)
|
||||
}
|
||||
|
||||
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
|
||||
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)
|
||||
? {
|
||||
__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,250 @@
|
||||
import _ from 'es-toolkit/compat'
|
||||
|
||||
import type { ColorOption, LGraph } from '@/lib/litegraph/src/litegraph'
|
||||
import {
|
||||
LGraphGroup,
|
||||
LGraphNode,
|
||||
Reroute,
|
||||
isColorable
|
||||
} from '@/lib/litegraph/src/litegraph'
|
||||
import type {
|
||||
ExportedSubgraph,
|
||||
ISerialisableNodeInput,
|
||||
ISerialisedGraph
|
||||
} from '@/lib/litegraph/src/types/serialisation'
|
||||
import type {
|
||||
IBaseWidget,
|
||||
IComboWidget
|
||||
} from '@/lib/litegraph/src/types/widgets'
|
||||
import type { InputSpec } from '@/schemas/nodeDef/nodeDefSchemaV2'
|
||||
|
||||
type ImageNode = LGraphNode & { imgs: HTMLImageElement[] | undefined }
|
||||
type VideoNode = LGraphNode & {
|
||||
videoContainer: HTMLElement | undefined
|
||||
imgs: HTMLVideoElement[] | undefined
|
||||
}
|
||||
|
||||
export function isImageNode(node: LGraphNode | undefined): node is ImageNode {
|
||||
if (!node) return false
|
||||
return (
|
||||
node.previewMediaType === 'image' ||
|
||||
(node.previewMediaType !== 'video' && !!node.imgs?.length)
|
||||
)
|
||||
}
|
||||
|
||||
export function isVideoNode(node: LGraphNode | undefined): node is VideoNode {
|
||||
if (!node) return false
|
||||
return node.previewMediaType === 'video' || !!node.videoContainer
|
||||
}
|
||||
|
||||
export function isAudioNode(node: LGraphNode | undefined): boolean {
|
||||
return !!node && node.previewMediaType === 'audio'
|
||||
}
|
||||
|
||||
export function addToComboValues(widget: IComboWidget, value: string) {
|
||||
if (!widget.options) widget.options = { values: [] }
|
||||
if (!widget.options.values) widget.options.values = []
|
||||
// @ts-expect-error Combo widget values may be a dictionary or legacy function type
|
||||
if (!widget.options.values.includes(value)) {
|
||||
// @ts-expect-error Combo widget values may be a dictionary or legacy function type
|
||||
widget.options.values.push(value)
|
||||
}
|
||||
}
|
||||
|
||||
export const isLGraphNode = (item: unknown): item is LGraphNode => {
|
||||
return item instanceof LGraphNode
|
||||
}
|
||||
|
||||
export const isLGraphGroup = (item: unknown): item is LGraphGroup => {
|
||||
return item instanceof LGraphGroup
|
||||
}
|
||||
|
||||
export const isReroute = (item: unknown): item is Reroute => {
|
||||
return item instanceof Reroute
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the color option of all canvas items if they are all the same.
|
||||
* @param items - The items to get the color option of.
|
||||
* @returns The color option of the item.
|
||||
*/
|
||||
export const getItemsColorOption = (items: unknown[]): ColorOption | null => {
|
||||
const validItems = _.filter(items, isColorable)
|
||||
if (_.isEmpty(validItems)) return null
|
||||
|
||||
const colorOptions = _.map(validItems, (item) => item.getColorOption())
|
||||
|
||||
return _.every(colorOptions, (option) =>
|
||||
_.isEqual(option, _.head(colorOptions))
|
||||
)
|
||||
? _.head(colorOptions)!
|
||||
: null
|
||||
}
|
||||
|
||||
export function executeWidgetsCallback(
|
||||
nodes: LGraphNode[],
|
||||
callbackName: 'onRemove' | 'beforeQueued' | 'afterQueued'
|
||||
) {
|
||||
for (const node of nodes) {
|
||||
for (const widget of node.widgets ?? []) {
|
||||
widget[callbackName]?.()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Since frontend version 1.16, forceInput input is no longer treated
|
||||
* as widget. So we need to remove the dummy widget value serialized
|
||||
* from workflows prior to v1.16.
|
||||
* Ref: https://github.com/Comfy-Org/ComfyUI_frontend/pull/3326
|
||||
*
|
||||
* @param nodeDef the node definition
|
||||
* @param widgets the widgets on the node instance (from node definition)
|
||||
* @param widgetsValues the widgets values to populate the node during configuration
|
||||
* @returns the widgets values without the dummy widget values
|
||||
*/
|
||||
export function migrateWidgetsValues<TWidgetValue>(
|
||||
inputDefs: Record<string, InputSpec>,
|
||||
widgets: IBaseWidget[],
|
||||
widgetsValues: TWidgetValue[]
|
||||
): TWidgetValue[] {
|
||||
const widgetNames = new Set(widgets.map((w) => w.name))
|
||||
const originalWidgetsInputs = Object.values(inputDefs).filter(
|
||||
(input) => widgetNames.has(input.name) || input.forceInput
|
||||
)
|
||||
// Count the number of original widgets inputs.
|
||||
const numOriginalWidgets = _.sum(
|
||||
originalWidgetsInputs.map((input) =>
|
||||
// If the input has control, it will have 2 widgets.
|
||||
input.control_after_generate ||
|
||||
['seed', 'noise_seed'].includes(input.name)
|
||||
? 2
|
||||
: 1
|
||||
)
|
||||
)
|
||||
|
||||
if (numOriginalWidgets === widgetsValues?.length) {
|
||||
return _.zip(originalWidgetsInputs, widgetsValues)
|
||||
.filter(([input]) => !input?.forceInput)
|
||||
.map(([_, value]) => value as TWidgetValue)
|
||||
}
|
||||
return widgetsValues
|
||||
}
|
||||
|
||||
/**
|
||||
* Fix link input slots after loading a graph. Because the node inputs follows
|
||||
* the node definition after 1.16, the node inputs array from previous versions,
|
||||
* might get added items in the middle, which can cause shift to link's slot index.
|
||||
* For example, the node inputs definition is:
|
||||
* "required": {
|
||||
* "input1": ["INT", { forceInput: true }],
|
||||
* "input2": ["MODEL", { forceInput: false }],
|
||||
* "input3": ["MODEL", { forceInput: false }]
|
||||
* }
|
||||
*
|
||||
* previously node inputs array was:
|
||||
* [{name: 'input2'}, {name: 'input3'}, {name: 'input1'}]
|
||||
* because input1 is created as widget first, then convert to input socket after
|
||||
* input 2 and 3.
|
||||
*
|
||||
* Now, the node inputs array just follows the definition order:
|
||||
* [{name: 'input1'}, {name: 'input2'}, {name: 'input3'}]
|
||||
*
|
||||
* We need to update the slot index of corresponding links to match the new
|
||||
* node inputs array order.
|
||||
*
|
||||
* Ref: https://github.com/Comfy-Org/ComfyUI_frontend/issues/3348
|
||||
*
|
||||
* @param graph - The graph to fix links for.
|
||||
*/
|
||||
export function fixLinkInputSlots(graph: LGraph) {
|
||||
// Note: We can't use forEachNode here because we need access to the graph's
|
||||
// links map at each level. Links are stored in their respective graph/subgraph.
|
||||
for (const node of graph.nodes) {
|
||||
// Fix links for the current node
|
||||
for (const [inputIndex, input] of node.inputs.entries()) {
|
||||
const linkId = input.link
|
||||
if (!linkId) continue
|
||||
|
||||
const link = graph.links.get(linkId)
|
||||
if (!link) continue
|
||||
|
||||
link.target_slot = inputIndex
|
||||
}
|
||||
|
||||
// Recursively fix links in subgraphs
|
||||
if (node.isSubgraphNode?.() && node.subgraph) {
|
||||
fixLinkInputSlots(node.subgraph)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Compress widget input slots by removing all unconnected widget input slots.
|
||||
* This should match the serialization format of legacy widget conversion.
|
||||
*
|
||||
* @param graph - The graph to compress widget input slots for.
|
||||
* @throws If an infinite loop is detected.
|
||||
*/
|
||||
export function compressWidgetInputSlots(graph: ISerialisedGraph) {
|
||||
for (const node of graph.nodes) {
|
||||
node.inputs = node.inputs?.filter(matchesLegacyApi)
|
||||
|
||||
for (const [inputIndex, input] of node.inputs?.entries() ?? []) {
|
||||
if (input.link) {
|
||||
const link = graph.links.find((link) => link[0] === input.link)
|
||||
if (link) {
|
||||
link[4] = inputIndex
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
compressSubgraphWidgetInputSlots(graph.definitions?.subgraphs)
|
||||
}
|
||||
|
||||
function matchesLegacyApi(input: ISerialisableNodeInput) {
|
||||
return !(input.widget && input.link === null && !input.label)
|
||||
}
|
||||
|
||||
/**
|
||||
* Duplication to handle the legacy link arrays in the root workflow.
|
||||
* @see compressWidgetInputSlots
|
||||
* @param subgraph The subgraph to compress widget input slots for.
|
||||
*/
|
||||
function compressSubgraphWidgetInputSlots(
|
||||
subgraphs: ExportedSubgraph[] | undefined,
|
||||
visited = new WeakSet<ExportedSubgraph>()
|
||||
) {
|
||||
if (!subgraphs) return
|
||||
|
||||
for (const subgraph of subgraphs) {
|
||||
if (visited.has(subgraph)) throw new Error('Infinite loop detected')
|
||||
visited.add(subgraph)
|
||||
|
||||
if (subgraph.nodes) {
|
||||
for (const node of subgraph.nodes) {
|
||||
node.inputs = node.inputs?.filter(matchesLegacyApi)
|
||||
|
||||
if (!subgraph.links) continue
|
||||
|
||||
for (const [inputIndex, input] of node.inputs?.entries() ?? []) {
|
||||
if (input.link) {
|
||||
const link = subgraph.links.find((link) => link.id === input.link)
|
||||
if (link) link.target_slot = inputIndex
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
compressSubgraphWidgetInputSlots(subgraph.definitions?.subgraphs, visited)
|
||||
}
|
||||
}
|
||||
|
||||
export function isLoad3dNode(node: LGraphNode) {
|
||||
return (
|
||||
node &&
|
||||
node.type &&
|
||||
(node.type === 'Load3D' || node.type === 'Load3DAnimation')
|
||||
)
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
Reference in New Issue
Block a user