| """ |
| audit_leakage.py — ERYON mandatory leakage audit. |
| |
| Checks performed: |
| 1. Patient overlap — no patient_id appears in more than one split |
| 2. Duplicate hashes — exact sha256 duplicates across splits |
| 3. Perceptual hashes — near-duplicate images across splits (pHash distance ≤ 8) |
| 4. Slice leakage — series_id must not span multiple splits |
| |
| Exits with code 1 if critical leakage (patient overlap, cross-split slice) is found. |
| Writes a JSON report to reports/leakage/. |
| |
| Usage: |
| python audit_leakage.py \\ |
| --manifest manifests/lidc/manifest_v1.0.0.jsonl \\ |
| --splits manifests/lidc/splits_v1.0.0.json \\ |
| --out reports/leakage/lidc_v1.0.0.json |
| """ |
|
|
| import argparse |
| import json |
| import sys |
| from collections import defaultdict |
| from pathlib import Path |
|
|
| try: |
| import imagehash |
| from PIL import Image |
| PHASH_AVAILABLE = True |
| except ImportError: |
| PHASH_AVAILABLE = False |
|
|
|
|
| def load_manifest(path: Path) -> list[dict]: |
| return [json.loads(l) for l in path.read_text().splitlines() if l.strip()] |
|
|
|
|
| def audit(manifest_path: Path, splits_path: Path, image_root: Path | None) -> dict: |
| records = load_manifest(manifest_path) |
| splits_js = json.loads(splits_path.read_text()) |
| split_map = splits_js.get("splits", {}) |
|
|
| critical: list[str] = [] |
| warnings: list[str] = [] |
|
|
| |
| patient_splits: dict[str, set] = defaultdict(set) |
| for r in records: |
| sid = r["series_id"] |
| split = split_map.get(sid, r.get("split", "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} appears in multiple splits: {real}") |
|
|
| |
| hash_to_records: dict[str, list] = defaultdict(list) |
| for r in records: |
| hash_to_records[r["sha256"]].append(r) |
| for h, recs in hash_to_records.items(): |
| split_set = {split_map.get(r["series_id"], r.get("split")) for r in recs} |
| if len(split_set) > 1: |
| critical.append(f"Exact duplicate sha256 {h[:12]}… spans splits {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: |
| sid = r["series_id"] |
| series_splits[sid].add(split_map.get(sid, r.get("split", "unassigned"))) |
| for sid, splits in series_splits.items(): |
| real = splits - {"unassigned"} |
| if len(real) > 1: |
| critical.append(f"series_id {sid} spans multiple splits: {real}") |
|
|
| |
| if PHASH_AVAILABLE and image_root is not None: |
| split_phashes: dict[str, list[tuple]] = defaultdict(list) |
| for r in records: |
| img_path = image_root / r["image_path"] |
| if not img_path.exists(): |
| continue |
| try: |
| ph = imagehash.phash(Image.open(img_path)) |
| split = split_map.get(r["series_id"], r.get("split", "unassigned")) |
| split_phashes[split].append((ph, r["image_path"])) |
| except Exception: |
| pass |
|
|
| splits_list = list(split_phashes.keys()) |
| for i, s1 in enumerate(splits_list): |
| for s2 in splits_list[i + 1 :]: |
| for ph1, p1 in split_phashes[s1]: |
| for ph2, p2 in split_phashes[s2]: |
| if ph1 - ph2 <= 8: |
| warnings.append( |
| f"Perceptual near-duplicate across {s1}/{s2}: {p1} ~ {p2}" |
| ) |
|
|
| return { |
| "total_records": len(records), |
| "critical": critical, |
| "warnings": warnings, |
| "passed": len(critical) == 0, |
| } |
|
|
|
|
| def main() -> None: |
| parser = argparse.ArgumentParser() |
| parser.add_argument("--manifest", required=True) |
| parser.add_argument("--splits", required=True) |
| parser.add_argument("--image-root", default=None, help="Root for perceptual hash check (optional)") |
| parser.add_argument("--out", required=True) |
| args = parser.parse_args() |
|
|
| result = audit( |
| manifest_path=Path(args.manifest), |
| splits_path=Path(args.splits), |
| image_root=Path(args.image_root) if args.image_root 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"Leakage audit {status}: {len(result['critical'])} critical, {len(result['warnings'])} warnings") |
| print(f"Report: {out_path}") |
|
|
| if not result["passed"]: |
| for c in result["critical"]: |
| print(f" CRITICAL: {c}", file=sys.stderr) |
| sys.exit(1) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|