Files
aigc-home/docs/hel-892/wantalk-document-evidence/verify_sources.py
T

336 lines
13 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Independent source/identity/protocol checks; no plugin imports or execution."""
import ast
import collections
import hashlib
import json
import re
from build_definition import BINDINGS, OUT, PATHS, REF, REPO, build, canonical, node_schema
from inventory import inventory
def write(name, value):
(OUT / name).write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n")
def main():
inv = inventory()
raw = (REPO / PATHS[0]).read_bytes()
g = json.loads(raw)
b = build()
nodes = {n["id"]: n for n in g["nodes"]}
assert inv["sha256"] == "98b4c399948f99aeac9326b4de9638d9a7bc3d718edd2561ab745f6bec12478c"
assert len(g["nodes"]) == 33 and len(g["links"]) == 29 and not g.get("definitions")
assert collections.Counter(n["mode"] for n in g["nodes"]) == {0: 31, 4: 2}
assert {n["id"] for n in g["nodes"] if n["mode"] == 4} == {316, 137}
assert all("widgets_values" in n and "widgets_values_named" not in n for n in g["nodes"])
assert (
len(inv["fields"]) == 118
and len(inv["notes"]) == 7
and inv["empty"] == [dict(node=291, pointer="/nodes/9", state="empty_list")]
)
assert collections.Counter(f["json_type"] for f in inv["fields"]) == dict(
str=50, int=33, bool=24, float=5, NoneType=5, dict=1
)
assert g["links"] == json.loads((OUT / "expected-edges.json").read_bytes())
for eid, src, si, dst, di, typ in g["links"]:
assert eid in nodes[src]["outputs"][si]["links"] and nodes[dst]["inputs"][di]["link"] == eid
# Source sockets include wildcard PreviewAny; preserve, do not force schema types.
assert nodes[src]["outputs"][si]["type"] == typ or typ == "*"
assert nodes[dst]["inputs"][di]["type"] == typ or nodes[dst]["inputs"][di]["type"] == "*"
for f, x in zip(b["fields"], inv["fields"], strict=True):
assert f["pointer"] == x["pointer"] and f["json_type"] == x["json_type"]
assert type(f["value"]).__name__ == f["json_type"] and canonical(f["value"]) == canonical(
x["value"]
)
assert f["named_state"] == "missing" and "named_pointer" not in f and "named_value" not in f
for note, x in zip(b["comments"], inv["notes"], strict=True):
assert (
note["pointer"] == x["pointer"]
and note["text"] == x["text"]
and "named_pointer" not in note
)
manifest = json.loads((REF / "sources.json").read_bytes())["sources"]
checks = []
trees = {}
for e in manifest:
data = (REF / e["local_file"]).read_bytes()
assert hashlib.sha256(data).hexdigest() == e["sha256"]
blob = hashlib.sha1(b"blob " + str(len(data)).encode() + b"\x00" + data).hexdigest()
if re.fullmatch("[0-9a-f]{40}", e.get("git_blob_sha1", "")):
assert blob == e["git_blob_sha1"]
if not e["license_file"].startswith("未知"):
assert (REF / e["license_file"]).is_file()
if e["file"].endswith(".py"):
trees[e["local_file"]] = ast.parse(data)
checks.append(
dict(
id=e["id"],
file=e["file"],
sha256=e["sha256"],
git_blob_sha1=e.get("git_blob_sha1", "unknown"),
first_acquisition=e.get("acquisition_time", "unknown"),
reverified_at=e.get("reverified_at", "unknown"),
license_file=e["license_file"],
)
)
ids = {e["id"] for e in manifest}
assert {
"wan373",
"wanff",
"wanc3",
"wan3d",
"wan058",
"wanbd",
"wan494",
"core0350",
"core0341",
"kj6df",
"kj136",
"audio",
"layer",
"cr",
"combine",
"frontend",
"litegraph",
} == ids
exact = []
gaps = []
schemas = {}
for binding in b["node_bindings"]:
nid = binding["node_id"]
key, file, symbol = BINDINGS[nid]
e = next(x for x in manifest if x["id"] == key and x["file"] == file)
tree = trees[e["local_file"]]
c = next((x for x in tree.body if isinstance(x, ast.ClassDef) and x.name == symbol), None)
if c is None:
assert not binding["candidates"] and binding["source_id"] == "unresolved-" + key
gaps.append(
dict(
node=nid,
class_type=binding["class_type"],
exact_source=key,
selected_entry=file,
commit=e["commit"],
reason="准确入口与所选注册/实现文件没有该类;不作全仓无类证明或借后版补实",
)
)
continue
assert binding["implementation_verified"] and binding["source_id"] == key
schemas[nid] = node_schema(c)
registered = []
for x in manifest:
if x["id"] != key or not x["file"].endswith(".py"):
continue
for d in ast.walk(trees[x["local_file"]]):
if not isinstance(d, ast.Dict):
continue
for dk, dv in zip(d.keys, d.values, strict=True):
if not isinstance(dk, ast.Constant) or dk.value != binding["class_type"]:
continue
okay = isinstance(dv, ast.Name) and dv.id == symbol
if isinstance(dv, ast.Dict):
okay = any(
isinstance(k, ast.Constant)
and k.value == "class"
and isinstance(v, ast.Name)
and v.id == symbol
for k, v in zip(dv.keys, dv.values, strict=True)
)
if okay:
registered.append(dict(file=x["file"], line=d.lineno))
assert registered, (nid, key, symbol, "registration missing in bounded selected paths")
exact.append(
dict(
node=nid,
source=key,
file=file,
symbol=symbol,
lines=[c.lineno, c.end_lineno],
registered=registered,
scope="准确静态类或发布成员,不认证目标安装/全图协议兼容",
)
)
assert len(exact) == 23 and {x["node"] for x in gaps} == {"137", "120", "192"}
def clsattr(nid, name):
key, file, symbol = BINDINGS[nid]
e = next(x for x in manifest if x["id"] == key and x["file"] == file)
c = next(
x
for x in trees[e["local_file"]].body
if isinstance(x, ast.ClassDef) and x.name == symbol
)
return ast.literal_eval(
next(
x.value
for x in c.body
if isinstance(x, ast.Assign)
and any(isinstance(t, ast.Name) and t.id == name for t in x.targets)
)
)
assert clsattr("194", "RETURN_TYPES") == ("MULTITALK_EMBEDS", "AUDIO")
assert clsattr("293", "RETURN_TYPES") == ()
assert clsattr("128", "RETURN_TYPES") == ("LATENT",)
for nid, absent in {
"194": ["add_noise_floor", "smooth_transients"],
"128": [
"start_step",
"end_step",
"add_noise_to_samples",
"multitalk_embeds",
"freeinit_args",
],
"138": ["merge_loras"],
"122": ["rms_norm_function", "multitalk_model", "extra_model", "fantasyportrait_model"],
"129": ["use_cpu_cache", "verbose"],
"130": ["normalization"],
"125": ["audioUI", "upload"],
}.items():
assert all(k not in schemas[nid] for k in absent), (nid, absent)
assert nodes[293]["widgets_values"] == [None, None, None] and nodes[125]["widgets_values"][
1:
] == [None, None]
assert nodes[137]["outputs"][0]["links"] == [] and "links" not in nodes[128]["outputs"][1]
assert "links" not in nodes[194]["outputs"][1] and nodes[194]["outputs"][2]["links"] == [556]
assert nodes[131]["widgets_values"]["frame_rate"] == 16
assert nodes[131]["widgets_values"]["videopreview"]["params"]["frame_rate"] == 25
assert type(nodes[131]["widgets_values"]["videopreview"]["params"]["score"]) is str
assert nodes[237]["widgets_values"][1] == 1.0010000000000003
assert nodes[128]["widgets_values"][1:3] == [1.0000000000000002, 11.000000000000002]
assert nodes[128]["widgets_values"][3:5] == [578348772950128, "randomize"]
assert nodes[159]["outputs"][0]["links"] == [301, 552]
assert nodes[170]["outputs"][3]["links"] == [335]
assert nodes[194]["inputs"][7]["link"] == 565 and nodes[305]["inputs"][2]["link"] == 559
assert g["extra"]["frontendVersion"] == "1.23.0"
resolution = json.loads((REF / "identity-resolution.json").read_bytes())
assert resolution["node306"]["aux_same_commit_http"] == 422
lock = next(e for e in manifest if e["id"] == "frontend" and e["file"] == "package-lock.json")
locked = json.loads((REF / lock["local_file"]).read_bytes())["packages"][
"node_modules/@comfyorg/litegraph"
]
assert locked["version"] == "0.15.15"
pkg = json.loads((REF / "kj136-registry-response.json").read_bytes())
assert pkg["version"] == "1.3.6"
range_record = json.loads((REF / "kj136-range-requests.json").read_bytes())
assert not range_record["full_archive_acquired"] and all(
r["status"] == 206 for r in range_record["requests"]
)
sensitive = []
def scan(v, p=""):
if isinstance(v, dict):
for k, x in v.items():
if k.lower() in [
"api_key",
"apikey",
"secret",
"password",
"token",
"access_token",
"authorization",
] and x not in [None, "", [], {}]:
sensitive.append(p + "/" + k)
scan(x, p + "/" + k)
elif isinstance(v, list):
for i, x in enumerate(v):
scan(x, p + "/" + str(i))
scan(g)
assert not sensitive
notes = []
for x in inv["notes"]:
raw = x["text"]
notes.append(
dict(
node=str(x["node"]),
characters=len(raw),
LF=raw.count("\n"),
CR=raw.count("\r"),
literal_backslash_n=raw.count("\\n"),
tail_LF=raw.endswith("\n"),
sha256=hashlib.sha256(raw.encode()).hexdigest(),
)
)
assert [(x["node"], x["characters"], x["LF"], x["tail_LF"]) for x in notes] == [
("313", 11, 1, False),
("311", 3, 0, False),
("310", 2, 0, False),
("309", 3, 0, False),
("315", 14, 0, False),
("299", 113, 2, False),
("239", 686, 15, True),
]
texts = []
for f in b["fields"]:
if isinstance(f["value"], str) and len(f["value"]) > 100:
t = f["value"]
texts.append(
dict(
node=f["node_id"],
field=f["field"],
characters=len(t),
LF=t.count("\n"),
CR=t.count("\r"),
literal_backslash_n=t.count("\\n"),
tail_LF=t.endswith("\n"),
sha256=hashlib.sha256(t.encode()).hexdigest(),
)
)
write(
"source-check.json",
dict(
source_sha256=inv["sha256"],
fields=118,
notes=notes,
texts=texts,
accurate_nodes=23,
unresolved_nodes=gaps,
unknown_nodes=0,
source_rows=len(manifest),
nonempty_credential_keys=sensitive,
no_upstream_execution=True,
),
)
write(
"exact-source-check.json",
dict(
files=checks,
classes=exact,
unresolved=gaps,
all_ast_only=True,
acquisition_and_reverification_separate=True,
),
)
write(
"identity-gaps.json",
dict(
unresolved=gaps,
protocol_mismatches=dict(
node194="准确两输出,无num_frames第三出口;add_noise_floor/smooth_transients无schema",
node293="准确无返回口;源STRING/null及三null历史另列",
node128="准确仅samples,multitalk/freeinit和末三额外位置无schema",
node122="multitalk_model/rms_norm_function等源口未获准确支持",
node129="use_cpu_cache/verbose额外",
node130="normalization额外",
node138="merge_loras额外",
),
release_identity=dict(
kj136="准确成员;Git/整包SHA未知",
litegraph="锁定0.15.15成员;非后版内置树,Git/本批整包重算未知",
),
audio_license="准确树无LICENSE,pyproject引用未兑现;不补别版许可",
ue_restoration="unknown",
),
)
print(
"PASS118 entries/7 notes/23 exact instances/3 bounded unresolved; "
"schema/port mismatches preserved"
)
if __name__ == "__main__":
main()