Chucks90 commited on
Commit
ffc7d60
·
verified ·
1 Parent(s): 59099ed

Upload scripts/run_validation_pipeline.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. scripts/run_validation_pipeline.py +218 -0
scripts/run_validation_pipeline.py ADDED
@@ -0,0 +1,218 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ run_validation_pipeline.py — ERYON validation + leakage audit pipeline.
3
+
4
+ Runs inside an HF Job with eryon-datasets bucket mounted at /mnt.
5
+ Steps:
6
+ 1. Download manifest + splits from eryon-data-pipelines repo
7
+ 2. Validate: required fields, sha256 checksums, split completeness
8
+ 3. Leakage audit: patient overlap, duplicate hashes, slice leakage
9
+ 4. Upload reports to eryon-data-pipelines repo
10
+
11
+ Corruption scan (PIL open) is skipped by default — files were just written
12
+ and never transferred across a network boundary. Set CORRUPTION_SCAN=True
13
+ to enable it (adds ~2hr on cpu-basic).
14
+
15
+ Usage:
16
+ python run_validation_pipeline.py
17
+ """
18
+
19
+ import sys
20
+ import json
21
+ import hashlib
22
+ from pathlib import Path
23
+ from collections import defaultdict
24
+
25
+ from huggingface_hub import HfApi, hf_hub_download
26
+
27
+ # ── Config ────────────────────────────────────────────────────────────────────
28
+ BUCKET_LIDC = Path("/mnt/raw/lidc")
29
+ TMP_OUT = Path("/tmp/validation_output")
30
+ REPO_ID = "Chucks90/eryon-data-pipelines"
31
+ CORRUPTION_SCAN = False # set True to enable PIL open on every PNG
32
+
33
+ REQUIRED_FIELDS = {
34
+ "patient_id", "study_id", "series_id", "image_path",
35
+ "modality", "split", "label", "dataset_version",
36
+ "preprocessing_version", "sha256",
37
+ }
38
+
39
+ # ── Helpers ───────────────────────────────────────────────────────────────────
40
+
41
+ def download_inputs() -> tuple[Path, Path]:
42
+ print("Downloading manifest + splits from repo …")
43
+ manifest_path = Path(hf_hub_download(
44
+ REPO_ID, "manifests/lidc/manifest_v1.0.0.jsonl",
45
+ repo_type="dataset", local_dir="/tmp", force_download=True,
46
+ ))
47
+ splits_path = Path(hf_hub_download(
48
+ REPO_ID, "manifests/lidc/splits_v1.0.0.json",
49
+ repo_type="dataset", local_dir="/tmp", force_download=True,
50
+ ))
51
+ return manifest_path, splits_path
52
+
53
+
54
+ def load_manifest(path: Path) -> list[dict]:
55
+ return [json.loads(l) for l in path.read_text().splitlines() if l.strip()]
56
+
57
+
58
+ def sha256_file(path: Path) -> str:
59
+ h = hashlib.sha256()
60
+ with open(path, "rb") as f:
61
+ for chunk in iter(lambda: f.read(65536), b""):
62
+ h.update(chunk)
63
+ return h.hexdigest()
64
+
65
+
66
+ # ── Step 1: Validation ────────────────────────────────────────────────────────
67
+
68
+ def run_validation(manifest_path: Path, splits_path: Path) -> dict:
69
+ print("Running validation …")
70
+ records = load_manifest(manifest_path)
71
+ split_map = json.loads(splits_path.read_text()).get("splits", {})
72
+ errors, warnings = [], []
73
+ total = len(records)
74
+
75
+ for i, rec in enumerate(records):
76
+ if i % 20000 == 0:
77
+ print(f" validating {i}/{total} …")
78
+
79
+ missing = REQUIRED_FIELDS - rec.keys()
80
+ if missing:
81
+ errors.append(f"record {i}: missing fields {missing}")
82
+ continue
83
+
84
+ img_path = BUCKET_LIDC / rec["image_path"]
85
+ if not img_path.exists():
86
+ errors.append(f"record {i}: file not found {rec['image_path']}")
87
+ continue
88
+
89
+ # sha256 verification
90
+ actual = sha256_file(img_path)
91
+ if actual != rec["sha256"]:
92
+ errors.append(f"record {i}: sha256 mismatch {rec['image_path']}")
93
+
94
+ # corruption scan (optional)
95
+ if CORRUPTION_SCAN:
96
+ try:
97
+ from PIL import Image
98
+ with Image.open(img_path) as img:
99
+ img.verify()
100
+ except Exception as exc:
101
+ errors.append(f"record {i}: corrupt image {rec['image_path']}: {exc}")
102
+
103
+ # split assignment
104
+ if rec["series_id"] not in split_map:
105
+ warnings.append(f"record {i}: series {rec['series_id']} has no split")
106
+
107
+ result = {
108
+ "total_records": total,
109
+ "errors": errors[:500], # cap at 500 to keep report readable
110
+ "error_count": len(errors),
111
+ "warnings": warnings[:200],
112
+ "warning_count": len(warnings),
113
+ "passed": len(errors) == 0,
114
+ }
115
+ print(f" Validation {'PASSED' if result['passed'] else 'FAILED'}: "
116
+ f"{result['error_count']} errors, {result['warning_count']} warnings")
117
+ return result
118
+
119
+
120
+ # ── Step 2: Leakage audit ─────────────────────────────────────────────────────
121
+
122
+ def run_leakage_audit(manifest_path: Path, splits_path: Path) -> dict:
123
+ print("Running leakage audit …")
124
+ records = load_manifest(manifest_path)
125
+ split_map = json.loads(splits_path.read_text()).get("splits", {})
126
+ critical, warnings = [], []
127
+
128
+ # patient overlap across splits
129
+ patient_splits: dict[str, set] = defaultdict(set)
130
+ for r in records:
131
+ sid = r["series_id"]
132
+ split = split_map.get(sid, "unassigned")
133
+ patient_splits[r["patient_id"]].add(split)
134
+ for pid, splits in patient_splits.items():
135
+ real = splits - {"unassigned"}
136
+ if len(real) > 1:
137
+ critical.append(f"Patient {pid} spans splits: {sorted(real)}")
138
+
139
+ # exact hash duplicates across splits
140
+ hash_records: dict[str, list] = defaultdict(list)
141
+ for r in records:
142
+ hash_records[r["sha256"]].append(r)
143
+ for h, recs in hash_records.items():
144
+ split_set = {split_map.get(r["series_id"], "unassigned") for r in recs} - {"unassigned"}
145
+ if len(split_set) > 1:
146
+ critical.append(f"Exact duplicate sha256 {h[:12]}… spans splits {sorted(split_set)}")
147
+ elif len(recs) > 1:
148
+ warnings.append(f"Duplicate sha256 {h[:12]}… within same split ({len(recs)} copies)")
149
+
150
+ # slice leakage — series_id in multiple splits
151
+ series_splits: dict[str, set] = defaultdict(set)
152
+ for r in records:
153
+ series_splits[r["series_id"]].add(split_map.get(r["series_id"], "unassigned"))
154
+ for sid, splits in series_splits.items():
155
+ real = splits - {"unassigned"}
156
+ if len(real) > 1:
157
+ critical.append(f"series_id {sid} spans splits: {sorted(real)}")
158
+
159
+ result = {
160
+ "total_records": len(records),
161
+ "critical": critical[:200],
162
+ "critical_count": len(critical),
163
+ "warnings": warnings[:200],
164
+ "warning_count": len(warnings),
165
+ "passed": len(critical) == 0,
166
+ }
167
+ print(f" Leakage audit {'PASSED' if result['passed'] else 'FAILED'}: "
168
+ f"{result['critical_count']} critical, {result['warning_count']} warnings")
169
+ return result
170
+
171
+
172
+ # ── Step 3: Upload reports ────────────────────────────────────────────────────
173
+
174
+ def upload_reports(val_result: dict, leakage_result: dict) -> None:
175
+ print("Uploading reports …")
176
+ TMP_OUT.mkdir(parents=True, exist_ok=True)
177
+ api = HfApi()
178
+
179
+ val_path = TMP_OUT / "validation_lidc_v1.0.0.json"
180
+ val_path.write_text(json.dumps(val_result, indent=2))
181
+ api.upload_file(
182
+ path_or_fileobj=str(val_path),
183
+ path_in_repo="reports/validation/lidc_v1.0.0.json",
184
+ repo_id=REPO_ID, repo_type="dataset",
185
+ )
186
+ print(" validation report uploaded")
187
+
188
+ leakage_path = TMP_OUT / "leakage_lidc_v1.0.0.json"
189
+ leakage_path.write_text(json.dumps(leakage_result, indent=2))
190
+ api.upload_file(
191
+ path_or_fileobj=str(leakage_path),
192
+ path_in_repo="reports/leakage/lidc_v1.0.0.json",
193
+ repo_id=REPO_ID, repo_type="dataset",
194
+ )
195
+ print(" leakage report uploaded")
196
+
197
+
198
+ # ── Main ──────────────────────────────────────────────────────────────────────
199
+
200
+ def main() -> None:
201
+ if not BUCKET_LIDC.exists():
202
+ print(f"ERROR: bucket not mounted at {BUCKET_LIDC}", file=sys.stderr)
203
+ sys.exit(1)
204
+
205
+ manifest_path, splits_path = download_inputs()
206
+ val_result = run_validation(manifest_path, splits_path)
207
+ leakage_result = run_leakage_audit(manifest_path, splits_path)
208
+ upload_reports(val_result, leakage_result)
209
+
210
+ if not val_result["passed"] or not leakage_result["passed"]:
211
+ print("\nPIPELINE FAILED — check reports before training", file=sys.stderr)
212
+ sys.exit(1)
213
+
214
+ print("\nAll checks passed. Dataset is trainable.")
215
+
216
+
217
+ if __name__ == "__main__":
218
+ main()