cmvr-visual/inference/scripts/verify_video_edit_profile.py

178 lines
6.9 KiB
Python
Raw Normal View History

"""Offline verification and fail-closed receipt generation for WanAnimate.
Default invocation creates config/video-edit-models.json with validated=false.
Existing receipts are not overwritten. --check-only does not write anything.
Separate --certify-evidence accepts an operator-reviewed real-PoC record bound
by receipt_sha256, hashes all evidence artifacts, and never changes service flags.
"""
import argparse
import json
from pathlib import Path
import download_video_edit_models as d
PROFILE = "wan-animate-replace-v1"
CHECKS = {
"single_person",
"multiple_people",
"unselected_protection",
"occlusion_identity",
"temporal_over_77_frames",
"frame_count_fps_duration",
"audio",
"gpu_budget_68gib",
"external_user_yield",
"cancel_process_tree",
}
def build_receipt(workspace, metadata, code):
workspace = Path(workspace).resolve(strict=True)
metadata = d.confined(workspace, metadata)
code = d.confined(workspace, code)
files = []
for folder, repo, revision, kind, cache in d.SPECS:
target = d.child_path(workspace, "models/" + folder)
selected = d.validate_metadata(
d.load_metadata(metadata, cache, repo, revision, offline=True),
repo,
revision,
kind,
)
expected = set()
for item in selected:
path = d.child_path(target, item["rfilename"])
if not d.checksum(path, item):
raise ValueError("Canonical model checksum mismatch: " + str(path))
expected.add(path.resolve())
files.append(
{
"path": str(path),
"size": path.stat().st_size,
"sha256": d.hash_file(path),
}
)
inventory = target if kind == "model" else target / "process_checkpoint"
for path in inventory.rglob("*"):
if path.is_symlink():
raise ValueError("Symlink model file is forbidden")
if (
path.is_file()
and not any(
part.startswith(".") for part in path.relative_to(inventory).parts
)
and path.resolve() not in expected
):
raise ValueError("Unverified file in model directory: " + str(path))
for name, expected in d.CODE_FILES.items():
path = d.child_path(code, name)
if not path.is_file() or d.hash_file(path) != expected:
raise ValueError("Pinned preprocessing code checksum mismatch: " + name)
files.append(
{"path": str(path), "size": path.stat().st_size, "sha256": expected}
)
return {
"profile": PROFILE,
"revision": d.MODEL_REVISION,
"preprocess_revision": d.PREPROCESS_REVISION,
"code_revision": d.CODE_REVISION,
"validated": False,
"model_dir": str(d.child_path(workspace, "models/wan2.2-animate-14b")),
"checkpoint_dir": str(
d.child_path(
workspace, "models/wan2.2-animate-preprocess/process_checkpoint"
)
),
"preprocess_dir": str(code),
"files": sorted(files, key=lambda entry: entry["path"]),
}
def validate_evidence(evidence, receipt_path, workspace):
if (
evidence.get("profile") != PROFILE
or evidence.get("revision") != d.MODEL_REVISION
or not isinstance(evidence.get("reviewed_by"), str)
or not evidence["reviewed_by"].strip()
or not isinstance(evidence.get("artifacts"), list)
or len(evidence["artifacts"]) < 2
or not CHECKS <= set(evidence.get("checks", {}))
or any(evidence["checks"][key] is not True for key in CHECKS)
):
raise ValueError("Real PoC evidence and explicit operator review are required")
if evidence.get("receipt_sha256") != d.hash_file(receipt_path):
raise ValueError("PoC evidence is not bound to the current receipt")
kinds = set()
for artifact in evidence["artifacts"]:
path = d.confined(workspace, artifact["path"])
if not path.is_file() or d.hash_file(path) != artifact.get("sha256"):
raise ValueError("PoC evidence artifact checksum mismatch")
kinds.add(artifact.get("kind"))
if not {"gpu_job_log", "output_video"} <= kinds:
raise ValueError("PoC evidence must include GPU job logs and output video")
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--workspace", type=Path, default=Path("/workspace"))
parser.add_argument(
"--app-root", type=Path, default=Path("/workspace/projects/llm-services")
)
parser.add_argument("--metadata-dir", type=Path, required=True)
parser.add_argument(
"--preprocess-dir",
type=Path,
help="Defaults to fixed downloaded code directory",
)
modes = parser.add_mutually_exclusive_group()
modes.add_argument("--check-only", action="store_true")
modes.add_argument(
"--certify-evidence",
type=Path,
help="Separate operator certification using real PoC evidence; never runs models",
)
args = parser.parse_args(argv)
workspace = args.workspace.resolve(strict=True)
app = d.confined(workspace, args.app_root)
code = args.preprocess_dir or workspace / "models/wan2.2-animate-preprocess/code"
receipt = build_receipt(workspace, args.metadata_dir, code)
destination = d.child_path(app, "config/video-edit-models.json")
if args.certify_evidence:
evidence_path = d.confined(workspace, args.certify_evidence)
evidence = json.loads(evidence_path.read_text(encoding="utf-8"))
previous = json.loads(destination.read_text(encoding="utf-8"))
if previous != receipt:
raise ValueError("Certification requires the unchanged unvalidated receipt")
validate_evidence(evidence, destination, workspace)
receipt.update(
validated=True,
poc_evidence_sha256=d.hash_file(evidence_path),
reviewed_by=evidence["reviewed_by"],
)
# 独立认证步骤显式绑定PoC文件和旧receipt,不能用下载成功冒充效果通过。
temporary = d.child_path(app, "config/video-edit-models.certifying.json")
with temporary.open("x", encoding="utf-8") as stream:
json.dump(receipt, stream, ensure_ascii=False, indent=2)
temporary.replace(destination)
elif not args.check_only:
destination.parent.mkdir(parents=True, exist_ok=True)
with destination.open("x", encoding="utf-8") as stream:
json.dump(receipt, stream, ensure_ascii=False, indent=2)
print(
json.dumps(
{
"profile": PROFILE,
"verified_files": len(receipt["files"]),
"validated": receipt["validated"],
"receipt": str(destination),
"check_only": args.check_only,
}
)
)
return 0
if __name__ == "__main__":
raise SystemExit(main())