#!/usr/bin/env python3 """Validate CFD_Benchmark dataset files without loading full arrays into memory.""" from __future__ import annotations import argparse import csv import hashlib import json from pathlib import Path from typing import Any def sha256_file(path: Path, chunk_size: int = 1024 * 1024 * 16) -> str: digest = hashlib.sha256() with path.open("rb") as handle: for chunk in iter(lambda: handle.read(chunk_size), b""): digest.update(chunk) return digest.hexdigest() def inspect_npy(path: Path) -> dict[str, Any]: import numpy as np array = np.load(path, mmap_mode="r") return {"format": "npy", "shape": list(array.shape), "dtype": str(array.dtype)} def inspect_mat(path: Path) -> dict[str, Any]: info: dict[str, Any] = {"format": "matlab_v5", "variables": []} try: import scipy.io as scio variables = [] for name, shape, dtype in scio.whosmat(path): variables.append({"name": name, "shape": list(shape), "dtype": str(dtype)}) info["variables"] = variables info["metadata_mode"] = "scipy.io.whosmat" except Exception as exc: # scipy is optional for integrity-only checks. info["metadata_mode"] = "header_only" info["metadata_warning"] = f"scipy.io.whosmat unavailable: {type(exc).__name__}: {exc}" with path.open("rb") as handle: info["header_prefix"] = handle.read(64).decode("latin1", errors="replace") return info def load_manifest(path: Path) -> list[dict[str, str]]: with path.open("r", newline="") as handle: return list(csv.DictReader(handle)) def main() -> int: parser = argparse.ArgumentParser() parser.add_argument("--data-root", default="data", help="Dataset data root") parser.add_argument( "--file-manifest", default="metadata/file_manifest.csv", help="CSV with rel_path,size,sha256 entries", ) parser.add_argument("--skip-sha256", action="store_true", help="Only check names and sizes") parser.add_argument("--report", default="reports/dataset_validation.json") args = parser.parse_args() data_root = Path(args.data_root) manifest_path = Path(args.file_manifest) report_path = Path(args.report) report_path.parent.mkdir(parents=True, exist_ok=True) rows = load_manifest(manifest_path) results = [] ok = True for row in rows: rel_path = row["rel_path"] expected_size = int(row["size"]) expected_sha256 = row["sha256"] path = data_root / rel_path item: dict[str, Any] = { "rel_path": rel_path, "exists": path.exists(), "expected_size": expected_size, "expected_sha256": expected_sha256, } if not path.exists(): item["status"] = "missing" ok = False results.append(item) continue actual_size = path.stat().st_size item["actual_size"] = actual_size if actual_size != expected_size: item["status"] = "size_mismatch" ok = False else: item["status"] = "ok" if not args.skip_sha256: actual_sha256 = sha256_file(path) item["actual_sha256"] = actual_sha256 if actual_sha256 != expected_sha256: item["status"] = "sha256_mismatch" ok = False if path.suffix == ".npy": item["schema"] = inspect_npy(path) elif path.suffix == ".mat": item["schema"] = inspect_mat(path) results.append(item) report = { "ok": ok, "data_root": str(data_root), "file_manifest": str(manifest_path), "checked_files": len(results), "results": results, } report_path.write_text(json.dumps(report, indent=2, ensure_ascii=False) + "\n") if ok: print(f"DATASET_VALIDATION_OK checked_files={len(results)} report={report_path}") return 0 print(f"DATASET_VALIDATION_FAILED report={report_path}") return 1 if __name__ == "__main__": raise SystemExit(main())