File size: 3,672 Bytes
6bcf82b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
"""
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()