HEL-892: document Qwen image editing with pinned subgraph and comparer evidence
Co-authored-by: multica-agent <github@multica.ai>
This commit is contained in:
@@ -15,6 +15,9 @@ DEFINITION_SHA256 = "4da30b7b4314d6e3e37b3cefcaae710072ae0ee4e323e999789e63b3860
|
||||
|
||||
# Explicit path allowlist; a recomputed caller-supplied digest cannot extend trust.
|
||||
DEFINITIONS = {
|
||||
(
|
||||
"example_ComfyUI_workflows/3-图像生成/Qwen-Image-2.1/Qwen_image2.1_图像编辑_提示词增强.json"
|
||||
): "dcbf1de5f2fb82465c6fe6c473e4c1ffa2e13d166e4becc62dc6d9acaec9a5ed",
|
||||
(
|
||||
"example_ComfyUI_workflows/3-图像生成/Qwen-Image-2.1/Qwen_image2.1_文生图_提示词增强.json"
|
||||
): "6dd26b64aecccd272af43f17a66f162f5bfd746807af46c5514c3eb9c00d6cb5",
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -202,8 +202,8 @@ def test_graph_specific_semantics_and_companion():
|
||||
assert d["dependencies"]["check_state"] == "unchecked"
|
||||
|
||||
|
||||
def test_other_eight_documents_and_block_swaps():
|
||||
assert len(DEFINITIONS) == 9
|
||||
def test_other_documents_and_block_swaps():
|
||||
assert len(DEFINITIONS) == 10
|
||||
for path in DEFINITIONS:
|
||||
if path == PATH:
|
||||
continue
|
||||
|
||||
@@ -0,0 +1,248 @@
|
||||
"""All saved scopes, bound overrides and rejection of forged editorial trust."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import copy
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from calliope.comfyui.fixed_document import DEFINITIONS, canonical
|
||||
from calliope.comfyui.library import build_document
|
||||
from calliope.comfyui.source_reviews import review_for
|
||||
|
||||
REPO = Path(__file__).resolve().parents[2]
|
||||
OUT = REPO / "docs/hel-892/qwen-edit-document-evidence"
|
||||
PATH = next(p for p in DEFINITIONS if p.endswith("Qwen_image2.1_图像编辑_提示词增强.json"))
|
||||
RAW = (REPO / PATH).read_bytes()
|
||||
SOURCE = json.loads(RAW)
|
||||
REVIEW = review_for(PATH, hashlib.sha1(RAW).hexdigest())
|
||||
BLOCK = REVIEW["fixed_version_document"]
|
||||
|
||||
|
||||
def doc(source=None, review=None, path=PATH):
|
||||
return build_document(
|
||||
path,
|
||||
SOURCE if source is None else source,
|
||||
None,
|
||||
None,
|
||||
[],
|
||||
REVIEW if review is None else review,
|
||||
)
|
||||
|
||||
|
||||
def pointer(obj, path):
|
||||
for part in path.strip("/").split("/"):
|
||||
part = part.replace("~1", "/").replace("~0", "~")
|
||||
obj = obj[int(part)] if isinstance(obj, list) else obj[part]
|
||||
return obj
|
||||
|
||||
|
||||
@pytest.mark.parametrize("index", range(70))
|
||||
def test_every_saved_position_scope_and_citation(index):
|
||||
f = BLOCK["fields"][index]
|
||||
v = pointer(SOURCE, f["pointer"])
|
||||
assert canonical(v) == canonical(f["value"]) and type(v).__name__ == f["json_type"]
|
||||
named = pointer(SOURCE, f["named_pointer"])
|
||||
if f["node_id"] == "501":
|
||||
assert named == {"images": [{**item, "img": {}} for item in v]}
|
||||
assert named != v
|
||||
else:
|
||||
assert canonical(named) == canonical(v)
|
||||
prefix = f["pointer"].split("/widgets_values/")[0]
|
||||
n = pointer(SOURCE, prefix)
|
||||
assert str(n["id"]) == f["definition_node_id"] and n["type"] == f["class_type"]
|
||||
assert f["node_id"] == ("459:" if f["scope"] == "definition" else "") + str(n["id"])
|
||||
assert all(
|
||||
f[k]
|
||||
for k in [
|
||||
"effect",
|
||||
"label",
|
||||
"schema_default",
|
||||
"unit",
|
||||
"limits",
|
||||
"execution_note",
|
||||
"evidence",
|
||||
]
|
||||
)
|
||||
if f["type"] in ("INT", "FLOAT"):
|
||||
assert "UI编辑步进step2=" in f["limits"]
|
||||
for i in f["evidence"]:
|
||||
e = BLOCK["sources"][i]
|
||||
raw = (OUT / e["local_file"]).read_bytes()
|
||||
assert hashlib.sha256(raw).hexdigest() == e["sha256"]
|
||||
assert len(e["commit"]) == 40 and e["commit"] in e["url"]
|
||||
assert 1 <= e["lines"][0] <= e["lines"][1] <= len(raw.decode().splitlines())
|
||||
|
||||
|
||||
@pytest.mark.parametrize("index", range(70))
|
||||
@pytest.mark.parametrize("kind", ["value", "type", "pointer", "named"])
|
||||
def test_saved_and_named_mutations_cannot_rebind_document(index, kind):
|
||||
s, r = copy.deepcopy(SOURCE), copy.deepcopy(REVIEW)
|
||||
f = r["fixed_version_document"]["fields"][index]
|
||||
if kind == "pointer":
|
||||
f["pointer"] = "/definitions/subgraphs/999/nodes/999/widgets_values/0"
|
||||
else:
|
||||
p = f["named_pointer"] if kind == "named" else f["pointer"]
|
||||
parent, _, key = p.rpartition("/")
|
||||
target = pointer(s, parent)
|
||||
target[int(key) if isinstance(target, list) else key] = (
|
||||
{"forged": True} if kind != "type" else str(f["value"]) + "tampered"
|
||||
)
|
||||
r["fixed_version_document"]["canonical_sha256"] = hashlib.sha256(canonical(s)).hexdigest()
|
||||
r["caller_digest"] = hashlib.sha256(canonical(r["fixed_version_document"])).hexdigest()
|
||||
fixed = doc(s, r)["fixed_version"]
|
||||
assert not fixed["matched"] and "fields" not in fixed
|
||||
|
||||
|
||||
@pytest.mark.parametrize("index", range(18))
|
||||
def test_host_bindings_are_scoped_named_and_have_physical_provenance(index):
|
||||
b = BLOCK["bindings"][index]
|
||||
assert b["value_pointer"] == f"/nodes/0/widgets_values/{index}"
|
||||
assert canonical(pointer(SOURCE, b["named_pointer"])) == canonical(
|
||||
pointer(SOURCE, b["value_pointer"])
|
||||
)
|
||||
boundary = pointer(SOURCE, b["boundary_pointer"])
|
||||
assert boundary["id"] == b["boundary_id"] and boundary["name"] == b["name"]
|
||||
for t in b["targets"]:
|
||||
socket = pointer(SOURCE, t["target_pointer"])
|
||||
edge = pointer(SOURCE, t["link_pointer"])
|
||||
assert socket["name"] == t["field"] and socket["link"] == edge["id"]
|
||||
assert edge["origin_slot"] == index and edge["target_id"] == int(t["definition_node_id"])
|
||||
assert "widgetId(rootGraph.id, 459," in b["widget_id_rule"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"location",
|
||||
[f["pointer"] for f in BLOCK["fields"]]
|
||||
+ [f["named_pointer"] for f in BLOCK["fields"]]
|
||||
+ [c["pointer"] for c in BLOCK["comments"]]
|
||||
+ [b["boundary_pointer"] for b in BLOCK["bindings"]]
|
||||
+ [
|
||||
"/definitions/subgraphs/0/id",
|
||||
"/nodes/0/type",
|
||||
"/nodes/0/inputs/22/name",
|
||||
"/extra/frontendVersion",
|
||||
"/nodes/6/properties/comparer_mode",
|
||||
"/nodes/6/widgets_values/0/0/url",
|
||||
"/nodes/6/widgets_values_named/rgthree_comparer/images/1/selected",
|
||||
"/definitions/subgraphs/0/nodes/0/properties/ver",
|
||||
"/links/3",
|
||||
"/definitions/subgraphs/0/links/0/target_slot",
|
||||
],
|
||||
)
|
||||
def test_recomputed_caller_digest_cannot_extend_trust(location):
|
||||
s, r = copy.deepcopy(SOURCE), copy.deepcopy(REVIEW)
|
||||
parent, _, key = location.rpartition("/")
|
||||
target = pointer(s, parent)
|
||||
target[int(key) if isinstance(target, list) else key] = (
|
||||
"forged" if location == "/nodes/0/type" else {"tampered": True}
|
||||
)
|
||||
r["fixed_version_document"]["canonical_sha256"] = hashlib.sha256(canonical(s)).hexdigest()
|
||||
r["fixed_version_document"]["subgraph_sha256"] = hashlib.sha256(
|
||||
canonical(s["definitions"]["subgraphs"][0])
|
||||
).hexdigest()
|
||||
r["caller_digest"] = hashlib.sha256(canonical(r["fixed_version_document"])).hexdigest()
|
||||
assert not doc(s, r)["fixed_version"]["matched"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"key",
|
||||
[
|
||||
"source_path",
|
||||
"source_sha1",
|
||||
"source_sha256",
|
||||
"canonical_sha256",
|
||||
"subgraph_sha256",
|
||||
"sources",
|
||||
"versions",
|
||||
"bindings",
|
||||
"flow",
|
||||
"comments",
|
||||
"counts",
|
||||
"fields",
|
||||
],
|
||||
)
|
||||
def test_editorial_or_source_identity_forgery(key):
|
||||
r = copy.deepcopy(REVIEW)
|
||||
r["fixed_version_document"][key] = "forged"
|
||||
r["caller_digest"] = hashlib.sha256(canonical(r["fixed_version_document"])).hexdigest()
|
||||
assert not doc(review=r)["fixed_version"]["matched"]
|
||||
|
||||
|
||||
def test_exact_counts_topology_and_distinct_frontend_state():
|
||||
b = doc()["fixed_version"]
|
||||
assert b["matched"]
|
||||
saved = set()
|
||||
for prefix, g in [
|
||||
("", SOURCE),
|
||||
("/definitions/subgraphs/0", SOURCE["definitions"]["subgraphs"][0]),
|
||||
]:
|
||||
for i, n in enumerate(g["nodes"]):
|
||||
if n["type"] in ("MarkdownNote", "Note"):
|
||||
continue
|
||||
saved.update(
|
||||
f"{prefix}/nodes/{i}/widgets_values/{j}"
|
||||
for j, _ in enumerate(n.get("widgets_values") or [])
|
||||
)
|
||||
assert saved == {f["pointer"] for f in b["fields"]} and len(saved) == 70
|
||||
assert sum(f["scope"] == "root" for f in b["fields"]) == 30
|
||||
assert len(b["comments"]) == 3 and all(
|
||||
pointer(SOURCE, c["pointer"]) == c["text"] for c in b["comments"]
|
||||
)
|
||||
fs = {(f["node_id"], f["field"]): f for f in b["fields"]}
|
||||
assert fs["459", "prompt"]["value"] == "为角色更换服装"
|
||||
assert fs["459", "resolution"]["value"] == 0 and fs["459:474", "resolution"]["value"] == 1024
|
||||
assert fs["459", "seed"]["value"] == 1054732230873463
|
||||
for nid, name in [("459:458", "seed"), ("459:500", "sampling_mode.seed")]:
|
||||
assert fs[nid, name]["value"] == 0
|
||||
assert fs[nid, name]["binding"]["value_pointer"] == "/nodes/0/widgets_values/11"
|
||||
assert fs["459:458", "control_after_generate"]["value"] == "randomize"
|
||||
assert fs["459:500", "thinking"]["value"] is True
|
||||
assert fs["459:500", "use_default_template"]["value"] is False
|
||||
assert "不采用" in fs["459:479", "value"]["execution_note"]
|
||||
for name, nid in [("switch", "459:468"), ("switch_1", "459:484")]:
|
||||
assert fs["459", name]["value"] is True and fs[nid, "switch"]["value"] is False
|
||||
assert fs[nid, "switch"]["binding"]["name"] == name
|
||||
for name, target in [("scheduler", "sampler_name"), ("scheduler_1", "scheduler")]:
|
||||
assert fs["459", name]["binding"]["targets"][0]["field"] == target
|
||||
assert b["counts"]["final_scalars"] == 0
|
||||
assert b["counts"]["final_prompt_constructed"] is False
|
||||
assert b["counts"]["frontend_only"] == 4
|
||||
assert fs["470", "upload"]["role"] == fs["475", "upload"]["role"] == "frontend"
|
||||
assert len(fs["501", "rgthree_comparer"]["value"]) == 2
|
||||
assert fs["501", "rgthree_comparer"]["role"] == "frontend"
|
||||
assert SOURCE["links"] == [
|
||||
[704, 470, 0, 459, 18, "IMAGE"],
|
||||
[728, 475, 0, 459, 19, "IMAGE"],
|
||||
[808, 470, 0, 501, 0, "IMAGE"],
|
||||
[809, 461, 0, 501, 1, "IMAGE"],
|
||||
[810, 502, 0, 459, 7, "INT"],
|
||||
[811, 502, 1, 459, 8, "INT"],
|
||||
[672, 459, 0, 461, 0, "IMAGE"],
|
||||
]
|
||||
assert not doc(path="unknown.json").get("fixed_version")
|
||||
|
||||
|
||||
def test_old_nine_blocks_and_other_editorial_content_preserved():
|
||||
import subprocess
|
||||
|
||||
path = "calliope-backend/src/calliope/comfyui/source_reviews.json"
|
||||
old = json.loads(subprocess.check_output(["git", "show", "157a296:" + path], cwd=REPO))
|
||||
now = json.loads((REPO / path).read_bytes())
|
||||
now[PATH].pop("fixed_version_document")
|
||||
assert old == now
|
||||
|
||||
|
||||
@pytest.mark.parametrize("directory", ["qwen-document-evidence", "qwen-edit-document-evidence"])
|
||||
def test_missing_packages_give_actionable_chinese_build_hint(tmp_path, directory):
|
||||
import runpy
|
||||
|
||||
namespace = runpy.run_path(str(REPO / "docs/hel-892" / directory / "recompute.py"))
|
||||
check = namespace["require_packages"]
|
||||
check.__globals__["REPO"] = tmp_path
|
||||
with pytest.raises(
|
||||
SystemExit, match="缺少wheel/sdist包产物.*uv build --project calliope-backend --offline"
|
||||
):
|
||||
check()
|
||||
@@ -24,7 +24,18 @@ def write(name, data):
|
||||
(OUT / name).write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n")
|
||||
|
||||
|
||||
def require_packages():
|
||||
dist = REPO / "calliope-backend/dist"
|
||||
wheels, archives = sorted(dist.glob("*.whl")), sorted(dist.glob("*.tar.gz"))
|
||||
if not wheels or not archives:
|
||||
raise SystemExit(
|
||||
"缺少wheel/sdist包产物,请先在仓库根执行:uv build --project calliope-backend --offline"
|
||||
)
|
||||
return wheels[-1], archives[-1]
|
||||
|
||||
|
||||
def main():
|
||||
wheel_path, sdist_path = require_packages()
|
||||
from calliope.comfyui.fixed_document import DEFINITIONS as ALL_DEFINITIONS
|
||||
from calliope.comfyui.fixed_document import canonical
|
||||
|
||||
@@ -266,8 +277,8 @@ def main():
|
||||
)
|
||||
packages = []
|
||||
with (
|
||||
zipfile.ZipFile(next((REPO / "calliope-backend/dist").glob("*.whl"))) as wheel,
|
||||
tarfile.open(next((REPO / "calliope-backend/dist").glob("*.tar.gz"))) as sdist,
|
||||
zipfile.ZipFile(wheel_path) as wheel,
|
||||
tarfile.open(sdist_path) as sdist,
|
||||
):
|
||||
for name in ["fixed_document.py", "source_reviews.json", "library.py"]:
|
||||
raw = (REPO / "calliope-backend/src/calliope/comfyui" / name).read_bytes()
|
||||
|
||||
@@ -0,0 +1,705 @@
|
||||
"""Build editorial evidence for the exact edit graph; never create an execution profile."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import copy
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
REPO = Path(__file__).resolve().parents[3]
|
||||
OUT = Path(__file__).resolve().parent
|
||||
PATH = "example_ComfyUI_workflows/3-图像生成/Qwen-Image-2.1/Qwen_image2.1_图像编辑_提示词增强.json"
|
||||
|
||||
|
||||
def canonical(value):
|
||||
return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode()
|
||||
|
||||
|
||||
def build():
|
||||
raw = (REPO / PATH).read_bytes()
|
||||
source = json.loads(raw)
|
||||
graph = source["definitions"]["subgraphs"][0]
|
||||
old = json.loads((OUT.parent / "qwen-document-evidence/definition.json").read_bytes())
|
||||
refs = copy.deepcopy(old["sources"])
|
||||
specs = {}
|
||||
for f in old["fields"]:
|
||||
if f["scope"] != "definition" and f["class_type"] not in (
|
||||
"ResolutionSelector",
|
||||
"SaveImageAdvanced",
|
||||
):
|
||||
continue
|
||||
specs[f["class_type"], f["field"]] = {
|
||||
k: copy.deepcopy(f[k])
|
||||
for k in (
|
||||
"field",
|
||||
"label",
|
||||
"type",
|
||||
"schema_default",
|
||||
"unit",
|
||||
"limits",
|
||||
"effect",
|
||||
"evidence",
|
||||
)
|
||||
}
|
||||
|
||||
def ref(directory, filename, start, end, claim):
|
||||
directory_path = OUT.parent / directory
|
||||
entry = next(
|
||||
x
|
||||
for x in json.loads((directory_path / "sources.json").read_bytes())["sources"]
|
||||
if x["local_file"] == filename
|
||||
)
|
||||
data = (directory_path / filename).read_bytes()
|
||||
assert hashlib.sha256(data).hexdigest() == entry["sha256"]
|
||||
assert 1 <= start <= end <= len(data.decode().splitlines())
|
||||
refs.append(
|
||||
{
|
||||
**{k: entry[k] for k in ("id", "commit", "file", "url", "sha256")},
|
||||
"local_file": "../" + directory + "/" + filename,
|
||||
"lines": [start, end],
|
||||
"claim": claim,
|
||||
}
|
||||
)
|
||||
return len(refs) - 1
|
||||
|
||||
load = ref(
|
||||
"promoted-reference",
|
||||
"core-0.38.0__nodes.py",
|
||||
1746,
|
||||
1820,
|
||||
"LoadImage动态文件列表、注解路径、加载分支、IMAGE/MASK与存在性校验",
|
||||
)
|
||||
preview = ref(
|
||||
"promoted-reference",
|
||||
"core-0.38.0__nodes.py",
|
||||
1667,
|
||||
1744,
|
||||
"SaveImage IMAGE出口及PNG保存、PreviewImage继承并改为temp目录/随机前缀",
|
||||
)
|
||||
py = ref(
|
||||
"qwen-edit-reference",
|
||||
"rgthree__py__image_comparer.py",
|
||||
1,
|
||||
45,
|
||||
"rgthree精确schema、A/B临时预览与result回传;继承core IMAGE出口",
|
||||
)
|
||||
js = ref(
|
||||
"qwen-edit-reference",
|
||||
"rgthree__web__comfyui__image_comparer.js",
|
||||
8,
|
||||
76,
|
||||
"历史URL构造、执行响应、rgthree_comparer创建和serialize去img保留数组",
|
||||
)
|
||||
restore = ref(
|
||||
"qwen-edit-reference",
|
||||
"rgthree__web__comfyui__image_comparer.js",
|
||||
180,
|
||||
243,
|
||||
"setter接受数组或images包装、selected与Image对象恢复;本轮不调用setter",
|
||||
)
|
||||
slide = ref(
|
||||
"qwen-edit-reference",
|
||||
"rgthree__web__comfyui__image_comparer.js",
|
||||
244,
|
||||
308,
|
||||
"Click与Slide的绘制条件;只读静态源码",
|
||||
)
|
||||
ref(
|
||||
"qwen-edit-reference",
|
||||
"rgthree____init__.py",
|
||||
35,
|
||||
73,
|
||||
"导入RgthreeImageComparer并以NAME注册",
|
||||
)
|
||||
ref(
|
||||
"qwen-edit-reference",
|
||||
"rgthree__py__constants.py",
|
||||
1,
|
||||
11,
|
||||
"Python Image Comparer名称后缀注册规则",
|
||||
)
|
||||
ref(
|
||||
"qwen-edit-reference",
|
||||
"rgthree__web__comfyui__constants.js",
|
||||
1,
|
||||
62,
|
||||
"前端Image Comparer名称枚举",
|
||||
)
|
||||
ref(
|
||||
"qwen-edit-reference",
|
||||
"core__comfy_extras__nodes_post_processing.py",
|
||||
519,
|
||||
593,
|
||||
"BatchImagesNode注册schema、空列表条件、首图尺寸及通道匹配(无None过滤)、合批",
|
||||
)
|
||||
ref(
|
||||
"qwen-edit-reference",
|
||||
"core__comfy_extras__nodes_post_processing.py",
|
||||
890,
|
||||
914,
|
||||
"BatchImagesNode扩展注册",
|
||||
)
|
||||
upload = ref(
|
||||
"qwen-edit-reference",
|
||||
"frontend__src__extensions__core__uploadImage.ts",
|
||||
1,
|
||||
40,
|
||||
"LoadImage前端上传控件注册和处理,非后端image参数",
|
||||
)
|
||||
|
||||
upload_widget = ref(
|
||||
"qwen-edit-reference",
|
||||
"frontend__src__renderer__extensions__vueNodes__widgets__composables__useImageUploadWidget.ts",
|
||||
105,
|
||||
142,
|
||||
"上传button初值image且serialize:false;含恢复后预览回调;本轮未执行",
|
||||
)
|
||||
ref(
|
||||
"qwen-edit-reference",
|
||||
"rgthree__web__comfyui__base_node.js",
|
||||
76,
|
||||
83,
|
||||
"rgthree configure委托固定LGraphNode,再恢复控件显示位置",
|
||||
)
|
||||
ref(
|
||||
"qwen-edit-reference",
|
||||
"rgthree__web__comfyui__utils_widgets.js",
|
||||
21,
|
||||
38,
|
||||
"RgthreeBaseWidget的serializeValue返回value,Comparer的onSerialize再转images数组",
|
||||
)
|
||||
effects = {
|
||||
"UNETLoader": (
|
||||
"按diffusion_models解析文件;default不强制"
|
||||
"dtype,fp8选项设置加载选项。宿主unet_name覆"
|
||||
"盖内部文件名,名称bf16/int8不证明精度或显存;权重/设备"
|
||||
"未核对。"
|
||||
),
|
||||
"CLIPLoader": (
|
||||
"按text_encoders解析文件、type映射CLIPTyp"
|
||||
"e;device=cpu显式设加载/卸载设备。453图像编码"
|
||||
"与477编辑PE文本生成均保存qwen_image,宿主文件各自"
|
||||
"覆盖;目标列表/硬件未知。"
|
||||
),
|
||||
"VAELoader": "按vae列表与近似模型条件解析文件并创建VAE;宿主覆盖内部文件"
|
||||
"名。本图既向474参考图编码供VAE也向457解码供VAE,文件"
|
||||
"存在与真实能力未知。",
|
||||
"EmptyLatentImage": (
|
||||
"width/height按像素尺度创建[batch,4,heig"
|
||||
"ht//8,width//8]空latent;宽高被宿主/根"
|
||||
"502覆盖。456槽0进468.on_true,不等于编码器47"
|
||||
"4的64通道latent,目标兼容和实际尺寸未验证。"
|
||||
),
|
||||
"ResolutionSelector": (
|
||||
"固定比例/MP/倍数参与total_pixels=MP×1024"
|
||||
"×1024、开方后round到倍数。源比例9:16,1.5M"
|
||||
"P与8不当实测产物;槽0/1经810/811覆盖宿主width/height。"
|
||||
),
|
||||
"KSampler": (
|
||||
"按固定core将seed/steps/cfg/sampler_name/scheduler/denoise交给common_"
|
||||
"ksampler。宿主scheduler实际绑定sampler_"
|
||||
"name,scheduler_1才是scheduler;不承"
|
||||
"诺质量/耗时/推理可重复。"
|
||||
),
|
||||
"ComfySwitchNode": (
|
||||
"固定代码true选择on_true,false选择on_fals"
|
||||
"e,并按lazy条件请求分支。484为提示优化,468为自定"
|
||||
"义尺寸;两个内部false都由不同宿主true覆盖,不能凭标签推"
|
||||
"分支。"
|
||||
),
|
||||
"QwenImage21Cache": (
|
||||
"clone模型并写transformer_options.qwen_image21_cache的device/dtype。a"
|
||||
"uto/gpu/cpu/off及default/int8/int"
|
||||
"4是固定枚举;没有运行模型,真实缓存/速度/显存/误差未知。"
|
||||
),
|
||||
"TextEncodeQwenImage21": (
|
||||
"474同时接两图与VAE:按数字后缀排序,跳过None,每项只取"
|
||||
"image[:1];resolution>0按像素预算缩放,"
|
||||
"0按各图本身尺寸round到32并至少32。首个有效图确定编码l"
|
||||
"atent空间;RGBA视觉分支合白底,VAE保留原通道。正"
|
||||
"负token与参考latent送458,不能保证实际素材/兼容性。"
|
||||
),
|
||||
"TextGenerate": (
|
||||
"500以477.clip和485图像批次tokenize;采样o"
|
||||
"n按限定sampling_mode.*取值,max_leng"
|
||||
"th为生成长度上限;thinking仅请求模型支持的思考。use"
|
||||
"_default_template=false令skip_t"
|
||||
"emplate=true且system_prompt为空,479"
|
||||
"指南虽连线仍不采用;MTP无权重不保证生效,未生成文本。"
|
||||
),
|
||||
"PrimitiveStringMultiline": (
|
||||
"479原始系统指南逐字保留,经807接500.system_pr"
|
||||
"ompt;当前use_default_template=fa"
|
||||
"lse使该指南不传入tokenize。原文不是本轮指令,也未改写或运行。"
|
||||
),
|
||||
"SaveImageAdvanced": (
|
||||
"461接459输出,保存分支为png/8-bit/sRGB;前缀"
|
||||
"image/Qwen_image_2.1参与目录/计数器及s"
|
||||
"erialize替换,PNG整数化/颜色处理和元数据受固定代码与"
|
||||
"disable_metadata条件控制。IMAGE透传经8"
|
||||
"09到501.image_b,ui.images仅协议,未实际保存文件。"
|
||||
),
|
||||
}
|
||||
individual = {
|
||||
("KSampler", "seed"): "采样噪声种子,与文本生成种子来源相同但语义独立。",
|
||||
("KSampler", "steps"): "去噪迭代步数,本图25;不保证质量或耗时。",
|
||||
("KSampler", "cfg"): "条件引导强度,本图1区别于schema默认8。",
|
||||
("KSampler", "sampler_name"): "采样算法,本图euler;宿主scheduler绑定此字段。",
|
||||
("KSampler", "scheduler"): "噪声序列调度,本图simple;宿主scheduler_1绑定此字段。",
|
||||
("KSampler", "denoise"): "去噪比例,本图1传入采样;不当实测质量。",
|
||||
("TextGenerate", "prompt"): "500收到宿主中文编辑请求,覆盖内部空串,无根483外线。",
|
||||
(
|
||||
"TextGenerate",
|
||||
"max_length",
|
||||
): "传clip.generate的最大生成长度16256,不是汉字数或实测输出长度。",
|
||||
("TextGenerate", "sampling_mode"): "on令do_sample为真并展开限定参数;off分支无子字段。",
|
||||
(
|
||||
"TextGenerate",
|
||||
"sampling_mode.temperature",
|
||||
): "on分支传temperature=1;随机性及文本效果未实测。",
|
||||
("TextGenerate", "sampling_mode.top_k"): "on分支传top_k=20,schema默认64与执行缺省50另列。",
|
||||
("TextGenerate", "sampling_mode.top_p"): "on分支传top_p=0.95;不承诺质量。",
|
||||
(
|
||||
"TextGenerate",
|
||||
"sampling_mode.min_p",
|
||||
): "on分支传min_p=0.05,本图与schema默认相同,执行缺省0另列。",
|
||||
(
|
||||
"TextGenerate",
|
||||
"sampling_mode.repetition_penalty",
|
||||
): "on分支传重复惩罚1.05,实际文本重复情况未知。",
|
||||
(
|
||||
"TextGenerate",
|
||||
"sampling_mode.seed",
|
||||
): "on分支种子由宿主1054732230873463覆盖内部0;限定名不自动添control_after_generate。",
|
||||
(
|
||||
"TextGenerate",
|
||||
"sampling_mode.presence_penalty",
|
||||
): "on分支传presence_penalty=0,调整效果未验证。",
|
||||
(
|
||||
"TextGenerate",
|
||||
"thinking",
|
||||
): "直接保存true,没有宿主思考控件覆盖;第二thinking输出未接,不声称有思考结果。",
|
||||
(
|
||||
"TextGenerate",
|
||||
"use_default_template",
|
||||
): "直接保存false,使原479指南不采用;不是schema默认true。",
|
||||
(
|
||||
"TextGenerate",
|
||||
"mtp",
|
||||
): "auto转True、off转False、数字转int;无MTP权重时无效,同seed输出亦不保证。",
|
||||
("EmptyLatentImage", "batch_size"): "决定空latent批量维,本图1;与两参考图数量不同。",
|
||||
("ResolutionSelector", "aspect_ratio"): "画面比例9:16,按冒号前后数值参与计算。",
|
||||
("ResolutionSelector", "megapixels"): "目标总像素预算1.5×1024×1024,不是宽或高。",
|
||||
(
|
||||
"ResolutionSelector",
|
||||
"multiple",
|
||||
): "宽高各自round到8倍数,schema步进4与UI显示步进区别保留。",
|
||||
("TextEncodeQwenImage21", "prompt"): "正向编码文本由484经480覆盖内部空串。",
|
||||
(
|
||||
"TextEncodeQwenImage21",
|
||||
"negative_prompt",
|
||||
): "负向编码文本由宿主空字符串覆盖,不等于未接参考图。",
|
||||
}
|
||||
for (cls, name), spec in specs.items():
|
||||
spec["effect"] = individual.get((cls, name), "") + effects[cls]
|
||||
spec["limits"] = (
|
||||
spec["limits"]
|
||||
.replace("源3:4", "源9:16")
|
||||
.replace("本图保存fixed", "本图保存randomize")
|
||||
.replace("本参考仅fixed", "本图randomize仅记录前端控制,不调用队列钩子")
|
||||
)
|
||||
if cls == "KSampler" and name == "control_after_generate":
|
||||
spec["schema_default"] = "裸seed附加控制默认randomize;本图也保存randomize"
|
||||
spec["effect"] = (
|
||||
"仅前端种子控制,不进入后端prompt。原件为randomize"
|
||||
",任务摘要fixed与原件不符;不改源值,不模拟队列变值,不"
|
||||
"保证宿主seed运行时保持。限定sampling_mode.seed不自动附加控制。"
|
||||
)
|
||||
if cls == "TextEncodeQwenImage21" and name == "resolution":
|
||||
spec["effect"] += (
|
||||
" 本图宿主resolution=0覆盖内部1024,是保持各参考"
|
||||
"图自身尺寸并对齐32的哨兵,不是无效或完全原尺寸。无有效图时"
|
||||
"latent_w/h回退resolution or 1024。"
|
||||
)
|
||||
|
||||
def add(cls, name, label, typ, default, unit, limits, effect, evidence):
|
||||
specs[cls, name] = dict(
|
||||
field=name,
|
||||
label=label,
|
||||
type=typ,
|
||||
schema_default=default,
|
||||
unit=unit,
|
||||
limits=limits,
|
||||
effect=effect,
|
||||
evidence=evidence,
|
||||
)
|
||||
|
||||
add(
|
||||
"LoadImage",
|
||||
"image",
|
||||
"输入图像文件",
|
||||
"动态COMBO / STRING",
|
||||
"目标动态列表首项,无固定文件默认",
|
||||
"不适用",
|
||||
"目标input文件列表/注解路径,未访问。",
|
||||
"保留源引用;固定加载器返回IMAGE和MASK,本图MASK均未"
|
||||
"接。470供编辑第一参考与对比A,475供第二参考,不保证文件可"
|
||||
"读/内容/批大小。",
|
||||
[load],
|
||||
)
|
||||
add(
|
||||
"LoadImage",
|
||||
"upload",
|
||||
"上传显示控制",
|
||||
"前端控件 / STRING",
|
||||
"image(前端显示状态)",
|
||||
"不适用",
|
||||
"前端上传控件,非后端执行字段。",
|
||||
"源保存image是前端上传显示值,不是图片数据或文件名;不进入LoadImage.image,不执行上传。",
|
||||
[upload, upload_widget, load],
|
||||
)
|
||||
add(
|
||||
"Image Comparer (rgthree)",
|
||||
"rgthree_comparer",
|
||||
"历史A/B对比状态",
|
||||
"前端复合ARRAY",
|
||||
"构造值{images: []},不是后端参数",
|
||||
"不适用",
|
||||
"一个保存位置含两记录;selected/url历史状态,不证明当前可达。",
|
||||
(
|
||||
"位置数组由onSerialize取value.images并删除"
|
||||
"img;具名包装仍为{images:[...img:{}]}"
|
||||
",setter支持两形态。本图保留两层原形,不强作逐JSON相等"
|
||||
"。固定Python继承PreviewImage,A/B各自可"
|
||||
"能写temp PNG并返回a_images/b_images;输"
|
||||
"出继承IMAGE,result优先A否则B。历史URL只作不"
|
||||
"透明文本,不加载、不嵌图、不探测。"
|
||||
),
|
||||
[py, preview, js, restore, slide],
|
||||
)
|
||||
|
||||
by_id = {n["id"]: n for n in graph["nodes"]}
|
||||
bindings = []
|
||||
for slot, boundary in enumerate(graph["inputs"][:18]):
|
||||
targets = []
|
||||
for lid in boundary["linkIds"]:
|
||||
ei, edge = next((i, e) for i, e in enumerate(graph["links"]) if e["id"] == lid)
|
||||
n = by_id[edge["target_id"]]
|
||||
inp = n["inputs"][edge["target_slot"]]
|
||||
targets.append(
|
||||
dict(
|
||||
node_id=f"459:{n['id']}",
|
||||
definition_node_id=str(n["id"]),
|
||||
field=inp["name"],
|
||||
link_pointer=f"/definitions/subgraphs/0/links/{ei}",
|
||||
target_pointer=f"/definitions/subgraphs/0/nodes/{graph['nodes'].index(n)}/inputs/{edge['target_slot']}",
|
||||
)
|
||||
)
|
||||
bindings.append(
|
||||
dict(
|
||||
slot=slot,
|
||||
name=boundary["name"],
|
||||
boundary_id=boundary["id"],
|
||||
boundary_pointer=f"/definitions/subgraphs/0/inputs/{slot}",
|
||||
widget_id_rule=f"widgetId(rootGraph.id, 459, {boundary['name']!r})",
|
||||
value_pointer=f"/nodes/0/widgets_values/{slot}",
|
||||
named_pointer="/nodes/0/widgets_values_named/" + boundary["name"],
|
||||
targets=targets,
|
||||
)
|
||||
)
|
||||
targets = {(t["node_id"], t["field"]): b for b in bindings for t in b["targets"]}
|
||||
fields = []
|
||||
comments = []
|
||||
for scope, g in [("root", source), ("definition", graph)]:
|
||||
for ni, n in enumerate(g["nodes"]):
|
||||
prefix = f"/nodes/{ni}" if scope == "root" else f"/definitions/subgraphs/0/nodes/{ni}"
|
||||
if n["type"] in ("MarkdownNote", "Note"):
|
||||
comments.append(
|
||||
dict(
|
||||
node_id=str(n["id"]),
|
||||
pointer=prefix + "/widgets_values/0",
|
||||
text=n["widgets_values"][0],
|
||||
)
|
||||
)
|
||||
continue
|
||||
names = list(n.get("widgets_values_named", {}))
|
||||
values = n.get("widgets_values") or []
|
||||
assert len(names) == len(values)
|
||||
for offset, (name, value) in enumerate(zip(names, values)):
|
||||
nid = str(n["id"]) if scope == "root" else f"459:{n['id']}"
|
||||
binding = None
|
||||
if n["id"] == 459:
|
||||
binding = next(b for b in bindings if b["name"] == name)
|
||||
t = next(
|
||||
t
|
||||
for t in binding["targets"]
|
||||
if (by_id[int(t["definition_node_id"])]["type"], t["field"]) in specs
|
||||
)
|
||||
spec = copy.deepcopy(
|
||||
specs[by_id[int(t["definition_node_id"])]["type"], t["field"]]
|
||||
)
|
||||
spec["label"] = "宿主暴露:" + spec["label"]
|
||||
spec["field"] = name
|
||||
note = "宿主保存值,经边界送至" + ", ".join(
|
||||
t["node_id"] + "." + t["field"] for t in binding["targets"]
|
||||
)
|
||||
else:
|
||||
spec = copy.deepcopy(specs[n["type"], name])
|
||||
note = "保留此保存值;仅固定源码参考,未实跑。"
|
||||
role = "scalar"
|
||||
if (nid, name) in targets:
|
||||
binding = targets[nid, name]
|
||||
role = "linked"
|
||||
note = f"内部保存值由宿主{binding['name']}({binding['value_pointer']})覆盖。"
|
||||
if (n["id"] == 459 and name in ("width", "height")) or (
|
||||
n["id"] == 456 and name in ("width", "height")
|
||||
):
|
||||
note += "根502经810/811覆盖宿主1024缓存,再经660/661到456;当前468选456。"
|
||||
role = "linked"
|
||||
if n["id"] == 459 and name == "prompt":
|
||||
note += ";本图没有根外线覆盖,原始中文编辑请求同时到484.on_false与500.prompt。"
|
||||
if n["id"] == 474 and name == "prompt":
|
||||
note = (
|
||||
"内部空串由480槽0经743覆盖,484槽0经791进480;switch_1=true选500生成文本。"
|
||||
)
|
||||
role = "linked"
|
||||
if n["id"] == 479:
|
||||
note = "经807连到500.system_prompt,use_default_template=false使指南不采用。"
|
||||
if name == "control_after_generate":
|
||||
role = "frontend"
|
||||
note = (
|
||||
"原保存randomize(并非fixed),前端控制不进prom"
|
||||
"pt;未调用钩子,不推断队列后值。"
|
||||
)
|
||||
if n["type"] == "LoadImage" and name == "upload":
|
||||
role = "frontend"
|
||||
note = (
|
||||
"前端上传button的保存显示值,serialize:false,"
|
||||
"不进入后端prompt;未上传或触发预览回调。"
|
||||
)
|
||||
if n["id"] == 501:
|
||||
role = "frontend"
|
||||
note = (
|
||||
"历史A/B预览复合状态,一项不是两项;具名包装另列在flow。URL仅文本,未请求。"
|
||||
)
|
||||
spec.update(
|
||||
node_id=nid,
|
||||
definition_node_id=str(n["id"]),
|
||||
scope=scope,
|
||||
class_type=n["type"],
|
||||
value=value,
|
||||
json_type=type(value).__name__,
|
||||
pointer=prefix + f"/widgets_values/{offset}",
|
||||
named_pointer=prefix + "/widgets_values_named/" + name,
|
||||
role=role,
|
||||
execution_note=note,
|
||||
)
|
||||
if binding:
|
||||
spec["binding"] = binding
|
||||
fields.append(spec)
|
||||
assert len(fields) == 70 and len(comments) == 3 and len(bindings) == 18
|
||||
comparer = next(n for n in source["nodes"] if n["id"] == 501)
|
||||
flows = [
|
||||
(
|
||||
"本图用途:以两张参考图和中文编辑请求“为角色更换服装”作条件,可"
|
||||
"选提示词优化,经采样/解码/PNG保存并与第一参考图对比。根"
|
||||
"9节点7边、定义15节点58边,共24源节点65物理边;70保存"
|
||||
"位置不是70最终执行参数,未构造执行候选。"
|
||||
"执行标量计数0仅表示本轮未构造候选,不表示运行无需参数。"
|
||||
),
|
||||
(
|
||||
"作用域:459引用bc1c967a-7f6a-4be9-a372"
|
||||
"-dad16e4f28e3;18宿主保存值、根其它12值与内"
|
||||
"部40值分列。widgetId(rootGraph.id,459"
|
||||
",input.name)按边界/原件恢复;物理外线优先于宿主"
|
||||
"保存,再覆盖内部保存值。未接images.image_3~10及"
|
||||
"images.image_5_1等源名全部保留,不能据固定核"
|
||||
"心同名认定前端兼容。"
|
||||
),
|
||||
(
|
||||
"提示链:宿主prompt无外线,同时经739到484.on_fa"
|
||||
"lse、802到500.prompt;switch_1=tr"
|
||||
"ue经741到484.switch,500槽0经806到on_true,484经791到480.source,480经743"
|
||||
"到474.prompt。false才直接采用原始编辑请求;Pre"
|
||||
"viewAny只文本预览/透传,未生成字幕文件。"
|
||||
),
|
||||
(
|
||||
"系统/思考:479指南经807进500.system_prompt,但use_default_template=false使"
|
||||
"skip_template=true、system_prompt"
|
||||
"为空;thinking=true仅请求支持能力,不是已产生思"
|
||||
"考结果。原请求和指南作为不透明字符串保存,未改写或运行。"
|
||||
),
|
||||
(
|
||||
"尺寸链:switch=true经703到468.switch,t"
|
||||
"rue取456空latent(684→on_true),fa"
|
||||
"lse才取474编码latent(724→on_false),输"
|
||||
"出682到458.latent_image。根502比例9:"
|
||||
"16/1.5MP/8经810/811覆盖宿主width/heig"
|
||||
"ht=1024,再经660/661到456。本图不是两个开关"
|
||||
"都控制提示词,也不保证不同latent通道与目标模型兼容。"
|
||||
),
|
||||
(
|
||||
"resolution=0经725覆盖474内部1024:>0按r"
|
||||
"esolution平方预算保持比例缩放,0按每项自身宽高ro"
|
||||
"und到32并至少32;首个有效图确定编码latent空间。没有"
|
||||
"图时回退resolution or 1024;自定义尺寸当前"
|
||||
"取456,所以编码分辨率与采样latent尺寸须分开,不把0解释"
|
||||
"成完全原尺寸或不生效。"
|
||||
),
|
||||
(
|
||||
"两图链:470槽0经704到459.images.image_1"
|
||||
",475槽0经728到image_2;分别扇出到474(71"
|
||||
"0/711)和485(750/779)。474按数字后缀排序、跳"
|
||||
"None、每项取首张;485将images.values送合"
|
||||
"批,空列表返回None,代码不主动过滤None;按最大通道数给不"
|
||||
"足者补1通道,再按首图宽高bilinear/center匹配"
|
||||
"后cat成batch,501不参与这条编辑条件链。真实素材/可用"
|
||||
"性/批大小/输出质量未知,不声称已读两图。"
|
||||
),
|
||||
(
|
||||
"双seed:宿主1054732230873463经667到458.seed、804到500.sampling_mode.se"
|
||||
"ed,两个内部0都保留为被覆盖保存值。KSampler实际con"
|
||||
"trol_after_generate=randomize,"
|
||||
"任务摘要fixed与源不符;只记录前端控制,不模拟队列随机化或保"
|
||||
"证重复性,限定sampling_mode.seed不自动加种"
|
||||
"子控制。"
|
||||
),
|
||||
(
|
||||
"模型/条件:451→469缓存→458.model,453→47"
|
||||
"4.clip,477→500.clip,两CLIP type"
|
||||
"均为qwen_image;454向474和457供VAE。474"
|
||||
"正负出口722/723到458,458经651到457解码,"
|
||||
"457经650到子图输出,再672→461。宿主unet_name/clip_name/clip_name_1/vae_na"
|
||||
"me与内部不同名均保留,路径反斜杠不归一化;动态选项、模型文件、"
|
||||
"设备、显存与UE7.8实际安装未知。"
|
||||
),
|
||||
(
|
||||
"对比拓扑:470槽0经808到501.image_a;459→4"
|
||||
"61槽0经809到501.image_b。第二张475不直接"
|
||||
"作A端。固定rgthree Python继承core Previ"
|
||||
"ewImage/SaveImage的IMAGE出口并返回re"
|
||||
"sult优先A,否则B;本图声明出口与该固定core一致,但其它"
|
||||
"目标版本仍未知,未使用出口不删除。A/B各可能保存temp "
|
||||
"PNG供UI,461永久输出与501临时预览分别说明,均未真实生成。"
|
||||
),
|
||||
(
|
||||
"复合双存储:501仅一项widgets_values数组,含两个"
|
||||
"历史A/B记录;widgets_values_named.r"
|
||||
"gthree_comparer是images包装且带img={}"
|
||||
"。固定JS setter接受数组或包装,serialize取"
|
||||
"images并删img;不能套逐JSON相等规则,也不能证明具名"
|
||||
"包装序列化钩子实际运行顺序。selected=true不证明"
|
||||
"当前预览/文件存在。历史/api/view URL只作为不透明文"
|
||||
"本,不加载、超链接探测或嵌图。"
|
||||
),
|
||||
"对比属性(不计入70项):"
|
||||
+ json.dumps(comparer["properties"], ensure_ascii=False)
|
||||
+ ";comparer_mode=Slide是显示属性,固定JS非C"
|
||||
"lick时按指针位置绘制滑动对比;不是后端参数。双存储原具名包装"
|
||||
":" + json.dumps(comparer["widgets_values_named"], ensure_ascii=False),
|
||||
(
|
||||
"三条源注释全文保留,可读但不当运行事实或下载授权。模型/素材链接"
|
||||
"、原生2K/关闭取原尺寸等注释建议不能代替固定算法和实际环境"
|
||||
"验证;仅本地说明GET,未访问历史/api/view或目标机。"
|
||||
),
|
||||
(
|
||||
"执行边界:此图不在已审九份完整参考候选中;仅接入固定说明,未添加"
|
||||
"profile或生成API。转换/未知依赖仍拦截,regis"
|
||||
"try/object_info/client/output_map/worker不改,155定稿0/实跑0。"
|
||||
),
|
||||
]
|
||||
for b in bindings:
|
||||
flows.append(
|
||||
"暴露绑定:459."
|
||||
+ b["name"]
|
||||
+ ";"
|
||||
+ b["widget_id_rule"]
|
||||
+ ";"
|
||||
+ b["value_pointer"]
|
||||
+ ";边界"
|
||||
+ b["boundary_pointer"]
|
||||
+ " → "
|
||||
+ json.dumps(b["targets"], ensure_ascii=False)
|
||||
)
|
||||
for scope, g in [("root", source), ("definition", graph)]:
|
||||
for i, e in enumerate(g["links"]):
|
||||
flows.append("源边 " + scope + " " + str(i) + ":" + json.dumps(e, ensure_ascii=False))
|
||||
return dict(
|
||||
notice="固定版本参考说明:frontend1.53.6/core0.38"
|
||||
".0与rgthree精确提交;UE7.8/目标安装/素材/实跑未"
|
||||
"知,执行仍关闭",
|
||||
source_path=PATH,
|
||||
source_sha1=hashlib.sha1(raw).hexdigest(),
|
||||
source_sha256=hashlib.sha256(raw).hexdigest(),
|
||||
canonical_sha256=hashlib.sha256(canonical(source)).hexdigest(),
|
||||
subgraph_sha256=hashlib.sha256(canonical(graph)).hexdigest(),
|
||||
versions=[
|
||||
"frontend1.53.6=7d533a4cd4c4904ff"
|
||||
"db0537f6b80ae9793dd62f1;固定保存/恢复参"
|
||||
"考,不证明队列或第三方具名序列化顺序。",
|
||||
(
|
||||
"核心声明core0.38.0=6b747c0428c343e1417219641db93a4fb7cb69ae;rgthre"
|
||||
"e-comfy=449c58fcdd612f7733e54c51"
|
||||
"f6758ead63fa180b;固定源码不证明目标安装。"
|
||||
),
|
||||
"UE7.8记录、未接动态端口/旧端口名与目标插件、动态模型/素材/设备/历史预览状态均待核对。",
|
||||
],
|
||||
counts=dict(
|
||||
saved_fields=70,
|
||||
root_saved=30,
|
||||
definition_saved=40,
|
||||
source_notes=3,
|
||||
host_saved=18,
|
||||
source_nodes=24,
|
||||
physical_edges=65,
|
||||
linked_saved_fields=sum(f["role"] == "linked" for f in fields),
|
||||
frontend_only=sum(f["role"] == "frontend" for f in fields),
|
||||
final_scalars=0,
|
||||
final_prompt_constructed=False,
|
||||
),
|
||||
fields=fields,
|
||||
sources=refs,
|
||||
flow=flows,
|
||||
flow_evidence=list(range(len(refs))),
|
||||
comments=comments,
|
||||
bindings=bindings,
|
||||
steps=[
|
||||
"核对两素材引用:470为第一参考和A端,475只作第二参考;MA"
|
||||
"SK未接,不能把文件名中的masked当遮罩已参与。",
|
||||
"核对宿主中文编辑请求,无根外线覆盖;提示词优化switch_1="
|
||||
"true选500结果,false才直传请求。系统指南当前不采用,"
|
||||
"思考仅支持条件。",
|
||||
"分别核对resolution=0参考图对齐规则与自定义尺寸swi"
|
||||
"tch=true空latent路径;根502宽高覆盖缓存,不能照"
|
||||
"注释声称原尺寸或实际输出尺寸。",
|
||||
"逐项核对18宿主绑定、40内部保存值及模型/两seed;rand"
|
||||
"omize只是原前端状态,未运行队列,不保证双seed运行时相同"
|
||||
"或可复现。",
|
||||
(
|
||||
"沿474条件→458采样→457解码→461 PNG→501.i"
|
||||
"mage_b,对照470→image_a;历史A/B sel"
|
||||
"ected和URL不是本次生成结果。常见误判是把第二参考作A、把"
|
||||
"系统指南当生效、把内部缓存当有效尺寸、把历史URL当当前文件"
|
||||
"。"
|
||||
),
|
||||
"真实文件读取、缺图/混合尺寸兼容、模型/设备/插件安装、hist"
|
||||
"ory与PNG/临时文件/质量须未来授权实跑核对;当前全停用、未"
|
||||
"定稿、未实跑。",
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
def main():
|
||||
target = REPO / "calliope-backend/src/calliope/comfyui/source_reviews.json"
|
||||
reviews = json.loads(target.read_bytes())
|
||||
block = build()
|
||||
assert reviews[PATH]["source_sha"] == block["source_sha1"]
|
||||
reviews[PATH]["fixed_version_document"] = block
|
||||
target.write_text(json.dumps(reviews, ensure_ascii=False, indent=2) + "\n")
|
||||
(OUT / "definition.json").write_text(json.dumps(block, ensure_ascii=False, indent=2) + "\n")
|
||||
print(hashlib.sha256(canonical(block)).hexdigest())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,310 @@
|
||||
"""Actual 157a296 upgrade, one-row rollback, user protection and package byte checks."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import sqlite3
|
||||
import subprocess
|
||||
import sys
|
||||
import tarfile
|
||||
import tempfile
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
REPO = Path(__file__).resolve().parents[3]
|
||||
OUT = Path(__file__).resolve().parent
|
||||
BASE = "157a29687ce15e936639387849863a228c26e367"
|
||||
sys.path.insert(0, str(REPO / "calliope-backend"))
|
||||
|
||||
|
||||
def write(name, data):
|
||||
(OUT / name).write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n")
|
||||
|
||||
|
||||
def require_packages():
|
||||
dist = REPO / "calliope-backend/dist"
|
||||
wheels, archives = sorted(dist.glob("*.whl")), sorted(dist.glob("*.tar.gz"))
|
||||
if not wheels or not archives:
|
||||
raise SystemExit(
|
||||
"缺少wheel/sdist包产物,请先在仓库根执行:uv build --project calliope-backend --offline"
|
||||
)
|
||||
return wheels[-1], archives[-1]
|
||||
|
||||
|
||||
def main():
|
||||
wheel_path, sdist_path = require_packages()
|
||||
from calliope.comfyui.fixed_document import DEFINITIONS as ALL_DEFINITIONS
|
||||
from calliope.comfyui.fixed_document import canonical
|
||||
|
||||
definitions = {
|
||||
p: d
|
||||
for p, d in ALL_DEFINITIONS.items()
|
||||
if p.endswith("Qwen_image2.1_图像编辑_提示词增强.json")
|
||||
}
|
||||
old_paths = ALL_DEFINITIONS.keys() - definitions.keys()
|
||||
from calliope.comfyui.library import rollback_batch
|
||||
from scripts.audit_library_documents import audit
|
||||
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
work = Path(directory)
|
||||
old = work / "old"
|
||||
old.mkdir()
|
||||
raw = subprocess.check_output(["git", "archive", BASE, "calliope-backend/src"], cwd=REPO)
|
||||
with tarfile.open(fileobj=io.BytesIO(raw)) as archive:
|
||||
archive.extractall(old, filter="data")
|
||||
db = work / "old.db"
|
||||
|
||||
def run(name, historical=False):
|
||||
output = work / name
|
||||
env = {
|
||||
**os.environ,
|
||||
"PYTHONPATH": str((old if historical else REPO) / "calliope-backend/src"),
|
||||
}
|
||||
subprocess.run(
|
||||
[
|
||||
sys.executable,
|
||||
"-m",
|
||||
"calliope.comfyui.library_cli",
|
||||
"import",
|
||||
"--root",
|
||||
str(REPO / "example_ComfyUI_workflows"),
|
||||
"--db",
|
||||
str(db),
|
||||
"--source-commit",
|
||||
BASE,
|
||||
"--companions",
|
||||
str(REPO / "docs/hel-892/supplied-api/manifest.json"),
|
||||
"--output-dir",
|
||||
str(output),
|
||||
],
|
||||
cwd=REPO,
|
||||
env=env,
|
||||
check=True,
|
||||
stdout=subprocess.DEVNULL,
|
||||
)
|
||||
return json.loads((output / "import_report.json").read_bytes()), output
|
||||
|
||||
def rows():
|
||||
with sqlite3.connect(db) as conn:
|
||||
conn.row_factory = sqlite3.Row
|
||||
return {
|
||||
r["source_repo_path"]: dict(r) for r in conn.execute("SELECT * FROM workflows")
|
||||
}
|
||||
|
||||
first, _ = run("old-first", True)
|
||||
before = rows()
|
||||
assert first["counts"] == {"imported": 155, "user_excluded": 1}
|
||||
for p in old_paths:
|
||||
assert json.loads(before[p]["doc_json"])["fixed_version"]["matched"]
|
||||
for p in definitions:
|
||||
assert "fixed_version" not in json.loads(before[p]["doc_json"])
|
||||
original = db
|
||||
old_protection = []
|
||||
|
||||
def protect_old(name):
|
||||
nonlocal db
|
||||
save_db = db
|
||||
db = work / (name + ".db")
|
||||
with sqlite3.connect(save_db) as src, sqlite3.connect(db) as dst:
|
||||
src.backup(dst)
|
||||
for p in old_paths:
|
||||
dst.execute(
|
||||
"UPDATE workflows SET description=? WHERE source_repo_path=?", (name, p)
|
||||
)
|
||||
snapshot = rows()
|
||||
protected, _ = run(name)
|
||||
assert (
|
||||
protected["counts"] == {"conflict": 9, "skipped": 146, "user_excluded": 1}
|
||||
if name == "old-user-after"
|
||||
else protected["counts"]
|
||||
== {"conflict": 9, "updated": 1, "skipped": 145, "user_excluded": 1}
|
||||
)
|
||||
# New document updates before upgrade are expected, every old edited row must be exact.
|
||||
result = rows()
|
||||
assert all(result[p] == snapshot[p] and len(result[p]) == 29 for p in old_paths)
|
||||
old_protection.append(
|
||||
{"phase": name, "counts": protected["counts"], "whole_old_rows_protected": 9}
|
||||
)
|
||||
db = save_db
|
||||
|
||||
protect_old("old-user-before")
|
||||
db = work / "user-before.db"
|
||||
with sqlite3.connect(original) as src, sqlite3.connect(db) as dst:
|
||||
src.backup(dst)
|
||||
for p in definitions:
|
||||
dst.execute(
|
||||
"UPDATE workflows SET description=? WHERE source_repo_path=?",
|
||||
("用户升级前编辑", p),
|
||||
)
|
||||
user_before = rows()
|
||||
protected_before, _ = run("user-before")
|
||||
assert protected_before["counts"] == {
|
||||
"conflict": 1,
|
||||
"skipped": 154,
|
||||
"user_excluded": 1,
|
||||
}
|
||||
assert rows() == user_before
|
||||
db = original
|
||||
upgrade, _exported = run("upgrade")
|
||||
after = rows()
|
||||
assert upgrade["counts"] == {"updated": 1, "skipped": 154, "user_excluded": 1}
|
||||
for path, row in after.items():
|
||||
if path not in definitions:
|
||||
assert row == before[path]
|
||||
else:
|
||||
for k in row.keys() - {
|
||||
"doc_json",
|
||||
"batch_id",
|
||||
"imported_at",
|
||||
"library_fingerprint",
|
||||
}:
|
||||
assert row[k] == before[path][k]
|
||||
d = json.loads(row["doc_json"])
|
||||
assert d["fixed_version"]["matched"]
|
||||
b = {k: v for k, v in d["fixed_version"].items() if k != "matched"}
|
||||
assert hashlib.sha256(canonical(b)).hexdigest() == definitions[path]
|
||||
write("actual-" + Path(path).stem + ".json", d)
|
||||
protect_old("old-user-after")
|
||||
repeat, _ = run("repeat")
|
||||
assert repeat["counts"] == {"skipped": 155, "user_excluded": 1}
|
||||
with sqlite3.connect(db) as conn:
|
||||
conn.row_factory = sqlite3.Row
|
||||
rollback = rollback_batch(conn, upgrade["batch_id"])
|
||||
assert len(rollback["files"]) == 1 and all(
|
||||
f["result"] == "restored" for f in rollback["files"]
|
||||
)
|
||||
assert rows() == before
|
||||
redo, _ = run("redo")
|
||||
assert redo["counts"] == upgrade["counts"]
|
||||
for p in definitions:
|
||||
with sqlite3.connect(db) as conn:
|
||||
conn.execute(
|
||||
"UPDATE workflows SET description=? WHERE source_repo_path=?",
|
||||
("用户升级后编辑", p),
|
||||
)
|
||||
user_after = rows()
|
||||
protected_after, _ = run("user-after")
|
||||
assert protected_after["counts"] == protected_before["counts"]
|
||||
assert rows() == user_after and all(len(user_after[p]) == 29 for p in definitions)
|
||||
db = work / "fresh.db"
|
||||
fresh, fresh_export = run("fresh")
|
||||
fresh_repeat, _ = run("fresh-repeat")
|
||||
assert fresh["counts"] == first["counts"]
|
||||
assert fresh["states"] == {"pending_check": 16, "needs_conversion": 139}
|
||||
assert fresh_repeat["counts"] == repeat["counts"]
|
||||
companion = 0
|
||||
for row in rows().values():
|
||||
d = json.loads(row["doc_json"])
|
||||
companion += sum(p.get("value_origin") == "supplied_api_companion" for p in d["params"])
|
||||
assert (
|
||||
not row["is_enabled"]
|
||||
and row["doc_completed_at"] is None
|
||||
and row["exec_verified_at"] is None
|
||||
)
|
||||
assert not d["status"]["doc_done"] and not d["status"]["exec_verified"]
|
||||
assert d["dependencies"]["check_state"] == "unchecked"
|
||||
assert companion == 294
|
||||
report = audit(REPO, fresh_export)
|
||||
assert report["named_values_preserved"] == 1217 and report["unnamed_widget_nodes"] == 3660
|
||||
assert report["full_documents_completed"] == report["real_executions"] == 0
|
||||
write("audit-summary.json", {k: v for k, v in report.items() if k != "files"})
|
||||
write(
|
||||
"import-protection.json",
|
||||
dict(
|
||||
historical_code=BASE,
|
||||
old_nine_protection=old_protection,
|
||||
first=first["counts"],
|
||||
upgrade=upgrade["counts"],
|
||||
repeat=repeat["counts"],
|
||||
restored_rows=1,
|
||||
untouched_whole_rows=154,
|
||||
eligibility_columns_unchanged=True,
|
||||
redo=redo["counts"],
|
||||
user_before=protected_before["counts"],
|
||||
user_after=protected_after["counts"],
|
||||
user_whole_row_columns=29,
|
||||
fresh=fresh["counts"],
|
||||
fresh_repeat=fresh_repeat["counts"],
|
||||
states=fresh["states"],
|
||||
source_named_fields=1217,
|
||||
positional_widgets=3660,
|
||||
companion_values=companion,
|
||||
new_saved_definitions=70,
|
||||
old_saved_definitions=202,
|
||||
all_disabled=True,
|
||||
dependencies_unchecked=True,
|
||||
doc_done=0,
|
||||
executed=0,
|
||||
),
|
||||
)
|
||||
reviews_path = "calliope-backend/src/calliope/comfyui/source_reviews.json"
|
||||
previous = json.loads(
|
||||
subprocess.check_output(["git", "show", f"{BASE}:{reviews_path}"], cwd=REPO)
|
||||
)
|
||||
current = json.loads((REPO / reviews_path).read_bytes())
|
||||
for p in definitions:
|
||||
assert "fixed_version_document" not in previous[p]
|
||||
current[p].pop("fixed_version_document")
|
||||
assert previous == current
|
||||
boundaries = json.loads(
|
||||
(REPO / "docs/hel-892/h3-document-evidence/unchanged-boundaries.json").read_bytes()
|
||||
)
|
||||
paths = [f["path"] for f in boundaries["files"]] + boundaries["frozen_conversion_and_audits"]
|
||||
paths += ["calliope-backend/src/calliope/comfyui/library.py"]
|
||||
kept = []
|
||||
for p in paths:
|
||||
raw = (REPO / p).read_bytes()
|
||||
assert raw == subprocess.check_output(["git", "show", f"{BASE}:{p}"], cwd=REPO)
|
||||
kept.append(dict(path=p, sha256=hashlib.sha256(raw).hexdigest()))
|
||||
ui = "calliope-web/src/lib/components/WorkflowDocumentDrawer.svelte"
|
||||
assert (REPO / ui).read_text().split("<style>")[1] == subprocess.check_output(
|
||||
["git", "show", f"{BASE}:{ui}"], cwd=REPO
|
||||
).decode().split("<style>")[1]
|
||||
write(
|
||||
"boundaries.json",
|
||||
dict(
|
||||
base=BASE,
|
||||
files=kept,
|
||||
originals=163,
|
||||
source_reviews_only_one_new_block=True,
|
||||
drawer_css_unchanged=True,
|
||||
conversion_rerun=False,
|
||||
old_28_profiles_9_candidates_6_diffs="unchanged artifacts and implementation",
|
||||
),
|
||||
)
|
||||
packages = []
|
||||
with (
|
||||
zipfile.ZipFile(wheel_path) as wheel,
|
||||
tarfile.open(sdist_path) as sdist,
|
||||
):
|
||||
for name in ["fixed_document.py", "source_reviews.json", "library.py"]:
|
||||
raw = (REPO / "calliope-backend/src/calliope/comfyui" / name).read_bytes()
|
||||
assert wheel.read("calliope/comfyui/" + name) == raw
|
||||
member = next(
|
||||
n for n in sdist.getnames() if n.endswith("/src/calliope/comfyui/" + name)
|
||||
)
|
||||
assert sdist.extractfile(member).read() == raw
|
||||
packages.append(
|
||||
dict(
|
||||
file=name,
|
||||
sha256=hashlib.sha256(raw).hexdigest(),
|
||||
wheel=True,
|
||||
sdist=True,
|
||||
)
|
||||
)
|
||||
write("package-check.json", packages)
|
||||
print(
|
||||
(
|
||||
"PASS: actual old-code upgrade1/skip154, ro"
|
||||
"llback1, user conflicts1 before/after, old"
|
||||
"9 protected, fresh155, 70+202 definitions, "
|
||||
"1217/3660/294, boundaries and packages"
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,73 @@
|
||||
"""Render the actual source-bound definition as a readable Chinese handoff appendix."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
OUT = Path(__file__).resolve().parent
|
||||
REPO = OUT.parents[2]
|
||||
|
||||
|
||||
def main():
|
||||
block = json.loads((OUT / "definition.json").read_bytes())
|
||||
lines = [
|
||||
"# Qwen图像编辑增强图固定参考中文说明",
|
||||
"",
|
||||
"本批接入现有详情抽屉;70新保存位置+3新注释,旧九图202保存位置+3注释不变,十图展示。155说明定稿0、实跑0,新增转换0,全量目标未完成。",
|
||||
"",
|
||||
"## 图特定说明与边界",
|
||||
"",
|
||||
block["notice"],
|
||||
"",
|
||||
*[line + "\n" for line in block["flow"][:14]],
|
||||
"## 使用与常见误判",
|
||||
"",
|
||||
*[line + "\n" for line in block["steps"]],
|
||||
"## 70处实际保存位置",
|
||||
"",
|
||||
]
|
||||
for i, field in enumerate(block["fields"], 1):
|
||||
lines += [
|
||||
f"### {i}. {field['node_id']} · {field['label']}({field['field']})",
|
||||
"",
|
||||
field["effect"],
|
||||
"",
|
||||
f"作用域:{field['scope']};原定义节点{field['definition_node_id']};类{field['class_type']};源JSON类型{field['json_type']}。",
|
||||
"",
|
||||
"```json",
|
||||
json.dumps(field["value"], ensure_ascii=False, indent=2),
|
||||
"```",
|
||||
"",
|
||||
f"源位置:`{field['pointer']}`;具名保存:`{field['named_pointer']}`。",
|
||||
"",
|
||||
f"schema默认:{field['schema_default']};单位:{field['unit']}。",
|
||||
"",
|
||||
field["limits"],
|
||||
"",
|
||||
field["execution_note"],
|
||||
"",
|
||||
]
|
||||
for index in field["evidence"]:
|
||||
evidence = block["sources"][index]
|
||||
lines += [
|
||||
f"- {evidence['claim']}:{evidence['url']};"
|
||||
f"完整提交{evidence['commit']};SHA256 `{evidence['sha256']}`;"
|
||||
f"行{evidence['lines'][0]}~{evidence['lines'][1]}。"
|
||||
]
|
||||
lines.append("")
|
||||
lines += ["## 三条不透明源注释", ""]
|
||||
for note in block["comments"]:
|
||||
lines += [
|
||||
f"### 节点{note['node_id']} · `{note['pointer']}`",
|
||||
"",
|
||||
"```json",
|
||||
json.dumps(note["text"], ensure_ascii=False),
|
||||
"```",
|
||||
"",
|
||||
]
|
||||
(OUT.parent / "Qwen图像编辑增强图固定参考中文说明.md").write_text("\n".join(lines) + "\n")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,22 @@
|
||||
# 仓库根;锁定既有依赖,全部数据库/服务均本地隔离,不连接目标机。
|
||||
uv sync --project calliope-backend --frozen --extra dev --python 3.11
|
||||
npm ci --prefix calliope-web --ignore-scripts
|
||||
uv run --project calliope-backend --offline python docs/hel-892/qwen-edit-document-evidence/build_definition.py
|
||||
uv run --project calliope-backend --offline python docs/hel-892/qwen-edit-document-evidence/render_report.py
|
||||
uv run --project calliope-backend --offline pytest calliope-backend/tests/test_qwen_edit_fixed_document.py calliope-backend/tests/test_qwen_fixed_document.py calliope-backend/tests/test_controlnet_fixed_document.py calliope-backend/tests/test_asr_fixed_document.py calliope-backend/tests/test_media_fixed_document.py calliope-backend/tests/test_audio_fixed_document.py calliope-backend/tests/test_fixed_document.py calliope-backend/tests/test_workflow_library.py calliope-backend/tests/test_supplied_companions.py calliope-backend/tests/test_delivery_scope.py calliope-backend/tests/test_case04_saved_reference.py -q --disable-warnings
|
||||
uv run --project calliope-backend --offline ruff check --config calliope-backend/pyproject.toml calliope-backend/src/calliope/comfyui/fixed_document.py calliope-backend/tests/test_qwen_edit_fixed_document.py calliope-backend/tests/test_controlnet_fixed_document.py docs/hel-892/qwen-edit-document-evidence/*.py docs/hel-892/qwen-document-evidence/recompute.py e2e/run-qwen-edit-document.py
|
||||
uv run --project calliope-backend --offline ruff format --config calliope-backend/pyproject.toml --check calliope-backend/src/calliope/comfyui/fixed_document.py calliope-backend/tests/test_qwen_edit_fixed_document.py calliope-backend/tests/test_controlnet_fixed_document.py docs/hel-892/qwen-edit-document-evidence/*.py docs/hel-892/qwen-document-evidence/recompute.py e2e/run-qwen-edit-document.py
|
||||
uv build --project calliope-backend --offline
|
||||
uv run --project calliope-backend --offline python docs/hel-892/qwen-edit-document-evidence/recompute.py
|
||||
# 先构建包再复算,缺包时中文提示构建命令。builder.build()连调两次不写源资源,和definition.json逐对象比较。
|
||||
# 重复recompute,比较repeatability.json所列5份确定性JSON的SHA256。样例import-protection.json、audit-summary.json、boundaries.json、package-check.json。
|
||||
npm run build --prefix calliope-web
|
||||
npm test --prefix calliope-web
|
||||
npm run check --prefix calliope-web
|
||||
# check旧基线:1错误/2警告;ESLint旧缺eslint.config退出2,不称全仓全绿。
|
||||
# 从calliope-web:npm exec -- eslint src/lib/components/WorkflowDocumentDrawer.svelte src/lib/comfy/types.ts
|
||||
node --check e2e/qwen-edit-document.mjs
|
||||
LD_LIBRARY_PATH=/home/xiaomo/chromium-libs/root/usr/lib/x86_64-linux-gnu:/home/xiaomo/browserlibs/root/usr/lib/x86_64-linux-gnu PLAYWRIGHT_MODULE=/home/xiaomo/.npm-global/lib/node_modules/playwright/index.mjs BROWSER_EXECUTABLE=/home/xiaomo/.cache/ms-playwright/chromium-1248/chrome-linux64/chrome uv run --project calliope-backend --offline python e2e/run-qwen-edit-document.py
|
||||
# --only-qwen仅复跑新编辑图;旧9图使用上面全组已完成证据。最后改动仅新图保存分类/数字类型,无前端产品变更。
|
||||
# 新图浏览将既有Google字体CSS请求本地空响应,不放行外网;/api/view和其它外部请求均拒绝并使测试失败。
|
||||
# Supervisor在正常/异常出口关闭全部自建服务;截图由工单附件交付,不含在线媒体。
|
||||
@@ -0,0 +1,914 @@
|
||||
from typing_extensions import override
|
||||
import numpy as np
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
from PIL import Image
|
||||
import math
|
||||
from enum import Enum
|
||||
from typing import TypedDict, Literal
|
||||
import kornia
|
||||
|
||||
import comfy.utils
|
||||
import comfy.model_management
|
||||
from comfy_extras.nodes_latent import reshape_latent_to
|
||||
import node_helpers
|
||||
from comfy_api.latest import ComfyExtension, io
|
||||
from nodes import MAX_RESOLUTION
|
||||
|
||||
class Blend(io.ComfyNode):
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
return io.Schema(
|
||||
node_id="ImageBlend",
|
||||
search_aliases=["mix images"],
|
||||
display_name="Blend Images",
|
||||
category="image/filters",
|
||||
essentials_category="Image Tools",
|
||||
inputs=[
|
||||
io.Image.Input("image1"),
|
||||
io.Image.Input("image2"),
|
||||
io.Float.Input("blend_factor", default=0.5, min=0.0, max=1.0, step=0.01),
|
||||
io.Combo.Input("blend_mode", options=["normal", "multiply", "screen", "overlay", "soft_light", "difference"]),
|
||||
],
|
||||
outputs=[
|
||||
io.Image.Output(),
|
||||
],
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def execute(cls, image1: torch.Tensor, image2: torch.Tensor, blend_factor: float, blend_mode: str) -> io.NodeOutput:
|
||||
image1, image2 = node_helpers.image_alpha_fix(image1, image2)
|
||||
image2 = image2.to(image1.device)
|
||||
if image1.shape != image2.shape:
|
||||
image2 = image2.permute(0, 3, 1, 2)
|
||||
image2 = comfy.utils.common_upscale(image2, image1.shape[2], image1.shape[1], upscale_method='bicubic', crop='center')
|
||||
image2 = image2.permute(0, 2, 3, 1)
|
||||
|
||||
blended_image = cls.blend_mode(image1, image2, blend_mode)
|
||||
blended_image = image1 * (1 - blend_factor) + blended_image * blend_factor
|
||||
blended_image = torch.clamp(blended_image, 0, 1)
|
||||
if image1.shape[-1] == 4: # alpha stores transparency, not color
|
||||
blended_image[..., 3] = image1[..., 3]
|
||||
return io.NodeOutput(blended_image)
|
||||
|
||||
@classmethod
|
||||
def blend_mode(cls, img1, img2, mode):
|
||||
if mode == "normal":
|
||||
return img2
|
||||
elif mode == "multiply":
|
||||
return img1 * img2
|
||||
elif mode == "screen":
|
||||
return 1 - (1 - img1) * (1 - img2)
|
||||
elif mode == "overlay":
|
||||
return torch.where(img1 <= 0.5, 2 * img1 * img2, 1 - 2 * (1 - img1) * (1 - img2))
|
||||
elif mode == "soft_light":
|
||||
return torch.where(img2 <= 0.5, img1 - (1 - 2 * img2) * img1 * (1 - img1), img1 + (2 * img2 - 1) * (cls.g(img1) - img1))
|
||||
elif mode == "difference":
|
||||
return img1 - img2
|
||||
raise ValueError(f"Unsupported blend mode: {mode}")
|
||||
|
||||
@classmethod
|
||||
def g(cls, x):
|
||||
return torch.where(x <= 0.25, ((16 * x - 12) * x + 4) * x, torch.sqrt(x))
|
||||
|
||||
def gaussian_kernel(kernel_size: int, sigma: float, device=None, dtype=torch.float32):
|
||||
x, y = torch.meshgrid(torch.linspace(-1, 1, kernel_size, device=device), torch.linspace(-1, 1, kernel_size, device=device), indexing="ij")
|
||||
d = torch.sqrt(x * x + y * y)
|
||||
g = torch.exp(-(d * d) / (2.0 * sigma * sigma))
|
||||
return (g / g.sum()).to(dtype)
|
||||
|
||||
class Blur(io.ComfyNode):
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
return io.Schema(
|
||||
node_id="ImageBlur",
|
||||
display_name="Blur Image",
|
||||
category="image/filters",
|
||||
inputs=[
|
||||
io.Image.Input("image"),
|
||||
io.Int.Input("blur_radius", default=1, min=1, max=31, step=1),
|
||||
io.Float.Input("sigma", default=1.0, min=0.1, max=10.0, step=0.1),
|
||||
],
|
||||
outputs=[
|
||||
io.Image.Output(),
|
||||
],
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def execute(cls, image: torch.Tensor, blur_radius: int, sigma: float) -> io.NodeOutput:
|
||||
if blur_radius == 0:
|
||||
return io.NodeOutput(image)
|
||||
|
||||
image = image.to(comfy.model_management.get_torch_device())
|
||||
batch_size, height, width, channels = image.shape
|
||||
|
||||
kernel_size = blur_radius * 2 + 1
|
||||
kernel = gaussian_kernel(kernel_size, sigma, device=image.device, dtype=image.dtype).repeat(channels, 1, 1).unsqueeze(1)
|
||||
|
||||
image = image.permute(0, 3, 1, 2) # Torch wants (B, C, H, W) we use (B, H, W, C)
|
||||
padded_image = F.pad(image, (blur_radius,blur_radius,blur_radius,blur_radius), 'reflect')
|
||||
blurred = F.conv2d(padded_image, kernel, padding=kernel_size // 2, groups=channels)[:,:,blur_radius:-blur_radius, blur_radius:-blur_radius]
|
||||
blurred = blurred.permute(0, 2, 3, 1)
|
||||
|
||||
return io.NodeOutput(blurred.to(comfy.model_management.intermediate_device()))
|
||||
|
||||
|
||||
class Quantize(io.ComfyNode):
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
return io.Schema(
|
||||
node_id="ImageQuantize",
|
||||
display_name="Quantize Image",
|
||||
category="image/filters",
|
||||
inputs=[
|
||||
io.Image.Input("image"),
|
||||
io.Int.Input("colors", default=256, min=1, max=256, step=1),
|
||||
io.Combo.Input("dither", options=["none", "floyd-steinberg", "bayer-2", "bayer-4", "bayer-8", "bayer-16"]),
|
||||
],
|
||||
outputs=[
|
||||
io.Image.Output(),
|
||||
],
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def bayer(im, pal_im, order):
|
||||
def normalized_bayer_matrix(n):
|
||||
if n == 0:
|
||||
return np.zeros((1,1), "float32")
|
||||
else:
|
||||
q = 4 ** n
|
||||
m = q * normalized_bayer_matrix(n - 1)
|
||||
return np.bmat(((m-1.5, m+0.5), (m+1.5, m-0.5))) / q
|
||||
|
||||
num_colors = len(pal_im.getpalette()) // 3
|
||||
spread = 2 * 256 / num_colors
|
||||
bayer_n = int(math.log2(order))
|
||||
bayer_matrix = torch.from_numpy(spread * normalized_bayer_matrix(bayer_n) + 0.5)
|
||||
|
||||
result = torch.from_numpy(np.array(im).astype(np.float32))
|
||||
tw = math.ceil(result.shape[0] / bayer_matrix.shape[0])
|
||||
th = math.ceil(result.shape[1] / bayer_matrix.shape[1])
|
||||
tiled_matrix = bayer_matrix.tile(tw, th).unsqueeze(-1)
|
||||
result.add_(tiled_matrix[:result.shape[0],:result.shape[1]]).clamp_(0, 255)
|
||||
result = result.to(dtype=torch.uint8)
|
||||
|
||||
im = Image.fromarray(result.cpu().numpy())
|
||||
im = im.quantize(palette=pal_im, dither=Image.Dither.NONE)
|
||||
return im
|
||||
|
||||
@classmethod
|
||||
def execute(cls, image: torch.Tensor, colors: int, dither: str) -> io.NodeOutput:
|
||||
rgb = image[..., :3]
|
||||
batch_size, height, width, _ = rgb.shape
|
||||
result = torch.zeros_like(rgb)
|
||||
|
||||
for b in range(batch_size):
|
||||
im = Image.fromarray((rgb[b] * 255).to(torch.uint8).numpy(), mode='RGB')
|
||||
|
||||
pal_im = im.quantize(colors=colors) # Required as described in https://github.com/python-pillow/Pillow/issues/5836
|
||||
|
||||
if dither == "none":
|
||||
quantized_image = im.quantize(palette=pal_im, dither=Image.Dither.NONE)
|
||||
elif dither == "floyd-steinberg":
|
||||
quantized_image = im.quantize(palette=pal_im, dither=Image.Dither.FLOYDSTEINBERG)
|
||||
elif dither.startswith("bayer"):
|
||||
order = int(dither.split('-')[-1])
|
||||
quantized_image = Quantize.bayer(im, pal_im, order)
|
||||
|
||||
quantized_array = torch.tensor(np.array(quantized_image.convert("RGB"))).float() / 255
|
||||
result[b] = quantized_array
|
||||
|
||||
if image.shape[-1] == 4:
|
||||
result = torch.cat((result, image[..., 3:]), dim=-1)
|
||||
return io.NodeOutput(result)
|
||||
|
||||
class Sharpen(io.ComfyNode):
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
return io.Schema(
|
||||
node_id="ImageSharpen",
|
||||
display_name="Sharpen Image",
|
||||
category="image/filters",
|
||||
inputs=[
|
||||
io.Image.Input("image"),
|
||||
io.Int.Input("sharpen_radius", default=1, min=1, max=31, step=1, advanced=True),
|
||||
io.Float.Input("sigma", default=1.0, min=0.1, max=10.0, step=0.01, advanced=True),
|
||||
io.Float.Input("alpha", default=1.0, min=0.0, max=5.0, step=0.01, advanced=True),
|
||||
],
|
||||
outputs=[
|
||||
io.Image.Output(),
|
||||
],
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def execute(cls, image: torch.Tensor, sharpen_radius: int, sigma:float, alpha: float) -> io.NodeOutput:
|
||||
if sharpen_radius == 0:
|
||||
return io.NodeOutput(image)
|
||||
|
||||
batch_size, height, width, channels = image.shape
|
||||
image = image.to(comfy.model_management.get_torch_device())
|
||||
|
||||
kernel_size = sharpen_radius * 2 + 1
|
||||
kernel = gaussian_kernel(kernel_size, sigma, device=image.device, dtype=image.dtype) * -(alpha*10)
|
||||
kernel = kernel.to(dtype=image.dtype)
|
||||
center = kernel_size // 2
|
||||
kernel[center, center] = kernel[center, center] - kernel.sum() + 1.0
|
||||
kernel = kernel.repeat(channels, 1, 1).unsqueeze(1)
|
||||
|
||||
tensor_image = image.permute(0, 3, 1, 2) # Torch wants (B, C, H, W) we use (B, H, W, C)
|
||||
tensor_image = F.pad(tensor_image, (sharpen_radius,sharpen_radius,sharpen_radius,sharpen_radius), 'reflect')
|
||||
sharpened = F.conv2d(tensor_image, kernel, padding=center, groups=channels)[:,:,sharpen_radius:-sharpen_radius, sharpen_radius:-sharpen_radius]
|
||||
sharpened = sharpened.permute(0, 2, 3, 1)
|
||||
|
||||
result = torch.clamp(sharpened, 0, 1)
|
||||
|
||||
return io.NodeOutput(result.to(comfy.model_management.intermediate_device()))
|
||||
|
||||
class ImageScaleToTotalPixels(io.ComfyNode):
|
||||
upscale_methods = ["nearest-exact", "bilinear", "area", "bicubic", "lanczos"]
|
||||
crop_methods = ["disabled", "center"]
|
||||
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
return io.Schema(
|
||||
node_id="ImageScaleToTotalPixels",
|
||||
display_name="Scale Image to Total Pixels",
|
||||
category="image/upscaling",
|
||||
inputs=[
|
||||
io.Image.Input("image"),
|
||||
io.Combo.Input("upscale_method", options=cls.upscale_methods),
|
||||
io.Float.Input("megapixels", default=1.0, min=0.01, max=16.0, step=0.01),
|
||||
io.Int.Input("resolution_steps", default=1, min=1, max=256, advanced=True),
|
||||
],
|
||||
outputs=[
|
||||
io.Image.Output(),
|
||||
],
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def execute(cls, image, upscale_method, megapixels, resolution_steps) -> io.NodeOutput:
|
||||
samples = image.movedim(-1,1)
|
||||
total = megapixels * 1024 * 1024
|
||||
|
||||
scale_by = math.sqrt(total / (samples.shape[3] * samples.shape[2]))
|
||||
width = round(samples.shape[3] * scale_by / resolution_steps) * resolution_steps
|
||||
height = round(samples.shape[2] * scale_by / resolution_steps) * resolution_steps
|
||||
|
||||
s = comfy.utils.common_upscale(samples, int(width), int(height), upscale_method, "disabled")
|
||||
s = s.movedim(1,-1)
|
||||
return io.NodeOutput(s)
|
||||
|
||||
class ResizeType(str, Enum):
|
||||
SCALE_BY = "scale by multiplier"
|
||||
SCALE_DIMENSIONS = "scale dimensions"
|
||||
SCALE_LONGER_DIMENSION = "scale longer dimension"
|
||||
SCALE_SHORTER_DIMENSION = "scale shorter dimension"
|
||||
SCALE_WIDTH = "scale width"
|
||||
SCALE_HEIGHT = "scale height"
|
||||
SCALE_TOTAL_PIXELS = "scale total pixels"
|
||||
MATCH_SIZE = "match size"
|
||||
SCALE_TO_MULTIPLE = "scale to multiple"
|
||||
|
||||
def is_image(input: torch.Tensor) -> bool:
|
||||
# images have 4 dimensions: [batch, height, width, channels]
|
||||
# masks have 3 dimensions: [batch, height, width]
|
||||
return len(input.shape) == 4
|
||||
|
||||
def init_image_mask_input(input: torch.Tensor, is_type_image: bool) -> torch.Tensor:
|
||||
if is_type_image:
|
||||
input = input.movedim(-1, 1)
|
||||
else:
|
||||
input = input.unsqueeze(1)
|
||||
return input
|
||||
|
||||
def finalize_image_mask_input(input: torch.Tensor, is_type_image: bool) -> torch.Tensor:
|
||||
if is_type_image:
|
||||
input = input.movedim(1, -1)
|
||||
else:
|
||||
input = input.squeeze(1)
|
||||
return input
|
||||
|
||||
def scale_by(input: torch.Tensor, multiplier: float, scale_method: str) -> torch.Tensor:
|
||||
is_type_image = is_image(input)
|
||||
input = init_image_mask_input(input, is_type_image)
|
||||
width = round(input.shape[-1] * multiplier)
|
||||
height = round(input.shape[-2] * multiplier)
|
||||
|
||||
input = comfy.utils.common_upscale(input, width, height, scale_method, "disabled")
|
||||
input = finalize_image_mask_input(input, is_type_image)
|
||||
return input
|
||||
|
||||
def scale_dimensions(input: torch.Tensor, width: int, height: int, scale_method: str, crop: str="disabled") -> torch.Tensor:
|
||||
if width == 0 and height == 0:
|
||||
return input
|
||||
is_type_image = is_image(input)
|
||||
input = init_image_mask_input(input, is_type_image)
|
||||
|
||||
if width == 0:
|
||||
width = max(1, round(input.shape[-1] * height / input.shape[-2]))
|
||||
elif height == 0:
|
||||
height = max(1, round(input.shape[-2] * width / input.shape[-1]))
|
||||
|
||||
input = comfy.utils.common_upscale(input, width, height, scale_method, crop)
|
||||
input = finalize_image_mask_input(input, is_type_image)
|
||||
return input
|
||||
|
||||
def scale_longer_dimension(input: torch.Tensor, longer_size: int, scale_method: str) -> torch.Tensor:
|
||||
is_type_image = is_image(input)
|
||||
input = init_image_mask_input(input, is_type_image)
|
||||
width = input.shape[-1]
|
||||
height = input.shape[-2]
|
||||
|
||||
if height > width:
|
||||
width = round((width / height) * longer_size)
|
||||
height = longer_size
|
||||
elif width > height:
|
||||
height = round((height / width) * longer_size)
|
||||
width = longer_size
|
||||
else:
|
||||
height = longer_size
|
||||
width = longer_size
|
||||
|
||||
input = comfy.utils.common_upscale(input, width, height, scale_method, "disabled")
|
||||
input = finalize_image_mask_input(input, is_type_image)
|
||||
return input
|
||||
|
||||
def scale_shorter_dimension(input: torch.Tensor, shorter_size: int, scale_method: str) -> torch.Tensor:
|
||||
is_type_image = is_image(input)
|
||||
input = init_image_mask_input(input, is_type_image)
|
||||
width = input.shape[-1]
|
||||
height = input.shape[-2]
|
||||
|
||||
if height < width:
|
||||
width = round((width / height) * shorter_size)
|
||||
height = shorter_size
|
||||
elif width < height:
|
||||
height = round((height / width) * shorter_size)
|
||||
width = shorter_size
|
||||
else:
|
||||
height = shorter_size
|
||||
width = shorter_size
|
||||
|
||||
input = comfy.utils.common_upscale(input, width, height, scale_method, "disabled")
|
||||
input = finalize_image_mask_input(input, is_type_image)
|
||||
return input
|
||||
|
||||
def scale_total_pixels(input: torch.Tensor, megapixels: float, scale_method: str) -> torch.Tensor:
|
||||
is_type_image = is_image(input)
|
||||
input = init_image_mask_input(input, is_type_image)
|
||||
total = int(megapixels * 1024 * 1024)
|
||||
|
||||
scale_by = math.sqrt(total / (input.shape[-1] * input.shape[-2]))
|
||||
width = round(input.shape[-1] * scale_by)
|
||||
height = round(input.shape[-2] * scale_by)
|
||||
|
||||
input = comfy.utils.common_upscale(input, width, height, scale_method, "disabled")
|
||||
input = finalize_image_mask_input(input, is_type_image)
|
||||
return input
|
||||
|
||||
def scale_match_size(input: torch.Tensor, match: torch.Tensor, scale_method: str, crop: str) -> torch.Tensor:
|
||||
is_type_image = is_image(input)
|
||||
input = init_image_mask_input(input, is_type_image)
|
||||
match = init_image_mask_input(match, is_image(match))
|
||||
|
||||
width = match.shape[-1]
|
||||
height = match.shape[-2]
|
||||
input = comfy.utils.common_upscale(input, width, height, scale_method, crop)
|
||||
input = finalize_image_mask_input(input, is_type_image)
|
||||
return input
|
||||
|
||||
def scale_to_multiple_cover(input: torch.Tensor, multiple: int, scale_method: str) -> torch.Tensor:
|
||||
if multiple <= 1:
|
||||
return input
|
||||
is_type_image = is_image(input)
|
||||
if is_type_image:
|
||||
_, height, width, _ = input.shape
|
||||
else:
|
||||
_, height, width = input.shape
|
||||
target_w = (width // multiple) * multiple
|
||||
target_h = (height // multiple) * multiple
|
||||
if target_w == 0 or target_h == 0:
|
||||
return input
|
||||
if target_w == width and target_h == height:
|
||||
return input
|
||||
s_w = target_w / width
|
||||
s_h = target_h / height
|
||||
if s_w >= s_h:
|
||||
scaled_w = target_w
|
||||
scaled_h = int(math.ceil(height * s_w))
|
||||
if scaled_h < target_h:
|
||||
scaled_h = target_h
|
||||
else:
|
||||
scaled_h = target_h
|
||||
scaled_w = int(math.ceil(width * s_h))
|
||||
if scaled_w < target_w:
|
||||
scaled_w = target_w
|
||||
input = init_image_mask_input(input, is_type_image)
|
||||
input = comfy.utils.common_upscale(input, scaled_w, scaled_h, scale_method, "disabled")
|
||||
input = finalize_image_mask_input(input, is_type_image)
|
||||
x0 = (scaled_w - target_w) // 2
|
||||
y0 = (scaled_h - target_h) // 2
|
||||
x1 = x0 + target_w
|
||||
y1 = y0 + target_h
|
||||
if is_type_image:
|
||||
return input[:, y0:y1, x0:x1, :]
|
||||
return input[:, y0:y1, x0:x1]
|
||||
|
||||
class ResizeImageMaskNode(io.ComfyNode):
|
||||
scale_methods = ["nearest-exact", "bilinear", "area", "bicubic", "lanczos"]
|
||||
crop_methods = ["disabled", "center"]
|
||||
|
||||
class ResizeTypedDict(TypedDict):
|
||||
resize_type: ResizeType
|
||||
scale_method: Literal["nearest-exact", "bilinear", "area", "bicubic", "lanczos"]
|
||||
crop: Literal["disabled", "center"]
|
||||
multiplier: float
|
||||
width: int
|
||||
height: int
|
||||
longer_size: int
|
||||
shorter_size: int
|
||||
megapixels: float
|
||||
multiple: int
|
||||
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
template = io.MatchType.Template("input_type", [io.Image, io.Mask])
|
||||
crop_combo = io.Combo.Input(
|
||||
"crop",
|
||||
options=cls.crop_methods,
|
||||
default="center",
|
||||
tooltip="How to handle aspect ratio mismatch: 'disabled' stretches to fit, 'center' crops to maintain aspect ratio.",
|
||||
)
|
||||
return io.Schema(
|
||||
node_id="ResizeImageMaskNode",
|
||||
display_name="Resize Image/Mask",
|
||||
description="Resize an image or mask using various scaling methods.",
|
||||
category="image/transform",
|
||||
search_aliases=["resize", "resize image", "resize mask", "scale", "scale image", "scale mask", "image resize", "change size", "dimensions", "shrink", "enlarge"],
|
||||
inputs=[
|
||||
io.MatchType.Input("input", template=template),
|
||||
io.DynamicCombo.Input(
|
||||
"resize_type",
|
||||
tooltip="Select how to resize: by exact dimensions, scale factor, matching another image, etc.",
|
||||
options=[
|
||||
io.DynamicCombo.Option(ResizeType.SCALE_DIMENSIONS, [
|
||||
io.Int.Input("width", default=512, min=0, max=MAX_RESOLUTION, step=1, tooltip="Target width in pixels. Set to 0 to auto-calculate from height while preserving aspect ratio."),
|
||||
io.Int.Input("height", default=512, min=0, max=MAX_RESOLUTION, step=1, tooltip="Target height in pixels. Set to 0 to auto-calculate from width while preserving aspect ratio."),
|
||||
crop_combo,
|
||||
]),
|
||||
io.DynamicCombo.Option(ResizeType.SCALE_BY, [
|
||||
io.Float.Input("multiplier", default=1.00, min=0.01, max=8.0, step=0.01, tooltip="Scale factor (e.g., 2.0 doubles size, 0.5 halves size)."),
|
||||
]),
|
||||
io.DynamicCombo.Option(ResizeType.SCALE_LONGER_DIMENSION, [
|
||||
io.Int.Input("longer_size", default=512, min=0, max=MAX_RESOLUTION, step=1, tooltip="The longer edge will be resized to this value. Aspect ratio is preserved."),
|
||||
]),
|
||||
io.DynamicCombo.Option(ResizeType.SCALE_SHORTER_DIMENSION, [
|
||||
io.Int.Input("shorter_size", default=512, min=0, max=MAX_RESOLUTION, step=1, tooltip="The shorter edge will be resized to this value. Aspect ratio is preserved."),
|
||||
]),
|
||||
io.DynamicCombo.Option(ResizeType.SCALE_WIDTH, [
|
||||
io.Int.Input("width", default=512, min=0, max=MAX_RESOLUTION, step=1, tooltip="Target width in pixels. Height auto-adjusts to preserve aspect ratio."),
|
||||
]),
|
||||
io.DynamicCombo.Option(ResizeType.SCALE_HEIGHT, [
|
||||
io.Int.Input("height", default=512, min=0, max=MAX_RESOLUTION, step=1, tooltip="Target height in pixels. Width auto-adjusts to preserve aspect ratio."),
|
||||
]),
|
||||
io.DynamicCombo.Option(ResizeType.SCALE_TOTAL_PIXELS, [
|
||||
io.Float.Input("megapixels", default=1.0, min=0.01, max=16.0, step=0.01, tooltip="Target total megapixels (e.g., 1.0 ≈ 1024×1024). Aspect ratio is preserved."),
|
||||
]),
|
||||
io.DynamicCombo.Option(ResizeType.MATCH_SIZE, [
|
||||
io.MultiType.Input("match", [io.Image, io.Mask], tooltip="Resize input to match the dimensions of this reference image or mask."),
|
||||
crop_combo,
|
||||
]),
|
||||
io.DynamicCombo.Option(ResizeType.SCALE_TO_MULTIPLE, [
|
||||
io.Int.Input("multiple", default=8, min=1, max=MAX_RESOLUTION, step=1, tooltip="Resize so width and height are divisible by this number. Useful for latent alignment (e.g., 8 or 64)."),
|
||||
]),
|
||||
],
|
||||
),
|
||||
io.Combo.Input(
|
||||
"scale_method",
|
||||
options=cls.scale_methods,
|
||||
default="area",
|
||||
tooltip="Interpolation algorithm. 'area' is best for downscaling, 'lanczos' for upscaling, 'nearest-exact' for pixel art.",
|
||||
),
|
||||
],
|
||||
outputs=[io.MatchType.Output(template=template, display_name="resized")]
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def execute(cls, input: io.Image.Type | io.Mask.Type, scale_method: io.Combo.Type, resize_type: ResizeTypedDict) -> io.NodeOutput:
|
||||
selected_type = resize_type["resize_type"]
|
||||
if selected_type == ResizeType.SCALE_BY:
|
||||
return io.NodeOutput(scale_by(input, resize_type["multiplier"], scale_method))
|
||||
elif selected_type == ResizeType.SCALE_DIMENSIONS:
|
||||
return io.NodeOutput(scale_dimensions(input, resize_type["width"], resize_type["height"], scale_method, resize_type["crop"]))
|
||||
elif selected_type == ResizeType.SCALE_LONGER_DIMENSION:
|
||||
return io.NodeOutput(scale_longer_dimension(input, resize_type["longer_size"], scale_method))
|
||||
elif selected_type == ResizeType.SCALE_SHORTER_DIMENSION:
|
||||
return io.NodeOutput(scale_shorter_dimension(input, resize_type["shorter_size"], scale_method))
|
||||
elif selected_type == ResizeType.SCALE_WIDTH:
|
||||
return io.NodeOutput(scale_dimensions(input, resize_type["width"], 0, scale_method))
|
||||
elif selected_type == ResizeType.SCALE_HEIGHT:
|
||||
return io.NodeOutput(scale_dimensions(input, 0, resize_type["height"], scale_method))
|
||||
elif selected_type == ResizeType.SCALE_TOTAL_PIXELS:
|
||||
return io.NodeOutput(scale_total_pixels(input, resize_type["megapixels"], scale_method))
|
||||
elif selected_type == ResizeType.MATCH_SIZE:
|
||||
return io.NodeOutput(scale_match_size(input, resize_type["match"], scale_method, resize_type["crop"]))
|
||||
elif selected_type == ResizeType.SCALE_TO_MULTIPLE:
|
||||
return io.NodeOutput(scale_to_multiple_cover(input, resize_type["multiple"], scale_method))
|
||||
raise ValueError(f"Unsupported resize type: {selected_type}")
|
||||
|
||||
def batch_images(images: list[torch.Tensor]) -> torch.Tensor | None:
|
||||
if len(images) == 0:
|
||||
return None
|
||||
# first, get the max channels count
|
||||
max_channels = max(image.shape[-1] for image in images)
|
||||
# then, pad all images to have the same channels count
|
||||
padded_images: list[torch.Tensor] = []
|
||||
for image in images:
|
||||
if image.shape[-1] < max_channels:
|
||||
padded_images.append(torch.nn.functional.pad(image, (0,1), mode='constant', value=1.0))
|
||||
else:
|
||||
padded_images.append(image)
|
||||
# resize all images to be the same size as the first image
|
||||
resized_images: list[torch.Tensor] = []
|
||||
first_image_shape = padded_images[0].shape
|
||||
for image in padded_images:
|
||||
if image.shape[1:] != first_image_shape[1:]:
|
||||
resized_images.append(comfy.utils.common_upscale(image.movedim(-1,1), first_image_shape[2], first_image_shape[1], "bilinear", "center").movedim(1,-1))
|
||||
else:
|
||||
resized_images.append(image)
|
||||
# batch the images in the format [b, h, w, c]
|
||||
return torch.cat(resized_images, dim=0)
|
||||
|
||||
def batch_masks(masks: list[torch.Tensor]) -> torch.Tensor | None:
|
||||
if len(masks) == 0:
|
||||
return None
|
||||
# resize all masks to be the same size as the first mask
|
||||
resized_masks: list[torch.Tensor] = []
|
||||
first_mask_shape = masks[0].shape
|
||||
for mask in masks:
|
||||
if mask.shape[1:] != first_mask_shape[1:]:
|
||||
mask = init_image_mask_input(mask, is_type_image=False)
|
||||
mask = comfy.utils.common_upscale(mask, first_mask_shape[2], first_mask_shape[1], "bilinear", "center")
|
||||
resized_masks.append(finalize_image_mask_input(mask, is_type_image=False))
|
||||
else:
|
||||
resized_masks.append(mask)
|
||||
# batch the masks in the format [b, h, w]
|
||||
return torch.cat(resized_masks, dim=0)
|
||||
|
||||
def batch_latents(latents: list[dict[str, torch.Tensor]]) -> dict[str, torch.Tensor] | None:
|
||||
if len(latents) == 0:
|
||||
return None
|
||||
samples_out = latents[0].copy()
|
||||
samples_out["batch_index"] = []
|
||||
first_samples = latents[0]["samples"]
|
||||
tensors: list[torch.Tensor] = []
|
||||
for latent in latents:
|
||||
# first, deal with latent tensors
|
||||
tensors.append(reshape_latent_to(first_samples.shape, latent["samples"], repeat_batch=False))
|
||||
# next, deal with batch_index
|
||||
samples_out["batch_index"].extend(latent.get("batch_index", [x for x in range(0, latent["samples"].shape[0])]))
|
||||
samples_out["samples"] = torch.cat(tensors, dim=0)
|
||||
return samples_out
|
||||
|
||||
class BatchImagesNode(io.ComfyNode):
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
autogrow_template = io.Autogrow.TemplatePrefix(io.Image.Input("image"), prefix="image", min=1, max=50)
|
||||
return io.Schema(
|
||||
node_id="BatchImagesNode",
|
||||
display_name="Batch Images",
|
||||
category="image/batch",
|
||||
essentials_category="Image Tools",
|
||||
search_aliases=["batch", "image batch", "batch images", "combine images", "merge images", "stack images"],
|
||||
inputs=[
|
||||
io.Autogrow.Input("images", template=autogrow_template)
|
||||
],
|
||||
outputs=[
|
||||
io.Image.Output()
|
||||
]
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def execute(cls, images: io.Autogrow.Type) -> io.NodeOutput:
|
||||
return io.NodeOutput(batch_images(list(images.values())))
|
||||
|
||||
class BatchMasksNode(io.ComfyNode):
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
autogrow_template = io.Autogrow.TemplatePrefix(io.Mask.Input("mask"), prefix="mask", min=1, max=50)
|
||||
return io.Schema(
|
||||
node_id="BatchMasksNode",
|
||||
search_aliases=["combine masks", "stack masks", "merge masks"],
|
||||
display_name="Batch Masks",
|
||||
category="image/mask",
|
||||
inputs=[
|
||||
io.Autogrow.Input("masks", template=autogrow_template)
|
||||
],
|
||||
outputs=[
|
||||
io.Mask.Output()
|
||||
]
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def execute(cls, masks: io.Autogrow.Type) -> io.NodeOutput:
|
||||
return io.NodeOutput(batch_masks(list(masks.values())))
|
||||
|
||||
class BatchLatentsNode(io.ComfyNode):
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
autogrow_template = io.Autogrow.TemplatePrefix(io.Latent.Input("latent"), prefix="latent", min=1, max=50)
|
||||
return io.Schema(
|
||||
node_id="BatchLatentsNode",
|
||||
search_aliases=["combine latents", "stack latents", "merge latents"],
|
||||
display_name="Batch Latents",
|
||||
category="model/latent/batch",
|
||||
inputs=[
|
||||
io.Autogrow.Input("latents", template=autogrow_template)
|
||||
],
|
||||
outputs=[
|
||||
io.Latent.Output()
|
||||
]
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def execute(cls, latents: io.Autogrow.Type) -> io.NodeOutput:
|
||||
return io.NodeOutput(batch_latents(list(latents.values())))
|
||||
|
||||
class BatchImagesMasksLatentsNode(io.ComfyNode):
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
matchtype_template = io.MatchType.Template("input", allowed_types=[io.Image, io.Mask, io.Latent])
|
||||
autogrow_template = io.Autogrow.TemplatePrefix(
|
||||
io.MatchType.Input("input", matchtype_template),
|
||||
prefix="input", min=1, max=50)
|
||||
return io.Schema(
|
||||
node_id="BatchImagesMasksLatentsNode",
|
||||
search_aliases=["combine batch", "merge batch", "stack inputs"],
|
||||
display_name="Batch Images/Masks/Latents",
|
||||
category="util",
|
||||
inputs=[
|
||||
io.Autogrow.Input("inputs", template=autogrow_template)
|
||||
],
|
||||
outputs=[
|
||||
io.MatchType.Output(id=None, template=matchtype_template)
|
||||
]
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def execute(cls, inputs: io.Autogrow.Type) -> io.NodeOutput:
|
||||
batched = None
|
||||
values = list(inputs.values())
|
||||
# latents
|
||||
if isinstance(values[0], dict):
|
||||
batched = batch_latents(values)
|
||||
# images
|
||||
elif is_image(values[0]):
|
||||
batched = batch_images(values)
|
||||
# masks
|
||||
else:
|
||||
batched = batch_masks(values)
|
||||
return io.NodeOutput(batched)
|
||||
|
||||
|
||||
class ColorTransfer(io.ComfyNode):
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
return io.Schema(
|
||||
node_id="ColorTransfer",
|
||||
display_name="Transfer Color",
|
||||
category="image/filters",
|
||||
description="Match the colors of one image to another using various algorithms.",
|
||||
search_aliases=["color match", "color grading", "color correction", "match colors", "color transform", "mkl", "reinhard", "histogram"],
|
||||
inputs=[
|
||||
io.Image.Input("image_target", tooltip="Image(s) to apply the color transform to."),
|
||||
io.Image.Input("image_ref", tooltip="Reference image(s) to match colors to."),
|
||||
io.Combo.Input("method", options=['reinhard_lab', 'mkl_lab', 'histogram'],),
|
||||
io.DynamicCombo.Input("source_stats",
|
||||
tooltip="per_frame: each frame matched to image_ref individually. uniform: pool stats across all source frames as baseline, match to image_ref. target_frame: use one chosen frame as the baseline for the transform to image_ref, applied uniformly to all frames (preserves relative differences)",
|
||||
options=[
|
||||
io.DynamicCombo.Option("per_frame", []),
|
||||
io.DynamicCombo.Option("uniform", []),
|
||||
io.DynamicCombo.Option("target_frame", [
|
||||
io.Int.Input("target_index", default=0, min=0, max=10000,
|
||||
tooltip="Frame index used as the source baseline for computing the transform to image_ref"),
|
||||
]),
|
||||
]),
|
||||
io.Float.Input("strength", default=1.0, min=0.0, max=10.0, step=0.01),
|
||||
],
|
||||
outputs=[
|
||||
io.Image.Output(display_name="image"),
|
||||
],
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _to_lab(images, i, device):
|
||||
return kornia.color.rgb_to_lab(
|
||||
images[i:i+1].to(device, dtype=torch.float32).permute(0, 3, 1, 2))
|
||||
|
||||
@staticmethod
|
||||
def _pool_stats(images, device, is_reinhard, eps):
|
||||
"""Two-pass pooled mean + std/cov across all frames."""
|
||||
N, C = images.shape[0], images.shape[3]
|
||||
HW = images.shape[1] * images.shape[2]
|
||||
mean = torch.zeros(C, 1, device=device, dtype=torch.float32)
|
||||
for i in range(N):
|
||||
mean += ColorTransfer._to_lab(images, i, device).view(C, -1).mean(dim=-1, keepdim=True)
|
||||
mean /= N
|
||||
acc = torch.zeros(C, 1 if is_reinhard else C, device=device, dtype=torch.float32)
|
||||
for i in range(N):
|
||||
centered = ColorTransfer._to_lab(images, i, device).view(C, -1) - mean
|
||||
if is_reinhard:
|
||||
acc += (centered * centered).mean(dim=-1, keepdim=True)
|
||||
else:
|
||||
acc += centered @ centered.T / HW
|
||||
if is_reinhard:
|
||||
return mean, torch.sqrt(acc / N).clamp_min_(eps)
|
||||
return mean, acc / N
|
||||
|
||||
@staticmethod
|
||||
def _frame_stats(lab_flat, hw, is_reinhard, eps):
|
||||
"""Per-frame mean + std/cov."""
|
||||
mean = lab_flat.mean(dim=-1, keepdim=True)
|
||||
if is_reinhard:
|
||||
return mean, lab_flat.std(dim=-1, keepdim=True, unbiased=False).clamp_min_(eps)
|
||||
centered = lab_flat - mean
|
||||
return mean, centered @ centered.T / hw
|
||||
|
||||
@staticmethod
|
||||
def _mkl_matrix(cov_s, cov_r, eps):
|
||||
"""Compute MKL 3x3 transform matrix from source and ref covariances."""
|
||||
eig_val_s, eig_vec_s = torch.linalg.eigh(cov_s)
|
||||
sqrt_val_s = torch.sqrt(eig_val_s.clamp_min(0)).clamp_min_(eps)
|
||||
|
||||
scaled_V = eig_vec_s * sqrt_val_s.unsqueeze(0)
|
||||
mid = scaled_V.T @ cov_r @ scaled_V
|
||||
eig_val_m, eig_vec_m = torch.linalg.eigh(mid)
|
||||
sqrt_m = torch.sqrt(eig_val_m.clamp_min(0))
|
||||
|
||||
inv_sqrt_s = 1.0 / sqrt_val_s
|
||||
inv_scaled_V = eig_vec_s * inv_sqrt_s.unsqueeze(0)
|
||||
M_half = (eig_vec_m * sqrt_m.unsqueeze(0)) @ eig_vec_m.T
|
||||
return inv_scaled_V @ M_half @ inv_scaled_V.T
|
||||
|
||||
@staticmethod
|
||||
def _histogram_lut(src, ref, bins=256):
|
||||
"""Build per-channel LUT from source and ref histograms. src/ref: (C, HW) in [0,1]."""
|
||||
s_bins = (src * (bins - 1)).long().clamp(0, bins - 1)
|
||||
r_bins = (ref * (bins - 1)).long().clamp(0, bins - 1)
|
||||
s_hist = torch.zeros(src.shape[0], bins, device=src.device, dtype=src.dtype)
|
||||
r_hist = torch.zeros(src.shape[0], bins, device=src.device, dtype=src.dtype)
|
||||
ones_s = torch.ones_like(src)
|
||||
ones_r = torch.ones_like(ref)
|
||||
s_hist.scatter_add_(1, s_bins, ones_s)
|
||||
r_hist.scatter_add_(1, r_bins, ones_r)
|
||||
s_cdf = s_hist.cumsum(1)
|
||||
s_cdf = s_cdf / s_cdf[:, -1:]
|
||||
r_cdf = r_hist.cumsum(1)
|
||||
r_cdf = r_cdf / r_cdf[:, -1:]
|
||||
return torch.searchsorted(r_cdf, s_cdf).clamp_max_(bins - 1).float() / (bins - 1)
|
||||
|
||||
@classmethod
|
||||
def _pooled_cdf(cls, images, device, num_bins=256):
|
||||
"""Build pooled CDF across all frames, one frame at a time."""
|
||||
C = images.shape[3]
|
||||
hist = torch.zeros(C, num_bins, device=device, dtype=torch.float32)
|
||||
for i in range(images.shape[0]):
|
||||
frame = images[i].to(device, dtype=torch.float32).permute(2, 0, 1).reshape(C, -1)
|
||||
bins = (frame * (num_bins - 1)).long().clamp(0, num_bins - 1)
|
||||
hist.scatter_add_(1, bins, torch.ones_like(frame))
|
||||
cdf = hist.cumsum(1)
|
||||
return cdf / cdf[:, -1:]
|
||||
|
||||
@classmethod
|
||||
def _build_histogram_transform(cls, image_target, image_ref, device, stats_mode, target_index, B):
|
||||
"""Build per-frame or uniform LUT transform for histogram mode."""
|
||||
if stats_mode == 'per_frame':
|
||||
return None # LUT computed per-frame in the apply loop
|
||||
|
||||
r_cdf = cls._pooled_cdf(image_ref, device)
|
||||
if stats_mode == 'target_frame':
|
||||
ti = min(target_index, B - 1)
|
||||
s_cdf = cls._pooled_cdf(image_target[ti:ti+1], device)
|
||||
else:
|
||||
s_cdf = cls._pooled_cdf(image_target, device)
|
||||
return torch.searchsorted(r_cdf, s_cdf).clamp_max_(255).float() / 255.0
|
||||
|
||||
@classmethod
|
||||
def _build_lab_transform(cls, image_target, image_ref, device, stats_mode, target_index, is_reinhard):
|
||||
"""Build transform parameters for Lab-based methods. Returns a transform function."""
|
||||
eps = 1e-6
|
||||
B, H, W, C = image_target.shape
|
||||
B_ref = image_ref.shape[0]
|
||||
single_ref = B_ref == 1
|
||||
HW = H * W
|
||||
HW_ref = image_ref.shape[1] * image_ref.shape[2]
|
||||
|
||||
# Precompute ref stats
|
||||
if single_ref or stats_mode in ('uniform', 'target_frame'):
|
||||
ref_mean, ref_sc = cls._pool_stats(image_ref, device, is_reinhard, eps)
|
||||
|
||||
# Uniform/target_frame: precompute single affine transform
|
||||
if stats_mode in ('uniform', 'target_frame'):
|
||||
if stats_mode == 'target_frame':
|
||||
ti = min(target_index, B - 1)
|
||||
s_lab = cls._to_lab(image_target, ti, device).view(C, -1)
|
||||
s_mean, s_sc = cls._frame_stats(s_lab, HW, is_reinhard, eps)
|
||||
else:
|
||||
s_mean, s_sc = cls._pool_stats(image_target, device, is_reinhard, eps)
|
||||
|
||||
if is_reinhard:
|
||||
scale = ref_sc / s_sc
|
||||
offset = ref_mean - scale * s_mean
|
||||
return lambda src_flat, **_: src_flat * scale + offset
|
||||
T = cls._mkl_matrix(s_sc, ref_sc, eps)
|
||||
offset = ref_mean - T @ s_mean
|
||||
return lambda src_flat, **_: T @ src_flat + offset
|
||||
|
||||
# per_frame
|
||||
def per_frame_transform(src_flat, frame_idx):
|
||||
s_mean, s_sc = cls._frame_stats(src_flat, HW, is_reinhard, eps)
|
||||
|
||||
if single_ref:
|
||||
r_mean, r_sc = ref_mean, ref_sc
|
||||
else:
|
||||
ri = min(frame_idx, B_ref - 1)
|
||||
r_mean, r_sc = cls._frame_stats(cls._to_lab(image_ref, ri, device).view(C, -1), HW_ref, is_reinhard, eps)
|
||||
|
||||
centered = src_flat - s_mean
|
||||
if is_reinhard:
|
||||
return centered * (r_sc / s_sc) + r_mean
|
||||
T = cls._mkl_matrix(centered @ centered.T / HW, r_sc, eps)
|
||||
return T @ centered + r_mean
|
||||
|
||||
return per_frame_transform
|
||||
|
||||
@classmethod
|
||||
def execute(cls, image_target, image_ref, method, source_stats, strength=1.0) -> io.NodeOutput:
|
||||
stats_mode = source_stats["source_stats"]
|
||||
target_index = source_stats.get("target_index", 0)
|
||||
|
||||
if strength == 0 or image_ref is None:
|
||||
return io.NodeOutput(image_target)
|
||||
|
||||
device = comfy.model_management.get_torch_device()
|
||||
intermediate_device = comfy.model_management.intermediate_device()
|
||||
intermediate_dtype = comfy.model_management.intermediate_dtype()
|
||||
|
||||
B, H, W, C = image_target.shape
|
||||
B_ref = image_ref.shape[0]
|
||||
pbar = comfy.utils.ProgressBar(B)
|
||||
out = torch.empty(B, H, W, C, device=intermediate_device, dtype=intermediate_dtype)
|
||||
|
||||
if method == 'histogram':
|
||||
uniform_lut = cls._build_histogram_transform(
|
||||
image_target, image_ref, device, stats_mode, target_index, B)
|
||||
|
||||
for i in range(B):
|
||||
src = image_target[i].to(device, dtype=torch.float32).permute(2, 0, 1)
|
||||
src_flat = src.reshape(C, -1)
|
||||
if uniform_lut is not None:
|
||||
lut = uniform_lut
|
||||
else:
|
||||
ri = min(i, B_ref - 1)
|
||||
ref = image_ref[ri].to(device, dtype=torch.float32).permute(2, 0, 1).reshape(C, -1)
|
||||
lut = cls._histogram_lut(src_flat, ref)
|
||||
bin_idx = (src_flat * 255).long().clamp(0, 255)
|
||||
matched = lut.gather(1, bin_idx).view(C, H, W)
|
||||
result = matched if strength == 1.0 else torch.lerp(src, matched, strength)
|
||||
out[i] = result.permute(1, 2, 0).clamp_(0, 1).to(device=intermediate_device, dtype=intermediate_dtype)
|
||||
pbar.update(1)
|
||||
else:
|
||||
transform = cls._build_lab_transform(image_target, image_ref, device, stats_mode, target_index, is_reinhard=method == "reinhard_lab")
|
||||
|
||||
for i in range(B):
|
||||
src_frame = cls._to_lab(image_target, i, device)
|
||||
corrected = transform(src_frame.view(C, -1), frame_idx=i)
|
||||
if strength == 1.0:
|
||||
result = kornia.color.lab_to_rgb(corrected.view(1, C, H, W))
|
||||
else:
|
||||
result = kornia.color.lab_to_rgb(torch.lerp(src_frame, corrected.view(1, C, H, W), strength))
|
||||
out[i] = result.squeeze(0).permute(1, 2, 0).clamp_(0, 1).to(device=intermediate_device, dtype=intermediate_dtype)
|
||||
pbar.update(1)
|
||||
|
||||
return io.NodeOutput(out)
|
||||
|
||||
|
||||
class PostProcessingExtension(ComfyExtension):
|
||||
@override
|
||||
async def get_node_list(self) -> list[type[io.ComfyNode]]:
|
||||
return [
|
||||
Blend,
|
||||
Blur,
|
||||
Quantize,
|
||||
Sharpen,
|
||||
ImageScaleToTotalPixels,
|
||||
ResizeImageMaskNode,
|
||||
BatchImagesNode,
|
||||
BatchMasksNode,
|
||||
BatchLatentsNode,
|
||||
ColorTransfer,
|
||||
# BatchImagesMasksLatentsNode,
|
||||
]
|
||||
|
||||
async def comfy_entrypoint() -> PostProcessingExtension:
|
||||
return PostProcessingExtension()
|
||||
@@ -0,0 +1,40 @@
|
||||
import type { LGraphNode } from '@/lib/litegraph/src/LGraphNode'
|
||||
import {
|
||||
type ComfyNodeDef,
|
||||
type InputSpec,
|
||||
isMediaUploadComboInput
|
||||
} from '@/schemas/nodeDefSchema'
|
||||
|
||||
import { app } from '../../scripts/app'
|
||||
|
||||
// Adds an upload button to the nodes
|
||||
|
||||
const createUploadInput = (
|
||||
imageInputName: string,
|
||||
imageInputOptions: InputSpec
|
||||
): InputSpec => [
|
||||
'IMAGEUPLOAD',
|
||||
{
|
||||
...imageInputOptions[1],
|
||||
imageInputName
|
||||
}
|
||||
]
|
||||
|
||||
app.registerExtension({
|
||||
name: 'Comfy.UploadImage',
|
||||
beforeRegisterNodeDef(_nodeType: typeof LGraphNode, nodeData: ComfyNodeDef) {
|
||||
const { input } = nodeData ?? {}
|
||||
const { required } = input ?? {}
|
||||
if (!required) return
|
||||
|
||||
const found = Object.entries(required).find(([_, input]) =>
|
||||
isMediaUploadComboInput(input)
|
||||
)
|
||||
|
||||
// If media combo input found, attach upload input
|
||||
if (found) {
|
||||
const [inputName, inputSpec] = found
|
||||
required.upload = createUploadInput(inputName, inputSpec)
|
||||
}
|
||||
}
|
||||
})
|
||||
+142
@@ -0,0 +1,142 @@
|
||||
import { useNodeImage, useNodeVideo } from '@/composables/node/useNodeImage'
|
||||
import { useNodeImageUpload } from '@/composables/node/useNodeImageUpload'
|
||||
import { t } from '@/i18n'
|
||||
import type { LGraphNode } from '@/lib/litegraph/src/litegraph'
|
||||
import type { IComboWidget } from '@/lib/litegraph/src/types/widgets'
|
||||
import type { ResultItem, ResultItemType } from '@/schemas/apiSchema'
|
||||
import type { InputSpec } from '@/schemas/nodeDefSchema'
|
||||
import { useWorkflowStore } from '@/platform/workflow/management/stores/workflowStore'
|
||||
import type { ComfyWidgetConstructor } from '@/scripts/widgets'
|
||||
import { useNodeOutputStore } from '@/stores/nodeOutputStore'
|
||||
import { isImageUploadInput } from '@/types/nodeDefAugmentation'
|
||||
import { createAnnotatedPath } from '@/utils/createAnnotatedPath'
|
||||
import { addToComboValues } from '@/utils/litegraphUtil'
|
||||
|
||||
import {
|
||||
ACCEPTED_IMAGE_TYPES,
|
||||
ACCEPTED_VIDEO_TYPES
|
||||
} from '@/utils/mediaUploadUtil'
|
||||
|
||||
const isImageFile = (file: File) => file.type.startsWith('image/')
|
||||
const isVideoFile = (file: File) => file.type.startsWith('video/')
|
||||
|
||||
const findFileComboWidget = (
|
||||
node: LGraphNode,
|
||||
inputName: string
|
||||
): IComboWidget | undefined =>
|
||||
node.widgets?.find((w): w is IComboWidget => w.name === inputName)
|
||||
|
||||
export const useImageUploadWidget = () => {
|
||||
const widgetConstructor: ComfyWidgetConstructor = (
|
||||
node: LGraphNode,
|
||||
inputName: string,
|
||||
inputData: InputSpec
|
||||
) => {
|
||||
if (!isImageUploadInput(inputData)) {
|
||||
throw new Error(
|
||||
'Image upload widget requires imageInputName augmentation'
|
||||
)
|
||||
}
|
||||
|
||||
const inputOptions = inputData[1]
|
||||
const { imageInputName, allow_batch, image_folder = 'input' } = inputOptions
|
||||
const folder: ResultItemType | undefined = image_folder
|
||||
const nodeOutputStore = useNodeOutputStore()
|
||||
|
||||
const isAnimated = !!inputOptions.animated_image_upload
|
||||
const isVideo = !!inputOptions.video_upload
|
||||
const accept = isVideo ? ACCEPTED_VIDEO_TYPES : ACCEPTED_IMAGE_TYPES
|
||||
const { showPreview } = isVideo ? useNodeVideo(node) : useNodeImage(node)
|
||||
|
||||
const fileFilter = isVideo ? isVideoFile : isImageFile
|
||||
const fileComboWidget = findFileComboWidget(node, imageInputName)
|
||||
if (!fileComboWidget) {
|
||||
throw new Error(`Widget "${imageInputName}" not found on node`)
|
||||
}
|
||||
function formatPath(value: string | ResultItem) {
|
||||
return typeof value === 'string'
|
||||
? createAnnotatedPath(value, { rootFolder: image_folder })
|
||||
: createAnnotatedPath(value)
|
||||
}
|
||||
|
||||
// Setup file upload handling
|
||||
let rollback: (() => void) | undefined
|
||||
const { openFileSelection } = useNodeImageUpload(node, {
|
||||
allow_batch,
|
||||
fileFilter,
|
||||
accept,
|
||||
folder,
|
||||
onUploadStart: (files) => {
|
||||
if (files.length > 0) {
|
||||
const prev = fileComboWidget.value
|
||||
fileComboWidget.value = files[0].name
|
||||
rollback = () => {
|
||||
fileComboWidget.value = prev
|
||||
}
|
||||
}
|
||||
},
|
||||
onUploadError: () => {
|
||||
rollback?.()
|
||||
rollback = undefined
|
||||
},
|
||||
onUploadComplete: (output) => {
|
||||
rollback = undefined
|
||||
const annotated = output.map(formatPath)
|
||||
annotated.forEach((path) => {
|
||||
addToComboValues(fileComboWidget, path)
|
||||
})
|
||||
|
||||
const newValue = allow_batch ? annotated : annotated[0]
|
||||
const oldValue = fileComboWidget.value
|
||||
|
||||
// @ts-expect-error litegraph combo value type does not support arrays yet
|
||||
fileComboWidget.value = newValue
|
||||
fileComboWidget.callback?.(newValue)
|
||||
node.onWidgetChanged?.(
|
||||
fileComboWidget.name,
|
||||
newValue,
|
||||
oldValue,
|
||||
fileComboWidget
|
||||
)
|
||||
useWorkflowStore().activeWorkflow?.changeTracker?.captureCanvasState()
|
||||
}
|
||||
})
|
||||
|
||||
// Create the button widget for selecting the files
|
||||
const uploadWidget = node.addWidget(
|
||||
'button',
|
||||
inputName,
|
||||
'image',
|
||||
() => openFileSelection(),
|
||||
{
|
||||
serialize: false,
|
||||
canvasOnly: true
|
||||
}
|
||||
)
|
||||
uploadWidget.label = t('g.choose_file_to_upload')
|
||||
|
||||
// Add our own callback to the combo widget to render an image when it changes
|
||||
fileComboWidget.callback = function () {
|
||||
node.imgs = undefined
|
||||
nodeOutputStore.setNodeOutputs(node, String(fileComboWidget.value), {
|
||||
isAnimated
|
||||
})
|
||||
node.graph?.setDirtyCanvas(true)
|
||||
}
|
||||
|
||||
// On load if we have a value then render the image
|
||||
// The value isn't set immediately so we need to wait a moment
|
||||
// No change callbacks seem to be fired on initial setting of the value
|
||||
requestAnimationFrame(() => {
|
||||
if (fileComboWidget.value != null)
|
||||
nodeOutputStore.setNodeOutputs(node, String(fileComboWidget.value), {
|
||||
isAnimated
|
||||
})
|
||||
showPreview({ block: false })
|
||||
})
|
||||
|
||||
return { widget: uploadWidget }
|
||||
}
|
||||
|
||||
return widgetConstructor
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2023 Regis Gaughan, III (rgthree)
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,115 @@
|
||||
"""
|
||||
@author: rgthree
|
||||
@title: Comfy Nodes
|
||||
@nickname: rgthree
|
||||
@description: A bunch of nodes I created that I also find useful.
|
||||
"""
|
||||
|
||||
from glob import glob
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import re
|
||||
import random
|
||||
|
||||
import execution
|
||||
|
||||
from .py.log import log, log_known_message
|
||||
from .py.config import get_config_value
|
||||
from .py.server.rgthree_server import *
|
||||
|
||||
from .py.context import RgthreeContext
|
||||
from .py.context_switch import RgthreeContextSwitch
|
||||
from .py.context_switch_big import RgthreeContextSwitchBig
|
||||
from .py.display_any import RgthreeDisplayAny, RgthreeDisplayInt
|
||||
from .py.lora_stack import RgthreeLoraLoaderStack
|
||||
from .py.seed import RgthreeSeed
|
||||
from .py.sdxl_empty_latent_image import RgthreeSDXLEmptyLatentImage
|
||||
from .py.power_prompt import RgthreePowerPrompt
|
||||
from .py.power_prompt_simple import RgthreePowerPromptSimple
|
||||
from .py.image_inset_crop import RgthreeImageInsetCrop
|
||||
from .py.context_big import RgthreeBigContext
|
||||
from .py.dynamic_context import RgthreeDynamicContext
|
||||
from .py.dynamic_context_switch import RgthreeDynamicContextSwitch
|
||||
from .py.ksampler_config import RgthreeKSamplerConfig
|
||||
from .py.sdxl_power_prompt_postive import RgthreeSDXLPowerPromptPositive
|
||||
from .py.sdxl_power_prompt_simple import RgthreeSDXLPowerPromptSimple
|
||||
from .py.any_switch import RgthreeAnySwitch
|
||||
from .py.context_merge import RgthreeContextMerge
|
||||
from .py.context_merge_big import RgthreeContextMergeBig
|
||||
from .py.image_comparer import RgthreeImageComparer
|
||||
from .py.power_lora_loader import RgthreePowerLoraLoader
|
||||
from .py.power_primitive import RgthreePowerPrimitive
|
||||
from .py.image_or_latent_size import RgthreeImageOrLatentSize
|
||||
from .py.image_resize import RgthreeImageResize
|
||||
from .py.power_puter import RgthreePowerPuter
|
||||
|
||||
NODE_CLASS_MAPPINGS = {
|
||||
RgthreeBigContext.NAME: RgthreeBigContext,
|
||||
RgthreeContext.NAME: RgthreeContext,
|
||||
RgthreeContextSwitch.NAME: RgthreeContextSwitch,
|
||||
RgthreeContextSwitchBig.NAME: RgthreeContextSwitchBig,
|
||||
RgthreeContextMerge.NAME: RgthreeContextMerge,
|
||||
RgthreeContextMergeBig.NAME: RgthreeContextMergeBig,
|
||||
RgthreeDisplayInt.NAME: RgthreeDisplayInt,
|
||||
RgthreeDisplayAny.NAME: RgthreeDisplayAny,
|
||||
RgthreeLoraLoaderStack.NAME: RgthreeLoraLoaderStack,
|
||||
RgthreeSeed.NAME: RgthreeSeed,
|
||||
RgthreeImageInsetCrop.NAME: RgthreeImageInsetCrop,
|
||||
RgthreePowerPrompt.NAME: RgthreePowerPrompt,
|
||||
RgthreePowerPromptSimple.NAME: RgthreePowerPromptSimple,
|
||||
RgthreeKSamplerConfig.NAME: RgthreeKSamplerConfig,
|
||||
RgthreeSDXLEmptyLatentImage.NAME: RgthreeSDXLEmptyLatentImage,
|
||||
RgthreeSDXLPowerPromptPositive.NAME: RgthreeSDXLPowerPromptPositive,
|
||||
RgthreeSDXLPowerPromptSimple.NAME: RgthreeSDXLPowerPromptSimple,
|
||||
RgthreeAnySwitch.NAME: RgthreeAnySwitch,
|
||||
RgthreeImageComparer.NAME: RgthreeImageComparer,
|
||||
RgthreePowerLoraLoader.NAME: RgthreePowerLoraLoader,
|
||||
RgthreePowerPrimitive.NAME: RgthreePowerPrimitive,
|
||||
RgthreeImageOrLatentSize.NAME: RgthreeImageOrLatentSize,
|
||||
RgthreeImageResize.NAME: RgthreeImageResize,
|
||||
RgthreePowerPuter.NAME: RgthreePowerPuter,
|
||||
}
|
||||
|
||||
if get_config_value('unreleased.dynamic_context.enabled') is True:
|
||||
NODE_CLASS_MAPPINGS[RgthreeDynamicContext.NAME] = RgthreeDynamicContext
|
||||
NODE_CLASS_MAPPINGS[RgthreeDynamicContextSwitch.NAME] = RgthreeDynamicContextSwitch
|
||||
|
||||
# WEB_DIRECTORY is the comfyui nodes directory that ComfyUI will link and auto-load.
|
||||
WEB_DIRECTORY = "./web/comfyui"
|
||||
|
||||
THIS_DIR = os.path.dirname(os.path.abspath(__file__))
|
||||
DIR_WEB = os.path.abspath(os.path.join(THIS_DIR, WEB_DIRECTORY))
|
||||
DIR_PY = os.path.abspath(os.path.join(THIS_DIR, 'py'))
|
||||
|
||||
# remove old directories
|
||||
OLD_DIRS = [
|
||||
os.path.abspath(os.path.join(THIS_DIR, '..', '..', 'web', 'extensions', 'rgthree')),
|
||||
os.path.abspath(os.path.join(THIS_DIR, '..', '..', 'web', 'extensions', 'rgthree-comfy')),
|
||||
]
|
||||
for old_dir in OLD_DIRS:
|
||||
if os.path.exists(old_dir):
|
||||
shutil.rmtree(old_dir)
|
||||
|
||||
__all__ = ['NODE_CLASS_MAPPINGS', 'WEB_DIRECTORY']
|
||||
|
||||
NOT_NODES = ['constants', 'log', 'utils', 'rgthree', 'rgthree_server', 'image_clipbaord', 'config']
|
||||
|
||||
nodes = []
|
||||
for file in glob(os.path.join(DIR_PY, '*.py')) + glob(os.path.join(DIR_WEB, '*.js')):
|
||||
name = os.path.splitext(os.path.basename(file))[0]
|
||||
if name in NOT_NODES or name in nodes:
|
||||
continue
|
||||
if name.startswith('_') or name.startswith('base') or 'utils' in name:
|
||||
continue
|
||||
nodes.append(name)
|
||||
if name == 'display_any':
|
||||
nodes.append('display_int')
|
||||
|
||||
print()
|
||||
adjs = ['exciting', 'extraordinary', 'epic', 'fantastic', 'magnificent']
|
||||
log(f'Loaded {len(nodes)} {random.choice(adjs)} nodes. 🎉', color='BRIGHT_GREEN')
|
||||
print()
|
||||
|
||||
if get_config_value('announcements.comfy-nodes-20.incompatible', True):
|
||||
log_known_message('NODES2.0')
|
||||
@@ -0,0 +1,11 @@
|
||||
|
||||
NAMESPACE='rgthree'
|
||||
|
||||
def get_name(name):
|
||||
return '{} ({})'.format(name, NAMESPACE)
|
||||
|
||||
def get_category(sub_dirs = None):
|
||||
if sub_dirs is None:
|
||||
return NAMESPACE
|
||||
else:
|
||||
return "{}/utils".format(NAMESPACE)
|
||||
@@ -0,0 +1,45 @@
|
||||
from nodes import PreviewImage
|
||||
|
||||
from .constants import get_category, get_name
|
||||
|
||||
|
||||
class RgthreeImageComparer(PreviewImage):
|
||||
"""A node that compares two images in the UI."""
|
||||
|
||||
NAME = get_name('Image Comparer')
|
||||
CATEGORY = get_category()
|
||||
FUNCTION = "compare_images"
|
||||
DESCRIPTION = "Compares two images with a hover slider, or click from properties."
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls): # pylint: disable = invalid-name, missing-function-docstring
|
||||
return {
|
||||
"required": {},
|
||||
"optional": {
|
||||
"image_a": ("IMAGE",),
|
||||
"image_b": ("IMAGE",),
|
||||
},
|
||||
"hidden": {
|
||||
"prompt": "PROMPT",
|
||||
"extra_pnginfo": "EXTRA_PNGINFO"
|
||||
},
|
||||
}
|
||||
|
||||
def compare_images(self,
|
||||
image_a=None,
|
||||
image_b=None,
|
||||
filename_prefix="rgthree.compare.",
|
||||
prompt=None,
|
||||
extra_pnginfo=None):
|
||||
|
||||
result = { "ui": { "a_images":[], "b_images": [] } }
|
||||
if image_a is not None and len(image_a) > 0:
|
||||
result['ui']['a_images'] = self.save_images(image_a, filename_prefix, prompt, extra_pnginfo)['ui']['images']
|
||||
|
||||
if image_b is not None and len(image_b) > 0:
|
||||
result['ui']['b_images'] = self.save_images(image_b, filename_prefix, prompt, extra_pnginfo)['ui']['images']
|
||||
|
||||
# RETURN_TYPES is inherited from SaveImage, so the node advertises an IMAGE
|
||||
# output. Without a 'result' key it stays empty and any link from it fails.
|
||||
result['result'] = (image_a if image_a is not None else image_b,)
|
||||
return result
|
||||
@@ -0,0 +1,316 @@
|
||||
import { app } from "../../scripts/app.js";
|
||||
import { ComfyWidgets } from "../../scripts/widgets.js";
|
||||
import { SERVICE as KEY_EVENT_SERVICE } from "./services/key_events_services.js";
|
||||
import { LogLevel, rgthree } from "./rgthree.js";
|
||||
import { addHelpMenuItem } from "./utils.js";
|
||||
import { RgthreeHelpDialog } from "../../rgthree/common/dialog.js";
|
||||
import { importIndividualNodesInnerOnDragDrop, importIndividualNodesInnerOnDragOver, } from "./feature_import_individual_nodes.js";
|
||||
import { defineProperty, moveArrayItem } from "../../rgthree/common/shared_utils.js";
|
||||
export class RgthreeBaseNode extends LGraphNode {
|
||||
constructor(title = RgthreeBaseNode.title, skipOnConstructedCall = true) {
|
||||
super(title);
|
||||
this.comfyClass = "__NEED_COMFY_CLASS__";
|
||||
this.nickname = "rgthree";
|
||||
this.isVirtualNode = false;
|
||||
this.isDropEnabled = false;
|
||||
this.removed = false;
|
||||
this.configuring = false;
|
||||
this._tempWidth = 0;
|
||||
this.__constructed__ = false;
|
||||
this.helpDialog = null;
|
||||
if (title == "__NEED_CLASS_TITLE__") {
|
||||
throw new Error("RgthreeBaseNode needs overrides.");
|
||||
}
|
||||
this.widgets = this.widgets || [];
|
||||
this.properties = this.properties || {};
|
||||
setTimeout(() => {
|
||||
if (this.comfyClass == "__NEED_COMFY_CLASS__") {
|
||||
throw new Error("RgthreeBaseNode needs a comfy class override.");
|
||||
}
|
||||
if (this.constructor.type == "__NEED_CLASS_TYPE__") {
|
||||
throw new Error("RgthreeBaseNode needs overrides.");
|
||||
}
|
||||
this.checkAndRunOnConstructed();
|
||||
});
|
||||
defineProperty(this, "mode", {
|
||||
get: () => {
|
||||
return this.rgthree_mode;
|
||||
},
|
||||
set: (mode) => {
|
||||
if (this.rgthree_mode != mode) {
|
||||
const oldMode = this.rgthree_mode;
|
||||
this.rgthree_mode = mode;
|
||||
this.onModeChange(oldMode, mode);
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
checkAndRunOnConstructed() {
|
||||
var _a;
|
||||
if (!this.__constructed__) {
|
||||
this.onConstructed();
|
||||
const [n, v] = rgthree.logger.logParts(LogLevel.DEV, `[RgthreeBaseNode] Child class did not call onConstructed for "${this.type}.`);
|
||||
(_a = console[n]) === null || _a === void 0 ? void 0 : _a.call(console, ...v);
|
||||
}
|
||||
return this.__constructed__;
|
||||
}
|
||||
onDragOver(e) {
|
||||
if (!this.isDropEnabled)
|
||||
return false;
|
||||
return importIndividualNodesInnerOnDragOver(this, e);
|
||||
}
|
||||
async onDragDrop(e) {
|
||||
if (!this.isDropEnabled)
|
||||
return false;
|
||||
return importIndividualNodesInnerOnDragDrop(this, e);
|
||||
}
|
||||
onConstructed() {
|
||||
var _a;
|
||||
if (this.__constructed__)
|
||||
return false;
|
||||
this.type = (_a = this.type) !== null && _a !== void 0 ? _a : undefined;
|
||||
this.__constructed__ = true;
|
||||
rgthree.invokeExtensionsAsync("nodeCreated", this);
|
||||
return this.__constructed__;
|
||||
}
|
||||
configure(info) {
|
||||
this.configuring = true;
|
||||
super.configure(info);
|
||||
for (const w of this.widgets || []) {
|
||||
w.last_y = w.last_y || 0;
|
||||
}
|
||||
this.configuring = false;
|
||||
}
|
||||
clone() {
|
||||
const cloned = super.clone();
|
||||
if ((cloned === null || cloned === void 0 ? void 0 : cloned.properties) && !!window.structuredClone) {
|
||||
cloned.properties = structuredClone(cloned.properties);
|
||||
}
|
||||
cloned.graph = this.graph;
|
||||
return cloned;
|
||||
}
|
||||
onModeChange(from, to) {
|
||||
}
|
||||
async handleAction(action) {
|
||||
action;
|
||||
}
|
||||
removeWidget(widget) {
|
||||
var _a;
|
||||
if (typeof widget === "number") {
|
||||
widget = this.widgets[widget];
|
||||
}
|
||||
if (!widget)
|
||||
return;
|
||||
const canUseComfyUIRemoveWidget = false;
|
||||
if (canUseComfyUIRemoveWidget && typeof super.removeWidget === "function") {
|
||||
super.removeWidget(widget);
|
||||
}
|
||||
else {
|
||||
const index = this.widgets.indexOf(widget);
|
||||
if (index > -1) {
|
||||
this.widgets.splice(index, 1);
|
||||
}
|
||||
(_a = widget.onRemove) === null || _a === void 0 ? void 0 : _a.call(widget);
|
||||
}
|
||||
}
|
||||
replaceWidget(widgetOrSlot, newWidget) {
|
||||
let index = null;
|
||||
if (widgetOrSlot) {
|
||||
index = typeof widgetOrSlot === "number" ? widgetOrSlot : this.widgets.indexOf(widgetOrSlot);
|
||||
this.removeWidget(this.widgets[index]);
|
||||
}
|
||||
index = index != null ? index : this.widgets.length - 1;
|
||||
if (this.widgets.includes(newWidget)) {
|
||||
moveArrayItem(this.widgets, newWidget, index);
|
||||
}
|
||||
else {
|
||||
this.widgets.splice(index, 0, newWidget);
|
||||
}
|
||||
}
|
||||
defaultGetSlotMenuOptions(slot) {
|
||||
var _a, _b;
|
||||
const menu_info = [];
|
||||
if ((_b = (_a = slot === null || slot === void 0 ? void 0 : slot.output) === null || _a === void 0 ? void 0 : _a.links) === null || _b === void 0 ? void 0 : _b.length) {
|
||||
menu_info.push({ content: "Disconnect Links", slot });
|
||||
}
|
||||
let inputOrOutput = slot.input || slot.output;
|
||||
if (inputOrOutput) {
|
||||
if (inputOrOutput.removable) {
|
||||
menu_info.push(inputOrOutput.locked ? { content: "Cannot remove" } : { content: "Remove Slot", slot });
|
||||
}
|
||||
if (!inputOrOutput.nameLocked) {
|
||||
menu_info.push({ content: "Rename Slot", slot });
|
||||
}
|
||||
}
|
||||
return menu_info;
|
||||
}
|
||||
onRemoved() {
|
||||
var _a;
|
||||
(_a = super.onRemoved) === null || _a === void 0 ? void 0 : _a.call(this);
|
||||
this.removed = true;
|
||||
}
|
||||
static setUp(...args) {
|
||||
}
|
||||
getHelp() {
|
||||
return "";
|
||||
}
|
||||
showHelp() {
|
||||
const help = this.getHelp() || this.constructor.help;
|
||||
if (help) {
|
||||
this.helpDialog = new RgthreeHelpDialog(this, help).show();
|
||||
this.helpDialog.addEventListener("close", (e) => {
|
||||
this.helpDialog = null;
|
||||
});
|
||||
}
|
||||
}
|
||||
onKeyDown(event) {
|
||||
KEY_EVENT_SERVICE.handleKeyDownOrUp(event);
|
||||
if (event.key == "?" && !this.helpDialog) {
|
||||
this.showHelp();
|
||||
}
|
||||
}
|
||||
onKeyUp(event) {
|
||||
KEY_EVENT_SERVICE.handleKeyDownOrUp(event);
|
||||
}
|
||||
getExtraMenuOptions(canvas, options) {
|
||||
var _a, _b, _c, _d, _e, _f;
|
||||
if (super.getExtraMenuOptions) {
|
||||
(_a = super.getExtraMenuOptions) === null || _a === void 0 ? void 0 : _a.apply(this, [canvas, options]);
|
||||
}
|
||||
else if ((_c = (_b = this.constructor.nodeType) === null || _b === void 0 ? void 0 : _b.prototype) === null || _c === void 0 ? void 0 : _c.getExtraMenuOptions) {
|
||||
(_f = (_e = (_d = this.constructor.nodeType) === null || _d === void 0 ? void 0 : _d.prototype) === null || _e === void 0 ? void 0 : _e.getExtraMenuOptions) === null || _f === void 0 ? void 0 : _f.apply(this, [canvas, options]);
|
||||
}
|
||||
const help = this.getHelp() || this.constructor.help;
|
||||
if (help) {
|
||||
addHelpMenuItem(this, help, options);
|
||||
}
|
||||
return [];
|
||||
}
|
||||
}
|
||||
RgthreeBaseNode.exposedActions = [];
|
||||
RgthreeBaseNode.title = "__NEED_CLASS_TITLE__";
|
||||
RgthreeBaseNode.type = "__NEED_CLASS_TYPE__";
|
||||
RgthreeBaseNode.category = "rgthree";
|
||||
RgthreeBaseNode._category = "rgthree";
|
||||
export class RgthreeBaseVirtualNode extends RgthreeBaseNode {
|
||||
constructor(title = RgthreeBaseNode.title) {
|
||||
super(title, false);
|
||||
this.isVirtualNode = true;
|
||||
}
|
||||
static setUp() {
|
||||
if (!this.type) {
|
||||
throw new Error(`Missing type for RgthreeBaseVirtualNode: ${this.title}`);
|
||||
}
|
||||
LiteGraph.registerNodeType(this.type, this);
|
||||
if (this._category) {
|
||||
this.category = this._category;
|
||||
}
|
||||
}
|
||||
}
|
||||
export class RgthreeBaseServerNode extends RgthreeBaseNode {
|
||||
constructor(title) {
|
||||
super(title, true);
|
||||
this.isDropEnabled = true;
|
||||
this.serialize_widgets = true;
|
||||
this.setupFromServerNodeData();
|
||||
this.onConstructed();
|
||||
}
|
||||
getWidgets() {
|
||||
return ComfyWidgets;
|
||||
}
|
||||
async setupFromServerNodeData() {
|
||||
var _a, _b, _c, _d, _e;
|
||||
const nodeData = this.constructor.nodeData;
|
||||
if (!nodeData) {
|
||||
throw Error("No node data");
|
||||
}
|
||||
this.comfyClass = nodeData.name;
|
||||
let inputs = nodeData["input"]["required"];
|
||||
if (nodeData["input"]["optional"] != undefined) {
|
||||
inputs = Object.assign({}, inputs, nodeData["input"]["optional"]);
|
||||
}
|
||||
const WIDGETS = this.getWidgets();
|
||||
const config = {
|
||||
minWidth: 1,
|
||||
minHeight: 1,
|
||||
widget: null,
|
||||
};
|
||||
for (const inputName in inputs) {
|
||||
const inputData = inputs[inputName];
|
||||
const type = inputData[0];
|
||||
if ((_a = inputData[1]) === null || _a === void 0 ? void 0 : _a.forceInput) {
|
||||
this.addInput(inputName, type);
|
||||
}
|
||||
else {
|
||||
let widgetCreated = true;
|
||||
if (Array.isArray(type)) {
|
||||
Object.assign(config, WIDGETS.COMBO(this, inputName, inputData, app) || {});
|
||||
}
|
||||
else if (`${type}:${inputName}` in WIDGETS) {
|
||||
Object.assign(config, WIDGETS[`${type}:${inputName}`](this, inputName, inputData, app) || {});
|
||||
}
|
||||
else if (type in WIDGETS) {
|
||||
Object.assign(config, WIDGETS[type](this, inputName, inputData, app) || {});
|
||||
}
|
||||
else {
|
||||
this.addInput(inputName, type);
|
||||
widgetCreated = false;
|
||||
}
|
||||
if (widgetCreated && ((_b = inputData[1]) === null || _b === void 0 ? void 0 : _b.forceInput) && (config === null || config === void 0 ? void 0 : config.widget)) {
|
||||
if (!config.widget.options)
|
||||
config.widget.options = {};
|
||||
config.widget.options.forceInput = inputData[1].forceInput;
|
||||
}
|
||||
if (widgetCreated && ((_c = inputData[1]) === null || _c === void 0 ? void 0 : _c.defaultInput) && (config === null || config === void 0 ? void 0 : config.widget)) {
|
||||
if (!config.widget.options)
|
||||
config.widget.options = {};
|
||||
config.widget.options.defaultInput = inputData[1].defaultInput;
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const o in nodeData["output"]) {
|
||||
let output = nodeData["output"][o];
|
||||
if (output instanceof Array)
|
||||
output = "COMBO";
|
||||
const outputName = nodeData["output_name"][o] || output;
|
||||
const outputShape = nodeData["output_is_list"][o]
|
||||
? LiteGraph.GRID_SHAPE
|
||||
: LiteGraph.CIRCLE_SHAPE;
|
||||
this.addOutput(outputName, output, { shape: outputShape });
|
||||
}
|
||||
const s = this.computeSize();
|
||||
s[0] = Math.max((_d = config.minWidth) !== null && _d !== void 0 ? _d : 1, s[0] * 1.5);
|
||||
s[1] = Math.max((_e = config.minHeight) !== null && _e !== void 0 ? _e : 1, s[1]);
|
||||
this.size = s;
|
||||
this.serialize_widgets = true;
|
||||
}
|
||||
static registerForOverride(comfyClass, nodeData, rgthreeClass) {
|
||||
if (OVERRIDDEN_SERVER_NODES.has(comfyClass)) {
|
||||
throw Error(`Already have a class to override ${comfyClass.type || comfyClass.name || comfyClass.title}`);
|
||||
}
|
||||
OVERRIDDEN_SERVER_NODES.set(comfyClass, rgthreeClass);
|
||||
if (!rgthreeClass.__registeredForOverride__) {
|
||||
rgthreeClass.__registeredForOverride__ = true;
|
||||
rgthreeClass.nodeType = comfyClass;
|
||||
rgthreeClass.nodeData = nodeData;
|
||||
rgthreeClass.onRegisteredForOverride(comfyClass, rgthreeClass);
|
||||
}
|
||||
}
|
||||
static onRegisteredForOverride(comfyClass, rgthreeClass) {
|
||||
}
|
||||
}
|
||||
RgthreeBaseServerNode.nodeType = null;
|
||||
RgthreeBaseServerNode.nodeData = null;
|
||||
RgthreeBaseServerNode.__registeredForOverride__ = false;
|
||||
const OVERRIDDEN_SERVER_NODES = new Map();
|
||||
const oldregisterNodeType = LiteGraph.registerNodeType;
|
||||
LiteGraph.registerNodeType = async function (nodeId, baseClass) {
|
||||
var _a;
|
||||
const clazz = OVERRIDDEN_SERVER_NODES.get(baseClass) || baseClass;
|
||||
if (clazz !== baseClass) {
|
||||
const classLabel = clazz.type || clazz.name || clazz.title;
|
||||
const [n, v] = rgthree.logger.logParts(LogLevel.DEBUG, `${nodeId}: replacing default ComfyNode implementation with custom ${classLabel} class.`);
|
||||
(_a = console[n]) === null || _a === void 0 ? void 0 : _a.call(console, ...v);
|
||||
}
|
||||
return oldregisterNodeType.call(LiteGraph, nodeId, clazz);
|
||||
};
|
||||
@@ -0,0 +1,62 @@
|
||||
import { SERVICE as CONFIG_SERVICE } from "./services/config_service.js";
|
||||
export function addRgthree(str) {
|
||||
return str + " (rgthree)";
|
||||
}
|
||||
export function stripRgthree(str) {
|
||||
return str.replace(/\s*\(rgthree\)$/, "");
|
||||
}
|
||||
export const NodeTypesString = {
|
||||
ANY_SWITCH: addRgthree("Any Switch"),
|
||||
CONTEXT: addRgthree("Context"),
|
||||
CONTEXT_BIG: addRgthree("Context Big"),
|
||||
CONTEXT_SWITCH: addRgthree("Context Switch"),
|
||||
CONTEXT_SWITCH_BIG: addRgthree("Context Switch Big"),
|
||||
CONTEXT_MERGE: addRgthree("Context Merge"),
|
||||
CONTEXT_MERGE_BIG: addRgthree("Context Merge Big"),
|
||||
DYNAMIC_CONTEXT: addRgthree("Dynamic Context"),
|
||||
DYNAMIC_CONTEXT_SWITCH: addRgthree("Dynamic Context Switch"),
|
||||
DISPLAY_ANY: addRgthree("Display Any"),
|
||||
IMAGE_OR_LATENT_SIZE: addRgthree("Image or Latent Size"),
|
||||
NODE_MODE_RELAY: addRgthree("Mute / Bypass Relay"),
|
||||
NODE_MODE_REPEATER: addRgthree("Mute / Bypass Repeater"),
|
||||
FAST_MUTER: addRgthree("Fast Muter"),
|
||||
FAST_BYPASSER: addRgthree("Fast Bypasser"),
|
||||
FAST_GROUPS_MUTER: addRgthree("Fast Groups Muter"),
|
||||
FAST_GROUPS_BYPASSER: addRgthree("Fast Groups Bypasser"),
|
||||
FAST_ACTIONS_BUTTON: addRgthree("Fast Actions Button"),
|
||||
LABEL: addRgthree("Label"),
|
||||
POWER_PRIMITIVE: addRgthree("Power Primitive"),
|
||||
POWER_PROMPT: addRgthree("Power Prompt"),
|
||||
POWER_PROMPT_SIMPLE: addRgthree("Power Prompt - Simple"),
|
||||
POWER_PUTER: addRgthree("Power Puter"),
|
||||
POWER_CONDUCTOR: addRgthree("Power Conductor"),
|
||||
SDXL_EMPTY_LATENT_IMAGE: addRgthree("SDXL Empty Latent Image"),
|
||||
SDXL_POWER_PROMPT_POSITIVE: addRgthree("SDXL Power Prompt - Positive"),
|
||||
SDXL_POWER_PROMPT_NEGATIVE: addRgthree("SDXL Power Prompt - Simple / Negative"),
|
||||
POWER_LORA_LOADER: addRgthree("Power Lora Loader"),
|
||||
KSAMPLER_CONFIG: addRgthree("KSampler Config"),
|
||||
NODE_COLLECTOR: addRgthree("Node Collector"),
|
||||
REROUTE: addRgthree("Reroute"),
|
||||
RANDOM_UNMUTER: addRgthree("Random Unmuter"),
|
||||
SEED: addRgthree("Seed"),
|
||||
BOOKMARK: addRgthree("Bookmark"),
|
||||
IMAGE_COMPARER: addRgthree("Image Comparer"),
|
||||
IMAGE_INSET_CROP: addRgthree("Image Inset Crop"),
|
||||
};
|
||||
const UNRELEASED_KEYS = {
|
||||
[NodeTypesString.DYNAMIC_CONTEXT]: "dynamic_context",
|
||||
[NodeTypesString.DYNAMIC_CONTEXT_SWITCH]: "dynamic_context",
|
||||
[NodeTypesString.POWER_CONDUCTOR]: "power_conductor",
|
||||
};
|
||||
export function getNodeTypeStrings() {
|
||||
const unreleasedKeys = Object.keys(UNRELEASED_KEYS);
|
||||
return Object.values(NodeTypesString)
|
||||
.map((i) => stripRgthree(i))
|
||||
.filter((i) => {
|
||||
if (unreleasedKeys.includes(i)) {
|
||||
return !!CONFIG_SERVICE.getConfigValue(`unreleased.${UNRELEASED_KEYS[i]}.enabled`);
|
||||
}
|
||||
return true;
|
||||
})
|
||||
.sort();
|
||||
}
|
||||
@@ -0,0 +1,365 @@
|
||||
import { app } from "../../scripts/app.js";
|
||||
import { api } from "../../scripts/api.js";
|
||||
import { RgthreeBaseServerNode } from "./base_node.js";
|
||||
import { NodeTypesString } from "./constants.js";
|
||||
import { addConnectionLayoutSupport } from "./utils.js";
|
||||
import { RgthreeBaseWidget } from "./utils_widgets.js";
|
||||
import { measureText } from "./utils_canvas.js";
|
||||
function imageDataToUrl(data) {
|
||||
return api.apiURL(`/view?filename=${encodeURIComponent(data.filename)}&type=${data.type}&subfolder=${data.subfolder}${app.getPreviewFormatParam()}${app.getRandParam()}`);
|
||||
}
|
||||
export class RgthreeImageComparer extends RgthreeBaseServerNode {
|
||||
constructor(title = RgthreeImageComparer.title) {
|
||||
super(title);
|
||||
this.imageIndex = 0;
|
||||
this.imgs = [];
|
||||
this.serialize_widgets = true;
|
||||
this.isPointerDown = false;
|
||||
this.isPointerOver = false;
|
||||
this.pointerOverPos = [0, 0];
|
||||
this.canvasWidget = null;
|
||||
this.properties["comparer_mode"] = "Slide";
|
||||
}
|
||||
onExecuted(output) {
|
||||
var _a;
|
||||
(_a = super.onExecuted) === null || _a === void 0 ? void 0 : _a.call(this, output);
|
||||
if ("images" in output) {
|
||||
this.canvasWidget.value = {
|
||||
images: (output.images || []).map((d, i) => {
|
||||
return {
|
||||
name: i === 0 ? "A" : "B",
|
||||
selected: true,
|
||||
url: imageDataToUrl(d),
|
||||
};
|
||||
}),
|
||||
};
|
||||
}
|
||||
else {
|
||||
output.a_images = output.a_images || [];
|
||||
output.b_images = output.b_images || [];
|
||||
const imagesToChoose = [];
|
||||
const multiple = output.a_images.length + output.b_images.length > 2;
|
||||
for (const [i, d] of output.a_images.entries()) {
|
||||
imagesToChoose.push({
|
||||
name: output.a_images.length > 1 || multiple ? `A${i + 1}` : "A",
|
||||
selected: i === 0,
|
||||
url: imageDataToUrl(d),
|
||||
});
|
||||
}
|
||||
for (const [i, d] of output.b_images.entries()) {
|
||||
imagesToChoose.push({
|
||||
name: output.b_images.length > 1 || multiple ? `B${i + 1}` : "B",
|
||||
selected: i === 0,
|
||||
url: imageDataToUrl(d),
|
||||
});
|
||||
}
|
||||
this.canvasWidget.value = { images: imagesToChoose };
|
||||
}
|
||||
}
|
||||
onSerialize(serialised) {
|
||||
var _a;
|
||||
super.onSerialize && super.onSerialize(serialised);
|
||||
for (let [index, widget_value] of (serialised.widgets_values || []).entries()) {
|
||||
if (((_a = this.widgets[index]) === null || _a === void 0 ? void 0 : _a.name) === "rgthree_comparer") {
|
||||
serialised.widgets_values[index] = this.widgets[index].value.images.map((d) => {
|
||||
d = { ...d };
|
||||
delete d.img;
|
||||
return d;
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
onNodeCreated() {
|
||||
this.canvasWidget = this.addCustomWidget(new RgthreeImageComparerWidget("rgthree_comparer", this));
|
||||
this.setSize(this.computeSize());
|
||||
this.setDirtyCanvas(true, true);
|
||||
}
|
||||
setIsPointerDown(down = this.isPointerDown) {
|
||||
const newIsDown = down && !!app.canvas.pointer_is_down;
|
||||
if (this.isPointerDown !== newIsDown) {
|
||||
this.isPointerDown = newIsDown;
|
||||
this.setDirtyCanvas(true, false);
|
||||
}
|
||||
this.imageIndex = this.isPointerDown ? 1 : 0;
|
||||
if (this.isPointerDown) {
|
||||
requestAnimationFrame(() => {
|
||||
this.setIsPointerDown();
|
||||
});
|
||||
}
|
||||
}
|
||||
onMouseDown(event, pos, canvas) {
|
||||
var _a;
|
||||
(_a = super.onMouseDown) === null || _a === void 0 ? void 0 : _a.call(this, event, pos, canvas);
|
||||
this.setIsPointerDown(true);
|
||||
return false;
|
||||
}
|
||||
onMouseEnter(event) {
|
||||
var _a;
|
||||
(_a = super.onMouseEnter) === null || _a === void 0 ? void 0 : _a.call(this, event);
|
||||
this.setIsPointerDown(!!app.canvas.pointer_is_down);
|
||||
this.isPointerOver = true;
|
||||
}
|
||||
onMouseLeave(event) {
|
||||
var _a;
|
||||
(_a = super.onMouseLeave) === null || _a === void 0 ? void 0 : _a.call(this, event);
|
||||
this.setIsPointerDown(false);
|
||||
this.isPointerOver = false;
|
||||
}
|
||||
onMouseMove(event, pos, canvas) {
|
||||
var _a;
|
||||
(_a = super.onMouseMove) === null || _a === void 0 ? void 0 : _a.call(this, event, pos, canvas);
|
||||
this.pointerOverPos = [...pos];
|
||||
this.imageIndex = this.pointerOverPos[0] > this.size[0] / 2 ? 1 : 0;
|
||||
}
|
||||
getHelp() {
|
||||
return `
|
||||
<p>
|
||||
The ${this.type.replace("(rgthree)", "")} node compares two images on top of each other.
|
||||
</p>
|
||||
<ul>
|
||||
<li>
|
||||
<p>
|
||||
<strong>Notes</strong>
|
||||
</p>
|
||||
<ul>
|
||||
<li><p>
|
||||
The right-click menu may show image options (Open Image, Save Image, etc.) which will
|
||||
correspond to the first image (image_a) if clicked on the left-half of the node, or
|
||||
the second image if on the right half of the node.
|
||||
</p></li>
|
||||
</ul>
|
||||
</li>
|
||||
<li>
|
||||
<p>
|
||||
<strong>Inputs</strong>
|
||||
</p>
|
||||
<ul>
|
||||
<li><p>
|
||||
<code>image_a</code> <i>Optional.</i> The first image to use to compare.
|
||||
image_a.
|
||||
</p></li>
|
||||
<li><p>
|
||||
<code>image_b</code> <i>Optional.</i> The second image to use to compare.
|
||||
</p></li>
|
||||
<li><p>
|
||||
<b>Note</b> <code>image_a</code> and <code>image_b</code> work best when a single
|
||||
image is provided. However, if each/either are a batch, you can choose which item
|
||||
from each batch are chosen to be compared. If either <code>image_a</code> or
|
||||
<code>image_b</code> are not provided, the node will choose the first two from the
|
||||
provided input if it's a batch, otherwise only show the single image (just as
|
||||
Preview Image would).
|
||||
</p></li>
|
||||
</ul>
|
||||
</li>
|
||||
<li>
|
||||
<p>
|
||||
<strong>Properties.</strong> You can change the following properties (by right-clicking
|
||||
on the node, and select "Properties" or "Properties Panel" from the menu):
|
||||
</p>
|
||||
<ul>
|
||||
<li><p>
|
||||
<code>comparer_mode</code> - Choose between "Slide" and "Click". Defaults to "Slide".
|
||||
</p></li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>`;
|
||||
}
|
||||
static setUp(comfyClass, nodeData) {
|
||||
RgthreeBaseServerNode.registerForOverride(comfyClass, nodeData, RgthreeImageComparer);
|
||||
}
|
||||
static onRegisteredForOverride(comfyClass) {
|
||||
addConnectionLayoutSupport(RgthreeImageComparer, app, [
|
||||
["Left", "Right"],
|
||||
["Right", "Left"],
|
||||
]);
|
||||
setTimeout(() => {
|
||||
RgthreeImageComparer.category = comfyClass.category;
|
||||
});
|
||||
}
|
||||
}
|
||||
RgthreeImageComparer.title = NodeTypesString.IMAGE_COMPARER;
|
||||
RgthreeImageComparer.type = NodeTypesString.IMAGE_COMPARER;
|
||||
RgthreeImageComparer.comfyClass = NodeTypesString.IMAGE_COMPARER;
|
||||
RgthreeImageComparer["@comparer_mode"] = {
|
||||
type: "combo",
|
||||
values: ["Slide", "Click"],
|
||||
};
|
||||
class RgthreeImageComparerWidget extends RgthreeBaseWidget {
|
||||
constructor(name, node) {
|
||||
super(name);
|
||||
this.type = "custom";
|
||||
this.hitAreas = {};
|
||||
this.selected = [];
|
||||
this._value = { images: [] };
|
||||
this.node = node;
|
||||
}
|
||||
set value(v) {
|
||||
let cleanedVal;
|
||||
if (Array.isArray(v)) {
|
||||
cleanedVal = v.map((d, i) => {
|
||||
if (!d || typeof d === "string") {
|
||||
d = { url: d, name: i == 0 ? "A" : "B", selected: true };
|
||||
}
|
||||
return d;
|
||||
});
|
||||
}
|
||||
else {
|
||||
cleanedVal = v.images || [];
|
||||
}
|
||||
if (cleanedVal.length > 2) {
|
||||
const hasAAndB = cleanedVal.some((i) => i.name.startsWith("A")) &&
|
||||
cleanedVal.some((i) => i.name.startsWith("B"));
|
||||
if (!hasAAndB) {
|
||||
cleanedVal = [cleanedVal[0], cleanedVal[1]];
|
||||
}
|
||||
}
|
||||
let selected = cleanedVal.filter((d) => d.selected);
|
||||
if (!selected.length && cleanedVal.length) {
|
||||
cleanedVal[0].selected = true;
|
||||
}
|
||||
selected = cleanedVal.filter((d) => d.selected);
|
||||
if (selected.length === 1 && cleanedVal.length > 1) {
|
||||
cleanedVal.find((d) => !d.selected).selected = true;
|
||||
}
|
||||
this._value.images = cleanedVal;
|
||||
selected = cleanedVal.filter((d) => d.selected);
|
||||
this.setSelected(selected);
|
||||
}
|
||||
get value() {
|
||||
return this._value;
|
||||
}
|
||||
setSelected(selected) {
|
||||
this._value.images.forEach((d) => (d.selected = false));
|
||||
this.node.imgs.length = 0;
|
||||
for (const sel of selected) {
|
||||
if (!sel.img) {
|
||||
sel.img = new Image();
|
||||
sel.img.src = sel.url;
|
||||
this.node.imgs.push(sel.img);
|
||||
}
|
||||
sel.selected = true;
|
||||
}
|
||||
this.selected = selected;
|
||||
}
|
||||
draw(ctx, node, width, y) {
|
||||
var _a;
|
||||
this.hitAreas = {};
|
||||
if (this.value.images.length > 2) {
|
||||
ctx.textAlign = "left";
|
||||
ctx.textBaseline = "top";
|
||||
ctx.font = `14px Arial`;
|
||||
const drawData = [];
|
||||
const spacing = 5;
|
||||
let x = 0;
|
||||
for (const img of this.value.images) {
|
||||
const width = measureText(ctx, img.name);
|
||||
drawData.push({
|
||||
img,
|
||||
text: img.name,
|
||||
x,
|
||||
width: measureText(ctx, img.name),
|
||||
});
|
||||
x += width + spacing;
|
||||
}
|
||||
x = (node.size[0] - (x - spacing)) / 2;
|
||||
for (const d of drawData) {
|
||||
ctx.fillStyle = d.img.selected ? "rgba(180, 180, 180, 1)" : "rgba(180, 180, 180, 0.5)";
|
||||
ctx.fillText(d.text, x, y);
|
||||
this.hitAreas[d.text] = {
|
||||
bounds: [x, y, d.width, 14],
|
||||
data: d.img,
|
||||
onDown: this.onSelectionDown,
|
||||
};
|
||||
x += d.width + spacing;
|
||||
}
|
||||
y += 20;
|
||||
}
|
||||
if (((_a = node.properties) === null || _a === void 0 ? void 0 : _a["comparer_mode"]) === "Click") {
|
||||
this.drawImage(ctx, this.selected[this.node.isPointerDown ? 1 : 0], y);
|
||||
}
|
||||
else {
|
||||
this.drawImage(ctx, this.selected[0], y);
|
||||
if (node.isPointerOver) {
|
||||
this.drawImage(ctx, this.selected[1], y, this.node.pointerOverPos[0]);
|
||||
}
|
||||
}
|
||||
}
|
||||
onSelectionDown(event, pos, node, bounds) {
|
||||
const selected = [...this.selected];
|
||||
if (bounds === null || bounds === void 0 ? void 0 : bounds.data.name.startsWith("A")) {
|
||||
selected[0] = bounds.data;
|
||||
}
|
||||
else if (bounds === null || bounds === void 0 ? void 0 : bounds.data.name.startsWith("B")) {
|
||||
selected[1] = bounds.data;
|
||||
}
|
||||
this.setSelected(selected);
|
||||
}
|
||||
drawImage(ctx, image, y, cropX) {
|
||||
var _a, _b;
|
||||
if (!((_a = image === null || image === void 0 ? void 0 : image.img) === null || _a === void 0 ? void 0 : _a.naturalWidth) || !((_b = image === null || image === void 0 ? void 0 : image.img) === null || _b === void 0 ? void 0 : _b.naturalHeight)) {
|
||||
return;
|
||||
}
|
||||
let [nodeWidth, nodeHeight] = this.node.size;
|
||||
const imageAspect = (image === null || image === void 0 ? void 0 : image.img.naturalWidth) / (image === null || image === void 0 ? void 0 : image.img.naturalHeight);
|
||||
let height = nodeHeight - y;
|
||||
const widgetAspect = nodeWidth / height;
|
||||
let targetWidth, targetHeight;
|
||||
let offsetX = 0;
|
||||
if (imageAspect > widgetAspect) {
|
||||
targetWidth = nodeWidth;
|
||||
targetHeight = nodeWidth / imageAspect;
|
||||
}
|
||||
else {
|
||||
targetHeight = height;
|
||||
targetWidth = height * imageAspect;
|
||||
offsetX = (nodeWidth - targetWidth) / 2;
|
||||
}
|
||||
const widthMultiplier = (image === null || image === void 0 ? void 0 : image.img.naturalWidth) / targetWidth;
|
||||
const sourceX = 0;
|
||||
const sourceY = 0;
|
||||
const sourceWidth = cropX != null ? (cropX - offsetX) * widthMultiplier : image === null || image === void 0 ? void 0 : image.img.naturalWidth;
|
||||
const sourceHeight = image === null || image === void 0 ? void 0 : image.img.naturalHeight;
|
||||
const destX = (nodeWidth - targetWidth) / 2;
|
||||
const destY = y + (height - targetHeight) / 2;
|
||||
const destWidth = cropX != null ? cropX - offsetX : targetWidth;
|
||||
const destHeight = targetHeight;
|
||||
ctx.save();
|
||||
ctx.beginPath();
|
||||
let globalCompositeOperation = ctx.globalCompositeOperation;
|
||||
if (cropX) {
|
||||
ctx.rect(destX, destY, destWidth, destHeight);
|
||||
ctx.clip();
|
||||
}
|
||||
ctx.drawImage(image === null || image === void 0 ? void 0 : image.img, sourceX, sourceY, sourceWidth, sourceHeight, destX, destY, destWidth, destHeight);
|
||||
if (cropX != null && cropX >= (nodeWidth - targetWidth) / 2 && cropX <= targetWidth + offsetX) {
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(cropX, destY);
|
||||
ctx.lineTo(cropX, destY + destHeight);
|
||||
ctx.globalCompositeOperation = "difference";
|
||||
ctx.strokeStyle = "rgba(255,255,255, 1)";
|
||||
ctx.stroke();
|
||||
}
|
||||
ctx.globalCompositeOperation = globalCompositeOperation;
|
||||
ctx.restore();
|
||||
}
|
||||
computeSize(width) {
|
||||
return [width, 20];
|
||||
}
|
||||
serializeValue(node, index) {
|
||||
const v = [];
|
||||
for (const data of this._value.images) {
|
||||
const d = { ...data };
|
||||
delete d.img;
|
||||
v.push(d);
|
||||
}
|
||||
return { images: v };
|
||||
}
|
||||
}
|
||||
app.registerExtension({
|
||||
name: "rgthree.ImageComparer",
|
||||
async beforeRegisterNodeDef(nodeType, nodeData) {
|
||||
if (nodeData.name === RgthreeImageComparer.type) {
|
||||
RgthreeImageComparer.setUp(nodeType, nodeData);
|
||||
}
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,748 @@
|
||||
import { app } from "../../scripts/app.js";
|
||||
import { api } from "../../scripts/api.js";
|
||||
import { getResolver, wait } from "../../rgthree/common/shared_utils.js";
|
||||
import { RgthreeHelpDialog } from "../../rgthree/common/dialog.js";
|
||||
const oldApiGetNodeDefs = api.getNodeDefs;
|
||||
api.getNodeDefs = async function () {
|
||||
const defs = await oldApiGetNodeDefs.call(api);
|
||||
this.dispatchEvent(new CustomEvent("fresh-node-defs", { detail: defs }));
|
||||
return defs;
|
||||
};
|
||||
export var IoDirection;
|
||||
(function (IoDirection) {
|
||||
IoDirection[IoDirection["INPUT"] = 0] = "INPUT";
|
||||
IoDirection[IoDirection["OUTPUT"] = 1] = "OUTPUT";
|
||||
})(IoDirection || (IoDirection = {}));
|
||||
const PADDING = 0;
|
||||
export const LAYOUT_LABEL_TO_DATA = {
|
||||
Left: [LiteGraph.LEFT, [0, 0.5], [PADDING, 0]],
|
||||
Right: [LiteGraph.RIGHT, [1, 0.5], [-PADDING, 0]],
|
||||
Top: [LiteGraph.UP, [0.5, 0], [0, PADDING]],
|
||||
Bottom: [LiteGraph.DOWN, [0.5, 1], [0, -PADDING]],
|
||||
};
|
||||
export const LAYOUT_LABEL_OPPOSITES = {
|
||||
Left: "Right",
|
||||
Right: "Left",
|
||||
Top: "Bottom",
|
||||
Bottom: "Top",
|
||||
};
|
||||
export const LAYOUT_CLOCKWISE = ["Top", "Right", "Bottom", "Left"];
|
||||
export function addMenuItem(node, _app, config, after = "Shape") {
|
||||
const oldGetExtraMenuOptions = node.prototype.getExtraMenuOptions;
|
||||
node.prototype.getExtraMenuOptions = function (canvas, menuOptions) {
|
||||
oldGetExtraMenuOptions && oldGetExtraMenuOptions.apply(this, [canvas, menuOptions]);
|
||||
addMenuItemOnExtraMenuOptions(this, config, menuOptions, after);
|
||||
};
|
||||
}
|
||||
let canvasResolver = null;
|
||||
export function waitForCanvas() {
|
||||
if (canvasResolver === null) {
|
||||
canvasResolver = getResolver();
|
||||
function _waitForCanvas() {
|
||||
if (!canvasResolver.completed) {
|
||||
if (app === null || app === void 0 ? void 0 : app.canvas) {
|
||||
canvasResolver.resolve(app.canvas);
|
||||
}
|
||||
else {
|
||||
requestAnimationFrame(_waitForCanvas);
|
||||
}
|
||||
}
|
||||
}
|
||||
_waitForCanvas();
|
||||
}
|
||||
return canvasResolver.promise;
|
||||
}
|
||||
let graphResolver = null;
|
||||
export function waitForGraph() {
|
||||
if (graphResolver === null) {
|
||||
graphResolver = getResolver();
|
||||
function _wait() {
|
||||
if (!graphResolver.completed) {
|
||||
if (app === null || app === void 0 ? void 0 : app.graph) {
|
||||
graphResolver.resolve(app.graph);
|
||||
}
|
||||
else {
|
||||
requestAnimationFrame(_wait);
|
||||
}
|
||||
}
|
||||
}
|
||||
_wait();
|
||||
}
|
||||
return graphResolver.promise;
|
||||
}
|
||||
export function addMenuItemOnExtraMenuOptions(node, config, menuOptions, after = "Shape") {
|
||||
let idx = menuOptions
|
||||
.slice()
|
||||
.reverse()
|
||||
.findIndex((option) => option === null || option === void 0 ? void 0 : option.isRgthree);
|
||||
if (idx == -1) {
|
||||
idx = menuOptions.findIndex((option) => { var _a; return (_a = option === null || option === void 0 ? void 0 : option.content) === null || _a === void 0 ? void 0 : _a.includes(after); }) + 1;
|
||||
if (!idx) {
|
||||
idx = menuOptions.length - 1;
|
||||
}
|
||||
menuOptions.splice(idx, 0, null);
|
||||
idx++;
|
||||
}
|
||||
else {
|
||||
idx = menuOptions.length - idx;
|
||||
}
|
||||
const subMenuOptions = typeof config.subMenuOptions === "function"
|
||||
? config.subMenuOptions(node)
|
||||
: config.subMenuOptions;
|
||||
menuOptions.splice(idx, 0, {
|
||||
content: typeof config.name == "function" ? config.name(node) : config.name,
|
||||
has_submenu: !!(subMenuOptions === null || subMenuOptions === void 0 ? void 0 : subMenuOptions.length),
|
||||
isRgthree: true,
|
||||
callback: (value, _options, event, parentMenu, _node) => {
|
||||
if (!!(subMenuOptions === null || subMenuOptions === void 0 ? void 0 : subMenuOptions.length)) {
|
||||
new LiteGraph.ContextMenu(subMenuOptions.map((option) => (option ? { content: option } : null)), {
|
||||
event,
|
||||
parentMenu,
|
||||
callback: (subValue, _options, _event, _parentMenu, _node) => {
|
||||
if (config.property) {
|
||||
node.properties = node.properties || {};
|
||||
node.properties[config.property] = config.prepareValue
|
||||
? config.prepareValue(subValue.content || "", node)
|
||||
: subValue.content || "";
|
||||
}
|
||||
config.callback && config.callback(node, subValue === null || subValue === void 0 ? void 0 : subValue.content);
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (config.property) {
|
||||
node.properties = node.properties || {};
|
||||
node.properties[config.property] = config.prepareValue
|
||||
? config.prepareValue(node.properties[config.property], node)
|
||||
: !node.properties[config.property];
|
||||
}
|
||||
config.callback && config.callback(node, value === null || value === void 0 ? void 0 : value.content);
|
||||
},
|
||||
});
|
||||
}
|
||||
export function addConnectionLayoutSupport(node, app, options = [
|
||||
["Left", "Right"],
|
||||
["Right", "Left"],
|
||||
], callback) {
|
||||
addMenuItem(node, app, {
|
||||
name: "Connections Layout",
|
||||
property: "connections_layout",
|
||||
subMenuOptions: options.map((option) => option[0] + (option[1] ? " -> " + option[1] : "")),
|
||||
prepareValue: (value, node) => {
|
||||
var _a;
|
||||
const values = String(value).split(" -> ");
|
||||
if (!values[1] && !((_a = node.outputs) === null || _a === void 0 ? void 0 : _a.length)) {
|
||||
values[1] = LAYOUT_LABEL_OPPOSITES[values[0]];
|
||||
}
|
||||
if (!LAYOUT_LABEL_TO_DATA[values[0]] || !LAYOUT_LABEL_TO_DATA[values[1]]) {
|
||||
throw new Error(`New Layout invalid: [${values[0]}, ${values[1]}]`);
|
||||
}
|
||||
return values;
|
||||
},
|
||||
callback: (node) => {
|
||||
var _a;
|
||||
callback && callback(node);
|
||||
(_a = node.graph) === null || _a === void 0 ? void 0 : _a.setDirtyCanvas(true, true);
|
||||
},
|
||||
});
|
||||
node.prototype.getConnectionPos = function (isInput, slotNumber, out) {
|
||||
return getConnectionPosForLayout(this, isInput, slotNumber, out);
|
||||
};
|
||||
node.prototype.getInputPos = function (slotNumber) {
|
||||
return getConnectionPosForLayout(this, true, slotNumber, [0, 0]);
|
||||
};
|
||||
node.prototype.getOutputPos = function (slotNumber) {
|
||||
return getConnectionPosForLayout(this, false, slotNumber, [0, 0]);
|
||||
};
|
||||
}
|
||||
export function setConnectionsLayout(node, newLayout) {
|
||||
var _a;
|
||||
newLayout = newLayout || node.defaultConnectionsLayout || ["Left", "Right"];
|
||||
if (!newLayout[1] && !((_a = node.outputs) === null || _a === void 0 ? void 0 : _a.length)) {
|
||||
newLayout[1] = LAYOUT_LABEL_OPPOSITES[newLayout[0]];
|
||||
}
|
||||
if (!LAYOUT_LABEL_TO_DATA[newLayout[0]] || !LAYOUT_LABEL_TO_DATA[newLayout[1]]) {
|
||||
throw new Error(`New Layout invalid: [${newLayout[0]}, ${newLayout[1]}]`);
|
||||
}
|
||||
node.properties = node.properties || {};
|
||||
node.properties["connections_layout"] = newLayout;
|
||||
}
|
||||
export function setConnectionsCollapse(node, collapseConnections = null) {
|
||||
node.properties = node.properties || {};
|
||||
collapseConnections =
|
||||
collapseConnections !== null ? collapseConnections : !node.properties["collapse_connections"];
|
||||
node.properties["collapse_connections"] = collapseConnections;
|
||||
}
|
||||
export function getConnectionPosForLayout(node, isInput, slotNumber, out) {
|
||||
var _a, _b, _c;
|
||||
out = out || new Float32Array(2);
|
||||
node.properties = node.properties || {};
|
||||
const layout = node.properties["connections_layout"] ||
|
||||
node.defaultConnectionsLayout || ["Left", "Right"];
|
||||
const collapseConnections = node.properties["collapse_connections"] || false;
|
||||
const offset = (_a = node.constructor.layout_slot_offset) !== null && _a !== void 0 ? _a : LiteGraph.NODE_SLOT_HEIGHT * 0.5;
|
||||
let side = isInput ? layout[0] : layout[1];
|
||||
const otherSide = isInput ? layout[1] : layout[0];
|
||||
let data = LAYOUT_LABEL_TO_DATA[side];
|
||||
const slotList = node[isInput ? "inputs" : "outputs"];
|
||||
const cxn = slotList[slotNumber];
|
||||
if (!cxn) {
|
||||
console.log("No connection found.. weird", isInput, slotNumber);
|
||||
return out;
|
||||
}
|
||||
if (cxn.disabled) {
|
||||
if (cxn.color_on !== "#666665") {
|
||||
cxn._color_on_org = cxn._color_on_org || cxn.color_on;
|
||||
cxn._color_off_org = cxn._color_off_org || cxn.color_off;
|
||||
}
|
||||
cxn.color_on = "#666665";
|
||||
cxn.color_off = "#666665";
|
||||
}
|
||||
else if (cxn.color_on === "#666665") {
|
||||
cxn.color_on = cxn._color_on_org || undefined;
|
||||
cxn.color_off = cxn._color_off_org || undefined;
|
||||
}
|
||||
const displaySlot = collapseConnections
|
||||
? 0
|
||||
: slotNumber -
|
||||
slotList.reduce((count, ioput, index) => {
|
||||
count += index < slotNumber && ioput.hidden ? 1 : 0;
|
||||
return count;
|
||||
}, 0);
|
||||
cxn.dir = data[0];
|
||||
const connections_dir = node.properties["connections_dir"];
|
||||
if ((node.size[0] == 10 || node.size[1] == 10) && connections_dir) {
|
||||
cxn.dir = connections_dir[isInput ? 0 : 1];
|
||||
}
|
||||
if (side === "Left") {
|
||||
if (node.flags.collapsed) {
|
||||
var w = node._collapsed_width || LiteGraph.NODE_COLLAPSED_WIDTH;
|
||||
out[0] = node.pos[0];
|
||||
out[1] = node.pos[1] - LiteGraph.NODE_TITLE_HEIGHT * 0.5;
|
||||
}
|
||||
else {
|
||||
toggleConnectionLabel(cxn, !isInput || collapseConnections || !!node.hideSlotLabels);
|
||||
out[0] = node.pos[0] + offset;
|
||||
if ((_b = node.constructor) === null || _b === void 0 ? void 0 : _b.type.includes("Reroute")) {
|
||||
out[1] = node.pos[1] + node.size[1] * 0.5;
|
||||
}
|
||||
else {
|
||||
out[1] =
|
||||
node.pos[1] +
|
||||
(displaySlot + 0.7) * LiteGraph.NODE_SLOT_HEIGHT +
|
||||
(node.constructor.slot_start_y || 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (side === "Right") {
|
||||
if (node.flags.collapsed) {
|
||||
var w = node._collapsed_width || LiteGraph.NODE_COLLAPSED_WIDTH;
|
||||
out[0] = node.pos[0] + w;
|
||||
out[1] = node.pos[1] - LiteGraph.NODE_TITLE_HEIGHT * 0.5;
|
||||
}
|
||||
else {
|
||||
toggleConnectionLabel(cxn, isInput || collapseConnections || !!node.hideSlotLabels);
|
||||
out[0] = node.pos[0] + node.size[0] + 1 - offset;
|
||||
if ((_c = node.constructor) === null || _c === void 0 ? void 0 : _c.type.includes("Reroute")) {
|
||||
out[1] = node.pos[1] + node.size[1] * 0.5;
|
||||
}
|
||||
else {
|
||||
out[1] =
|
||||
node.pos[1] +
|
||||
(displaySlot + 0.7) * LiteGraph.NODE_SLOT_HEIGHT +
|
||||
(node.constructor.slot_start_y || 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (side === "Top") {
|
||||
if (!cxn.has_old_label) {
|
||||
cxn.has_old_label = true;
|
||||
cxn.old_label = cxn.label;
|
||||
cxn.label = " ";
|
||||
}
|
||||
out[0] = node.pos[0] + node.size[0] * 0.5;
|
||||
out[1] = node.pos[1] + offset;
|
||||
}
|
||||
else if (side === "Bottom") {
|
||||
if (!cxn.has_old_label) {
|
||||
cxn.has_old_label = true;
|
||||
cxn.old_label = cxn.label;
|
||||
cxn.label = " ";
|
||||
}
|
||||
out[0] = node.pos[0] + node.size[0] * 0.5;
|
||||
out[1] = node.pos[1] + node.size[1] - offset;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
function toggleConnectionLabel(cxn, hide = true) {
|
||||
if (hide) {
|
||||
if (!cxn.has_old_label) {
|
||||
cxn.has_old_label = true;
|
||||
cxn.old_label = cxn.label;
|
||||
}
|
||||
cxn.label = " ";
|
||||
}
|
||||
else if (!hide && cxn.has_old_label) {
|
||||
cxn.has_old_label = false;
|
||||
cxn.label = cxn.old_label;
|
||||
cxn.old_label = undefined;
|
||||
}
|
||||
return cxn;
|
||||
}
|
||||
export function addHelpMenuItem(node, content, menuOptions) {
|
||||
addMenuItemOnExtraMenuOptions(node, {
|
||||
name: "🛟 Node Help",
|
||||
callback: (node) => {
|
||||
if (node.showHelp) {
|
||||
node.showHelp();
|
||||
}
|
||||
else {
|
||||
new RgthreeHelpDialog(node, content).show();
|
||||
}
|
||||
},
|
||||
}, menuOptions, "Properties Panel");
|
||||
}
|
||||
export var PassThroughFollowing;
|
||||
(function (PassThroughFollowing) {
|
||||
PassThroughFollowing[PassThroughFollowing["ALL"] = 0] = "ALL";
|
||||
PassThroughFollowing[PassThroughFollowing["NONE"] = 1] = "NONE";
|
||||
PassThroughFollowing[PassThroughFollowing["REROUTE_ONLY"] = 2] = "REROUTE_ONLY";
|
||||
})(PassThroughFollowing || (PassThroughFollowing = {}));
|
||||
export function shouldPassThrough(node, passThroughFollowing = PassThroughFollowing.ALL) {
|
||||
var _a;
|
||||
const type = (_a = node === null || node === void 0 ? void 0 : node.constructor) === null || _a === void 0 ? void 0 : _a.type;
|
||||
if (!type || passThroughFollowing === PassThroughFollowing.NONE) {
|
||||
return false;
|
||||
}
|
||||
if (passThroughFollowing === PassThroughFollowing.REROUTE_ONLY) {
|
||||
return type.includes("Reroute");
|
||||
}
|
||||
return (type.includes("Reroute") || type.includes("Node Combiner") || type.includes("Node Collector"));
|
||||
}
|
||||
function filterOutPassthroughNodes(infos, passThroughFollowing = PassThroughFollowing.ALL) {
|
||||
return infos.filter((i) => !shouldPassThrough(i.node, passThroughFollowing));
|
||||
}
|
||||
export function getConnectedInputNodes(startNode, currentNode, slot, passThroughFollowing = PassThroughFollowing.ALL) {
|
||||
return getConnectedNodesInfo(startNode, IoDirection.INPUT, currentNode, slot, passThroughFollowing).map((n) => n.node);
|
||||
}
|
||||
export function getConnectedInputInfosAndFilterPassThroughs(startNode, currentNode, slot, passThroughFollowing = PassThroughFollowing.ALL) {
|
||||
return filterOutPassthroughNodes(getConnectedNodesInfo(startNode, IoDirection.INPUT, currentNode, slot, passThroughFollowing), passThroughFollowing);
|
||||
}
|
||||
export function getConnectedInputNodesAndFilterPassThroughs(startNode, currentNode, slot, passThroughFollowing = PassThroughFollowing.ALL) {
|
||||
return getConnectedInputInfosAndFilterPassThroughs(startNode, currentNode, slot, passThroughFollowing).map((n) => n.node);
|
||||
}
|
||||
export function getConnectedOutputNodes(startNode, currentNode, slot, passThroughFollowing = PassThroughFollowing.ALL) {
|
||||
return getConnectedNodesInfo(startNode, IoDirection.OUTPUT, currentNode, slot, passThroughFollowing).map((n) => n.node);
|
||||
}
|
||||
export function getConnectedOutputNodesAndFilterPassThroughs(startNode, currentNode, slot, passThroughFollowing = PassThroughFollowing.ALL) {
|
||||
return filterOutPassthroughNodes(getConnectedNodesInfo(startNode, IoDirection.OUTPUT, currentNode, slot, passThroughFollowing), passThroughFollowing).map((n) => n.node);
|
||||
}
|
||||
export function getConnectedNodesInfo(startNode, dir = IoDirection.INPUT, currentNode, slot, passThroughFollowing = PassThroughFollowing.ALL, originTravelFromSlot) {
|
||||
var _a, _b, _c, _d, _e, _f, _g, _h;
|
||||
currentNode = currentNode || startNode;
|
||||
let rootNodes = [];
|
||||
if (startNode === currentNode || shouldPassThrough(currentNode, passThroughFollowing)) {
|
||||
let linkIds;
|
||||
slot = slot != null && slot > -1 ? slot : undefined;
|
||||
if (dir == IoDirection.OUTPUT) {
|
||||
if (slot != null) {
|
||||
linkIds = [...(((_b = (_a = currentNode.outputs) === null || _a === void 0 ? void 0 : _a[slot]) === null || _b === void 0 ? void 0 : _b.links) || [])];
|
||||
}
|
||||
else {
|
||||
linkIds = ((_c = currentNode.outputs) === null || _c === void 0 ? void 0 : _c.flatMap((i) => i.links)) || [];
|
||||
}
|
||||
}
|
||||
else {
|
||||
if (slot != null) {
|
||||
linkIds = [(_e = (_d = currentNode.inputs) === null || _d === void 0 ? void 0 : _d[slot]) === null || _e === void 0 ? void 0 : _e.link];
|
||||
}
|
||||
else {
|
||||
linkIds = ((_f = currentNode.inputs) === null || _f === void 0 ? void 0 : _f.map((i) => i.link)) || [];
|
||||
}
|
||||
}
|
||||
const graph = (_g = currentNode.graph) !== null && _g !== void 0 ? _g : app.graph;
|
||||
for (const linkId of linkIds) {
|
||||
let link = null;
|
||||
if (typeof linkId == "number") {
|
||||
link = (_h = graph.links[linkId]) !== null && _h !== void 0 ? _h : null;
|
||||
}
|
||||
if (!link) {
|
||||
continue;
|
||||
}
|
||||
const travelFromSlot = dir == IoDirection.OUTPUT ? link.origin_slot : link.target_slot;
|
||||
const connectedId = dir == IoDirection.OUTPUT ? link.target_id : link.origin_id;
|
||||
const travelToSlot = dir == IoDirection.OUTPUT ? link.target_slot : link.origin_slot;
|
||||
originTravelFromSlot = originTravelFromSlot != null ? originTravelFromSlot : travelFromSlot;
|
||||
const originNode = graph.getNodeById(connectedId);
|
||||
if (!link) {
|
||||
console.error("No connected node found... weird");
|
||||
continue;
|
||||
}
|
||||
if (rootNodes.some((n) => n.node == originNode)) {
|
||||
console.log(`${startNode.title} (${startNode.id}) seems to have two links to ${originNode.title} (${originNode.id}). One may be stale: ${linkIds.join(", ")}`);
|
||||
}
|
||||
else {
|
||||
rootNodes.push({ node: originNode, travelFromSlot, travelToSlot, originTravelFromSlot });
|
||||
if (shouldPassThrough(originNode, passThroughFollowing)) {
|
||||
for (const foundNode of getConnectedNodesInfo(startNode, dir, originNode, undefined, undefined, originTravelFromSlot)) {
|
||||
if (!rootNodes.map((n) => n.node).includes(foundNode.node)) {
|
||||
rootNodes.push(foundNode);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return rootNodes;
|
||||
}
|
||||
export function followConnectionUntilType(node, dir, slotNum, skipSelf = false) {
|
||||
const slots = dir === IoDirection.OUTPUT ? node.outputs : node.inputs;
|
||||
if (!slots || !slots.length) {
|
||||
return null;
|
||||
}
|
||||
let type = null;
|
||||
if (slotNum) {
|
||||
if (!slots[slotNum]) {
|
||||
return null;
|
||||
}
|
||||
type = getTypeFromSlot(slots[slotNum], dir, skipSelf);
|
||||
}
|
||||
else {
|
||||
for (const slot of slots) {
|
||||
type = getTypeFromSlot(slot, dir, skipSelf);
|
||||
if (type) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return type;
|
||||
}
|
||||
function getTypeFromSlot(slot, dir, skipSelf = false) {
|
||||
let graph = app.canvas.getCurrentGraph();
|
||||
let type = slot === null || slot === void 0 ? void 0 : slot.type;
|
||||
if (!skipSelf && type != null && type != "*") {
|
||||
return { type: type, label: slot === null || slot === void 0 ? void 0 : slot.label, name: slot === null || slot === void 0 ? void 0 : slot.name };
|
||||
}
|
||||
const links = getSlotLinks(slot);
|
||||
for (const link of links) {
|
||||
const connectedId = dir == IoDirection.OUTPUT ? link.link.target_id : link.link.origin_id;
|
||||
const connectedSlotNum = dir == IoDirection.OUTPUT ? link.link.target_slot : link.link.origin_slot;
|
||||
const connectedNode = graph.getNodeById(connectedId);
|
||||
const connectedSlots = dir === IoDirection.OUTPUT ? connectedNode.inputs : connectedNode.outputs;
|
||||
let connectedSlot = connectedSlots[connectedSlotNum];
|
||||
if ((connectedSlot === null || connectedSlot === void 0 ? void 0 : connectedSlot.type) != null && (connectedSlot === null || connectedSlot === void 0 ? void 0 : connectedSlot.type) != "*") {
|
||||
return {
|
||||
type: connectedSlot.type,
|
||||
label: connectedSlot === null || connectedSlot === void 0 ? void 0 : connectedSlot.label,
|
||||
name: connectedSlot === null || connectedSlot === void 0 ? void 0 : connectedSlot.name,
|
||||
};
|
||||
}
|
||||
else if ((connectedSlot === null || connectedSlot === void 0 ? void 0 : connectedSlot.type) == "*") {
|
||||
return followConnectionUntilType(connectedNode, dir);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
export async function replaceNode(existingNode, typeOrNewNode, inputNameMap) {
|
||||
const existingCtor = existingNode.constructor;
|
||||
const newNode = typeof typeOrNewNode === "string" ? LiteGraph.createNode(typeOrNewNode) : typeOrNewNode;
|
||||
if (existingNode.title != existingCtor.title) {
|
||||
newNode.title = existingNode.title;
|
||||
}
|
||||
newNode.pos = [...existingNode.pos];
|
||||
newNode.properties = { ...existingNode.properties };
|
||||
const oldComputeSize = [...existingNode.computeSize()];
|
||||
const oldSize = [
|
||||
existingNode.size[0] === oldComputeSize[0] ? null : existingNode.size[0],
|
||||
existingNode.size[1] === oldComputeSize[1] ? null : existingNode.size[1],
|
||||
];
|
||||
let setSizeIters = 0;
|
||||
const setSizeFn = () => {
|
||||
const newComputesize = newNode.computeSize();
|
||||
newNode.size[0] = Math.max(oldSize[0] || 0, newComputesize[0]);
|
||||
newNode.size[1] = Math.max(oldSize[1] || 0, newComputesize[1]);
|
||||
setSizeIters++;
|
||||
if (setSizeIters > 10) {
|
||||
requestAnimationFrame(setSizeFn);
|
||||
}
|
||||
};
|
||||
setSizeFn();
|
||||
const links = [];
|
||||
const graph = existingNode.graph || app.graph;
|
||||
for (const [index, output] of existingNode.outputs.entries()) {
|
||||
for (const linkId of output.links || []) {
|
||||
const link = graph.links[linkId];
|
||||
if (!link)
|
||||
continue;
|
||||
const targetNode = graph.getNodeById(link.target_id);
|
||||
links.push({ node: newNode, slot: output.name, targetNode, targetSlot: link.target_slot });
|
||||
}
|
||||
}
|
||||
for (const [index, input] of existingNode.inputs.entries()) {
|
||||
const linkId = input.link;
|
||||
if (linkId) {
|
||||
const link = graph.links[linkId];
|
||||
const originNode = graph.getNodeById(link.origin_id);
|
||||
links.push({
|
||||
node: originNode,
|
||||
slot: link.origin_slot,
|
||||
targetNode: newNode,
|
||||
targetSlot: (inputNameMap === null || inputNameMap === void 0 ? void 0 : inputNameMap.has(input.name))
|
||||
? inputNameMap.get(input.name)
|
||||
: input.name || index,
|
||||
});
|
||||
}
|
||||
}
|
||||
graph.add(newNode);
|
||||
await wait();
|
||||
for (const link of links) {
|
||||
link.node.connect(link.slot, link.targetNode, link.targetSlot);
|
||||
}
|
||||
await wait();
|
||||
graph.remove(existingNode);
|
||||
newNode.size = newNode.computeSize();
|
||||
newNode.setDirtyCanvas(true, true);
|
||||
return newNode;
|
||||
}
|
||||
export function getOriginNodeByLink(linkId) {
|
||||
let node = null;
|
||||
if (linkId != null) {
|
||||
const link = getLinkById(linkId);
|
||||
node = (link != null && getNodeById(link.origin_id)) || null;
|
||||
}
|
||||
return node;
|
||||
}
|
||||
export function getLinkById(linkId) {
|
||||
var _a, _b, _c;
|
||||
if (linkId == null)
|
||||
return null;
|
||||
let link = (_a = app.graph.links[linkId]) !== null && _a !== void 0 ? _a : null;
|
||||
link = (_c = link !== null && link !== void 0 ? link : (_b = app.canvas.getCurrentGraph()) === null || _b === void 0 ? void 0 : _b.links[linkId]) !== null && _c !== void 0 ? _c : null;
|
||||
return link || findSomethingInAllSubgraphs((subgraph) => { var _a; return (_a = subgraph === null || subgraph === void 0 ? void 0 : subgraph.links[linkId]) !== null && _a !== void 0 ? _a : null; });
|
||||
}
|
||||
export function getNodeById(id) {
|
||||
var _a, _b;
|
||||
if (id == null)
|
||||
return null;
|
||||
let node = app.graph.getNodeById(id);
|
||||
node = (_b = node !== null && node !== void 0 ? node : (_a = app.canvas.getCurrentGraph()) === null || _a === void 0 ? void 0 : _a.getNodeById(id)) !== null && _b !== void 0 ? _b : null;
|
||||
return node || findSomethingInAllSubgraphs((subgraph) => { var _a; return (_a = subgraph === null || subgraph === void 0 ? void 0 : subgraph.getNodeById(id)) !== null && _a !== void 0 ? _a : null; });
|
||||
}
|
||||
export function getNodeByIdFromApiPrompt(apiPrompt, id) {
|
||||
var _a, _b, _c, _d;
|
||||
const fullId = getFullNodeIdFromApiPrompt(apiPrompt, id);
|
||||
const workflow = (_a = apiPrompt.workflow) !== null && _a !== void 0 ? _a : {};
|
||||
const nodeIds = String(fullId).split(":");
|
||||
const workflowNodes = (_b = workflow === null || workflow === void 0 ? void 0 : workflow["nodes"]) !== null && _b !== void 0 ? _b : [];
|
||||
const workflowSubgraphs = (_d = (_c = workflow === null || workflow === void 0 ? void 0 : workflow["definitions"]) === null || _c === void 0 ? void 0 : _c["subgraphs"]) !== null && _d !== void 0 ? _d : [];
|
||||
let nodesList = workflowNodes;
|
||||
let found = null;
|
||||
for (const nodeId of nodeIds) {
|
||||
found = nodesList.find((n) => String(n.id) === String(nodeId)) || null;
|
||||
if (found === null || found === void 0 ? void 0 : found["type"]) {
|
||||
const subgraph = workflowSubgraphs.find((n) => n.id === found["type"]) || null;
|
||||
if (subgraph === null || subgraph === void 0 ? void 0 : subgraph["nodes"]) {
|
||||
nodesList = subgraph["nodes"];
|
||||
}
|
||||
}
|
||||
}
|
||||
return found;
|
||||
}
|
||||
export function getFullNodeIdFromApiPrompt(apiPrompt, id) {
|
||||
var _a;
|
||||
const output = (_a = apiPrompt.output) !== null && _a !== void 0 ? _a : {};
|
||||
return output[id] ? id : Object.keys(output).find((i) => i.endsWith(`:${id}`));
|
||||
}
|
||||
export function findFromNodeForSubgraph(subgraphId) {
|
||||
var _a;
|
||||
const node = (_a = findSomethingInAllSubgraphs((subgraph) => subgraph.nodes
|
||||
.filter((node) => node.isSubgraphNode())
|
||||
.find((node) => node.subgraph.id === subgraphId))) !== null && _a !== void 0 ? _a : null;
|
||||
return node;
|
||||
}
|
||||
function findSomethingInAllSubgraphs(fn) {
|
||||
var _a, _b;
|
||||
const rootGraph = (_a = app.rootGraph) !== null && _a !== void 0 ? _a : app.graph.rootGraph;
|
||||
const subgraphs = [rootGraph, ...(_b = rootGraph.subgraphs) === null || _b === void 0 ? void 0 : _b.values()];
|
||||
for (const subgraph of subgraphs) {
|
||||
const thing = fn(subgraph);
|
||||
if (thing)
|
||||
return thing;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
export function applyMixins(original, constructors) {
|
||||
constructors.forEach((baseCtor) => {
|
||||
Object.getOwnPropertyNames(baseCtor.prototype).forEach((name) => {
|
||||
Object.defineProperty(original.prototype, name, Object.getOwnPropertyDescriptor(baseCtor.prototype, name) || Object.create(null));
|
||||
});
|
||||
});
|
||||
}
|
||||
export function getSlotLinks(inputOrOutput) {
|
||||
var _a;
|
||||
const links = [];
|
||||
if (!inputOrOutput) {
|
||||
return links;
|
||||
}
|
||||
if ((_a = inputOrOutput.links) === null || _a === void 0 ? void 0 : _a.length) {
|
||||
const output = inputOrOutput;
|
||||
for (const linkId of output.links || []) {
|
||||
const link = app.graph.links[linkId];
|
||||
if (link) {
|
||||
links.push({ id: linkId, link: link });
|
||||
}
|
||||
}
|
||||
}
|
||||
if (inputOrOutput.link) {
|
||||
const input = inputOrOutput;
|
||||
const link = app.graph.links[input.link];
|
||||
if (link) {
|
||||
links.push({ id: input.link, link: link });
|
||||
}
|
||||
}
|
||||
return links;
|
||||
}
|
||||
export async function matchLocalSlotsToServer(node, direction, serverNodeData) {
|
||||
var _a, _b, _c, _d;
|
||||
const serverSlotNames = direction == IoDirection.INPUT
|
||||
? Object.keys(((_a = serverNodeData.input) === null || _a === void 0 ? void 0 : _a.optional) || {})
|
||||
: ((_b = serverNodeData.output_name) !== null && _b !== void 0 ? _b : []);
|
||||
const serverSlotTypes = direction == IoDirection.INPUT
|
||||
? Object.values(((_c = serverNodeData.input) === null || _c === void 0 ? void 0 : _c.optional) || {}).map((i) => i[0])
|
||||
: serverNodeData.output;
|
||||
const slots = direction == IoDirection.INPUT ? node.inputs : node.outputs;
|
||||
let firstIndex = slots.findIndex((o, i) => i !== serverSlotNames.indexOf(o.name));
|
||||
if (firstIndex > -1) {
|
||||
const links = {};
|
||||
slots.map((slot) => {
|
||||
var _a;
|
||||
links[slot.name] = links[slot.name] || [];
|
||||
(_a = links[slot.name]) === null || _a === void 0 ? void 0 : _a.push(...getSlotLinks(slot));
|
||||
});
|
||||
for (const [index, serverSlotName] of serverSlotNames.entries()) {
|
||||
const currentNodeSlot = slots.map((s) => s.name).indexOf(serverSlotName);
|
||||
if (currentNodeSlot > -1) {
|
||||
if (currentNodeSlot != index) {
|
||||
const splicedItem = slots.splice(currentNodeSlot, 1)[0];
|
||||
slots.splice(index, 0, splicedItem);
|
||||
}
|
||||
}
|
||||
else if (currentNodeSlot === -1) {
|
||||
const splicedItem = {
|
||||
name: serverSlotName,
|
||||
type: serverSlotTypes[index],
|
||||
links: [],
|
||||
};
|
||||
slots.splice(index, 0, splicedItem);
|
||||
}
|
||||
}
|
||||
if (slots.length > serverSlotNames.length) {
|
||||
for (let i = slots.length - 1; i > serverSlotNames.length - 1; i--) {
|
||||
if (direction == IoDirection.INPUT) {
|
||||
node.disconnectInput(i);
|
||||
node.removeInput(i);
|
||||
}
|
||||
else {
|
||||
node.disconnectOutput(i);
|
||||
node.removeOutput(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const [name, slotLinks] of Object.entries(links)) {
|
||||
let currentNodeSlot = slots.map((s) => s.name).indexOf(name);
|
||||
if (currentNodeSlot > -1) {
|
||||
for (const linkData of slotLinks) {
|
||||
if (direction == IoDirection.INPUT) {
|
||||
linkData.link.target_slot = currentNodeSlot;
|
||||
}
|
||||
else {
|
||||
linkData.link.origin_slot = currentNodeSlot;
|
||||
const nextNode = app.graph.getNodeById(linkData.link.target_id);
|
||||
if (nextNode && ((_d = nextNode.constructor) === null || _d === void 0 ? void 0 : _d.type.includes("Reroute"))) {
|
||||
nextNode.stabilize && nextNode.stabilize();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
export function isValidConnection(ioA, ioB) {
|
||||
if (!ioA || !ioB) {
|
||||
return false;
|
||||
}
|
||||
const typeA = String(ioA.type);
|
||||
const typeB = String(ioB.type);
|
||||
let isValid = LiteGraph.isValidConnection(typeA, typeB);
|
||||
if (!isValid) {
|
||||
let areCombos = (typeA.includes(",") && typeB === "COMBO") || (typeA === "COMBO" && typeB.includes(","));
|
||||
if (areCombos) {
|
||||
const nameA = ioA.name.toUpperCase().replace("_NAME", "").replace("CKPT", "MODEL");
|
||||
const nameB = ioB.name.toUpperCase().replace("_NAME", "").replace("CKPT", "MODEL");
|
||||
isValid = nameA.includes(nameB) || nameB.includes(nameA);
|
||||
}
|
||||
}
|
||||
return isValid;
|
||||
}
|
||||
const oldIsValidConnection = LiteGraph.isValidConnection;
|
||||
LiteGraph.isValidConnection = function (typeA, typeB) {
|
||||
let isValid = oldIsValidConnection.call(LiteGraph, typeA, typeB);
|
||||
if (!isValid) {
|
||||
typeA = String(typeA);
|
||||
typeB = String(typeB);
|
||||
let areCombos = (typeA.includes(",") && typeB === "COMBO") || (typeA === "COMBO" && typeB.includes(","));
|
||||
isValid = areCombos;
|
||||
}
|
||||
return isValid;
|
||||
};
|
||||
export function getOutputNodes(nodes) {
|
||||
return ((nodes === null || nodes === void 0 ? void 0 : nodes.filter((n) => {
|
||||
var _a;
|
||||
return (n.mode != LiteGraph.NEVER && ((_a = n.constructor.nodeData) === null || _a === void 0 ? void 0 : _a.output_node));
|
||||
})) || []);
|
||||
}
|
||||
export function changeModeOfNodes(nodeOrNodes, mode) {
|
||||
reduceNodesDepthFirst(nodeOrNodes, (n) => {
|
||||
n.mode = mode;
|
||||
});
|
||||
}
|
||||
export function reduceNodesDepthFirst(nodeOrNodes, reduceFn, reduceTo) {
|
||||
var _a;
|
||||
const nodes = Array.isArray(nodeOrNodes) ? nodeOrNodes : [nodeOrNodes];
|
||||
const stack = nodes.map((node) => ({ node }));
|
||||
while (stack.length > 0) {
|
||||
const { node } = stack.pop();
|
||||
const result = reduceFn(node, reduceTo);
|
||||
if (result !== undefined && result !== reduceTo) {
|
||||
reduceTo = result;
|
||||
}
|
||||
if (((_a = node.isSubgraphNode) === null || _a === void 0 ? void 0 : _a.call(node)) && node.subgraph) {
|
||||
const children = node.subgraph.nodes;
|
||||
for (let i = children.length - 1; i >= 0; i--) {
|
||||
stack.push({ node: children[i] });
|
||||
}
|
||||
}
|
||||
}
|
||||
return reduceTo;
|
||||
}
|
||||
export function getGroupNodes(group) {
|
||||
return Array.from(group._children).filter((c) => c instanceof LGraphNode);
|
||||
}
|
||||
export function getGraphDependantNodeKey(node) {
|
||||
var _a;
|
||||
const graph = (_a = node.graph) !== null && _a !== void 0 ? _a : app.graph;
|
||||
return `${graph.id}:${node.id}`;
|
||||
}
|
||||
export function getFullColor(color, liteGraphKey = "color") {
|
||||
if (!color) {
|
||||
return "";
|
||||
}
|
||||
if (LGraphCanvas.node_colors[color]) {
|
||||
color = LGraphCanvas.node_colors[color][liteGraphKey];
|
||||
}
|
||||
color = color.replace("#", "").toLocaleLowerCase();
|
||||
if (color.length === 3) {
|
||||
color = color.replace(/(.)(.)(.)/, "$1$1$2$2$3$3");
|
||||
}
|
||||
return `#${color}`;
|
||||
}
|
||||
@@ -0,0 +1,292 @@
|
||||
import { app } from "../../scripts/app.js";
|
||||
import { drawNodeWidget, drawWidgetButton, fitString, isLowQuality } from "./utils_canvas.js";
|
||||
export function drawLabelAndValue(ctx, label, value, width, posY, height, options) {
|
||||
var _a;
|
||||
const outerMargin = 15;
|
||||
const innerMargin = 10;
|
||||
const midY = posY + height / 2;
|
||||
ctx.save();
|
||||
ctx.textAlign = "left";
|
||||
ctx.textBaseline = "middle";
|
||||
ctx.fillStyle = LiteGraph.WIDGET_SECONDARY_TEXT_COLOR;
|
||||
const labelX = outerMargin + innerMargin + ((_a = options === null || options === void 0 ? void 0 : options.offsetLeft) !== null && _a !== void 0 ? _a : 0);
|
||||
ctx.fillText(label, labelX, midY);
|
||||
const valueXLeft = labelX + ctx.measureText(label).width + 7;
|
||||
const valueXRight = width - (outerMargin + innerMargin);
|
||||
ctx.fillStyle = LiteGraph.WIDGET_TEXT_COLOR;
|
||||
ctx.textAlign = "right";
|
||||
ctx.fillText(fitString(ctx, value, valueXRight - valueXLeft), valueXRight, midY);
|
||||
ctx.restore();
|
||||
}
|
||||
export class RgthreeBaseWidget {
|
||||
constructor(name) {
|
||||
this.type = "custom";
|
||||
this.options = {};
|
||||
this.y = 0;
|
||||
this.last_y = 0;
|
||||
this.disabled = false;
|
||||
this.mouseDowned = null;
|
||||
this.isMouseDownedAndOver = false;
|
||||
this.hitAreas = {};
|
||||
this.downedHitAreasForMove = [];
|
||||
this.downedHitAreasForClick = [];
|
||||
this.name = name;
|
||||
}
|
||||
serializeValue(node, index) {
|
||||
return this.value;
|
||||
}
|
||||
clickWasWithinBounds(pos, bounds) {
|
||||
let xStart = bounds[0];
|
||||
let xEnd = xStart + (bounds.length > 2 ? bounds[2] : bounds[1]);
|
||||
const clickedX = pos[0] >= xStart && pos[0] <= xEnd;
|
||||
if (bounds.length === 2) {
|
||||
return clickedX;
|
||||
}
|
||||
return clickedX && pos[1] >= bounds[1] && pos[1] <= bounds[1] + bounds[3];
|
||||
}
|
||||
mouse(event, pos, node) {
|
||||
var _a, _b, _c;
|
||||
const canvas = app.canvas;
|
||||
if (event.type == "pointerdown") {
|
||||
this.mouseDowned = [...pos];
|
||||
this.isMouseDownedAndOver = true;
|
||||
this.downedHitAreasForMove.length = 0;
|
||||
this.downedHitAreasForClick.length = 0;
|
||||
let anyHandled = false;
|
||||
for (const part of Object.values(this.hitAreas)) {
|
||||
if (this.clickWasWithinBounds(pos, part.bounds)) {
|
||||
if (part.onMove) {
|
||||
this.downedHitAreasForMove.push(part);
|
||||
}
|
||||
if (part.onClick) {
|
||||
this.downedHitAreasForClick.push(part);
|
||||
}
|
||||
if (part.onDown) {
|
||||
const thisHandled = part.onDown.apply(this, [event, pos, node, part]);
|
||||
anyHandled = anyHandled || thisHandled == true;
|
||||
}
|
||||
part.wasMouseClickedAndIsOver = true;
|
||||
}
|
||||
}
|
||||
return (_a = this.onMouseDown(event, pos, node)) !== null && _a !== void 0 ? _a : anyHandled;
|
||||
}
|
||||
if (event.type == "pointerup") {
|
||||
if (!this.mouseDowned)
|
||||
return true;
|
||||
this.downedHitAreasForMove.length = 0;
|
||||
const wasMouseDownedAndOver = this.isMouseDownedAndOver;
|
||||
this.cancelMouseDown();
|
||||
let anyHandled = false;
|
||||
for (const part of Object.values(this.hitAreas)) {
|
||||
if (part.onUp && this.clickWasWithinBounds(pos, part.bounds)) {
|
||||
const thisHandled = part.onUp.apply(this, [event, pos, node, part]);
|
||||
anyHandled = anyHandled || thisHandled == true;
|
||||
}
|
||||
part.wasMouseClickedAndIsOver = false;
|
||||
}
|
||||
for (const part of this.downedHitAreasForClick) {
|
||||
if (this.clickWasWithinBounds(pos, part.bounds)) {
|
||||
const thisHandled = part.onClick.apply(this, [event, pos, node, part]);
|
||||
anyHandled = anyHandled || thisHandled == true;
|
||||
}
|
||||
}
|
||||
this.downedHitAreasForClick.length = 0;
|
||||
if (wasMouseDownedAndOver) {
|
||||
const thisHandled = this.onMouseClick(event, pos, node);
|
||||
anyHandled = anyHandled || thisHandled == true;
|
||||
}
|
||||
return (_b = this.onMouseUp(event, pos, node)) !== null && _b !== void 0 ? _b : anyHandled;
|
||||
}
|
||||
if (event.type == "pointermove") {
|
||||
this.isMouseDownedAndOver = !!this.mouseDowned;
|
||||
if (this.mouseDowned &&
|
||||
(pos[0] < 15 ||
|
||||
pos[0] > node.size[0] - 15 ||
|
||||
pos[1] < this.last_y ||
|
||||
pos[1] > this.last_y + LiteGraph.NODE_WIDGET_HEIGHT)) {
|
||||
this.isMouseDownedAndOver = false;
|
||||
}
|
||||
for (const part of Object.values(this.hitAreas)) {
|
||||
if (this.downedHitAreasForMove.includes(part)) {
|
||||
part.onMove.apply(this, [event, pos, node, part]);
|
||||
}
|
||||
if (this.downedHitAreasForClick.includes(part)) {
|
||||
part.wasMouseClickedAndIsOver = this.clickWasWithinBounds(pos, part.bounds);
|
||||
}
|
||||
}
|
||||
return (_c = this.onMouseMove(event, pos, node)) !== null && _c !== void 0 ? _c : true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
cancelMouseDown() {
|
||||
this.mouseDowned = null;
|
||||
this.isMouseDownedAndOver = false;
|
||||
this.downedHitAreasForMove.length = 0;
|
||||
}
|
||||
onMouseDown(event, pos, node) {
|
||||
return;
|
||||
}
|
||||
onMouseUp(event, pos, node) {
|
||||
return;
|
||||
}
|
||||
onMouseClick(event, pos, node) {
|
||||
return;
|
||||
}
|
||||
onMouseMove(event, pos, node) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
export class RgthreeBetterButtonWidget extends RgthreeBaseWidget {
|
||||
constructor(name, mouseClickCallback, label) {
|
||||
super(name);
|
||||
this.type = "custom";
|
||||
this.value = "";
|
||||
this.label = "";
|
||||
this.mouseClickCallback = mouseClickCallback;
|
||||
this.label = label || name;
|
||||
}
|
||||
draw(ctx, node, width, y, height) {
|
||||
drawWidgetButton(ctx, { size: [width - 30, height], pos: [15, y] }, this.label, this.isMouseDownedAndOver);
|
||||
}
|
||||
onMouseClick(event, pos, node) {
|
||||
return this.mouseClickCallback(event, pos, node);
|
||||
}
|
||||
}
|
||||
export class RgthreeBetterTextWidget extends RgthreeBaseWidget {
|
||||
constructor(name, value) {
|
||||
super(name);
|
||||
this.name = name;
|
||||
this.value = value;
|
||||
}
|
||||
draw(ctx, node, width, y, height) {
|
||||
const widgetData = drawNodeWidget(ctx, { size: [width, height], pos: [15, y] });
|
||||
if (!widgetData.lowQuality) {
|
||||
drawLabelAndValue(ctx, this.name, this.value, width, y, height);
|
||||
}
|
||||
}
|
||||
mouse(event, pos, node) {
|
||||
const canvas = app.canvas;
|
||||
if (event.type == "pointerdown") {
|
||||
canvas.prompt("Label", this.value, (v) => (this.value = v), event);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
export class RgthreeDividerWidget extends RgthreeBaseWidget {
|
||||
constructor(widgetOptions) {
|
||||
super("divider");
|
||||
this.value = {};
|
||||
this.options = { serialize: false };
|
||||
this.type = "custom";
|
||||
this.widgetOptions = {
|
||||
marginTop: 7,
|
||||
marginBottom: 7,
|
||||
marginLeft: 15,
|
||||
marginRight: 15,
|
||||
color: LiteGraph.WIDGET_OUTLINE_COLOR,
|
||||
thickness: 1,
|
||||
};
|
||||
Object.assign(this.widgetOptions, widgetOptions || {});
|
||||
}
|
||||
draw(ctx, node, width, posY, h) {
|
||||
if (this.widgetOptions.thickness) {
|
||||
ctx.strokeStyle = this.widgetOptions.color;
|
||||
const x = this.widgetOptions.marginLeft;
|
||||
const y = posY + this.widgetOptions.marginTop;
|
||||
const w = width - this.widgetOptions.marginLeft - this.widgetOptions.marginRight;
|
||||
ctx.stroke(new Path2D(`M ${x} ${y} h ${w}`));
|
||||
}
|
||||
}
|
||||
computeSize(width) {
|
||||
return [
|
||||
width,
|
||||
this.widgetOptions.marginTop + this.widgetOptions.marginBottom + this.widgetOptions.thickness,
|
||||
];
|
||||
}
|
||||
}
|
||||
export class RgthreeLabelWidget extends RgthreeBaseWidget {
|
||||
constructor(name, widgetOptions) {
|
||||
super(name);
|
||||
this.type = "custom";
|
||||
this.options = { serialize: false };
|
||||
this.value = "";
|
||||
this.widgetOptions = {};
|
||||
this.posY = 0;
|
||||
Object.assign(this.widgetOptions, widgetOptions);
|
||||
}
|
||||
update(widgetOptions) {
|
||||
Object.assign(this.widgetOptions, widgetOptions);
|
||||
}
|
||||
draw(ctx, node, width, posY, height) {
|
||||
var _a;
|
||||
this.posY = posY;
|
||||
ctx.save();
|
||||
let text = (_a = this.widgetOptions.text) !== null && _a !== void 0 ? _a : this.name;
|
||||
if (typeof text === "function") {
|
||||
text = text();
|
||||
}
|
||||
ctx.textAlign = this.widgetOptions.align || "left";
|
||||
ctx.fillStyle = this.widgetOptions.color || LiteGraph.WIDGET_TEXT_COLOR;
|
||||
const oldFont = ctx.font;
|
||||
if (this.widgetOptions.italic) {
|
||||
ctx.font = "italic " + ctx.font;
|
||||
}
|
||||
if (this.widgetOptions.size) {
|
||||
ctx.font = ctx.font.replace(/\d+px/, `${this.widgetOptions.size}px`);
|
||||
}
|
||||
const midY = posY + height / 2;
|
||||
ctx.textBaseline = "middle";
|
||||
if (this.widgetOptions.align === "center") {
|
||||
ctx.fillText(text, node.size[0] / 2, midY);
|
||||
}
|
||||
else {
|
||||
ctx.fillText(text, 15, midY);
|
||||
}
|
||||
ctx.font = oldFont;
|
||||
if (this.widgetOptions.actionLabel === "__PLUS_ICON__") {
|
||||
const plus = new Path2D(`M${node.size[0] - 15 - 2} ${posY + 7} v4 h-4 v4 h-4 v-4 h-4 v-4 h4 v-4 h4 v4 h4 z`);
|
||||
ctx.lineJoin = "round";
|
||||
ctx.lineCap = "round";
|
||||
ctx.fillStyle = "#3a3";
|
||||
ctx.strokeStyle = "#383";
|
||||
ctx.fill(plus);
|
||||
ctx.stroke(plus);
|
||||
}
|
||||
ctx.restore();
|
||||
}
|
||||
mouse(event, nodePos, node) {
|
||||
if (event.type !== "pointerdown" ||
|
||||
isLowQuality() ||
|
||||
!this.widgetOptions.actionLabel ||
|
||||
!this.widgetOptions.actionCallback) {
|
||||
return false;
|
||||
}
|
||||
const pos = [nodePos[0], nodePos[1] - this.posY];
|
||||
const rightX = node.size[0] - 15;
|
||||
if (pos[0] > rightX || pos[0] < rightX - 16) {
|
||||
return false;
|
||||
}
|
||||
this.widgetOptions.actionCallback(event);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
export class RgthreeInvisibleWidget extends RgthreeBaseWidget {
|
||||
constructor(name, type, value, serializeValueFn) {
|
||||
super(name);
|
||||
this.type = "custom";
|
||||
this.value = value;
|
||||
this.serializeValueFn = serializeValueFn;
|
||||
}
|
||||
draw() {
|
||||
return;
|
||||
}
|
||||
computeSize(width) {
|
||||
return [0, 0];
|
||||
}
|
||||
serializeValue(node, index) {
|
||||
return this.serializeValueFn != null
|
||||
? this.serializeValueFn(node, index)
|
||||
: super.serializeValue(node, index);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
{
|
||||
"sources": [
|
||||
{
|
||||
"id": "rgthree/rgthree-comfy:py/image_comparer.py",
|
||||
"commit": "449c58fcdd612f7733e54c51f6758ead63fa180b",
|
||||
"file": "py/image_comparer.py",
|
||||
"url": "https://raw.githubusercontent.com/rgthree/rgthree-comfy/449c58fcdd612f7733e54c51f6758ead63fa180b/py/image_comparer.py",
|
||||
"sha256": "ca1813747bb7742779b363aa4633841312392d5a64cd5e8402784e3a61018187",
|
||||
"local_file": "rgthree__py__image_comparer.py"
|
||||
},
|
||||
{
|
||||
"id": "rgthree/rgthree-comfy:web/comfyui/image_comparer.js",
|
||||
"commit": "449c58fcdd612f7733e54c51f6758ead63fa180b",
|
||||
"file": "web/comfyui/image_comparer.js",
|
||||
"url": "https://raw.githubusercontent.com/rgthree/rgthree-comfy/449c58fcdd612f7733e54c51f6758ead63fa180b/web/comfyui/image_comparer.js",
|
||||
"sha256": "b6dd39b71a2722774ecad101e12823220c6905f9f2a3d1cefca077e1aaa08a49",
|
||||
"local_file": "rgthree__web__comfyui__image_comparer.js"
|
||||
},
|
||||
{
|
||||
"id": "rgthree/rgthree-comfy:web/comfyui/utils.js",
|
||||
"commit": "449c58fcdd612f7733e54c51f6758ead63fa180b",
|
||||
"file": "web/comfyui/utils.js",
|
||||
"url": "https://raw.githubusercontent.com/rgthree/rgthree-comfy/449c58fcdd612f7733e54c51f6758ead63fa180b/web/comfyui/utils.js",
|
||||
"sha256": "cf43bc82e83a864905c5a12423d8ceb157e465a2f656201b3c7bb7a2b023edfe",
|
||||
"local_file": "rgthree__web__comfyui__utils.js"
|
||||
},
|
||||
{
|
||||
"id": "rgthree/rgthree-comfy:py/__init__.py",
|
||||
"commit": "449c58fcdd612f7733e54c51f6758ead63fa180b",
|
||||
"file": "py/__init__.py",
|
||||
"url": "https://raw.githubusercontent.com/rgthree/rgthree-comfy/449c58fcdd612f7733e54c51f6758ead63fa180b/py/__init__.py",
|
||||
"sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
|
||||
"local_file": "rgthree__py____init__.py"
|
||||
},
|
||||
{
|
||||
"id": "rgthree/rgthree-comfy:__init__.py",
|
||||
"commit": "449c58fcdd612f7733e54c51f6758ead63fa180b",
|
||||
"file": "__init__.py",
|
||||
"url": "https://raw.githubusercontent.com/rgthree/rgthree-comfy/449c58fcdd612f7733e54c51f6758ead63fa180b/__init__.py",
|
||||
"sha256": "c51fdbaf7ed4c397be33413b7464dc3653714711d8a77d4c3e9a410a9d3de152",
|
||||
"local_file": "rgthree____init__.py"
|
||||
},
|
||||
{
|
||||
"id": "rgthree/rgthree-comfy:LICENSE",
|
||||
"commit": "449c58fcdd612f7733e54c51f6758ead63fa180b",
|
||||
"file": "LICENSE",
|
||||
"url": "https://raw.githubusercontent.com/rgthree/rgthree-comfy/449c58fcdd612f7733e54c51f6758ead63fa180b/LICENSE",
|
||||
"sha256": "b34faf7c3e2975fe08d0169958e2b39f076d4d4289cbe2560dd7dd5b1a613ed1",
|
||||
"local_file": "rgthree__LICENSE"
|
||||
},
|
||||
{
|
||||
"id": "Comfy-Org/ComfyUI:comfy_extras/nodes_post_processing.py",
|
||||
"commit": "6b747c0428c343e1417219641db93a4fb7cb69ae",
|
||||
"file": "comfy_extras/nodes_post_processing.py",
|
||||
"url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI/6b747c0428c343e1417219641db93a4fb7cb69ae/comfy_extras/nodes_post_processing.py",
|
||||
"sha256": "4ee06e8e5911c844ba49d97e54c90081c539d57e6dc53f1185900e3a79ce4c98",
|
||||
"local_file": "core__comfy_extras__nodes_post_processing.py"
|
||||
},
|
||||
{
|
||||
"id": "rgthree/rgthree-comfy:py/constants.py",
|
||||
"commit": "449c58fcdd612f7733e54c51f6758ead63fa180b",
|
||||
"file": "py/constants.py",
|
||||
"url": "https://raw.githubusercontent.com/rgthree/rgthree-comfy/449c58fcdd612f7733e54c51f6758ead63fa180b/py/constants.py",
|
||||
"sha256": "50dee946013b1d88d01fe9d63c2a7ab4d4c59be218cf80171f3542b43f0d8558",
|
||||
"local_file": "rgthree__py__constants.py"
|
||||
},
|
||||
{
|
||||
"id": "rgthree/rgthree-comfy:web/comfyui/constants.js",
|
||||
"commit": "449c58fcdd612f7733e54c51f6758ead63fa180b",
|
||||
"file": "web/comfyui/constants.js",
|
||||
"url": "https://raw.githubusercontent.com/rgthree/rgthree-comfy/449c58fcdd612f7733e54c51f6758ead63fa180b/web/comfyui/constants.js",
|
||||
"sha256": "01bddadcbeb27f4f3519987fb1e3f8fbed5b8c5e0bff1180e0f6cf3348c89ad9",
|
||||
"local_file": "rgthree__web__comfyui__constants.js"
|
||||
},
|
||||
{
|
||||
"id": "rgthree/rgthree-comfy:web/comfyui/base_node.js",
|
||||
"commit": "449c58fcdd612f7733e54c51f6758ead63fa180b",
|
||||
"file": "web/comfyui/base_node.js",
|
||||
"url": "https://raw.githubusercontent.com/rgthree/rgthree-comfy/449c58fcdd612f7733e54c51f6758ead63fa180b/web/comfyui/base_node.js",
|
||||
"sha256": "22798683ec2a1b402bfec93ef098b753dc373753a3622a9b200d7389dcda5702",
|
||||
"local_file": "rgthree__web__comfyui__base_node.js"
|
||||
},
|
||||
{
|
||||
"id": "rgthree/rgthree-comfy:web/comfyui/utils_widgets.js",
|
||||
"commit": "449c58fcdd612f7733e54c51f6758ead63fa180b",
|
||||
"file": "web/comfyui/utils_widgets.js",
|
||||
"url": "https://raw.githubusercontent.com/rgthree/rgthree-comfy/449c58fcdd612f7733e54c51f6758ead63fa180b/web/comfyui/utils_widgets.js",
|
||||
"sha256": "211ec018039e3bd5bcc78cafd4c64db33bcb1f02df60c93d45ff76ac96718b18",
|
||||
"local_file": "rgthree__web__comfyui__utils_widgets.js"
|
||||
},
|
||||
{
|
||||
"id": "Comfy-Org/ComfyUI_frontend:src/extensions/core/uploadImage.ts",
|
||||
"commit": "7d533a4cd4c4904ffdb0537f6b80ae9793dd62f1",
|
||||
"file": "src/extensions/core/uploadImage.ts",
|
||||
"url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/7d533a4cd4c4904ffdb0537f6b80ae9793dd62f1/src/extensions/core/uploadImage.ts",
|
||||
"sha256": "48d062c2ee95bd77c537c539e6c8f8bc03bd71dcec94c5b82487c014ea3e9c06",
|
||||
"local_file": "frontend__src__extensions__core__uploadImage.ts"
|
||||
},
|
||||
{
|
||||
"id": "frontend:src/renderer/extensions/vueNodes/widgets/composables/useImageUploadWidget.ts",
|
||||
"commit": "7d533a4cd4c4904ffdb0537f6b80ae9793dd62f1",
|
||||
"file": "src/renderer/extensions/vueNodes/widgets/composables/useImageUploadWidget.ts",
|
||||
"url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/7d533a4cd4c4904ffdb0537f6b80ae9793dd62f1/src/renderer/extensions/vueNodes/widgets/composables/useImageUploadWidget.ts",
|
||||
"sha256": "290857313fac311112203286cbf231551ec94cd19ee10596f20ed20520ca24a3",
|
||||
"local_file": "frontend__src__renderer__extensions__vueNodes__widgets__composables__useImageUploadWidget.ts"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
// Source-bound Qwen detail GET; no processing, writes or external requests.
|
||||
import fs from 'node:fs';
|
||||
import assert from 'node:assert/strict';
|
||||
const { chromium } = await import(process.env.PLAYWRIGHT_MODULE || 'playwright');
|
||||
const out = '.local-evidence/qwen-edit-document/browser';
|
||||
fs.mkdirSync(out, { recursive:true });
|
||||
const checks=[], requests=[], errors=[], blockedFonts=[];
|
||||
function check(value,text) { assert.ok(value,text); checks.push(text); console.log('PASS '+text); }
|
||||
const browser=await chromium.launch({headless:true,executablePath:process.env.BROWSER_EXECUTABLE});
|
||||
try {
|
||||
const page=await browser.newPage({viewport:{width:1440,height:1000}});
|
||||
await page.route('**/*', route => {
|
||||
const u=new URL(route.request().url());
|
||||
if(u.hostname==='fonts.googleapis.com') {blockedFonts.push(String(u));return route.fulfill({contentType:'text/css',body:''});}
|
||||
if(u.hostname!=='127.0.0.1'||u.pathname==='/api/view') {errors.push('Forbidden request '+u);console.error('FORBIDDEN '+u);return route.abort();}
|
||||
return route.continue();
|
||||
});
|
||||
page.on('request',r=>{if(r.url().includes('/api/'))requests.push({method:r.method(),url:r.url()});});
|
||||
page.on('pageerror',e=>{errors.push(e.message);console.error('PAGEERROR '+e.message);});
|
||||
const list=await(await fetch('http://127.0.0.1:8247/api/workflows')).json();
|
||||
const details=[];
|
||||
for(const name of ['Qwen_image2.1_图像编辑_提示词增强','Qwen_image2.1_文生图_提示词增强','ControlNet_aux_常用样例','Qwen3-ASR-语音转文字','Qwen3-ASR-Subtitle语音转字幕','Minimax-H3提示词增强','音频转MP3格式','音频人声分离','视频-音频分离','图像嵌入文字描述']) {
|
||||
const record=list.find(x=>x.name===name);assert.ok(record);
|
||||
const url=`http://127.0.0.1:8247/api/workflows/${record.id}`;requests.push({method:'GET',url});details.push(await(await fetch(url)).json());
|
||||
}
|
||||
check(details.map(d=>d.doc_json.fixed_version.fields.length).join(',')==='70,64,36,19,30,18,5,8,8,14','70新项与202旧项,十图独立');
|
||||
await page.goto('http://127.0.0.1:5173/connections',{waitUntil:'networkidle'});
|
||||
const dialog=page.getByRole('dialog',{name:'工作流说明'});
|
||||
async function begin(name) {
|
||||
const row=page.locator('.wf-row').filter({has:page.locator('.wf-name').filter({hasText:name})}).first();
|
||||
const button=row.getByRole('button',{name:'说明',exact:true});await button.focus();await page.keyboard.press('Enter');return button;
|
||||
}
|
||||
async function loaded() {
|
||||
await dialog.getByText('用途与来源',{exact:true}).waitFor();
|
||||
await dialog.evaluate(el=>Promise.all(el.getAnimations().map(a=>a.finished)));
|
||||
}
|
||||
const detail=details[0],fixed=detail.doc_json.fixed_version;
|
||||
for(const width of [1440,390]) {
|
||||
await page.setViewportSize({width,height:width===390?844:1000});
|
||||
const button=await begin(detail.name);await loaded();
|
||||
check((await dialog.innerText()).includes(fixed.notice),`${width}声明/参考/未知提示`);
|
||||
for(const t of ['说明未定稿','未验证实跑','未检查'])check((await dialog.innerText()).includes(t),`${width} ${t}`);
|
||||
check(!detail.is_enabled&&!detail.doc_completed_at&&!detail.exec_verified_at,`${width}停用与时间戳保持`);
|
||||
for(const field of fixed.fields) {
|
||||
const summary=dialog.getByText(`节点 ${field.node_id} · ${field.label}(${field.field})`,{exact:true});
|
||||
await summary.focus();await page.keyboard.press('Enter');const box=summary.locator('..');
|
||||
check(await box.evaluate(el=>el.open),`${width} ${field.node_id}.${field.field}键盘展开`);
|
||||
const text=await box.innerText();
|
||||
check(text.includes(field.effect)&&text.includes(field.limits)&&text.includes(field.schema_default)&&text.includes(field.execution_note),`${width} ${field.node_id}.${field.field}语义/默认/条件`);
|
||||
check(await box.locator(':scope > pre').textContent()===(typeof field.value==='string'?field.value:JSON.stringify(field.value,null,2)),`${width} ${field.node_id}.${field.field}原值类型`);
|
||||
await box.getByText('来源依据',{exact:true}).click();const evidence=await box.innerText();
|
||||
check(evidence.includes(field.pointer)&&field.evidence.every(i=>{const e=fixed.sources[i];return evidence.includes(e.commit)&&evidence.includes(e.sha256)&&evidence.includes(e.lines.join('~'));}),`${width} ${field.node_id}.${field.field}精确引用`);
|
||||
check(!evidence.includes('undefined'),`${width} ${field.node_id}.${field.field}无伪指针`);
|
||||
check(await dialog.locator('.drawer-body').evaluate(el=>el.scrollWidth<=el.clientWidth),`${width} ${field.node_id}.${field.field}无横向溢出`);
|
||||
if(['switch','use_default_template','seed','sampling_mode.seed','width','prompt','value'].includes(field.field))await page.screenshot({path:`${out}/${width}-${field.node_id}-${field.field}.png`});
|
||||
await summary.click();
|
||||
}
|
||||
const text=await dialog.innerText();
|
||||
for(const t of ['70保存位置不是70最终执行参数','18宿主保存值','widgetId(rootGraph.id,459,input.name)','双seed','use_default_template=false','三条源注释','resolution=0','65物理边','image_a','image_b','randomize','comparer_mode=Slide'])check(text.includes(t),`${width}图特定用途 ${t}`);
|
||||
check(await dialog.locator('summary').filter({hasText:/节点 [\d:]+ · .*(/}).count()===70,`${width}恰好70项`);
|
||||
for(const note of fixed.comments) {
|
||||
const summary=dialog.getByText(`节点 ${note.node_id}`,{exact:true});
|
||||
await summary.click();const box=summary.locator('..');
|
||||
const expected=detail.doc_json.source_notes.find(n=>n.node_id===note.node_id || String(n.node_id)===note.node_id);
|
||||
check(await box.locator('pre').textContent()===JSON.stringify(expected.content,null,2),`${width}注释${note.node_id}原文完整可读`);
|
||||
check(await dialog.locator('.drawer-body').evaluate(el=>el.scrollWidth<=el.clientWidth),`${width}注释${note.node_id}无溢出`);
|
||||
await summary.click();
|
||||
}
|
||||
const basis=dialog.getByText('版本、源图与连线依据',{exact:true});await basis.click();
|
||||
check((await basis.locator('..').innerText()).includes('UE7.8'),`${width}扩展与目标绑定未知`);
|
||||
await dialog.getByText('固定版本参数说明',{exact:true}).scrollIntoViewIfNeeded();await page.screenshot({path:`${out}/${width}-overview.png`});
|
||||
await page.keyboard.press('Escape');await dialog.waitFor({state:'hidden'});check(await button.evaluate(el=>el===document.activeElement),`${width}焦点归还`);
|
||||
for(const d of [...details.slice(1),details[0]]) {
|
||||
await begin(d.name);await loaded();check(await dialog.locator('summary').filter({hasText:/节点 [\d:]+ · .*(/}).count()===d.doc_json.fixed_version.fields.length,`${width}切换${d.name}不串条`);await page.keyboard.press('Escape');
|
||||
}
|
||||
}
|
||||
let release,entered,delivered;const hold=new Promise(r=>release=r),intercept=new Promise(r=>entered=r),done=new Promise(r=>delivered=r);
|
||||
await page.route(`**/api/workflows/${details[0].id}`,async route=>{entered();await hold;await route.fulfill({json:details[0]});delivered();});
|
||||
await begin(details[0].name);await intercept;await page.keyboard.press('Escape');await begin(details[1].name);await loaded();release();await done;
|
||||
check(await dialog.locator('summary').filter({hasText:/节点 [\d:]+ · .*(/}).count()===64,'迟到编辑图响应不覆盖旧Qwen64项');await page.keyboard.press('Escape');
|
||||
check(errors.length===0,'无脚本错误 '+JSON.stringify(errors));check(requests.every(r=>r.method==='GET'&&new URL(r.url).hostname==='127.0.0.1'&&!r.url.includes('/api/view?')),'全本地GET无写/生成/目标请求');
|
||||
fs.writeFileSync(`${out}/browser-results.json`,JSON.stringify({checks,requests,errors,blockedFonts,viewports:[1440,390]},null,2));
|
||||
} finally {await browser.close();}
|
||||
@@ -0,0 +1,82 @@
|
||||
"""Foreground local browser check; stop every owned service before returning."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
OUT = ROOT / ".local-evidence/qwen-edit-document/browser"
|
||||
|
||||
|
||||
def main():
|
||||
OUT.mkdir(parents=True, exist_ok=True)
|
||||
# Refuse to reuse another operator's service or port.
|
||||
import socket
|
||||
|
||||
for port in (8247, 5173):
|
||||
with socket.socket() as sock:
|
||||
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
||||
sock.bind(("127.0.0.1", port))
|
||||
processes = []
|
||||
logs = []
|
||||
try:
|
||||
commands = [
|
||||
([sys.executable, str(ROOT / "e2e/workflow-document-server.py")], ROOT),
|
||||
(
|
||||
["node", "node_modules/vite/bin/vite.js", "--host", "127.0.0.1"],
|
||||
ROOT / "calliope-web",
|
||||
),
|
||||
]
|
||||
for i, (command, cwd) in enumerate(commands):
|
||||
log = (OUT / f"service-{i}.log").open("w")
|
||||
logs.append(log)
|
||||
processes.append(
|
||||
subprocess.Popen(command, cwd=cwd, stdout=log, stderr=log, start_new_session=True)
|
||||
)
|
||||
for url in (
|
||||
"http://127.0.0.1:8247/api/workflows",
|
||||
"http://127.0.0.1:5173/connections",
|
||||
):
|
||||
deadline = time.monotonic() + 30
|
||||
while True:
|
||||
if any(p.poll() is not None for p in processes):
|
||||
raise RuntimeError("Local service exited; inspect service logs")
|
||||
try:
|
||||
with urllib.request.urlopen(url, timeout=1) as response:
|
||||
if response.status == 200:
|
||||
break
|
||||
except (urllib.error.URLError, TimeoutError):
|
||||
pass
|
||||
if time.monotonic() > deadline:
|
||||
raise TimeoutError(url)
|
||||
time.sleep(0.2)
|
||||
names = (
|
||||
["qwen-edit"]
|
||||
if "--only-qwen" in sys.argv
|
||||
else ["qwen-edit", "qwen", "controlnet", "asr", "media", "audio", "h3"]
|
||||
)
|
||||
for name in names:
|
||||
subprocess.run(["node", f"e2e/{name}-document.mjs"], cwd=ROOT, check=True)
|
||||
finally:
|
||||
for p in processes:
|
||||
if p.poll() is None:
|
||||
os.killpg(p.pid, signal.SIGTERM)
|
||||
try:
|
||||
p.wait(timeout=10)
|
||||
except subprocess.TimeoutExpired:
|
||||
os.killpg(p.pid, signal.SIGKILL)
|
||||
p.wait(timeout=5)
|
||||
for log in logs:
|
||||
log.close()
|
||||
print("All owned browser services stopped.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user