motion-graphics-bench / scripts /verify_animations.py
jama1017's picture
Initial commit
89592d6
Raw History Blame Contribute Delete
5.09 kB
"""Measure SVG frames and run trusted benchmark verifiers without OS sandboxing."""
from __future__ import annotations
import ast
import hashlib
import json
import os
import re
import shutil
import subprocess
import sys
import tempfile
import time
from pathlib import Path
from typing import Any
_BASE64_BLOB = re.compile(r"(;base64,)([A-Za-z0-9+/=]{64,})")
def strip_base64(svg: str) -> str:
def replace(match: re.Match[str]) -> str:
blob = match.group(2)
digest = hashlib.sha1(blob.encode()).hexdigest()[:12]
return f";base64,STRIPPED[{len(blob)}B,sha1:{digest}]"
return _BASE64_BLOB.sub(replace, svg)
def run_verifiers(program: str, matrix: dict[str, Any], *, timeout: float = 900) -> dict[str, Any]:
module_error = ""
try:
tree = ast.parse(program)
except SyntaxError as error:
module_error = str(error)
checks = []
else:
checks = sorted({
node.name for node in tree.body
if isinstance(node, ast.FunctionDef) and node.name.startswith("ver_")
})
if not checks:
module_error = "no top-level ver_*(matrix) functions found"
results = []
with tempfile.TemporaryDirectory(prefix="mgb-verifiers-") as temporary:
root = Path(temporary)
shutil.copyfile(__file__, root / "verify_animations.py")
shutil.copyfile(Path(__file__).with_name("verifier_helper_library.py"), root / "verifier_helper_library.py")
(root / "matrix.json").write_text(json.dumps(matrix, allow_nan=False), encoding="utf-8")
(root / "verifier.py").write_text(program, encoding="utf-8")
deadline = time.monotonic() + timeout
for name in checks:
result = {"name": name, "passed": False, "detail": "", "measured": {}, "logs": "", "error": ""}
remaining = deadline - time.monotonic()
if remaining <= 0:
result["error"] = "verification deadline expired before this check"
else:
output = root / f"{name}.json"
try:
process = subprocess.run(
[sys.executable, "-I", "-S", "-B", str(root / "verify_animations.py"),
str(root / "matrix.json"), str(root / "verifier.py"), name, str(output)],
cwd=root, env={"TMPDIR": str(root), "LANG": "C.UTF-8"},
stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=remaining,
)
except subprocess.TimeoutExpired:
result["error"] = f"verification timed out after {timeout:g} seconds"
else:
result["logs"] = process.stdout
if process.returncode or not output.is_file():
result["error"] = process.stderr or f"verifier exited {process.returncode} without a result"
else:
result.update(json.loads(output.read_text(encoding="utf-8")))
results.append(result)
return {
"passed_checks": [result["name"] for result in results if result["passed"]],
"failed_checks": [result["name"] for result in results if not result["passed"]],
"verification_decision": not module_error and bool(results) and all(result["passed"] for result in results),
"module_error": module_error,
"verification_errors": {result["name"]: result["error"] for result in results if result["error"]},
"results": results,
}
def verify_animations(
program: str, frames: list[str], *, fps: float, timeout: float = 900,
) -> dict[str, Any]:
from frames_to_matrix import measure
matrix = measure([strip_base64(frame) for frame in frames], fps=fps, timeout=timeout)
return {
"frame_count": len(frames),
"measurement": matrix["info"],
**run_verifiers(program, matrix, timeout=timeout),
}
def _run_check(matrix_path: str, program_path: str, name: str, output_path: str) -> None:
sys.path.insert(0, os.getcwd())
matrix = json.loads(Path(matrix_path).read_text(encoding="utf-8"))
namespace: dict[str, Any] = {}
exec(compile(Path(program_path).read_text(encoding="utf-8"), "<verifier_module>", "exec"), namespace)
result = namespace[name](matrix)
if isinstance(result, bool):
result = {"passed": result, "detail": "", "measured": {}}
if not isinstance(result, dict) or not isinstance(result.get("passed"), bool):
raise TypeError(f"{name} must return a bool or a dictionary with a boolean 'passed' field")
detail, measured = result.get("detail", ""), result.get("measured", {})
if not isinstance(detail, str) or not isinstance(measured, dict):
raise TypeError(f"{name} must return a string detail and a dictionary of measurements")
Path(output_path).write_text(json.dumps({
"name": name, "passed": result["passed"], "detail": detail, "measured": measured,
}, allow_nan=False), encoding="utf-8")
if __name__ == "__main__":
_run_check(*sys.argv[1:])