Files
aigc-home/calliope-backend/scripts/verify_output_protocol_sources.py
T
2026-10-29 22:51:08 +08:00

133 lines
5.6 KiB
Python

"""Verify frozen public sources and execute ONLY extracted core serialization methods.
No plugin imports, torch, model loading, audio encoding, service access or generation.
Use --fetch to download the pinned Python source files into --source-dir.
"""
from __future__ import annotations
import argparse
import ast
import hashlib
import json
from enum import Enum
from pathlib import Path
from types import SimpleNamespace
from urllib.request import urlopen
REPO = Path(__file__).resolve().parents[2]
CONTRACTS = REPO / "calliope-backend/src/calliope/comfyui/protocol_references.json"
def verify(source_dir: Path, fetch: bool = False) -> dict:
data = json.loads(CONTRACTS.read_text(encoding="utf-8"))
trees = {}
verified = []
for source in data["sources"]:
cache = source.get("cache_directory", source["repository"].rsplit("/", 1)[-1])
path = source_dir / cache / source["file"]
if fetch:
with urlopen(source["raw_url"], timeout=30) as response:
raw = response.read()
if hashlib.sha256(raw).hexdigest() != source["sha256"]:
raise ValueError(f"Source hash mismatch: {source['id']}")
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(raw)
raw = path.read_bytes()
if hashlib.sha256(raw).hexdigest() != source["sha256"]:
raise ValueError(f"Source hash mismatch: {source['id']}")
trees[source["id"]] = ast.parse(raw.decode("utf-8"))
verified.append({"id": source["id"], "sha256": source["sha256"]})
# Execute only these two core dict wrappers, after full-file hash verification.
# Enum/base stand-ins avoid importing ComfyUI or any of its dependencies.
folder_type = Enum("FolderType", {"output": "output"})
namespace = {"FolderType": folder_type, "_UIOutput": object}
wrappers = [
n
for n in trees["core-ui"].body
if isinstance(n, ast.ClassDef) and n.name in ("SavedResult", "SavedAudios")
]
module = ast.Module(
body=[
ast.ImportFrom(module="__future__", names=[ast.alias(name="annotations")], level=0),
*wrappers,
],
type_ignores=[],
)
exec(compile(ast.fix_missing_locations(module), "<pinned-core-wrappers>", "exec"), namespace)
descriptor = namespace["SavedResult"]("music_00001.mp3", "audio", folder_type.output)
audio_ui = namespace["SavedAudios"]([descriptor]).as_dict()
preview = next(n for n in trees["core-preview"].body if isinstance(n, ast.ClassDef))
method = next(n for n in preview.body if isinstance(n, ast.FunctionDef) and n.name == "main")
namespace = {"json": json, "torch": SimpleNamespace(set_printoptions=lambda **kw: None)}
exec(
compile(ast.Module(body=[method], type_ignores=[]), "<pinned-core-preview>", "exec"),
namespace,
)
values = ["正文", "0.00-1.20: 字幕文本", "Chinese", ""]
preview_ui = {
str(n): namespace["main"](None, values[slot])["ui"]
for n, slot in [(1, 3), (2, 1), (3, 2), (4, 0)]
}
# The source graph claims core 0.11.0. Its preview has no result socket,
# while the newer reference has one. Both serialize the same text UI.
old_preview = next(n for n in trees["core-preview-v011"].body if isinstance(n, ast.ClassDef))
old_method = next(
n for n in old_preview.body if isinstance(n, ast.FunctionDef) and n.name == "main"
)
old_namespace = {"json": json}
exec(
compile(ast.Module(body=[old_method], type_ignores=[]), "<pinned-011-preview>", "exec"),
old_namespace,
)
old_result = old_namespace["main"](None, "字幕文本")
assert old_result == {"ui": {"text": ("字幕文本",)}}
assert namespace["main"](None, "字幕文本")["result"] == ("字幕文本",)
subtitle = next(
n
for n in trees["qwen-subtitle"].body
if isinstance(n, ast.ClassDef) and n.name == "AILab_Qwen3ASRSubtitle"
)
literal_attributes = {
n.targets[0].id: ast.literal_eval(n.value)
for n in subtitle.body
if isinstance(n, ast.Assign)
and isinstance(n.targets[0], ast.Name)
and n.targets[0].id in ("RETURN_TYPES", "RETURN_NAMES")
}
assert literal_attributes["RETURN_TYPES"] == ("STRING",) * 4
assert literal_attributes["RETURN_NAMES"] == ("TEXT", "SUBTITLES", "LANGUAGE", "OUTPUT_PATH")
return {
"evidence_layer": "pinned_source_serialization_contract_fixture",
"target_history_observed": False,
"verified_sources": verified,
"execution_boundary": "AST-extracted SavedResult/SavedAudios and PreviewAny.main "
"(current and v0.11.0) only; "
"torch print configuration stubbed; subtitle class parsed, never executed; "
"no audio encoder, plugin imports, model or ComfyUI execution",
"subtitle_return_names": literal_attributes["RETURN_NAMES"],
"preview_v011_has_result": "result" in old_result,
"subtitle_history_fixture": {"outputs": preview_ui},
"audio_history_fixture": {"outputs": {"35": audio_ui}},
}
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--source-dir", type=Path, required=True)
parser.add_argument("--fetch", action="store_true")
parser.add_argument("--output", type=Path, required=True)
args = parser.parse_args()
result = verify(args.source_dir, args.fetch)
args.output.parent.mkdir(parents=True, exist_ok=True)
args.output.write_text(
json.dumps(result, ensure_ascii=False, indent=2) + "\n", encoding="utf-8"
)
print(f"Verified {len(result['verified_sources'])} pinned source files; serialization only")
if __name__ == "__main__":
main()