airfrans / scripts /validate_airfrans_dataset.py
Zhongning's picture
Upload folder using huggingface_hub (part 9)
eb96d23 verified
Raw
History Blame Contribute Delete
4.86 kB
#!/usr/bin/env python3
"""Validate the standardized AirfRANS dataset package."""
from __future__ import annotations
import argparse
import hashlib
import json
import re
import sys
from pathlib import Path
REPO_ROOT = Path(__file__).resolve().parents[1]
DATASET_ROOT = REPO_ROOT / "data" / "Dataset"
CHECKSUM_PATH = REPO_ROOT / "files_sha256.jsonl"
REQUIRED_SUFFIXES = ("internal.vtu", "freestream.vtp", "aerofoil.vtp")
SCHEMA_HINTS = {
"internal.vtu": ("UnstructuredGrid", "implicit_distance", "U", "p", "nut"),
"aerofoil.vtp": ("PolyData", "Normals", "U", "p", "nut"),
"freestream.vtp": ("PolyData", "U", "p", "nut"),
}
def fail(message: str) -> None:
print(f"[FAIL] {message}")
raise SystemExit(1)
def ok(message: str) -> None:
print(f"[OK] {message}")
def warn(message: str) -> None:
print(f"[WARN] {message}")
def sha256_file(path: Path) -> str:
h = hashlib.sha256()
with path.open("rb") as f:
for chunk in iter(lambda: f.read(1024 * 1024), b""):
h.update(chunk)
return h.hexdigest()
def load_manifest() -> dict:
manifest_path = DATASET_ROOT / "manifest.json"
if not manifest_path.exists():
fail(f"missing manifest.json: {manifest_path}")
try:
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
except json.JSONDecodeError as exc:
fail(f"manifest.json is not valid JSON: {exc}")
for key in ("full_train", "full_test"):
if key not in manifest or not isinstance(manifest[key], list) or not manifest[key]:
fail(f"manifest key is missing or empty: {key}")
return manifest
def inspect_vtk_header(path: Path, suffix: str) -> None:
blob = path.read_bytes()[:262144].decode("utf-8", errors="ignore")
if "<VTKFile" not in blob:
fail(f"not a VTK XML file: {path}")
for token in SCHEMA_HINTS[suffix]:
if token not in blob:
fail(f"schema token {token!r} not found in {path}")
piece = re.search(r"NumberOfPoints=\"(\d+)\"", blob)
if piece and int(piece.group(1)) <= 0:
fail(f"NumberOfPoints is not positive in {path}")
def validate_files(manifest: dict, sample_count: int) -> None:
actual_dirs = sorted(p for p in DATASET_ROOT.iterdir() if p.is_dir())
referenced = list(dict.fromkeys(manifest["full_train"] + manifest["full_test"]))
if len(actual_dirs) != len(referenced):
fail(f"case count mismatch: dirs={len(actual_dirs)}, manifest_unique={len(referenced)}")
missing = []
for sim_name in referenced:
sim_dir = DATASET_ROOT / sim_name
if not sim_dir.is_dir():
missing.append(str(sim_dir))
continue
for suffix in REQUIRED_SUFFIXES:
file_path = sim_dir / f"{sim_name}_{suffix}"
if not file_path.is_file():
missing.append(str(file_path))
elif file_path.stat().st_size <= 0:
fail(f"empty file: {file_path}")
if missing:
fail("missing required files, first entries: " + "; ".join(missing[:8]))
for sim_name in referenced[:sample_count]:
for suffix in REQUIRED_SUFFIXES:
inspect_vtk_header(DATASET_ROOT / sim_name / f"{sim_name}_{suffix}", suffix)
ok(f"dataset file structure and sampled VTK schema are valid: {len(referenced)} cases")
def verify_checksums(full_hash: bool) -> None:
if not CHECKSUM_PATH.exists():
warn(f"checksum manifest is not present: {CHECKSUM_PATH}")
return
checked = 0
for line in CHECKSUM_PATH.read_text(encoding="utf-8").splitlines():
if not line.strip():
continue
record = json.loads(line)
path = REPO_ROOT / record["path"]
if not path.exists():
fail(f"checksum entry points to missing file: {path}")
size = path.stat().st_size
if size != record["size"]:
fail(f"size mismatch for {path}: expected {record['size']}, got {size}")
if full_hash:
digest = sha256_file(path)
if digest != record["sha256"]:
fail(f"sha256 mismatch for {path}")
checked += 1
mode = "size+sha256" if full_hash else "size"
ok(f"checksum manifest verified in {mode} mode: {checked} files")
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument("--sample-count", type=int, default=3)
parser.add_argument("--full-hash", action="store_true")
args = parser.parse_args()
if args.sample_count < 1:
fail("--sample-count must be positive")
if not DATASET_ROOT.exists():
fail(f"dataset root does not exist: {DATASET_ROOT}")
manifest = load_manifest()
validate_files(manifest, args.sample_count)
verify_checksums(args.full_hash)
ok("dataset validation completed")
return 0
if __name__ == "__main__":
sys.exit(main())