← Back to the animated process

scripts/pnp_snapshot.py

Implementation snapshot supporting the published lesson. Only cited line ranges are included; this is not a runnable source file. Configuration and recorded examples describe this project snapshot.

… uncited lines omitted …
12FILES = {13    "calibration.json": Path("calibration.json"),14    "object_keypoints.yaml": Path("yolo_seg_pose_onthefly/object_keypoints.yaml"),15}161718def digest(path):19    return hashlib.sha256(path.read_bytes()).hexdigest()202122def verify(snapshot):23    manifest = json.loads((snapshot / "manifest.json").read_text())24    if manifest.get("schema_version") != 1 or set(manifest.get("sha256", {})) != set(FILES):25        raise ValueError("Invalid PnP snapshot manifest")26    for name, expected in manifest["sha256"].items():27        if digest(snapshot / name) != expected:28            raise ValueError(f"PnP snapshot changed: {snapshot / name}")29    return manifest303132def save(dataset):33    dataset = Path(dataset).resolve()34    snapshot = dataset / "training_pnp"35    sources = {name: dataset / relative for name, relative in FILES.items()}36    for source in sources.values():37        if not source.is_file():38            raise FileNotFoundError(source)39    source_hashes = {name: digest(path) for name, path in sources.items()}40    if snapshot.exists():41        manifest = verify(snapshot)42        if manifest["sha256"] != source_hashes:43            raise ValueError("Training PnP snapshot differs from current calibration or keypoints; "44                             "use a new session for a different box")45        return snapshot46    with tempfile.TemporaryDirectory(prefix=".training_pnp_", dir=dataset) as temporary:47        stage = Path(temporary) / "training_pnp"48        stage.mkdir()49        for name, source in sources.items():50            shutil.copy2(source, stage / name)51        if {name: digest(stage / name) for name in FILES} != source_hashes:52            raise ValueError("PnP inputs changed while saving the snapshot")53        calibration = json.loads((stage / "calibration.json").read_text())54        manifest = {55            "schema_version": 1,56            "calibration_revision": calibration["revision"],57            "sha256": source_hashes,58        }59        (stage / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n")60        stage.rename(snapshot)