File size: 4,131 Bytes
9bbbe29 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 | #!/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())
|