eryon-data-pipelines / scripts /validate_dataset.py
Chucks90's picture
Upload folder using huggingface_hub
6bcf82b verified
Raw
History Blame Contribute Delete
3.67 kB
"""
validate_dataset.py — ERYON dataset validation gate.
Runs mandatory checks before a dataset becomes trainable:
1. Corruption scan — every PNG opens without error
2. Manifest validation — all required fields present, paths exist
3. Checksum verification — stored sha256 matches file on disk
4. Split completeness — every series_id in manifest has a split assignment
Exits with code 1 if any check fails. Writes a JSON report to reports/validation/.
Usage:
python validate_dataset.py \\
--root /mnt/raw/lidc \\
--manifest manifests/lidc/manifest_v1.0.0.jsonl \\
--splits manifests/lidc/splits_v1.0.0.json \\
--out reports/validation/lidc_v1.0.0.json
"""
import argparse
import hashlib
import json
import sys
from pathlib import Path
from PIL import Image
REQUIRED_FIELDS = {
"patient_id", "study_id", "series_id", "image_path",
"modality", "split", "label", "dataset_version",
"preprocessing_version", "sha256",
}
def sha256_file(path: Path) -> str:
h = hashlib.sha256()
with open(path, "rb") as f:
for chunk in iter(lambda: f.read(65536), b""):
h.update(chunk)
return h.hexdigest()
def validate(root: Path, manifest_path: Path, splits_path: Path) -> dict:
records = [json.loads(l) for l in manifest_path.read_text().splitlines() if l.strip()]
splits_data = json.loads(splits_path.read_text()) if splits_path else {}
split_map = splits_data.get("splits", {}) if splits_data else {}
errors: list[str] = []
warnings: list[str] = []
for i, rec in enumerate(records):
missing = REQUIRED_FIELDS - rec.keys()
if missing:
errors.append(f"record {i}: missing fields {missing}")
continue
img_path = root / rec["image_path"]
if not img_path.exists():
errors.append(f"record {i}: file not found {img_path}")
continue
# corruption check
try:
with Image.open(img_path) as img:
img.verify()
except Exception as exc:
errors.append(f"record {i}: corrupt image {img_path}: {exc}")
continue
# checksum
actual = sha256_file(img_path)
if actual != rec["sha256"]:
errors.append(f"record {i}: sha256 mismatch {rec['image_path']}")
# split assignment
if split_map and rec["series_id"] not in split_map:
warnings.append(f"record {i}: series_id {rec['series_id']} has no split assignment")
return {
"total_records": len(records),
"errors": errors,
"warnings": warnings,
"passed": len(errors) == 0,
}
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--root", required=True)
parser.add_argument("--manifest", required=True)
parser.add_argument("--splits", default=None)
parser.add_argument("--out", required=True)
args = parser.parse_args()
result = validate(
root=Path(args.root),
manifest_path=Path(args.manifest),
splits_path=Path(args.splits) if args.splits else None,
)
out_path = Path(args.out)
out_path.parent.mkdir(parents=True, exist_ok=True)
out_path.write_text(json.dumps(result, indent=2))
status = "PASSED" if result["passed"] else "FAILED"
print(f"Validation {status}: {len(result['errors'])} errors, {len(result['warnings'])} warnings")
print(f"Report: {out_path}")
if not result["passed"]:
for e in result["errors"]:
print(f" ERROR: {e}", file=sys.stderr)
sys.exit(1)
if __name__ == "__main__":
main()