File size: 4,978 Bytes
dc0b89d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
#!/usr/bin/env python3
"""Report and validate SUMI OpenCT collection readiness without network I/O."""

from __future__ import annotations

import argparse
import csv
import json
from pathlib import Path


EXPECTED_DATASETS = {
    "DSB17",
    "LIDC-IDRI",
    "LNDb19",
    "LTRC",
    "LUNA16",
    "MIDRC",
    "NLST",
    "RSNA-STR",
}
MIRROR_ALLOWED = {
    "mirror_allowed_with_attribution",
    "mirror_selected_public_ct_with_attribution",
}


def read_jsonl(path: Path) -> list[dict]:
    if not path.exists():
        return []
    rows: list[dict] = []
    with path.open(encoding="utf-8") as f:
        for line_number, line in enumerate(f, start=1):
            if not line.strip():
                continue
            try:
                value = json.loads(line)
            except json.JSONDecodeError as exc:
                raise RuntimeError(f"Invalid JSON at {path}:{line_number}: {exc}") from exc
            if not isinstance(value, dict):
                raise RuntimeError(f"Expected an object at {path}:{line_number}")
            rows.append(value)
    return rows


def count_csv_rows(path: Path) -> int:
    if not path.exists():
        return 0
    with path.open(newline="", encoding="utf-8") as f:
        return sum(1 for _ in csv.DictReader(f))


def collect_status(root: Path) -> tuple[list[dict], list[str]]:
    registry_path = root / "manifests/source_datasets.csv"
    with registry_path.open(newline="", encoding="utf-8") as f:
        registry = list(csv.DictReader(f))

    errors: list[str] = []
    names = {row.get("dataset", "") for row in registry}
    if names != EXPECTED_DATASETS:
        errors.append(
            f"registry datasets differ: missing={sorted(EXPECTED_DATASETS - names)}, "
            f"unexpected={sorted(names - EXPECTED_DATASETS)}"
        )

    status: list[dict] = []
    for source in registry:
        dataset = source["dataset"]
        planned = int(source["planned_scans"])
        manifest_path = root / f"manifests/{dataset}.jsonl"
        manifest = read_jsonl(manifest_path)
        folders = [str(row.get("folder", "")) for row in manifest]
        source_uids = [str(row.get("source_series_uid", "")) for row in manifest]

        if len(folders) != len(set(folders)):
            errors.append(f"{dataset}: duplicate folder in {manifest_path}")
        if any(not value for value in folders):
            errors.append(f"{dataset}: manifest row missing folder")
        if len(source_uids) != len(set(source_uids)):
            errors.append(f"{dataset}: duplicate source_series_uid in {manifest_path}")
        if any(not value for value in source_uids):
            errors.append(f"{dataset}: manifest row missing source_series_uid")
        if len(manifest) > planned:
            errors.append(f"{dataset}: {len(manifest)} uploads exceed planned count {planned}")

        collector = source.get("collector", "")
        if collector and collector != "none" and not (root / collector).is_file():
            errors.append(f"{dataset}: collector does not exist: {collector}")
        policy = source.get("mirror_policy", "")
        if policy not in MIRROR_ALLOWED and manifest:
            errors.append(f"{dataset}: restricted source has {len(manifest)} uploaded manifest rows")

        selection_path = source.get("required_selection", "")
        selection_rows = count_csv_rows(root / selection_path) if selection_path else None
        status.append(
            {
                "dataset": dataset,
                "planned": planned,
                "uploaded": len(manifest),
                "preparation_status": source.get("preparation_status", ""),
                "mirror_policy": policy,
                "selection_rows": selection_rows,
            }
        )
    return status, errors


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--root", type=Path, default=Path("."))
    parser.add_argument("--json", action="store_true")
    args = parser.parse_args()

    root = args.root.resolve()
    status, errors = collect_status(root)
    if args.json:
        print(json.dumps({"sources": status, "errors": errors}, indent=2, sort_keys=True))
    else:
        print(f"{'dataset':<12} {'planned':>8} {'uploaded':>8}  preparation")
        for row in status:
            selection = row["selection_rows"]
            suffix = f" (selection rows: {selection})" if selection is not None else ""
            print(
                f"{row['dataset']:<12} {row['planned']:>8} {row['uploaded']:>8}  "
                f"{row['preparation_status']}{suffix}"
            )
        print(
            f"{'TOTAL':<12} {sum(row['planned'] for row in status):>8} "
            f"{sum(row['uploaded'] for row in status):>8}"
        )
        print("validation: " + ("OK" if not errors else "FAILED"))
        for error in errors:
            print(f"- {error}")

    if errors:
        raise SystemExit(1)


if __name__ == "__main__":
    main()