"""Rebuild the preprocessed images/masks and the benchmark-plan annotations for any MedVision dataset, from the original public sources. # reproduce what is published (the default) python scripts/gen-annotations/build_dataset.py --data_dir "$MedVision_DATA_DIR" --dataset KiTS23 python scripts/gen-annotations/build_dataset.py --data_dir "$MedVision_DATA_DIR" --all --dry_run # publish a NEW annotation version (maintainers; bump __version__ first) python scripts/gen-annotations/build_dataset.py --data_dir "$MedVision_DATA_DIR" \ --dataset KiTS23 --new-annotation-version This does NOT upload anything. Publishing to HuggingFace is a separate, deliberate step. Prerequisites: see setup-env.sh and README.md in this directory. Only the CURRENT LATEST annotation version can be reproduced from this codebase ------------------------------------------------------------------------------ The generation code changes between annotation versions -- that is *why* the version is bumped. v1.1.0 changed the tumour/lesion cluster-size threshold (200px -> 20px), v1.1.1 corrected the transposed in-plane spacing in the ellipse fit, v1.2.1 pinned float promotion against NEP 50. Running HEAD while naming an older version would emit a file NAMED benchmark_plan_biometry_v1.1.0.json.gz but FILLED with HEAD-era values: a mislabelled artifact colliding with a published name, which is exactly what the annotation-identity policy exists to prevent. So the reproducible set is the per-(dataset, task) latest in _ANNOTATION_INDEX, by construction: any code change that alters output ships with a version bump, so "latest" and "reproducible by HEAD" are the same set. Where they diverge, that divergence IS a bug, and this tool is where it surfaces. To rebuild an older version, check out the git tag that published it and install that src/. The version string is the only identity the data has, and the code that produced it is part of that identity. """ import argparse import ast import os import subprocess import sys sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from dataset_specs import DATASETS # noqa: E402 REPO_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) STAGES = ("download", "segmentation", "detection", "biometry") # --------------------------------------------------------------------- MedVision.py def load_tables(medvision_py): """Read _ANNOTATION_INDEX and _BIOMETRY_FAMILY out of the loader. Parsed, never imported: both are plain dict literals, so ast.literal_eval reads them with no import and no execution. They are deliberately not copied into dataset_specs.py -- a second record of the same fact has no mechanism to stay in sync, and would silently regenerate a superseded version while reporting success. """ tree = ast.parse(open(medvision_py).read()) out = {} for node in tree.body: if isinstance(node, ast.Assign) and getattr(node.targets[0], "id", "") in ( "_ANNOTATION_INDEX", "_BIOMETRY_FAMILY", ): out[node.targets[0].id] = ast.literal_eval(node.value) missing = {"_ANNOTATION_INDEX", "_BIOMETRY_FAMILY"} - set(out) if missing: sys.exit(f"error: {medvision_py} defines no {', '.join(sorted(missing))}") return out["_ANNOTATION_INDEX"], out["_BIOMETRY_FAMILY"] def semver(v): """('1.10.0') -> (1, 10, 0). Compared as a tuple, never as a string: '1.10.0' sorts BELOW '1.9.0' lexicographically, which is the wrong answer.""" return tuple(int(x) for x in v.split(".")) def installed_version(): """The version the planner will stamp when no --annotation_version is passed.""" try: import medvision_ds return medvision_ds.__version__, "installed" except ImportError: path = os.path.join(REPO_ROOT, "src", "medvision_ds", "__version__.py") ns = {} exec(open(path).read(), ns) # noqa: S102 - a one-line literal assignment return ns["__version__"], "repo source (medvision_ds is NOT installed)" def accepts_reorient(step, dataset, family): """Whether preprocess_.py for this dataset has a --reorient2RAS flag. Every segmentation and detection script does. For biometry only the tumour/lesion (fromSeg) family does -- the landmark planner has no such parameter, because its datasets are reoriented by their downloader before landmark indices are derived. """ if step in ("segmentation", "detection"): return True return family.get(dataset) == "fromSeg" # ------------------------------------------------------------------------- commands def build_commands(name, spec, args, index, family): """Return [(stage, argv, plan_path_or_None)] for one dataset.""" datasets_dir = os.path.join(args.data_dir, "Datasets") module = f"medvision_ds.datasets.{spec['pkg']}" cmds = [] if "download" in args.stages: argv = [sys.executable, "-m", f"{module}.{spec['download']}", "-d", datasets_dir, "-n", name] if spec["supports_max_workers"] and args.max_workers: argv += ["--max_workers", str(args.max_workers)] cmds.append(("download", argv, None)) for step in spec["steps"]: if step not in args.stages: continue argv = [sys.executable, "-m", f"{module}.preprocess_{step}", "-d", datasets_dir, "-n", name] if spec["reorient"] == "preprocess" and accepts_reorient(step, name, family): argv.append("--reorient2RAS") if args.use_latest: published = index.get(name, {}).get(step) if not published: sys.exit( f"error: {name}/{step} has no published annotation in " f"_ANNOTATION_INDEX, so there is nothing to reproduce. Use " f"--new-annotation-version to create one." ) version = max(published, key=semver) argv += ["--annotation_version", version] else: # Form (B): pass nothing, so the planner stamps the installed __version__. version = args.new_version cmds.append((step, argv, os.path.join( datasets_dir, name, f"benchmark_plan_{step}_v{version}.json.gz"))) return cmds def preflight(name, spec, args, index, cmds): """Everything that can refuse a run, checked before any of it starts.""" problems = [] for var in spec["requires_env"]: if not os.environ.get(var): problems.append( f"{name}: ${var} is not set; the download will fail. Export it from your " f"environment (never read it from a file inside a script)." ) if not args.use_latest: # Bump check: __version__ must be strictly ABOVE every affected pair's newest # published version. Equal is refused too -- stamping a version that already # exists is an in-place overwrite of published data. for step in spec["steps"]: if step not in args.stages: continue published = index.get(name, {}).get(step) if not published: continue # nothing published for this pair, so no lower bound newest = max(published, key=semver) if semver(args.new_version) <= semver(newest): problems.append( f"{name}/{step} already publishes {newest}, and __version__ is " f"{args.new_version}. Bump src/medvision_ds/__version__.py above " f"{newest}, or drop --new-annotation-version to reproduce {newest}." ) if not args.force: for _stage, _argv, plan in cmds: if plan and os.path.exists(plan): problems.append( f"{name}: {os.path.relpath(plan, args.data_dir)} already exists. " f"Pass --force to overwrite it." ) return problems def run(name, cmds, dry_run): print(f"\n{'=' * 78}\n{name}\n{'=' * 78}") for stage, argv, plan in cmds: print(f" [{stage}] {' '.join(argv)}") if plan: print(f" -> {os.path.basename(plan)}") if dry_run: continue result = subprocess.run(argv) if result.returncode != 0: # Fail fast. The ad-hoc drivers this replaces used # `|| echo "... FAILED (continuing)"`, and a stale FAILED line in a shared # log later misled a waiter script into publishing nothing. sys.exit(f"\nerror: {name} {stage} exited {result.returncode}; stopping.") def main(): p = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter ) p.add_argument("--data_dir", required=True, help="MedVision_DATA_DIR; datasets are built under /Datasets/") p.add_argument("--dataset", action="append", metavar="NAME", help="dataset to build (repeatable)") p.add_argument("--all", action="store_true", help="build every dataset") p.add_argument("--steps", default=",".join(STAGES), help=f"comma-separated subset of {','.join(STAGES)} (default: all)") p.add_argument("--max_workers", type=int, default=None, help="parallelism for downloads that support it") p.add_argument("--force", action="store_true", help="overwrite an existing benchmark plan file") p.add_argument("--dry_run", action="store_true", help="print the commands that would run, then exit") p.add_argument("--medvision_py", default=os.path.join(REPO_ROOT, "MedVision.py"), help="loader to read _ANNOTATION_INDEX / _BIOMETRY_FAMILY from") # Two option strings, ONE dest. The contradictory state is unrepresentable rather # than detected-and-rejected: there is no combination of these flags that yields # "both", so no mutual-exclusion check is needed. Same semantics as # argparse.BooleanOptionalAction, but the negative branch gets a name that says what # it does rather than what it is not. p.add_argument("--latest", dest="use_latest", action="store_true", default=True, help="reproduce the newest published annotation of each " "(dataset, task). Default.") p.add_argument("--new-annotation-version", dest="use_latest", action="store_false", help="stamp the installed medvision_ds __version__ instead. Use ONLY " "when publishing a new annotation version; requires __version__ " "to have been bumped above every existing annotation.") args = p.parse_args() names = sorted(DATASETS) if args.all else (args.dataset or []) if not names: p.error("pass --dataset NAME (repeatable) or --all") unknown = [n for n in names if n not in DATASETS] if unknown: p.error(f"unknown dataset(s): {', '.join(unknown)}. " f"Known: {', '.join(sorted(DATASETS))}") args.stages = [s.strip() for s in args.steps.split(",") if s.strip()] bad = [s for s in args.stages if s not in STAGES] if bad: p.error(f"unknown step(s): {', '.join(bad)}. Known: {', '.join(STAGES)}") args.data_dir = os.path.abspath(os.path.expanduser(args.data_dir)) index, family = load_tables(args.medvision_py) args.new_version = None if not args.use_latest: args.new_version, source = installed_version() print(f"minting annotation version {args.new_version} (from {source})") all_cmds, problems = {}, [] for name in names: cmds = build_commands(name, DATASETS[name], args, index, family) all_cmds[name] = cmds problems += preflight(name, DATASETS[name], args, index, cmds) if problems: # A dry run is "show me what would happen", so it reports the blockers and still # prints the commands -- being unable to preview a run because of a missing token # would defeat the point. A real run stops here. header = "would refuse to run:" if args.dry_run else "refusing to run:" print(f"{header}\n", file=sys.stderr) for problem in problems: print(f" - {problem}", file=sys.stderr) print(file=sys.stderr) if not args.dry_run: sys.exit(1) for name in names: run(name, all_cmds[name], args.dry_run) print(f"\n{'dry run: ' if args.dry_run else ''}{len(names)} dataset(s) " f"{'listed' if args.dry_run else 'built'}.") if __name__ == "__main__": main()