File size: 12,722 Bytes
dc096c2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
"""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_<step>.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 <data_dir>/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()