| """ |
| run_validation_pipeline.py — ERYON validation + leakage audit pipeline. |
| |
| Runs inside an HF Job with eryon-datasets bucket mounted at /mnt. |
| Steps: |
| 1. Download manifest + splits from eryon-data-pipelines repo |
| 2. Validate: required fields, sha256 checksums, split completeness |
| 3. Leakage audit: patient overlap, duplicate hashes, slice leakage |
| 4. Upload reports to eryon-data-pipelines repo |
| |
| Corruption scan (PIL open) is skipped by default — files were just written |
| and never transferred across a network boundary. Set CORRUPTION_SCAN=True |
| to enable it (adds ~2hr on cpu-basic). |
| |
| Usage: |
| python run_validation_pipeline.py |
| """ |
|
|
| import sys |
| import json |
| import hashlib |
| from pathlib import Path |
| from collections import defaultdict |
|
|
| from huggingface_hub import HfApi, hf_hub_download |
|
|
| |
| BUCKET_LIDC = Path("/mnt/raw/lidc") |
| TMP_OUT = Path("/tmp/validation_output") |
| REPO_ID = "Chucks90/eryon-data-pipelines" |
| CORRUPTION_SCAN = False |
|
|
| REQUIRED_FIELDS = { |
| "patient_id", "study_id", "series_id", "image_path", |
| "modality", "split", "label", "dataset_version", |
| "preprocessing_version", "sha256", |
| } |
|
|
| |
|
|
| def download_inputs() -> tuple[Path, Path]: |
| print("Downloading manifest + splits from repo …") |
| manifest_path = Path(hf_hub_download( |
| REPO_ID, "manifests/lidc/manifest_v1.0.0.jsonl", |
| repo_type="dataset", local_dir="/tmp", force_download=True, |
| )) |
| splits_path = Path(hf_hub_download( |
| REPO_ID, "manifests/lidc/splits_v1.0.0.json", |
| repo_type="dataset", local_dir="/tmp", force_download=True, |
| )) |
| return manifest_path, splits_path |
|
|
|
|
| def load_manifest(path: Path) -> list[dict]: |
| return [json.loads(l) for l in path.read_text().splitlines() if l.strip()] |
|
|
|
|
| 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 run_validation(manifest_path: Path, splits_path: Path) -> dict: |
| print("Running validation …") |
| records = load_manifest(manifest_path) |
| split_map = json.loads(splits_path.read_text()).get("splits", {}) |
| errors, warnings = [], [] |
| total = len(records) |
|
|
| for i, rec in enumerate(records): |
| if i % 20000 == 0: |
| print(f" validating {i}/{total} …") |
|
|
| missing = REQUIRED_FIELDS - rec.keys() |
| if missing: |
| errors.append(f"record {i}: missing fields {missing}") |
| continue |
|
|
| img_path = BUCKET_LIDC / rec["image_path"] |
| if not img_path.exists(): |
| errors.append(f"record {i}: file not found {rec['image_path']}") |
| continue |
|
|
| |
| actual = sha256_file(img_path) |
| if actual != rec["sha256"]: |
| errors.append(f"record {i}: sha256 mismatch {rec['image_path']}") |
|
|
| |
| if CORRUPTION_SCAN: |
| try: |
| from PIL import Image |
| with Image.open(img_path) as img: |
| img.verify() |
| except Exception as exc: |
| errors.append(f"record {i}: corrupt image {rec['image_path']}: {exc}") |
|
|
| |
| if rec["series_id"] not in split_map: |
| warnings.append(f"record {i}: series {rec['series_id']} has no split") |
|
|
| result = { |
| "total_records": total, |
| "errors": errors[:500], |
| "error_count": len(errors), |
| "warnings": warnings[:200], |
| "warning_count": len(warnings), |
| "passed": len(errors) == 0, |
| } |
| print(f" Validation {'PASSED' if result['passed'] else 'FAILED'}: " |
| f"{result['error_count']} errors, {result['warning_count']} warnings") |
| return result |
|
|
|
|
| |
|
|
| def run_leakage_audit(manifest_path: Path, splits_path: Path) -> dict: |
| print("Running leakage audit …") |
| records = load_manifest(manifest_path) |
| split_map = json.loads(splits_path.read_text()).get("splits", {}) |
| critical, warnings = [], [] |
|
|
| |
| patient_splits: dict[str, set] = defaultdict(set) |
| for r in records: |
| sid = r["series_id"] |
| split = split_map.get(sid, "unassigned") |
| patient_splits[r["patient_id"]].add(split) |
| for pid, splits in patient_splits.items(): |
| real = splits - {"unassigned"} |
| if len(real) > 1: |
| critical.append(f"Patient {pid} spans splits: {sorted(real)}") |
|
|
| |
| hash_records: dict[str, list] = defaultdict(list) |
| for r in records: |
| hash_records[r["sha256"]].append(r) |
| for h, recs in hash_records.items(): |
| split_set = {split_map.get(r["series_id"], "unassigned") for r in recs} - {"unassigned"} |
| if len(split_set) > 1: |
| critical.append(f"Exact duplicate sha256 {h[:12]}… spans splits {sorted(split_set)}") |
| elif len(recs) > 1: |
| warnings.append(f"Duplicate sha256 {h[:12]}… within same split ({len(recs)} copies)") |
|
|
| |
| series_splits: dict[str, set] = defaultdict(set) |
| for r in records: |
| series_splits[r["series_id"]].add(split_map.get(r["series_id"], "unassigned")) |
| for sid, splits in series_splits.items(): |
| real = splits - {"unassigned"} |
| if len(real) > 1: |
| critical.append(f"series_id {sid} spans splits: {sorted(real)}") |
|
|
| result = { |
| "total_records": len(records), |
| "critical": critical[:200], |
| "critical_count": len(critical), |
| "warnings": warnings[:200], |
| "warning_count": len(warnings), |
| "passed": len(critical) == 0, |
| } |
| print(f" Leakage audit {'PASSED' if result['passed'] else 'FAILED'}: " |
| f"{result['critical_count']} critical, {result['warning_count']} warnings") |
| return result |
|
|
|
|
| |
|
|
| def upload_reports(val_result: dict, leakage_result: dict) -> None: |
| print("Uploading reports …") |
| TMP_OUT.mkdir(parents=True, exist_ok=True) |
| api = HfApi() |
|
|
| val_path = TMP_OUT / "validation_lidc_v1.0.0.json" |
| val_path.write_text(json.dumps(val_result, indent=2)) |
| api.upload_file( |
| path_or_fileobj=str(val_path), |
| path_in_repo="reports/validation/lidc_v1.0.0.json", |
| repo_id=REPO_ID, repo_type="dataset", |
| ) |
| print(" validation report uploaded") |
|
|
| leakage_path = TMP_OUT / "leakage_lidc_v1.0.0.json" |
| leakage_path.write_text(json.dumps(leakage_result, indent=2)) |
| api.upload_file( |
| path_or_fileobj=str(leakage_path), |
| path_in_repo="reports/leakage/lidc_v1.0.0.json", |
| repo_id=REPO_ID, repo_type="dataset", |
| ) |
| print(" leakage report uploaded") |
|
|
|
|
| |
|
|
| def main() -> None: |
| if not BUCKET_LIDC.exists(): |
| print(f"ERROR: bucket not mounted at {BUCKET_LIDC}", file=sys.stderr) |
| sys.exit(1) |
|
|
| manifest_path, splits_path = download_inputs() |
| val_result = run_validation(manifest_path, splits_path) |
| leakage_result = run_leakage_audit(manifest_path, splits_path) |
| upload_reports(val_result, leakage_result) |
|
|
| if not val_result["passed"] or not leakage_result["passed"]: |
| print("\nPIPELINE FAILED — check reports before training", file=sys.stderr) |
| sys.exit(1) |
|
|
| print("\nAll checks passed. Dataset is trainable.") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|