"""Write a SHA-256 manifest for a dataset and check it against the committed manifest. python scripts/00_data_manifest.py # create/update the F3 manifest python scripts/00_data_manifest.py --check # check only; exit 1 on mismatch python scripts/00_data_manifest.py --dataset volve # same for data/Volve python scripts/00_data_manifest.py --dataset nlog # same for data/NLOG """ from __future__ import annotations import argparse import hashlib import json import sys from concurrent.futures import ThreadPoolExecutor from datetime import datetime, timezone from pathlib import Path from ml_porosity.paths import REPO_ROOT, f3_root, nlog_root, volve_root DATASETS = { "f3": (f3_root, "f3_demo_2023.json", "F3 Demo 2023 (dGB Earth Sciences / TerraNubis), CC BY-SA 3.0"), "volve": (volve_root, "volve.json", "Volve data village (Equinor), HRS licence / CC BY-NC-SA 4.0"), "nlog": (nlog_root, "nlog.json", "NLOG (TNO), public LAS and TD data for the F3 wells; URLs in docs/research/f3-nlog-inventory.xlsx"), } def sha256(path: Path, chunk: int = 1 << 22) -> str: h = hashlib.sha256() with path.open("rb") as f: while block := f.read(chunk): h.update(block) return h.hexdigest() def scan(root: Path) -> dict[str, dict]: files = sorted(p for p in root.rglob("*") if p.is_file()) with ThreadPoolExecutor(max_workers=8) as ex: digests = list(ex.map(sha256, files)) return { p.relative_to(root).as_posix(): {"size_bytes": p.stat().st_size, "sha256": d} for p, d in zip(files, digests) } def main() -> int: ap = argparse.ArgumentParser() ap.add_argument("--check", action="store_true") ap.add_argument("--dataset", choices=sorted(DATASETS), default="f3") args = ap.parse_args() root_fn, manifest_name, description = DATASETS[args.dataset] manifest = REPO_ROOT / "data_manifest" / manifest_name root = root_fn() current = scan(root) if args.check: ref = json.loads(manifest.read_text())["files"] missing = sorted(set(ref) - set(current)) changed = sorted(k for k in set(ref) & set(current) if ref[k]["sha256"] != current[k]["sha256"]) extra = sorted(set(current) - set(ref)) for name, items in (("missing", missing), ("hash mismatch", changed), ("extra", extra)): for k in items: print(f"{name}: {k}") print(f"{len(current)} files, {len(missing)} missing, {len(changed)} hash mismatch, {len(extra)} extra") return 1 if (missing or changed) else 0 out = { "dataset": description, "root": root.relative_to(REPO_ROOT).as_posix() if root.is_relative_to(REPO_ROOT) else str(root), "created_utc": datetime.now(timezone.utc).isoformat(timespec="seconds"), "n_files": len(current), "total_bytes": sum(v["size_bytes"] for v in current.values()), "files": current, } manifest.parent.mkdir(parents=True, exist_ok=True) manifest.write_text(json.dumps(out, indent=1, ensure_ascii=False) + "\n") print(f"{out['n_files']} file, {out['total_bytes'] / 1e9:.2f} GB -> {manifest.relative_to(REPO_ROOT)}") return 0 if __name__ == "__main__": sys.exit(main())