"""Materialize a read-only, train-only snapshot view for standalone resampling.""" import argparse import json import os from pathlib import Path import shutil from checkers.inventory import ALLOWLIST_SHA256, train_allowlist from sandbox.snapshot import FILES def prepare(run, w301, snapshots, window_index): allowed = train_allowlist(w301 / "data/allowlists.json") windows = json.loads(window_index.read_bytes()) train_windows = {} source_roots = w301 / "roots/train_roots.json" roots = json.loads(source_roots.read_bytes()) if {(dataset, case) for dataset, group in roots.items() for case in group} != allowed: raise ValueError("unexpected_train_roots") snapshots = snapshots.resolve(strict=True) for dataset, case in sorted(allowed): origin = snapshots / dataset / case if origin.is_symlink() or set(item.name for item in origin.iterdir()) != FILES: raise ValueError("invalid_snapshot_layout") target = run / "snapshots" / dataset / case target.mkdir(parents=True, exist_ok=True) for name in FILES: source = origin / name if source.is_symlink() or not source.is_file(): raise ValueError("invalid_snapshot_file") out = target / name if not out.exists(): os.link(source, out) elif not os.path.samefile(source, out): raise ValueError("snapshot_view_content_changed") train_windows.setdefault(dataset, {})[case] = windows["windows"][dataset][case] present = {(path.parent.name, path.name) for path in (run / "snapshots").glob("*/*") if path.is_dir()} if present != allowed: raise ValueError("unexpected_snapshot_view_inventory") (run / "data").mkdir(exist_ok=True) (run / "roots").mkdir(exist_ok=True) (run / "verified").mkdir(exist_ok=True) roles = {"train": sorted(allowed), "id_test": [], "ood_test": [], "ood_all": []} (run / "data/allowlists.json").write_text(json.dumps(roles, separators=(",", ":"))) (run / "data/windows.json").write_text(json.dumps({"version": 1, "windows": train_windows})) shutil.copyfile(source_roots, run / "roots/train_roots.json") (run / "roots/train_roots.json").chmod(0o444) for file in (w301 / "verified").iterdir(): shutil.copyfile(file, run / "verified" / file.name) (run / "input_audit.json").write_text(json.dumps({ "source_allowlist_sha256": ALLOWLIST_SHA256, "train_snapshot_count": len(present), "eval_snapshots_in_view": 0, "vault_mounted": False, "train_roots_only": True, }, indent=2) + "\n") if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) for option in ("run", "w301", "snapshots", "window-index"): parser.add_argument("--" + option, required=True, type=Path) args = parser.parse_args() prepare(args.run, args.w301, args.snapshots, args.window_index)