#!/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()