"""Bounded, serial video reconstruction smoke tests; never claim quality from exit codes.""" from __future__ import annotations import argparse import hashlib import json from pathlib import Path import re import shutil import subprocess import time ROOT = Path(__file__).resolve().parents[1] def run_batch(manifest_path: Path, output: Path) -> dict: manifest = json.loads(manifest_path.read_text(encoding="utf-8")) scenes = manifest["scenes"] ids = [scene["id"] for scene in scenes] if len(set(ids)) != len(ids) or any(not re.fullmatch(r"[a-z0-9][a-z0-9-]*", x) for x in ids): raise ValueError("Scene IDs must be unique safe lowercase identifiers") output.mkdir(parents=True, exist_ok=False) frozen = json.dumps(manifest, indent=2, ensure_ascii=False) (output / "manifest.json").write_text(frozen, encoding="utf-8") settings = manifest["settings"] powershell = shutil.which("pwsh") or shutil.which("powershell") if not powershell: raise RuntimeError("PowerShell runtime missing") report = {"schema": "kineworld.video-batch.v1", "manifest_sha256": hashlib.sha256(frozen.encode()).hexdigest(), "scope": "Reconstruction smoke test only; no completion or generalization quality claim", "settings": settings, "scenes": []} for scene in scenes: started = time.monotonic() job = output / scene["id"] job.mkdir() video = (manifest_path.parent / scene["video"]).resolve() item = {"id": scene["id"], "status": "running", "quality_status": "not_evaluated"} report["scenes"].append(item) (output / "report.json").write_text(json.dumps(report, indent=2), encoding="utf-8") try: if not video.is_file(): raise FileNotFoundError(video.name) expected = scene.get("sha256", "") if not re.fullmatch(r"[a-fA-F0-9]{64}", expected): raise ValueError("Input is not ready: freeze SHA-256 only after download completes") with video.open("rb") as source: actual = hashlib.file_digest(source, "sha256").hexdigest() if actual != expected.lower(): raise ValueError("Input checksum mismatch; incomplete or changed video") item["input_sha256"] = actual commands = [ [powershell, "-NoProfile", "-File", str(ROOT / "scripts/extract-video.ps1"), "-VideoPath", str(video), "-FramesPath", str(job / "capture/frames"), "-FramesPerSecond", str(settings["fps"]), "-MaximumFrames", str(settings["frames"]), "-MaximumWidth", str(settings["width"])], [powershell, "-NoProfile", "-File", str(ROOT / "scripts/run-da3.ps1"), "-InputPath", str(job / "capture/frames"), "-OutputPath", str(job / "reconstruction"), "-ProcessResolution", str(settings["resolution"]), "-MaxPoints", str(settings["points"])], ] for stage, command in zip(["extract", "reconstruct"], commands): item["stage"] = stage with (job / f"{stage}.log").open("w", encoding="utf-8") as log: subprocess.run(command, cwd=ROOT, stdout=log, stderr=subprocess.STDOUT, check=True, timeout=settings["stage_timeout_seconds"]) run = json.loads((job / "reconstruction/run.json").read_text(encoding="utf-8")) item.update(status="reconstruction_completed", performance=run["performance"], frame_count=run["input"]["count"], result=run["result"]) except (OSError, ValueError, subprocess.SubprocessError, KeyError) as error: item.update(status="failed", error=str(error)) item["elapsed_seconds"] = round(time.monotonic() - started, 3) (output / "report.json").write_text(json.dumps(report, indent=2), encoding="utf-8") print(f'{scene["id"]}: {item["status"]} ({item["elapsed_seconds"]}s)', flush=True) return report if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("manifest", type=Path) parser.add_argument("output", type=Path) args = parser.parse_args() result = run_batch(args.manifest.resolve(), args.output.resolve()) raise SystemExit(1 if any(x["status"] == "failed" for x in result["scenes"]) else 0)