HEL-892: document ControlNet sample with immutable source and branch evidence

Co-authored-by: multica-agent <github@multica.ai>
This commit is contained in:
leefer
2026-10-30 10:08:01 +08:00
co-authored by multica-agent
parent a4f3616516
commit 885602848b
19 changed files with 6245 additions and 1 deletions
@@ -16,6 +16,10 @@ DEFINITION_SHA256 = "4da30b7b4314d6e3e37b3cefcaae710072ae0ee4e323e999789e63b3860
# Explicit path allowlist; a recomputed caller-supplied digest cannot extend trust.
DEFINITIONS = {
SOURCE_PATH: DEFINITION_SHA256,
(
"example_ComfyUI_workflows/0-基础处理:图像合"
"并-音频分离-视频截取合并-图像视频放大/ControlNet_aux_常用样例.json"
): "b1962f8f98c002594982d536fc24384a692460e0ce9253fbddd5bfade1c01078",
(
"example_ComfyUI_workflows/0-基础处理:图像合"
"并-音频分离-视频截取合并-图像视频放大/音频转MP3格式.json"
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,217 @@
"""36 saved values and complete source/citation bindings cannot grant execution."""
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/controlnet-document-evidence"
PATH = next(p for p in DEFINITIONS if p.endswith("ControlNet_aux_常用样例.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("/"):
obj = obj[int(part)] if isinstance(obj, list) else obj[part]
return obj
@pytest.mark.parametrize("index", range(36))
def test_saved_positions_and_evidence(index):
f = BLOCK["fields"][index]
v = pointer(SOURCE, f["pointer"])
assert canonical(v) == canonical(f["value"]) and type(v).__name__ == f["json_type"]
n = next(n for n in SOURCE["nodes"] if str(n["id"]) == f["node_id"])
assert n["type"] == f["class_type"]
assert all(
f[k]
for k in [
"effect",
"label",
"schema_default",
"unit",
"limits",
"execution_note",
"evidence",
]
)
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(36))
@pytest.mark.parametrize("kind", ["value", "type", "pointer"])
def test_each_source_and_definition_change_is_refused(index, kind):
s, r = copy.deepcopy(SOURCE), copy.deepcopy(REVIEW)
f = r["fixed_version_document"]["fields"][index]
if kind == "pointer":
f["pointer"] = "/nodes/999/widgets_values/999"
else:
path = f["pointer"]
parent, _, key = path.rpartition("/")
target = pointer(s, parent)
target[int(key)] = (
str(target[int(key)])
if kind == "type" and not isinstance(target[int(key)], str)
else {"tampered": True}
)
r["fixed_version_document"]["canonical_sha256"] = hashlib.sha256(canonical(s)).hexdigest()
assert doc(s, r)["fixed_version"]["matched"] is False
@pytest.mark.parametrize(
"kind",
[
"path",
"sha1",
"sha256",
"canonical",
"version",
"frontend",
"node",
"mode",
"edge",
"reroute",
"input",
"output",
"citation",
"definition",
"selector",
"preview",
"model",
"upload",
"companion",
],
)
def test_source_identity_graph_and_recomputed_hash_refused(kind):
s, r = copy.deepcopy(SOURCE), copy.deepcopy(REVIEW)
b = r["fixed_version_document"]
if kind == "path":
b["source_path"] = "other.json"
elif kind == "sha1":
r["source_sha"] = "0" * 40
elif kind == "sha256":
b["source_sha256"] = "0" * 64
elif kind == "canonical":
b["canonical_sha256"] = "0" * 64
elif kind == "version":
s["nodes"][0]["properties"]["ver"] = "1.1.6"
elif kind == "frontend":
s.setdefault("extra", {})["frontendVersion"] = "1.53.10"
elif kind == "node":
s["nodes"][0]["id"] = 999
elif kind == "mode":
s["nodes"][0]["mode"] = 2
elif kind == "edge":
s["links"][0][2] = 1
elif kind == "reroute":
s["links"][16][1] = 38
elif kind == "input":
s["nodes"][0]["inputs"][0]["link"] = 45
elif kind == "output":
s["nodes"][0]["outputs"][0]["type"] = "MASK"
elif kind == "citation":
b["sources"][0]["lines"] = [1, 2]
elif kind == "definition":
b["fields"][0]["effect"] = "篡改"
elif kind == "selector":
next(n for n in s["nodes"] if n["id"] == 18)["widgets_values"][0] = "none"
elif kind == "preview":
s["nodes"][1]["widgets_values"] = ["extra"]
elif kind == "model":
s["nodes"][0]["widgets_values"][0] = "different.pth"
elif kind == "upload":
next(n for n in s["nodes"] if n["id"] == 2)["widgets_values"][1] = "other"
else:
b["companion_difference"]["scalar_matches"] = 0
if kind != "canonical":
b["canonical_sha256"] = hashlib.sha256(canonical(s)).hexdigest()
r["caller_digest"] = hashlib.sha256(canonical(b)).hexdigest()
assert doc(s, r)["fixed_version"]["matched"] is False
def test_graph_specific_semantics_and_companion():
d = doc()
b = d["fixed_version"]
assert b["matched"] and len(b["fields"]) == 36
assert b["counts"] == dict(
saved_fields=36, final_scalars=34, linked_saved_fields=0, frontend_only=2, physical_edges=27
)
assert len(SOURCE["nodes"]) == 26 and len(SOURCE["links"]) == 27
saved = {
f"/nodes/{i}/widgets_values/{j}"
for i, n in enumerate(SOURCE["nodes"])
for j, _ in enumerate(n.get("widgets_values", []))
}
assert saved == {f["pointer"] for f in b["fields"]}
assert sum(f["role"] == "frontend" for f in b["fields"]) == 2
assert "前端未声明" in b["notice"] and "假设" in b["notice"]
ep = b["resolved_endpoints"]
assert len(ep) == 23 and sum(len(e["source_chain"]) > 1 for e in ep) == 9
api = json.loads((REPO / "docs/hel-892/supplied-api/01.api.json").read_bytes())
for e in ep:
assert api[e["node_id"]]["inputs"][e["field"]] == e["endpoint"]
for hop in e["source_chain"]:
assert pointer(SOURCE, hop["pointer"]) == hop["edge"]
assert len(b["companion_difference"]["title_differences"]) == 13
f = {(f["node_id"], f["field"]): f for f in b["fields"]}
assert {i: f[str(i), "preprocessor"]["value"] for i in [1, 12, 18, 19, 20, 21, 33, 34]} == {
1: "DepthAnythingPreprocessor",
12: "CannyEdgePreprocessor",
18: "AnyLineArtPreprocessor_aux",
19: "LineArtPreprocessor",
20: "AnimeLineArtPreprocessor",
21: "LineartStandardPreprocessor",
33: "DWPreprocessor",
34: "AnimalPosePreprocessor",
}
assert f["4", "ckpt_name"]["value"] == "depth_anything_vitl14.pth"
assert [f[str(i), "direction"]["value"] for i in [28, 29, 30]] == ["right", "right", "down"]
text = "".join(b["flow"])
assert all(
t in text
for t in ["2×2", "3/5/11/13/22/36/37", "temp", "ui.images", "两素材", "9经转接", "13处标题"]
)
assert d["status"] == dict(imported=True, doc_done=False, exec_verified=False)
assert d["dependencies"]["check_state"] == "unchecked"
def test_other_seven_documents_and_block_swaps():
assert len(DEFINITIONS) == 8
for path in DEFINITIONS:
if path == PATH:
continue
raw = (REPO / path).read_bytes()
review = review_for(path, hashlib.sha1(raw).hexdigest())
assert build_document(path, json.loads(raw), None, None, [], review)["fixed_version"][
"matched"
]
r = copy.deepcopy(REVIEW)
r["fixed_version_document"] = review["fixed_version_document"]
assert not doc(review=r)["fixed_version"]["matched"]
@@ -0,0 +1,647 @@
"ControlNet source-bound Chinese editorial data; never execute upstream code."
from __future__ import annotations
import hashlib
import json
from pathlib import Path
REPO = Path(__file__).resolve().parents[3]
OUT = Path(__file__).resolve().parent
PATH = (
"example_ComfyUI_workflows/0-基础处理:图像合并-音频分离-视频截取合并-图像视频放大/Control"
"Net_aux_常用样例.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)
refs, fields = [], []
def ref(directory, filename, start, end, claim):
root = OUT.parent / directory
item = next(
s
for s in json.loads((root / "sources.json").read_bytes())["sources"]
if s["local_file"] == filename
)
data = (root / filename).read_bytes()
assert hashlib.sha256(data).hexdigest() == item["sha256"]
assert 1 <= start <= end <= len(data.decode().splitlines())
refs.append(
{
**{k: item[k] for k in ("id", "commit", "file", "sha256", "url")},
"license": item.get("license", "沿用来源manifest许可"),
"local_file": "../" + directory + "/" + filename,
"lines": [start, end],
"claim": claim,
}
)
return len(refs) - 1
def own(filename, start, end, claim):
return ref(OUT.name, filename, start, end, claim)
dispatch = ref(
"controlnet-reference",
"__init__.py",
25,
130,
"导入失败影响动态注册;AIO选项排除、none分支、选中类schema默认分派与FUNCTION调用",
)
common = ref(
"controlnet-reference",
"utils.py",
60,
120,
(
"required image/optional顺序;resolution schema 512/64..16384/64;COM"
"BO首项默认与逐图像公共调用"
),
)
depth = ref(
"controlnet-reference",
"node_wrappers__depth_anything.py",
4,
25,
"Depth schema、vitl14默认与from_pretrained/设备/common_annotator_call调用",
)
depthreg = ref(
"controlnet-reference",
"node_wrappers__depth_anything.py",
48,
55,
"DepthAnythingPreprocessor注册到具体类",
)
depthimpl = own(
"src__custom_controlnet_aux__depth_anything__transformers.py",
13,
80,
"旧checkpoint名映射HF模型;先local_files_only尝试后pipeline回退;分辨率缩放与深度归一化",
)
depthalias = own(
"src__custom_controlnet_aux__depth_anything____init__.py",
1,
1,
"DepthAnythingDetector导出到transformers实现",
)
resize = own(
"src__custom_controlnet_aux__util.py",
155,
173,
"短边比例缩放/取整、pad64与remove_pad;不保证源resolution等于输出宽高",
)
cannyaux = own(
"node_wrappers__canny.py",
4,
29,
"AIO Canny整数阈值100/200(0..255)、resolution与CannyDetector调用",
)
cannyimpl = own(
"src__custom_controlnet_aux__canny____init__.py",
7,
17,
"AIO所选Canny实现经resize_image_with_pad调用cv2.Canny;不等于core kornia尺度",
)
anyline = own(
"node_wrappers__anyline.py",
22,
87,
"AnyLine schema/默认、MTEED与标准线稿合成、形态小对象过滤;AIO传自身resolution覆盖1280默认",
)
lineart = own(
"node_wrappers__lineart.py", 4, 29, "写实线稿schema coarse首项disable、模型调用与注册"
)
anime = own(
"node_wrappers__lineart_anime.py", 4, 26, "动漫线稿schema、from_pretrained/公共调用与注册"
)
standard = own(
"node_wrappers__lineart_standard.py",
4,
26,
"标准线稿guassian_sigma=6.0、intensity_threshold=8及调用/注册(原拼写保留)",
)
dw = own(
"node_wrappers__dwpose.py",
31,
107,
"DW schema默认手/身体/面部enable与两个模型选择、实际调用/字典result",
)
animal = own(
"node_wrappers__dwpose.py",
109,
166,
"AnimalPose schema默认与函数默认区别、模型路由、结果及注册",
)
canny = ref(
"serialization-evidence",
"corev0.21.1__comfy_extras__nodes_canny.py",
9,
44,
"core0.21.1 Canny schema浮点0.01..0.99、默认0.4/0.8与kornia输出处理",
)
stitch = ref(
"serialization-evidence",
"corev0.17.0__comfy_extras__nodes_images.py",
253,
424,
"ImageStitch schema与方向/批量补齐/匹配缩放/通道补齐/间隔/拼接条件",
)
load = ref(
"serialization-evidence",
"corev0.21.1__nodes.py",
1678,
1754,
"LoadImage动态输入文件列表、IMAGE/MASK出口、读取/校验;未执行",
)
ref(
"serialization-evidence",
"corev0.21.1__nodes.py",
1609,
1679,
"PreviewImage继承SaveImage:temp目录PNG和ui.images文件描述,非不落盘预览",
)
restore = ref(
"serialization-evidence",
"src__lib__litegraph__src__LGraphNode.ts",
862,
922,
"configure按控件位置恢复;serialize按下标保存;不按UI input数组猜字段",
)
order = ref(
"serialization-evidence",
"src__services__litegraphService.ts",
143,
230,
"schema有序输入与控件构造",
)
upload = ref(
"serialization-evidence",
"src__extensions__core__uploadImage.ts",
12,
53,
"image_upload附加upload输入",
)
uploadwidget = ref(
"serialization-evidence",
("src__renderer__extensions__vueNodes__widgets__composables__useImageUploadWidget.ts"),
90,
104,
"upload按钮初值image,options.serialize=false,非后端image字段",
)
execution = ref(
"serialization-evidence",
"src__utils__executionUtil.ts",
76,
150,
"执行剔除options.serialize=false、沿Reroute解析连线并覆盖同名输入",
)
ref(
"serialization-evidence",
"src__extensions__core__rerouteNode.ts",
26,
47,
"Reroute纯前端虚拟节点,无执行算法",
)
def field(
node, offset, name, label, typ, unit, limits, effect, default, evidence, role="scalar"
):
i = next(i for i, n in enumerate(source["nodes"]) if n["id"] == node)
n = source["nodes"][i]
v = n["widgets_values"][offset]
fields.append(
dict(
node_id=str(node),
class_type=n["type"],
field=name,
label=label,
type=typ,
value=v,
json_type=type(v).__name__,
pointer=f"/nodes/{i}/widgets_values/{offset}",
unit=unit,
limits=limits,
effect=effect,
schema_default=default,
evidence=[*evidence, restore, order, execution],
role=role,
execution_note="仅前端上传按钮保存状态;options.serialize=false,执行时剔除,不能当第二个素材参数。"
if role == "frontend"
else "固定参考恢复后的标量;源图原值保留,目标UE改写/环境/实跑未知。",
)
)
def resolution(node, evidence):
field(
node,
1,
"resolution",
"处理分辨率",
"INT",
"像素尺度(非实际输出尺寸)",
"schema 64..16384、步进64、默认512;公共调用仅对int且>=64直接采用,否则回退512。",
(
"传给选中处理器的detect_resolution。512/1024是源值,非推荐值;Depth/Canny固定实现按短边比例缩"
"放取整并补边/去边;其它处理器深层尺寸行为未核实,不承诺输出宽高或细节/识别精度。"
),
(
"AIO/Depth schema 512;选中AnyLine自身schema1280被AIO传入值覆盖。"
if node == 18
else "AIO/Depth schema 512;源值与schema默认分开。"
),
[common, resize, *evidence],
)
field(
4,
0,
"ckpt_name",
"深度模型选择",
"COMBO / STRING",
"不适用",
"固定列表vitl14/vitb14/vits14三个.pth名称;目标模型/缓存/列表可用性未知。",
(
"显式Depth4选择vitl14。固定实现映射LiheYoung/depth-anything-large-hf,先尝试本地缓存"
",异常回退pipeline可能联网取模型;本轮仅静态读取,不查目录/加载/下载。深度相对归一化不代表物理距离或识别精度。"
),
"schema首项depth_anything_vitl14.pth;函数同名默认。",
[depth, depthreg, depthalias, depthimpl, common],
)
resolution(4, [depth, depthimpl])
branches = {
1: (
"AIO深度分支",
[depth, depthimpl, depthalias],
(
"选DepthAnythingPreprocessor,AIO取schema ckpt首项vitl14并传512;与显式Depth"
"4静态参数可对应,但未证明目标扩展/模型/结果等价。"
),
),
12: (
"AIO边缘分支",
[cannyaux, cannyimpl],
(
"选CannyEdgePreprocessor,AIO补整数low=100/high=200,传1024,经cv2.Canny;与"
"core10的kornia浮点0.4/0.8不是同尺度,不换算为相同阈值。"
),
),
18: (
"AnyLine线稿分支",
[anyline],
(
"选AnyLineArtPreprocessor_aux,默认merge_with_lineart=lineart_standar"
"d、lower/upper=0/1、object_min_size=36/connectivity=1;MTEED与标准线稿合成"
",内部sigma=2/intensity=3,AIO1024覆盖其schema1280。模型和skimage依赖未知。"
),
),
19: (
"写实线稿分支",
[lineart],
(
"选LineArtPreprocessor,AIO补coarse=disable并传1024;调用LineartDetector."
"from_pretrained,不保证真实画面线条质量。"
),
),
20: (
"动漫线稿分支",
[anime],
"选AnimeLineArtPreprocessor,传1024至LineartAnimeDetector公共调用;权重及真实适用性未知。",
),
21: (
"标准线稿分支",
[standard],
(
"选LineartStandardPreprocessor,AIO补guassian_sigma=6.0、intensity_th"
"reshold=8并传1024;与AnyLine内部2/3设置不同;深层算法效果未扩查。"
),
),
33: (
"DW人物姿态分支",
[dw],
(
"选DWPreprocessor,AIO补hand/body/face=enable、bbox=yolox_l.onnx、pose"
"=dw-ll_ucoco_384_bs5.torchscript.pt、scale_stick=disable并传1024;sc"
"hema pose默认与函数默认不同,AIO用schema。结果字典含IMAGE/POSE_KEYPOINT与openpose_"
"json;AIO本身声明仅IMAGE,本图图像接Preview36;不保证识别精度或设备后端可用。"
),
),
34: (
"Animal动物姿态分支",
[animal],
(
"选AnimalPosePreprocessor,AIO补bbox=yolox_l.torchscript.pt、pose=rtm"
"pose-m_ap10k_256_bs5.torchscript.pt并传1024;schema默认与函数onnx默认分开,AI"
"O用schema。38单独供图,结果图像接Preview37;AIO本身声明仅IMAGE,关键点不构成本图文件产物。"
),
),
}
for node, (label, evidence, effect) in branches.items():
field(
node,
0,
"preprocessor",
label + "选择器",
"动态COMBO / STRING",
"不适用",
"注册成功的AUX_NODE_MAPPINGS键剔除不支持类后构成动态选项;源保存名称不证明目标已注册。",
effect
+ (
" AIO按选中类schema填默认、image/resolution显式传入再调FUNCTION;"
"none直接返回输入。本图均非none。"
),
"AIO schema none;本图源选择分别保留。",
[dispatch, common, *evidence],
)
resolution(node, [dispatch, *evidence])
for off, name, label, default in [
(0, "low_threshold", "核心Canny低阈值", "0.4"),
(1, "high_threshold", "核心Canny高阈值", "0.8"),
]:
field(
10,
off,
name,
label,
"FLOAT",
"无额外物理单位;kornia阈值尺度",
"schema 0.01..0.99、步进0.01;不与AIO整数0..255混用。",
(
"将输入转设备float32并movedim送kornia.filters.canny,取边缘输出复制三通道。改变阈值影响该调用条"
"件,具体画面/边缘细节未实测。"
),
default,
[canny],
)
for node in [28, 29, 30]:
for off, name, label, typ, unit, limits, effect, default in [
(
0,
"direction",
"拼接方向",
"COMBO / STRING",
"不适用",
"right/down/left/up",
"image2相对image1位置;28/29为right构成两行,30为down将第二行置下。",
"right",
),
(
1,
"match_image_size",
"匹配拼接尺寸",
"BOOLEAN",
"不适用",
"true/false",
(
"true时水平拼接把image2等比缩放至image1高度,垂直匹配宽度,lanczos且禁裁切;false对非拼接维居中补齐。"
"批量不足重复末张、通道不足补1;不保证真实产物尺寸。"
),
"true",
),
(
2,
"spacing_width",
"拼接间隔",
"INT",
"像素",
"0..1024、步进2",
"源2作为拼接方向的间隔宽度;缺image2直接原样返回image1,不创建比较图。",
"0",
),
(
3,
"spacing_color",
"间隔颜色",
"COMBO / STRING",
"不适用",
"white/black/red/green/blue",
"源white为间隔填充白色;非匹配尺寸时也影响补齐颜色规则,不改变输入素材身份。",
"white",
),
]:
field(node, off, name, label, typ, unit, limits, effect, default, [stitch])
for node in [2, 38]:
field(
node,
0,
"image",
"输入图像引用",
"动态COMBO / STRING",
"不适用",
"按input目录文件及图像类型过滤的动态列表;引用不证明文件存在、可读或主体合适。",
(
"2供深度/边缘/四线稿/DW;38独立供AnimalPose。未来获准环境核对2中需观察的轮廓/人物、38中动物主体是否清晰,不"
"能凭文件名确认内容。LoadImage返回IMAGE与MASK,本图MASK均未接。"
),
"动态文件列表,无固定通用文件默认。",
[load, upload],
)
field(
node,
1,
"upload",
"上传按钮保存状态",
"前端按钮 / STRING",
"不适用",
"源字符串image,非运行枚举或第二素材。",
"附加upload按钮初值image;保存状态与image引用分开,不能拼成素材路径或执行字段。",
"按钮初值image。",
[upload, uploadwidget],
role="frontend",
)
# Expand physical paths without executing any processing algorithm.
nodes = {n["id"]: n for n in source["nodes"]}
links = {e[0]: (i, e) for i, e in enumerate(source["links"])}
endpoints = []
for n in source["nodes"]:
if n["type"] == "Reroute":
continue
for inp in n.get("inputs", []):
lid = inp.get("link")
if lid is None:
continue
chain = []
while True:
i, e = links[lid]
chain.append(dict(pointer=f"/links/{i}", edge=e))
upstream = nodes[e[1]]
if upstream["type"] != "Reroute":
break
lid = upstream["inputs"][0]["link"]
endpoints.append(
dict(
node_id=str(n["id"]),
field=inp["name"],
endpoint=[str(e[1]), e[2]],
source_chain=chain,
)
)
assert len(endpoints) == 23 and sum(len(e["source_chain"]) > 1 for e in endpoints) == 9
api_raw = (OUT.parent / "supplied-api/01.api.json").read_bytes()
api = json.loads(api_raw)
from calliope.comfyui.serialization_reference import AUX_PROFILE
from calliope.comfyui.ui2api import convert_reference
candidate = convert_reference(source, AUX_PROFILE).prompt
assert candidate and len(candidate) == len(api) == 22
assert all(candidate[k]["class_type"] == api[k]["class_type"] for k in api)
binding = next(
c
for c in json.loads((OUT.parent / "supplied-api/manifest.json").read_bytes())["cases"]
if c["id"] == "01"
)
assert binding["source_sha256"] == hashlib.sha256(raw).hexdigest()
assert binding["export_sha256"] == hashlib.sha256(api_raw).hexdigest()
assert all(
candidate[k]["inputs"] == api[k]["inputs"]
and canonical(candidate[k]["inputs"]) == canonical(api[k]["inputs"])
for k in api
)
assert all(api[e["node_id"]]["inputs"][e["field"]] == e["endpoint"] for e in endpoints)
titles = [
dict(node_id=k, reference=candidate[k].get("_meta"), api=api[k].get("_meta"))
for k in api
if candidate[k].get("_meta") != api[k].get("_meta")
]
assert len(titles) == 13
flow = [
(
"用途:同一输入2对比深度、两种边缘、四种线稿与DW人物姿态,输入38单独观察AnimalPose;本轮不处理图像。26源节点/2"
"7物理边,4虚拟Reroute无保存控件;22实体参考候选含34标量+23端点(9经转接),不是57个源保存值。"
),
(
"两素材引用独立保留:2=comfyui-airport-editorial_00001_.png,38=177208682157"
"3.png;可达性、图像尺寸/内容与真实主体未知,两个MASK出口均未接。"
),
(
"深度:2槽0→Reroute32→4.image与1.image,4→Preview5,1→Preview3;4显式vitl14"
"/512,1选DepthAnything/512由分派填同名schema默认;静态参数对应不保证执行或效果相同。"
),
(
"边缘:2槽0→Reroute31→Canny10与AIO12,10→Preview11、12→Preview13;core0.4"
"/0.8与AIO内部100/200分属不同实现与尺度,不能换算/承诺对照效果。"
),
(
"线稿:2槽0→Reroute24→AIO18/19/20/21;18/19→ImageStitch28(right),20/21"
"→29(right),28/29→30(down)→Preview22;这是一张2×2线稿比较排版,非已生成四张等大图片。"
),
(
"姿态:2槽0→Reroute35→AIO33→Preview36;38槽0→AIO34→Preview37。人物/动物支路各自保"
"留输入、选择与结果路径;所选类的POSE_KEYPOINT并非本图AIO声明出口,不视为下载产物。"
),
(
"七预览3/5/11/13/22/36/37均无保存控件:分别对应AIO深度/显式深度/core边缘/AIO边缘/四线稿拼接/DW"
"/Animal。core0.21.1 Preview继承保存逻辑,将PNG落temp目录,返回ui.images含filenam"
"e/subfolder/type=temp;不表示永久导出或实际history成功。"
),
"case01配套01.api.json SHA256 "
+ hashlib.sha256(api_raw).hexdigest()
+ (
":原始API与当前固定候选22实体、57输入(34标量/23端点)逐项及JSON类型一致,9经转接链最终端点一致;完整JSON仍"
"13处标题元数据差异。历史配套不是目标安装/运行等价证明,不改294原配套参数、companion_unverified/env"
"ironment_unchecked/空映射/停用资格。"
),
]
for e in endpoints:
flow.append(
"逐跳依据:"
+ e["node_id"]
+ "."
+ e["field"]
+ " ← "
+ json.dumps(e["endpoint"], ensure_ascii=False)
+ ";"
+ " ← ".join(
x["pointer"] + "=" + json.dumps(x["edge"], ensure_ascii=False)
for x in e["source_chain"]
)
)
fields.sort(key=lambda f: tuple(int(f["pointer"].split("/")[i]) for i in (2, 4)))
assert len(fields) == 36
return dict(
notice="固定版本参考说明:节点按源声明分别核对固定提交;前端未声明,1.37.11仅显式假设;aux发布包与提交绑定、UE与目标环境未知",
source_path=PATH,
source_sha1=hashlib.sha1(raw).hexdigest(),
source_sha256=hashlib.sha256(raw).hexdigest(),
canonical_sha256=hashlib.sha256(canonical(source)).hexdigest(),
versions=[
(
"AIO/Depth声明comfyui_controlnet_aux1.1.5,仅参考e8b689a513c3e6b63edc44"
"066560ca5919c0576e;pyproject变更不证明发布包/registry→commit或目标安装绑定。"
),
(
"LoadImage/Canny/Preview声明core0.21.1=26515acd23fa291a8f5ab53c5997"
"258598de0701;ImageStitch声明0.17.0=63d1bbdb407c69370d407ce5ced6ca3"
"f917528a8。"
),
(
"前端未声明,仅参考1.37.11=4bf6a1960028cc5cda57d48f9fb01a74dfaade43;UE7.8/"
"7.7记录不证明序列化影响已验证,动态选项/依赖/权重/缓存/设备/真实history未知。"
),
],
counts=dict(
saved_fields=36,
final_scalars=34,
linked_saved_fields=0,
frontend_only=2,
physical_edges=27,
),
fields=fields,
sources=refs,
flow=flow,
flow_evidence=list(range(len(refs))),
resolved_endpoints=endpoints,
companion_difference=dict(
historical_binding={
k: binding[k]
for k in (
"id",
"attachment_id",
"received_at",
"source_comment_id",
"exported_at",
"frontend_version",
"node_versions",
)
},
export_file="01.api.json",
export_sha256=hashlib.sha256(api_raw).hexdigest(),
scalar_matches=34,
endpoint_matches=23,
rerouted_endpoints=9,
title_differences=titles,
source_export_equivalence_verified=False,
),
steps=[
"未来获得实跑授权后先核对真实前端/插件版本、动态选项、权重及两张素材;本轮只读固定源码,不查目标目录、不加载/下载。",
"核对输入2在32/31/24/35四个转接分配到九个处理分支,输入38仅供Animal;保持两引用和未接MASK,不合并换图。",
"分开核对4与1的checkpoint/选择器和512、10浮点阈值与12整数默认和1024,再观察对应5/3/11/13预览;不将参数相近视为效果等同。",
(
"逐路核对18 AnyLine、19写实、20动漫、21标准线稿选择与1024;"
"检查18/19→28右拼、20/21→29右拼、2"
"8/29→30下拼→22的2×2布局及2像素白间隔,尺寸/画面内容仍待实际核对。"
),
"分别检查33人物/34动物支路及36/37预览;检查七Preview临时PNG和实际history后才讨论产物,不能将说明展示视为已运行。",
"保留API配套层与源图层独立、标题差异与逐跳链可回读;当前说明未定稿、依赖未检查、实跑未验证、全停用,不新增转换资格。",
],
)
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 it is too large Load Diff
@@ -0,0 +1,87 @@
import torch
import numpy as np
import comfy.model_management as model_management
import comfy.utils
# Requires comfyui_controlnet_aux funcsions and classes
from ..utils import common_annotator_call, INPUT, define_preprocessor_inputs
def get_intensity_mask(image_array, lower_bound, upper_bound):
mask = image_array[:, :, 0]
mask = np.where((mask >= lower_bound) & (mask <= upper_bound), mask, 0)
mask = np.expand_dims(mask, 2).repeat(3, axis=2)
return mask
def combine_layers(base_layer, top_layer):
mask = top_layer.astype(bool)
temp = 1 - (1 - top_layer) * (1 - base_layer)
result = base_layer * (~mask) + temp * mask
return result
class AnyLinePreprocessor:
@classmethod
def INPUT_TYPES(s):
return define_preprocessor_inputs(
merge_with_lineart=INPUT.COMBO(["lineart_standard", "lineart_realisitic", "lineart_anime", "manga_line"], default="lineart_standard"),
resolution=INPUT.RESOLUTION(default=1280, step=8),
lineart_lower_bound=INPUT.FLOAT(default=0),
lineart_upper_bound=INPUT.FLOAT(default=1),
object_min_size=INPUT.INT(default=36, min=1),
object_connectivity=INPUT.INT(default=1, min=1)
)
RETURN_TYPES = ("IMAGE",)
RETURN_NAMES = ("image",)
FUNCTION = "get_anyline"
CATEGORY = "ControlNet Preprocessors/Line Extractors"
def __init__(self):
self.device = model_management.get_torch_device()
def get_anyline(self, image, merge_with_lineart="lineart_standard", resolution=512, lineart_lower_bound=0, lineart_upper_bound=1, object_min_size=36, object_connectivity=1):
from custom_controlnet_aux.teed import TEDDetector
from skimage import morphology
pbar = comfy.utils.ProgressBar(3)
# Process the image with MTEED model
mteed_model = TEDDetector.from_pretrained("TheMistoAI/MistoLine", "MTEED.pth", subfolder="Anyline").to(self.device)
mteed_result = common_annotator_call(mteed_model, image, resolution=resolution, show_pbar=False)
mteed_result = mteed_result.numpy()
del mteed_model
pbar.update(1)
# Process the image with the lineart standard preprocessor
if merge_with_lineart == "lineart_standard":
from custom_controlnet_aux.lineart_standard import LineartStandardDetector
lineart_standard_detector = LineartStandardDetector()
lineart_result = common_annotator_call(lineart_standard_detector, image, guassian_sigma=2, intensity_threshold=3, resolution=resolution, show_pbar=False).numpy()
del lineart_standard_detector
else:
from custom_controlnet_aux.lineart import LineartDetector
from custom_controlnet_aux.lineart_anime import LineartAnimeDetector
from custom_controlnet_aux.manga_line import LineartMangaDetector
lineart_detector = dict(lineart_realisitic=LineartDetector, lineart_anime=LineartAnimeDetector, manga_line=LineartMangaDetector)[merge_with_lineart]
lineart_detector = lineart_detector.from_pretrained().to(self.device)
lineart_result = common_annotator_call(lineart_detector, image, resolution=resolution, show_pbar=False).numpy()
del lineart_detector
pbar.update(1)
final_result = []
for i in range(len(image)):
_lineart_result = get_intensity_mask(lineart_result[i], lower_bound=lineart_lower_bound, upper_bound=lineart_upper_bound)
_cleaned = morphology.remove_small_objects(_lineart_result.astype(bool), min_size=object_min_size, connectivity=object_connectivity)
_lineart_result = _lineart_result * _cleaned
_mteed_result = mteed_result[i]
# Combine the results
final_result.append(torch.from_numpy(combine_layers(_mteed_result, _lineart_result)))
pbar.update(1)
return (torch.stack(final_result),)
NODE_CLASS_MAPPINGS = {
"AnyLineArtPreprocessor_aux": AnyLinePreprocessor
}
NODE_DISPLAY_NAME_MAPPINGS = {
"AnyLineArtPreprocessor_aux": "AnyLine Lineart"
}
@@ -0,0 +1,30 @@
from ..utils import common_annotator_call, INPUT, define_preprocessor_inputs
import comfy.model_management as model_management
class Canny_Edge_Preprocessor:
@classmethod
def INPUT_TYPES(s):
return define_preprocessor_inputs(
low_threshold=INPUT.INT(default=100, max=255),
high_threshold=INPUT.INT(default=200, max=255),
resolution=INPUT.RESOLUTION()
)
RETURN_TYPES = ("IMAGE",)
FUNCTION = "execute"
CATEGORY = "ControlNet Preprocessors/Line Extractors"
def execute(self, image, low_threshold=100, high_threshold=200, resolution=512, **kwargs):
from custom_controlnet_aux.canny import CannyDetector
return (common_annotator_call(CannyDetector(), image, low_threshold=low_threshold, high_threshold=high_threshold, resolution=resolution), )
NODE_CLASS_MAPPINGS = {
"CannyEdgePreprocessor": Canny_Edge_Preprocessor
}
NODE_DISPLAY_NAME_MAPPINGS = {
"CannyEdgePreprocessor": "Canny Edge"
}
@@ -0,0 +1,166 @@
from ..utils import common_annotator_call, define_preprocessor_inputs, INPUT
import comfy.model_management as model_management
import numpy as np
import warnings
from ..src.custom_controlnet_aux.dwpose import DwposeDetector, AnimalposeDetector
import os
import json
DWPOSE_MODEL_NAME = "yzd-v/DWPose"
#Trigger startup caching for onnxruntime
GPU_PROVIDERS = ["CUDAExecutionProvider", "DirectMLExecutionProvider", "OpenVINOExecutionProvider", "ROCMExecutionProvider", "CoreMLExecutionProvider"]
def check_ort_gpu():
try:
import onnxruntime as ort
for provider in GPU_PROVIDERS:
if provider in ort.get_available_providers():
return True
return False
except:
return False
if not os.environ.get("DWPOSE_ONNXRT_CHECKED"):
if check_ort_gpu():
print("DWPose: Onnxruntime with acceleration providers detected")
else:
warnings.warn("DWPose: Onnxruntime not found or doesn't come with acceleration providers, switch to OpenCV with CPU device. DWPose might run very slowly")
os.environ['AUX_ORT_PROVIDERS'] = ''
os.environ["DWPOSE_ONNXRT_CHECKED"] = '1'
class DWPose_Preprocessor:
@classmethod
def INPUT_TYPES(s):
return define_preprocessor_inputs(
detect_hand=INPUT.COMBO(["enable", "disable"]),
detect_body=INPUT.COMBO(["enable", "disable"]),
detect_face=INPUT.COMBO(["enable", "disable"]),
resolution=INPUT.RESOLUTION(),
bbox_detector=INPUT.COMBO(
["None"] + ["yolox_l.torchscript.pt", "yolox_l.onnx", "yolo_nas_l_fp16.onnx", "yolo_nas_m_fp16.onnx", "yolo_nas_s_fp16.onnx"],
default="yolox_l.onnx"
),
pose_estimator=INPUT.COMBO(
["dw-ll_ucoco_384_bs5.torchscript.pt", "dw-ll_ucoco_384.onnx", "dw-ll_ucoco.onnx"],
default="dw-ll_ucoco_384_bs5.torchscript.pt"
),
scale_stick_for_xinsr_cn=INPUT.COMBO(["disable", "enable"])
)
RETURN_TYPES = ("IMAGE", "POSE_KEYPOINT")
FUNCTION = "estimate_pose"
CATEGORY = "ControlNet Preprocessors/Faces and Poses Estimators"
def estimate_pose(self, image, detect_hand="enable", detect_body="enable", detect_face="enable", resolution=512, bbox_detector="yolox_l.onnx", pose_estimator="dw-ll_ucoco_384.onnx", scale_stick_for_xinsr_cn="disable", **kwargs):
if bbox_detector == "None":
yolo_repo = DWPOSE_MODEL_NAME
elif bbox_detector == "yolox_l.onnx":
yolo_repo = DWPOSE_MODEL_NAME
elif "yolox" in bbox_detector:
yolo_repo = "hr16/yolox-onnx"
elif "yolo_nas" in bbox_detector:
yolo_repo = "hr16/yolo-nas-fp16"
else:
raise NotImplementedError(f"Download mechanism for {bbox_detector}")
if pose_estimator == "dw-ll_ucoco_384.onnx":
pose_repo = DWPOSE_MODEL_NAME
elif pose_estimator.endswith(".onnx"):
pose_repo = "hr16/UnJIT-DWPose"
elif pose_estimator.endswith(".torchscript.pt"):
pose_repo = "hr16/DWPose-TorchScript-BatchSize5"
else:
raise NotImplementedError(f"Download mechanism for {pose_estimator}")
model = DwposeDetector.from_pretrained(
pose_repo,
yolo_repo,
det_filename=(None if bbox_detector == "None" else bbox_detector), pose_filename=pose_estimator,
torchscript_device=model_management.get_torch_device()
)
detect_hand = detect_hand == "enable"
detect_body = detect_body == "enable"
detect_face = detect_face == "enable"
scale_stick_for_xinsr_cn = scale_stick_for_xinsr_cn == "enable"
self.openpose_dicts = []
def func(image, **kwargs):
pose_img, openpose_dict = model(image, **kwargs)
self.openpose_dicts.append(openpose_dict)
return pose_img
out = common_annotator_call(func, image, include_hand=detect_hand, include_face=detect_face, include_body=detect_body, image_and_json=True, resolution=resolution, xinsr_stick_scaling=scale_stick_for_xinsr_cn)
del model
return {
'ui': { "openpose_json": [json.dumps(self.openpose_dicts, indent=4)] },
"result": (out, self.openpose_dicts)
}
class AnimalPose_Preprocessor:
@classmethod
def INPUT_TYPES(s):
return define_preprocessor_inputs(
bbox_detector = INPUT.COMBO(
["None"] + ["yolox_l.torchscript.pt", "yolox_l.onnx", "yolo_nas_l_fp16.onnx", "yolo_nas_m_fp16.onnx", "yolo_nas_s_fp16.onnx"],
default="yolox_l.torchscript.pt"
),
pose_estimator = INPUT.COMBO(
["rtmpose-m_ap10k_256_bs5.torchscript.pt", "rtmpose-m_ap10k_256.onnx"],
default="rtmpose-m_ap10k_256_bs5.torchscript.pt"
),
resolution = INPUT.RESOLUTION()
)
RETURN_TYPES = ("IMAGE", "POSE_KEYPOINT")
FUNCTION = "estimate_pose"
CATEGORY = "ControlNet Preprocessors/Faces and Poses Estimators"
def estimate_pose(self, image, resolution=512, bbox_detector="yolox_l.onnx", pose_estimator="rtmpose-m_ap10k_256.onnx", **kwargs):
if bbox_detector == "None":
yolo_repo = DWPOSE_MODEL_NAME
elif bbox_detector == "yolox_l.onnx":
yolo_repo = DWPOSE_MODEL_NAME
elif "yolox" in bbox_detector:
yolo_repo = "hr16/yolox-onnx"
elif "yolo_nas" in bbox_detector:
yolo_repo = "hr16/yolo-nas-fp16"
else:
raise NotImplementedError(f"Download mechanism for {bbox_detector}")
if pose_estimator == "dw-ll_ucoco_384.onnx":
pose_repo = DWPOSE_MODEL_NAME
elif pose_estimator.endswith(".onnx"):
pose_repo = "hr16/UnJIT-DWPose"
elif pose_estimator.endswith(".torchscript.pt"):
pose_repo = "hr16/DWPose-TorchScript-BatchSize5"
else:
raise NotImplementedError(f"Download mechanism for {pose_estimator}")
model = AnimalposeDetector.from_pretrained(
pose_repo,
yolo_repo,
det_filename=(None if bbox_detector == "None" else bbox_detector), pose_filename=pose_estimator,
torchscript_device=model_management.get_torch_device()
)
self.openpose_dicts = []
def func(image, **kwargs):
pose_img, openpose_dict = model(image, **kwargs)
self.openpose_dicts.append(openpose_dict)
return pose_img
out = common_annotator_call(func, image, image_and_json=True, resolution=resolution)
del model
return {
'ui': { "openpose_json": [json.dumps(self.openpose_dicts, indent=4)] },
"result": (out, self.openpose_dicts)
}
NODE_CLASS_MAPPINGS = {
"DWPreprocessor": DWPose_Preprocessor,
"AnimalPosePreprocessor": AnimalPose_Preprocessor
}
NODE_DISPLAY_NAME_MAPPINGS = {
"DWPreprocessor": "DWPose Estimator",
"AnimalPosePreprocessor": "AnimalPose Estimator (AP10K)"
}
@@ -0,0 +1,30 @@
from ..utils import common_annotator_call, define_preprocessor_inputs, INPUT
import comfy.model_management as model_management
class LineArt_Preprocessor:
@classmethod
def INPUT_TYPES(s):
return define_preprocessor_inputs(
coarse=INPUT.COMBO((["disable", "enable"])),
resolution=INPUT.RESOLUTION()
)
RETURN_TYPES = ("IMAGE",)
FUNCTION = "execute"
CATEGORY = "ControlNet Preprocessors/Line Extractors"
def execute(self, image, resolution=512, **kwargs):
from custom_controlnet_aux.lineart import LineartDetector
model = LineartDetector.from_pretrained().to(model_management.get_torch_device())
out = common_annotator_call(model, image, resolution=resolution, coarse = kwargs["coarse"] == "enable")
del model
return (out, )
NODE_CLASS_MAPPINGS = {
"LineArtPreprocessor": LineArt_Preprocessor
}
NODE_DISPLAY_NAME_MAPPINGS = {
"LineArtPreprocessor": "Realistic Lineart"
}
@@ -0,0 +1,27 @@
from ..utils import common_annotator_call, define_preprocessor_inputs, INPUT
import comfy.model_management as model_management
class AnimeLineArt_Preprocessor:
@classmethod
def INPUT_TYPES(s):
return define_preprocessor_inputs(resolution=INPUT.RESOLUTION())
RETURN_TYPES = ("IMAGE",)
FUNCTION = "execute"
CATEGORY = "ControlNet Preprocessors/Line Extractors"
def execute(self, image, resolution=512, **kwargs):
from custom_controlnet_aux.lineart_anime import LineartAnimeDetector
model = LineartAnimeDetector.from_pretrained().to(model_management.get_torch_device())
out = common_annotator_call(model, image, resolution=resolution)
del model
return (out, )
NODE_CLASS_MAPPINGS = {
"AnimeLineArtPreprocessor": AnimeLineArt_Preprocessor
}
NODE_DISPLAY_NAME_MAPPINGS = {
"AnimeLineArtPreprocessor": "Anime Lineart"
}
@@ -0,0 +1,27 @@
from ..utils import common_annotator_call, define_preprocessor_inputs, INPUT
import comfy.model_management as model_management
class Lineart_Standard_Preprocessor:
@classmethod
def INPUT_TYPES(s):
return define_preprocessor_inputs(
guassian_sigma=INPUT.FLOAT(default=6.0, max=100.0),
intensity_threshold=INPUT.INT(default=8, max=16),
resolution=INPUT.RESOLUTION()
)
RETURN_TYPES = ("IMAGE",)
FUNCTION = "execute"
CATEGORY = "ControlNet Preprocessors/Line Extractors"
def execute(self, image, guassian_sigma=6, intensity_threshold=8, resolution=512, **kwargs):
from custom_controlnet_aux.lineart_standard import LineartStandardDetector
return (common_annotator_call(LineartStandardDetector(), image, guassian_sigma=guassian_sigma, intensity_threshold=intensity_threshold, resolution=resolution), )
NODE_CLASS_MAPPINGS = {
"LineartStandardPreprocessor": Lineart_Standard_Preprocessor
}
NODE_DISPLAY_NAME_MAPPINGS = {
"LineartStandardPreprocessor": "Standard Lineart"
}
@@ -0,0 +1,297 @@
"""Actual a4f3616 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 = "a4f36165162c4c793aa93934bb5bd2607df54cc0"
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 main():
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("ControlNet_aux_常用样例.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": 7, "skipped": 148, "user_excluded": 1}
if name == "old-user-after"
else protected["counts"]
== {"conflict": 7, "updated": 1, "skipped": 147, "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": 7}
)
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_seven_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=36,
old_saved_definitions=102,
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(next((REPO / "calliope-backend/dist").glob("*.whl"))) as wheel,
tarfile.open(next((REPO / "calliope-backend/dist").glob("*.tar.gz"))) 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"
"7 protected, fresh155, 36+102 definitions, "
"1217/3660/294, boundaries and packages"
)
)
if __name__ == "__main__":
main()
@@ -0,0 +1,94 @@
{
"sources": [
{
"id": "controlnet_aux:node_wrappers/anyline.py",
"commit": "e8b689a513c3e6b63edc44066560ca5919c0576e",
"file": "node_wrappers/anyline.py",
"url": "https://raw.githubusercontent.com/Fannovel16/comfyui_controlnet_aux/e8b689a513c3e6b63edc44066560ca5919c0576e/node_wrappers/anyline.py",
"sha256": "552f22763ef0d3494d2a2e76f1d17e5798c7ebd0363feb80eb62918609e1a660",
"local_file": "node_wrappers__anyline.py",
"license": "Apache-2.0; ../controlnet-reference/LICENSE.txt"
},
{
"id": "controlnet_aux:node_wrappers/canny.py",
"commit": "e8b689a513c3e6b63edc44066560ca5919c0576e",
"file": "node_wrappers/canny.py",
"url": "https://raw.githubusercontent.com/Fannovel16/comfyui_controlnet_aux/e8b689a513c3e6b63edc44066560ca5919c0576e/node_wrappers/canny.py",
"sha256": "978dc783428aece63d04bfefb167790ffd6a7020ca4cc613da3b5287614d1fcc",
"local_file": "node_wrappers__canny.py",
"license": "Apache-2.0; ../controlnet-reference/LICENSE.txt"
},
{
"id": "controlnet_aux:node_wrappers/dwpose.py",
"commit": "e8b689a513c3e6b63edc44066560ca5919c0576e",
"file": "node_wrappers/dwpose.py",
"url": "https://raw.githubusercontent.com/Fannovel16/comfyui_controlnet_aux/e8b689a513c3e6b63edc44066560ca5919c0576e/node_wrappers/dwpose.py",
"sha256": "3b08fb623ea3898cedf864e96cfd7993265101100a3dd9666a6c66b03c15e481",
"local_file": "node_wrappers__dwpose.py",
"license": "Apache-2.0; ../controlnet-reference/LICENSE.txt"
},
{
"id": "controlnet_aux:node_wrappers/lineart.py",
"commit": "e8b689a513c3e6b63edc44066560ca5919c0576e",
"file": "node_wrappers/lineart.py",
"url": "https://raw.githubusercontent.com/Fannovel16/comfyui_controlnet_aux/e8b689a513c3e6b63edc44066560ca5919c0576e/node_wrappers/lineart.py",
"sha256": "24efe04f9ee3a9b932adddf52f60a659b6d3c95991fec5f9182b7fde955e7ffa",
"local_file": "node_wrappers__lineart.py",
"license": "Apache-2.0; ../controlnet-reference/LICENSE.txt"
},
{
"id": "controlnet_aux:node_wrappers/lineart_anime.py",
"commit": "e8b689a513c3e6b63edc44066560ca5919c0576e",
"file": "node_wrappers/lineart_anime.py",
"url": "https://raw.githubusercontent.com/Fannovel16/comfyui_controlnet_aux/e8b689a513c3e6b63edc44066560ca5919c0576e/node_wrappers/lineart_anime.py",
"sha256": "f85b6515705bfeb5a49215a1e345e7b522af90d87a9bd20e1313330fd7ceae7f",
"local_file": "node_wrappers__lineart_anime.py",
"license": "Apache-2.0; ../controlnet-reference/LICENSE.txt"
},
{
"id": "controlnet_aux:node_wrappers/lineart_standard.py",
"commit": "e8b689a513c3e6b63edc44066560ca5919c0576e",
"file": "node_wrappers/lineart_standard.py",
"url": "https://raw.githubusercontent.com/Fannovel16/comfyui_controlnet_aux/e8b689a513c3e6b63edc44066560ca5919c0576e/node_wrappers/lineart_standard.py",
"sha256": "cf8773ecccb4cf18c1caf4d9da755972161e52d96a2a79005a8bf5f0796a7020",
"local_file": "node_wrappers__lineart_standard.py",
"license": "Apache-2.0; ../controlnet-reference/LICENSE.txt"
},
{
"id": "controlnet_aux:src/custom_controlnet_aux/depth_anything/__init__.py",
"commit": "e8b689a513c3e6b63edc44066560ca5919c0576e",
"file": "src/custom_controlnet_aux/depth_anything/__init__.py",
"url": "https://raw.githubusercontent.com/Fannovel16/comfyui_controlnet_aux/e8b689a513c3e6b63edc44066560ca5919c0576e/src/custom_controlnet_aux/depth_anything/__init__.py",
"sha256": "7bfb7a8efe99bfb5c767fbec3aed311b2ecf87ff8b815fd2080526267a1f025c",
"local_file": "src__custom_controlnet_aux__depth_anything____init__.py",
"license": "Apache-2.0; ../controlnet-reference/LICENSE.txt"
},
{
"id": "controlnet_aux:src/custom_controlnet_aux/util.py",
"commit": "e8b689a513c3e6b63edc44066560ca5919c0576e",
"file": "src/custom_controlnet_aux/util.py",
"url": "https://raw.githubusercontent.com/Fannovel16/comfyui_controlnet_aux/e8b689a513c3e6b63edc44066560ca5919c0576e/src/custom_controlnet_aux/util.py",
"sha256": "956ff6eb649148c98e68591824e9d029be527ea8f52eb1841b1b1c9f18f37b34",
"local_file": "src__custom_controlnet_aux__util.py",
"license": "Apache-2.0; ../controlnet-reference/LICENSE.txt"
},
{
"id": "controlnet_aux:src/custom_controlnet_aux/depth_anything/transformers.py",
"commit": "e8b689a513c3e6b63edc44066560ca5919c0576e",
"file": "src/custom_controlnet_aux/depth_anything/transformers.py",
"url": "https://raw.githubusercontent.com/Fannovel16/comfyui_controlnet_aux/e8b689a513c3e6b63edc44066560ca5919c0576e/src/custom_controlnet_aux/depth_anything/transformers.py",
"sha256": "7f9f571ab6a410fb43c14dc70a292d8987f8e1a2ac389b19ecc1b4e852966c22",
"local_file": "src__custom_controlnet_aux__depth_anything__transformers.py",
"license": "Apache-2.0; ../controlnet-reference/LICENSE.txt"
},
{
"id": "controlnet_aux:src/custom_controlnet_aux/canny/__init__.py",
"commit": "e8b689a513c3e6b63edc44066560ca5919c0576e",
"file": "src/custom_controlnet_aux/canny/__init__.py",
"url": "https://raw.githubusercontent.com/Fannovel16/comfyui_controlnet_aux/e8b689a513c3e6b63edc44066560ca5919c0576e/src/custom_controlnet_aux/canny/__init__.py",
"sha256": "247db43e90d1bc32cfeaeabc6686595015186838ea709f1fd094c7e9528ccae2",
"local_file": "src__custom_controlnet_aux__canny____init__.py",
"license": "Apache-2.0; ../controlnet-reference/LICENSE.txt"
}
]
}
@@ -0,0 +1,17 @@
import warnings
import cv2
import numpy as np
from PIL import Image
from custom_controlnet_aux.util import resize_image_with_pad, common_input_validate, HWC3
class CannyDetector:
def __call__(self, input_image=None, low_threshold=100, high_threshold=200, detect_resolution=512, output_type=None, upscale_method="INTER_CUBIC", **kwargs):
input_image, output_type = common_input_validate(input_image, output_type, **kwargs)
detected_map, remove_pad = resize_image_with_pad(input_image, detect_resolution, upscale_method)
detected_map = cv2.Canny(detected_map, low_threshold, high_threshold)
detected_map = HWC3(remove_pad(detected_map))
if output_type == "pil":
detected_map = Image.fromarray(detected_map)
return detected_map
@@ -0,0 +1 @@
from .transformers import DepthAnythingDetector
@@ -0,0 +1,81 @@
"""
Modern DepthAnything implementation using HuggingFace transformers.
Replaces legacy torch.hub.load DINOv2 backbone with transformers pipeline.
"""
import numpy as np
import torch
from PIL import Image
from transformers import pipeline
from custom_controlnet_aux.util import HWC3, common_input_validate, resize_image_with_pad
class DepthAnythingDetector:
"""DepthAnything depth estimation using HuggingFace transformers."""
def __init__(self, model_name="LiheYoung/depth-anything-large-hf"):
"""Initialize DepthAnything with specified model."""
from transformers import AutoImageProcessor, AutoModelForDepthEstimation
try:
image_processor = AutoImageProcessor.from_pretrained(model_name, local_files_only=True)
model = AutoModelForDepthEstimation.from_pretrained(model_name, local_files_only=True)
self.pipe = pipeline(task="depth-estimation", model=model, image_processor=image_processor)
except Exception as e:
self.pipe = pipeline(task="depth-estimation", model=model_name)
self.device = "cpu"
@classmethod
def from_pretrained(cls, pretrained_model_or_path=None, filename="depth_anything_vitl14.pth"):
"""Create DepthAnything from pretrained model, mapping legacy names to HuggingFace models."""
# Map legacy checkpoint names to modern HuggingFace models
model_mapping = {
"depth_anything_vitl14.pth": "LiheYoung/depth-anything-large-hf",
"depth_anything_vitb14.pth": "LiheYoung/depth-anything-base-hf",
"depth_anything_vits14.pth": "LiheYoung/depth-anything-small-hf"
}
model_name = model_mapping.get(filename, "LiheYoung/depth-anything-large-hf")
return cls(model_name=model_name)
def to(self, device):
"""Move model to specified device."""
self.pipe.model = self.pipe.model.to(device)
self.device = device
return self
def __call__(self, input_image, detect_resolution=512, output_type=None, upscale_method="INTER_CUBIC", **kwargs):
"""Perform depth estimation on input image."""
input_image, output_type = common_input_validate(input_image, output_type, **kwargs)
input_image, remove_pad = resize_image_with_pad(input_image, detect_resolution, upscale_method)
if isinstance(input_image, np.ndarray):
pil_image = Image.fromarray(input_image)
else:
pil_image = input_image
with torch.no_grad():
result = self.pipe(pil_image)
depth = result["depth"]
if isinstance(depth, Image.Image):
depth_array = np.array(depth, dtype=np.float32)
else:
depth_array = np.array(depth)
# Normalize depth values to 0-255 range
depth_min = depth_array.min()
depth_max = depth_array.max()
if depth_max > depth_min:
depth_array = (depth_array - depth_min) / (depth_max - depth_min) * 255.0
else:
depth_array = np.zeros_like(depth_array)
depth_image = depth_array.astype(np.uint8)
detected_map = remove_pad(HWC3(depth_image))
if output_type == "pil":
detected_map = Image.fromarray(detected_map)
return detected_map
@@ -0,0 +1,350 @@
import os
import random
import tempfile
import warnings
from contextlib import suppress
from pathlib import Path
import cv2
import numpy as np
import torch
from huggingface_hub import constants, hf_hub_download
from torch.utils.model_zoo import load_url
from ast import literal_eval
HF_MODEL_NAME = "lllyasviel/Annotators"
DWPOSE_MODEL_NAME = "yzd-v/DWPose"
BDS_MODEL_NAME = "bdsqlsz/qinglong_controlnet-lllite"
DENSEPOSE_MODEL_NAME = "LayerNorm/DensePose-TorchScript-with-hint-image"
MESH_GRAPHORMER_MODEL_NAME = "hr16/ControlNet-HandRefiner-pruned"
SAM_MODEL_NAME = "dhkim2810/MobileSAM"
UNIMATCH_MODEL_NAME = "hr16/Unimatch"
DEPTH_ANYTHING_MODEL_NAME = "LiheYoung/Depth-Anything" #HF Space
DIFFUSION_EDGE_MODEL_NAME = "hr16/Diffusion-Edge"
METRIC3D_MODEL_NAME = "JUGGHM/Metric3D"
DEPTH_ANYTHING_V2_MODEL_NAME_DICT = {
"depth_anything_v2_vits.pth": "depth-anything/Depth-Anything-V2-Small",
"depth_anything_v2_vitb.pth": "depth-anything/Depth-Anything-V2-Base",
"depth_anything_v2_vitl.pth": "depth-anything/Depth-Anything-V2-Large",
"depth_anything_v2_vitg.pth": "depth-anything/Depth-Anything-V2-Giant",
"depth_anything_v2_metric_vkitti_vitl.pth": "depth-anything/Depth-Anything-V2-Metric-VKITTI-Large",
"depth_anything_v2_metric_hypersim_vitl.pth": "depth-anything/Depth-Anything-V2-Metric-Hypersim-Large"
}
temp_dir = tempfile.gettempdir()
annotator_ckpts_path = os.path.join(Path(__file__).parents[2], 'ckpts')
USE_SYMLINKS = False
try:
annotator_ckpts_path = os.environ['AUX_ANNOTATOR_CKPTS_PATH']
except:
warnings.warn("Custom pressesor model path not set successfully.")
pass
try:
USE_SYMLINKS = literal_eval(os.environ['AUX_USE_SYMLINKS'])
except:
warnings.warn("USE_SYMLINKS not set successfully. Using default value: False to download models.")
pass
try:
temp_dir = os.environ['AUX_TEMP_DIR']
if len(temp_dir) >= 60:
warnings.warn(f"custom temp dir is too long. Using default")
temp_dir = tempfile.gettempdir()
except:
warnings.warn(f"custom temp dir not set successfully")
pass
here = Path(__file__).parent.resolve()
def HWC3(x):
assert x.dtype == np.uint8
if x.ndim == 2:
x = x[:, :, None]
assert x.ndim == 3
H, W, C = x.shape
assert C == 1 or C == 3 or C == 4
if C == 3:
return x
if C == 1:
return np.concatenate([x, x, x], axis=2)
if C == 4:
color = x[:, :, 0:3].astype(np.float32)
alpha = x[:, :, 3:4].astype(np.float32) / 255.0
y = color * alpha + 255.0 * (1.0 - alpha)
y = y.clip(0, 255).astype(np.uint8)
return y
def make_noise_disk(H, W, C, F, rng=None):
if rng:
noise = rng.uniform(low=0, high=1, size=((H // F) + 2, (W // F) + 2, C))
else:
noise = np.random.uniform(low=0, high=1, size=((H // F) + 2, (W // F) + 2, C))
noise = cv2.resize(noise, (W + 2 * F, H + 2 * F), interpolation=cv2.INTER_CUBIC)
noise = noise[F: F + H, F: F + W]
noise -= np.min(noise)
noise /= np.max(noise)
if C == 1:
noise = noise[:, :, None]
return noise
def nms(x, t, s):
x = cv2.GaussianBlur(x.astype(np.float32), (0, 0), s)
f1 = np.array([[0, 0, 0], [1, 1, 1], [0, 0, 0]], dtype=np.uint8)
f2 = np.array([[0, 1, 0], [0, 1, 0], [0, 1, 0]], dtype=np.uint8)
f3 = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]], dtype=np.uint8)
f4 = np.array([[0, 0, 1], [0, 1, 0], [1, 0, 0]], dtype=np.uint8)
y = np.zeros_like(x)
for f in [f1, f2, f3, f4]:
np.putmask(y, cv2.dilate(x, kernel=f) == x, x)
z = np.zeros_like(y, dtype=np.uint8)
z[y > t] = 255
return z
def min_max_norm(x):
x -= np.min(x)
x /= np.maximum(np.max(x), 1e-5)
return x
def safe_step(x, step=2):
y = x.astype(np.float32) * float(step + 1)
y = y.astype(np.int32).astype(np.float32) / float(step)
return y
def img2mask(img, H, W, low=10, high=90):
assert img.ndim == 3 or img.ndim == 2
assert img.dtype == np.uint8
if img.ndim == 3:
y = img[:, :, random.randrange(0, img.shape[2])]
else:
y = img
y = cv2.resize(y, (W, H), interpolation=cv2.INTER_CUBIC)
if random.uniform(0, 1) < 0.5:
y = 255 - y
return y < np.percentile(y, random.randrange(low, high))
def safer_memory(x):
# Fix many MAC/AMD problems
return np.ascontiguousarray(x.copy()).copy()
UPSCALE_METHODS = ["INTER_NEAREST", "INTER_LINEAR", "INTER_AREA", "INTER_CUBIC", "INTER_LANCZOS4"]
def get_upscale_method(method_str):
assert method_str in UPSCALE_METHODS, f"Method {method_str} not found in {UPSCALE_METHODS}"
return getattr(cv2, method_str)
def pad64(x):
return int(np.ceil(float(x) / 64.0) * 64 - x)
#https://github.com/Mikubill/sd-webui-controlnet/blob/main/scripts/processor.py#L17
#Added upscale_method, mode params
def resize_image_with_pad(input_image, resolution, upscale_method = "", skip_hwc3=False, mode='edge'):
if skip_hwc3:
img = input_image
else:
img = HWC3(input_image)
H_raw, W_raw, _ = img.shape
if resolution == 0:
return img, lambda x: x
k = float(resolution) / float(min(H_raw, W_raw))
H_target = int(np.round(float(H_raw) * k))
W_target = int(np.round(float(W_raw) * k))
img = cv2.resize(img, (W_target, H_target), interpolation=get_upscale_method(upscale_method) if k > 1 else cv2.INTER_AREA)
H_pad, W_pad = pad64(H_target), pad64(W_target)
img_padded = np.pad(img, [[0, H_pad], [0, W_pad], [0, 0]], mode=mode)
def remove_pad(x):
return safer_memory(x[:H_target, :W_target, ...])
return safer_memory(img_padded), remove_pad
def common_input_validate(input_image, output_type, **kwargs):
if "img" in kwargs:
warnings.warn("img is deprecated, please use `input_image=...` instead.", DeprecationWarning)
input_image = kwargs.pop("img")
if "return_pil" in kwargs:
warnings.warn("return_pil is deprecated. Use output_type instead.", DeprecationWarning)
output_type = "pil" if kwargs["return_pil"] else "np"
if type(output_type) is bool:
warnings.warn("Passing `True` or `False` to `output_type` is deprecated and will raise an error in future versions")
if output_type:
output_type = "pil"
if input_image is None:
raise ValueError("input_image must be defined.")
if not isinstance(input_image, np.ndarray):
input_image = np.array(input_image, dtype=np.uint8)
output_type = output_type or "pil"
else:
output_type = output_type or "np"
return (input_image, output_type)
def torch_gc():
if torch.cuda.is_available():
torch.cuda.empty_cache()
torch.cuda.ipc_collect()
def ade_palette():
"""ADE20K palette that maps each class to RGB values."""
return [[120, 120, 120], [180, 120, 120], [6, 230, 230], [80, 50, 50],
[4, 200, 3], [120, 120, 80], [140, 140, 140], [204, 5, 255],
[230, 230, 230], [4, 250, 7], [224, 5, 255], [235, 255, 7],
[150, 5, 61], [120, 120, 70], [8, 255, 51], [255, 6, 82],
[143, 255, 140], [204, 255, 4], [255, 51, 7], [204, 70, 3],
[0, 102, 200], [61, 230, 250], [255, 6, 51], [11, 102, 255],
[255, 7, 71], [255, 9, 224], [9, 7, 230], [220, 220, 220],
[255, 9, 92], [112, 9, 255], [8, 255, 214], [7, 255, 224],
[255, 184, 6], [10, 255, 71], [255, 41, 10], [7, 255, 255],
[224, 255, 8], [102, 8, 255], [255, 61, 6], [255, 194, 7],
[255, 122, 8], [0, 255, 20], [255, 8, 41], [255, 5, 153],
[6, 51, 255], [235, 12, 255], [160, 150, 20], [0, 163, 255],
[140, 140, 140], [250, 10, 15], [20, 255, 0], [31, 255, 0],
[255, 31, 0], [255, 224, 0], [153, 255, 0], [0, 0, 255],
[255, 71, 0], [0, 235, 255], [0, 173, 255], [31, 0, 255],
[11, 200, 200], [255, 82, 0], [0, 255, 245], [0, 61, 255],
[0, 255, 112], [0, 255, 133], [255, 0, 0], [255, 163, 0],
[255, 102, 0], [194, 255, 0], [0, 143, 255], [51, 255, 0],
[0, 82, 255], [0, 255, 41], [0, 255, 173], [10, 0, 255],
[173, 255, 0], [0, 255, 153], [255, 92, 0], [255, 0, 255],
[255, 0, 245], [255, 0, 102], [255, 173, 0], [255, 0, 20],
[255, 184, 184], [0, 31, 255], [0, 255, 61], [0, 71, 255],
[255, 0, 204], [0, 255, 194], [0, 255, 82], [0, 10, 255],
[0, 112, 255], [51, 0, 255], [0, 194, 255], [0, 122, 255],
[0, 255, 163], [255, 153, 0], [0, 255, 10], [255, 112, 0],
[143, 255, 0], [82, 0, 255], [163, 255, 0], [255, 235, 0],
[8, 184, 170], [133, 0, 255], [0, 255, 92], [184, 0, 255],
[255, 0, 31], [0, 184, 255], [0, 214, 255], [255, 0, 112],
[92, 255, 0], [0, 224, 255], [112, 224, 255], [70, 184, 160],
[163, 0, 255], [153, 0, 255], [71, 255, 0], [255, 0, 163],
[255, 204, 0], [255, 0, 143], [0, 255, 235], [133, 255, 0],
[255, 0, 235], [245, 0, 255], [255, 0, 122], [255, 245, 0],
[10, 190, 212], [214, 255, 0], [0, 204, 255], [20, 0, 255],
[255, 255, 0], [0, 153, 255], [0, 41, 255], [0, 255, 204],
[41, 0, 255], [41, 255, 0], [173, 0, 255], [0, 245, 255],
[71, 0, 255], [122, 0, 255], [0, 255, 184], [0, 92, 255],
[184, 255, 0], [0, 133, 255], [255, 214, 0], [25, 194, 194],
[102, 255, 0], [92, 0, 255]]
#https://stackoverflow.com/a/44873382
#Assume that the minimum version of Python ppl use is 3.9
def sha256sum(file_path):
import hashlib
h = hashlib.sha256()
b = bytearray(128*1024)
mv = memoryview(b)
with open(file_path, 'rb', buffering=0) as f:
while n := f.readinto(mv):
h.update(mv[:n])
return h.hexdigest()
def check_hash_from_torch_hub(file_path, filename):
basename, _ = filename.split('.')
_, ref_hash = basename.split('-')
curr_hash = sha256sum(file_path)
return curr_hash[:len(ref_hash)] == ref_hash
def custom_torch_download(filename, ckpts_dir=annotator_ckpts_path):
"""Download PyTorch models using PyTorch 2.7's built-in download mechanism."""
model_url = "https://download.pytorch.org/models/" + filename
# Use PyTorch's built-in model downloading with custom cache directory
local_dir = os.path.join(ckpts_dir, "torch")
if not os.path.exists(local_dir):
os.makedirs(local_dir, exist_ok=True)
model_path = os.path.join(local_dir, filename)
if not os.path.exists(model_path):
print(f"Downloading {filename} from pytorch.org...")
try:
# Use PyTorch 2.7's load_url which handles caching, progress, and hash checking
state_dict = load_url(model_url, model_dir=local_dir, file_name=filename, progress=True, check_hash=True)
# The file is already saved by load_url, we just need the path
except Exception as e:
warnings.warn(f"Download failed with error: {e}")
raise
print(f"model_path is {model_path}")
return model_path
def custom_hf_download(pretrained_model_or_path, filename, cache_dir=temp_dir, ckpts_dir=annotator_ckpts_path, subfolder='', use_symlinks=USE_SYMLINKS, repo_type="model"):
local_dir = os.path.join(ckpts_dir, pretrained_model_or_path)
model_path = Path(local_dir).joinpath(*subfolder.split('/'), filename).__str__()
if len(str(model_path)) >= 255:
warnings.warn(f"Path {model_path} is too long, \n please change annotator_ckpts_path in config.yaml")
if not os.path.exists(model_path):
print(f"Failed to find {model_path}.\n Downloading from huggingface.co")
print(f"cacher folder is {cache_dir}, you can change it by custom_tmp_path in config.yaml")
if use_symlinks:
cache_dir_d = constants.HF_HUB_CACHE # use huggingface newer env variables `HF_HUB_CACHE`
if cache_dir_d is None:
import platform
if platform.system() == "Windows":
cache_dir_d = Path(os.getenv("USERPROFILE")).joinpath(".cache", "huggingface", "hub").__str__()
else:
cache_dir_d = os.path.join(os.getenv("HOME"), ".cache", "huggingface", "hub")
try:
# test_link
Path(cache_dir_d).mkdir(parents=True, exist_ok=True)
Path(ckpts_dir).mkdir(parents=True, exist_ok=True)
(Path(cache_dir_d) / f"linktest_{filename}.txt").touch()
# symlink instead of link avoid `invalid cross-device link` error.
os.symlink(os.path.join(cache_dir_d, f"linktest_{filename}.txt"), os.path.join(ckpts_dir, f"linktest_{filename}.txt"))
print("Using symlinks to download models. \n",\
"Make sure you have enough space on your cache folder. \n",\
"And do not purge the cache folder after downloading.\n",\
"Otherwise, you will have to re-download the models every time you run the script.\n",\
"You can use USE_SYMLINKS: False in config.yaml to avoid this behavior.")
except:
print("Maybe not able to create symlink. Disable using symlinks.")
use_symlinks = False
cache_dir_d = Path(cache_dir).joinpath("ckpts", pretrained_model_or_path).__str__()
finally: # always remove test link files
with suppress(FileNotFoundError):
os.remove(os.path.join(ckpts_dir, f"linktest_{filename}.txt"))
os.remove(os.path.join(cache_dir_d, f"linktest_{filename}.txt"))
else:
cache_dir_d = os.path.join(cache_dir, "ckpts", pretrained_model_or_path)
model_path = hf_hub_download(repo_id=pretrained_model_or_path,
cache_dir=cache_dir_d,
local_dir=local_dir,
subfolder=subfolder,
filename=filename,
local_dir_use_symlinks=use_symlinks,
resume_download=True,
etag_timeout=100,
repo_type=repo_type
)
if not use_symlinks:
try:
import shutil
shutil.rmtree(os.path.join(cache_dir, "ckpts"))
except Exception as e :
print(e)
print(f"model_path is {model_path}")
return model_path
+69
View File
@@ -0,0 +1,69 @@
// Source-bound ControlNet 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/controlnet-document/browser';
fs.mkdirSync(out, { recursive:true });
const checks=[], requests=[], errors=[];
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}});
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));
const list=await(await fetch('http://127.0.0.1:8247/api/workflows')).json();
const details=[];
for(const name of ['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(',')==='36,19,30,18,5,8,8,14','36新项与102旧项,八图独立');
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),`${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(['preprocessor','ckpt_name','low_threshold','direction','image','upload'].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 ['2×2','3/5/11/13/22/36/37','2=comfyui-airport-editorial_00001_.png','38=1772086821573.png','Reroute32','Reroute31','Reroute24','Reroute35','ui.images','9经转接','13处标题','22实体','34标量+23端点'])check(text.includes(t),`${width}图特定用途 ${t}`);
check(await dialog.locator('summary').filter({hasText:/节点 \d+ · .*(/}).count()===36,`${width}恰好36项`);
const basis=dialog.getByText('版本、源图与连线依据',{exact:true});await basis.click();
check((await basis.locator('..').innerText()).includes('发布包/registry→commit'),`${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()===19,'迟到ControlNet响应不覆盖ASR19项');await page.keyboard.press('Escape');
check(errors.length===0,'无脚本错误');check(requests.every(r=>r.method==='GET'&&new URL(r.url).hostname==='127.0.0.1'),'全本地GET无写/生成/目标请求');
fs.writeFileSync(`${out}/browser-results.json`,JSON.stringify({checks,requests,errors,viewports:[1440,390]},null,2));
} finally {await browser.close();}
+80
View File
@@ -0,0 +1,80 @@
"""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/controlnet-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)
subprocess.run(["node", "e2e/controlnet-document.mjs"], cwd=ROOT, check=True)
subprocess.run(["node", "e2e/asr-document.mjs"], cwd=ROOT, check=True)
subprocess.run(["node", "e2e/media-document.mjs"], cwd=ROOT, check=True)
subprocess.run(["node", "e2e/audio-document.mjs"], cwd=ROOT, check=True)
subprocess.run(["node", "e2e/h3-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()