"""Ghi manifest SHA-256 cho một bộ dữ liệu và đối chiếu với manifest đã commit. python scripts/00_data_manifest.py # tạo/cập nhật manifest F3 python scripts/00_data_manifest.py --check # chỉ kiểm tra, exit 1 nếu lệch python scripts/00_data_manifest.py --dataset volve # tương tự cho data/Volve python scripts/00_data_manifest.py --dataset nlog # tương tự cho 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), giấy phép HRS / CC BY-NC-SA 4.0"), "nlog": (nlog_root, "nlog.json", "NLOG (TNO), LAS và TD công khai của giếng F3; URL ở 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 (("thiếu", missing), ("khác hash", changed), ("thừa", extra)): for k in items: print(f"{name}: {k}") print(f"{len(current)} file, {len(missing)} thiếu, {len(changed)} khác hash, {len(extra)} thừa") 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())