YongchengYAO commited on
Commit
f034ba2
·
1 Parent(s): 9f6c83c

[src] fix: fetch QC figures on every load and track them per annotation version

Browse files

The fetch used to sit in _split_generators, which made it unreachable after a
config's first build: datasets consults the Arrow cache after _info() and skips
_split_generators on a hit, so a machine whose figures had gone stale could not
obtain the current ones by any means short of deleting that cache.

QC figures:
- move the fetch into _ensure_qc_figures and call it from BOTH _info() and
_split_generators. _info() is the only hook a warm-cache load reaches, since
DatasetBuilder.__init__ runs it before the cache directory is consulted --
the same reasoning that put the paused-annotation gate there
- defer in _info() while the dataset's files are absent, so a first install is
served by the _split_generators call site instead. That one runs after step
3.3, whose reorientation pass globs "<dataset_dir>/**/*.nii.gz" recursively and
would otherwise walk hundreds of thousands of freshly extracted PNGs per
dataset for nothing. The two conditions are complementary: a warm cache skips
_split_generators, but having been built at all implies the files are on disk
- memoise per (data root, dataset, requested version): _info() runs once per
config, a sweep constructs hundreds of them over a handful of datasets, and an
annotation-version bump fires both call sites, since planner_version changes
and the config_id is therefore cold
- not covered, and deliberately so: a data directory deleted while its HF cache
is kept. That state already yields rows whose image_file paths do not exist,
and MedVision_FORCE_DOWNLOAD_DATA=True rebuilds out of it
- record "qc_figures_<dataset>" in .downloaded_datasets.json as the biometry
annotation version the figures belong to rather than a bare true, so a release
that regenerates a dataset re-fetches its figures while one that leaves the
dataset alone re-pulls nothing; keying on the release version instead would
invalidate all 295 GB on every release
- resolve the wanted version from the dataset's declared biometry versions --
figures are generated with the biometry plans and their directories carry that
version (Landmarks-Label2-fig-v1.4.0) -- whatever task type the config loads
- fall back to reading those directories when the tracker names no usable
version, which is every install predating v1.4.0: the figures shipped inside
Datasets/<name>.zip then, so such a machine already holds the set but never ran
a figure download to record it
- treat a legacy `true` as "version unknown" so it neither forces a blanket
re-pull nor blocks a genuine refresh; MedVision_FORCE_DOWNLOAD_DATA still
overrides the skip
- keep _figure_versions bounded: os.scandir over only the two directory levels
the archives use, emptiness tested by first entry, so a directory holding
hundreds of thousands of PNGs is never enumerated; an empty one does not count,
since that is the shape a crashed extract leaves behind
- five datasets predate the -fig-v{X} naming (AFIDs, Ceph-Biometrics-400,
FeTA24, PDDCA, VerSe); for them presence is the only on-disk signal, and the
tracker entry is what still lets a later release invalidate them
- keep the directory regex identical to FIG_COMPONENT in
scripts/split_qc_figures.py, which decided what went into those archives
- wrap both call sites in _try_ensure_qc_figures so a Hub failure warns instead
of raising. _info() runs inside DatasetBuilder.__init__, so an exception there
blocked even a fully cached local dataset from loading. Swallowing is safe here
in a way it is not at step 3.2: the tracker entry is written last and only on a
clean pass, so a failure leaves it unwritten and the next load retries, rather
than stamping a marker later runs would trust
- create the data root explicitly rather than relying on filelock to make the
parent of the lock files it opens, which is not a documented guarantee

Configs:
- add the 8 DEEP-PSMA and 4 LNQ2023 tumour/lesion sagittal+coronal configs; every
other T/L dataset already published all three planes

Files changed (1) hide show
  1. MedVision.py +464 -88
MedVision.py CHANGED
@@ -452,6 +452,107 @@ def _discover_versions(dataset_dir, kind):
452
  return sorted(found, key=_version_tuple)
453
 
454
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
455
  def _check_biometry_family(dataset_name, task_type):
456
  """Fail loudly if a dataset's biometry plan could be the wrong family."""
457
  if _PLAN_KIND_BY_TASKTYPE.get(task_type) != "biometry":
@@ -786,6 +887,189 @@ def _enforce_release_ack(planner_version, latest_version, ack_value=None,
786
  )
787
 
788
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
789
  class MedVisionConfig(BuilderConfig):
790
  """BuilderConfig for MedVision."""
791
 
@@ -9660,6 +9944,46 @@ class MedVision(GeneratorBasedBuilder):
9660
  split="test",
9661
  ),
9662
  # DEEP-PSMA:Tumor-Lesion-Size:Task01
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9663
  MedVisionConfig(
9664
  name="DEEP-PSMA_TumorLesionSize_Task01_Axial_Train",
9665
  dataset_name="DEEP-PSMA",
@@ -9681,6 +10005,46 @@ class MedVision(GeneratorBasedBuilder):
9681
  split="test",
9682
  ),
9683
  # DEEP-PSMA:Tumor-Lesion-Size:Task02
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9684
  MedVisionConfig(
9685
  name="DEEP-PSMA_TumorLesionSize_Task02_Axial_Train",
9686
  dataset_name="DEEP-PSMA",
@@ -10007,6 +10371,46 @@ class MedVision(GeneratorBasedBuilder):
10007
  split="test",
10008
  ),
10009
  # LNQ2023:Tumor-Lesion-Size:Task01
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10010
  MedVisionConfig(
10011
  name="LNQ2023_TumorLesionSize_Task01_Axial_Train",
10012
  dataset_name="LNQ2023",
@@ -11184,6 +11588,56 @@ class MedVision(GeneratorBasedBuilder):
11184
  _paused_versions(self.config.dataset_name, _kind),
11185
  )
11186
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11187
  # Define dataset information including feature schema
11188
  dataset_description = f"You are using the configuration <{self.config.name}> of the <{self.config.dataset_name}> dataset."
11189
  return DatasetInfo(
@@ -11592,96 +12046,18 @@ class MedVision(GeneratorBasedBuilder):
11592
  _discover_versions(dataset_dir, _kind),
11593
  )
11594
 
11595
- # 3.5 QC figures — opt-in, off by default.
11596
- #
11597
- # Until v1.4.0 the per-slice QC figures shipped inside Datasets/<name>.zip.
11598
- # They are ~99% of that payload 298 GB of PNG against 3 GB of annotation —
11599
- # nothing in this loader reads them, and they pushed BraTS24.zip to 72.6 GB
11600
- # and MSD.zip to 51.4 GB, past HuggingFace's 50 GB per-file limit. That is a
11601
- # hard publish failure (HTTP 422), not merely a slow download. The figures
11602
- # now ship as Datasets/<name>_fig.zip, or <name>_fig.partNN.zip where a
11603
- # single archive would again clear 50 GB.
11604
- #
11605
- # The archives carry the SAME arcnames the figures had inside the dataset
11606
- # archive, so restoring them is the same extractall into the same root: every
11607
- # figure lands back at the path it used to occupy. Nothing is relocated
11608
- # afterwards, so there is no path mapping here that can drift out of step
11609
- # with whatever wrote the archives. Shards are independent zips, not `zip -s`
11610
- # volumes, so they extract in any order and a missing one costs only its own
11611
- # figures.
11612
- #
11613
- # This sits OUTSIDE the `_needs_download` block deliberately. A user who sets
11614
- # the flag on a machine whose annotations are already present takes the
11615
- # "using existing dataset" branch above, and would otherwise never get the
11616
- # figures at all.
11617
  if download_qc_figures:
11618
- _fig_lock_file = os.path.join(
11619
- MedVision_data_dir, f".{dataset_name}_fig.zip.lock"
11620
  )
11621
- with FileLock(_fig_lock_file):
11622
- # Re-read the tracker inside the lock instead of trusting the copy
11623
- # loaded at entry: a sibling config of the same dataset may have
11624
- # fetched the figures while this process waited. Lock order stays
11625
- # zip-lock -> tracker-lock, matching step 3.1, so it cannot invert.
11626
- _figs_present = False
11627
- with FileLock(dataset_cache_lock_file):
11628
- if os.path.exists(dataset_cache_file):
11629
- try:
11630
- with open(dataset_cache_file, "r") as f:
11631
- _figs_present = bool(
11632
- json.load(f).get(f"qc_figures_{dataset_name}")
11633
- )
11634
- except Exception:
11635
- _figs_present = False
11636
-
11637
- if _figs_present and not force_download_data:
11638
- logger.info(
11639
- f" - QC figures for {dataset_name} already on disk; skipping"
11640
- )
11641
- else:
11642
- logger.info(f"Downloading QC figures for {dataset_name}...")
11643
- _datasets_root = os.path.join(MedVision_data_dir, "Datasets")
11644
- snapshot_download(
11645
- repo_id="YongchengYAO/MedVision",
11646
- repo_type="dataset",
11647
- allow_patterns=[
11648
- f"Datasets/{dataset_name}_fig.zip",
11649
- f"Datasets/{dataset_name}_fig.part*.zip",
11650
- ],
11651
- local_dir=MedVision_data_dir,
11652
- max_workers=self.config.num_proc,
11653
- )
11654
- _fig_zips = sorted(
11655
- glob.glob(
11656
- os.path.join(_datasets_root, f"{dataset_name}_fig.zip")
11657
- )
11658
- + glob.glob(
11659
- os.path.join(
11660
- _datasets_root, f"{dataset_name}_fig.part*.zip"
11661
- )
11662
- )
11663
- )
11664
- # Roughly half the datasets have no figures at all. Record the
11665
- # attempt anyway so a figure-less dataset does not re-query the
11666
- # Hub on every single load; MedVision_FORCE_DOWNLOAD_DATA is the
11667
- # way back if figures are published for it later.
11668
- if not _fig_zips:
11669
- logger.info(
11670
- f" - No QC figures are published for {dataset_name}"
11671
- )
11672
- else:
11673
- for _fig_zip in _fig_zips:
11674
- with zipfile.ZipFile(_fig_zip, "r") as zip_ref:
11675
- zip_ref.extractall(_datasets_root)
11676
- os.remove(_fig_zip)
11677
- logger.info(
11678
- f" - QC figures restored to {dataset_dir} from "
11679
- f"{len(_fig_zips)} archive(s)"
11680
- )
11681
- # Written last, and only on a clean pass: a crash mid-extract
11682
- # leaves the flag unset, so the next load redoes the whole
11683
- # download and extractall overwrites whatever landed.
11684
- _update_download_status(f"qc_figures_{dataset_name}", True)
11685
 
11686
  # 4. Get the benchmark planner file - this is config specific but should use existing files if possible
11687
  # NOTE: MUST NOT move the import to the front, as the "medvision_ds" package may not be installed yet at the beginning
 
452
  return sorted(found, key=_version_tuple)
453
 
454
 
455
+ # A path COMPONENT that is a QC-figure directory: "Landmarks-Label1-fig-v1.4.0",
456
+ # "Landmarks-fig", "Landmarks-fig-w-projection". Kept identical to FIG_COMPONENT
457
+ # in scripts/split_qc_figures.py, which is what decided the CONTENTS of the _fig
458
+ # archives: a probe that disagreed with the splitter would either call a dataset
459
+ # "already has figures" on directories the archives never carried, or miss the
460
+ # ones they did. The leading hyphen is what keeps this off innocent names --
461
+ # "config" contains "fig" but not "-fig".
462
+ _FIG_COMPONENT = re.compile(r"-fig(?:-|$)")
463
+
464
+ # The annotation version a figure directory belongs to. Figures are generated
465
+ # alongside the biometry plans and carry the same version, so
466
+ # "Landmarks-Label2-fig-v1.4.0" holds the figures for biometry v1.4.0. Five
467
+ # datasets (AFIDs, Ceph-Biometrics-400, FeTA24, PDDCA, VerSe) predate the
468
+ # convention and have only unversioned directories; they are handled separately
469
+ # rather than being forced into it.
470
+ _FIG_VERSION = re.compile(r"-fig-v(\d+\.\d+\.\d+)$")
471
+
472
+
473
+ def _figure_versions(dataset_dir):
474
+ """QC-figure state on disk: (annotation versions present, any unversioned dir).
475
+
476
+ Answers a different question from the tracker's qc_figures_<name> key. The
477
+ tracker records which version was fetched HERE; this records what is actually
478
+ on disk, however it arrived. Only the second one covers an install made before
479
+ v1.4.0, when the figures shipped INSIDE Datasets/<name>.zip: such a machine
480
+ holds figures already, yet no figure download ever ran on it, so the key
481
+ cannot exist and the tracker alone would re-pull the entire set.
482
+
483
+ Bounded on purpose. Only the two directory levels the archives use are
484
+ scanned - <dataset>/<figdir> and <dataset>/<subset>/<figdir>, the latter for
485
+ the subset-bearing datasets (BraTS24/BraTS24-GLI/...). os.scandir, not glob:
486
+ glob would stat every sibling of every Images/ tree on the way past, and the
487
+ emptiness test stops at the first entry so a directory holding hundreds of
488
+ thousands of PNGs is never enumerated.
489
+
490
+ A figure directory that exists but is EMPTY does not count. That is the shape
491
+ a crashed extract leaves behind, and treating it as present would suppress
492
+ the retry forever. A half-filled one still counts - the same limitation the
493
+ tracker has always had, since it is written only after a clean pass and a
494
+ partial extract is indistinguishable from a complete one without a manifest.
495
+ """
496
+
497
+ def _subdirs(path):
498
+ try:
499
+ with os.scandir(path) as it:
500
+ return [e for e in it if e.is_dir()]
501
+ except OSError:
502
+ return []
503
+
504
+ def _nonempty(path):
505
+ try:
506
+ with os.scandir(path) as it:
507
+ return any(True for _ in it)
508
+ except OSError:
509
+ return False
510
+
511
+ versions, unversioned = set(), False
512
+
513
+ def _record(name, path):
514
+ nonlocal unversioned
515
+ if not _nonempty(path):
516
+ return
517
+ match = _FIG_VERSION.search(name)
518
+ if match:
519
+ versions.add(match.group(1))
520
+ else:
521
+ unversioned = True
522
+
523
+ for _lvl1 in _subdirs(dataset_dir):
524
+ if _FIG_COMPONENT.search(_lvl1.name):
525
+ _record(_lvl1.name, _lvl1.path)
526
+ else:
527
+ for _lvl2 in _subdirs(_lvl1.path):
528
+ if _FIG_COMPONENT.search(_lvl2.name):
529
+ _record(_lvl2.name, _lvl2.path)
530
+ return versions, unversioned
531
+
532
+
533
+ def _figures_current(dataset_dir, target):
534
+ """Whether the figures on disk cover the annotation version being loaded.
535
+
536
+ `target` is the biometry version this request resolves to - figures track the
537
+ biometry plans, so that is the only version that can be asked about. A
538
+ dataset that publishes no biometry has no figures either, which is `target is
539
+ None` and is decided by the caller.
540
+
541
+ Exact membership, not ">=": the figure archive carries every version's
542
+ directories at once, so holding v1.4.0 but not the v1.2.0 a pin asked for
543
+ means the extract is incomplete, and re-fetching is the right answer.
544
+
545
+ The unversioned fallback exists for the five datasets whose figures predate
546
+ the "-fig-v{X}" convention. For them presence is the only signal available;
547
+ the tracker entry written alongside is what lets a later release still
548
+ invalidate them.
549
+ """
550
+ versions, unversioned = _figure_versions(dataset_dir)
551
+ if versions:
552
+ return target in versions
553
+ return unversioned
554
+
555
+
556
  def _check_biometry_family(dataset_name, task_type):
557
  """Fail loudly if a dataset's biometry plan could be the wrong family."""
558
  if _PLAN_KIND_BY_TASKTYPE.get(task_type) != "biometry":
 
887
  )
888
 
889
 
890
+ # QC figures already handled in THIS process, keyed by (data root, dataset,
891
+ # requested version). _info() runs once per config and a sweep constructs
892
+ # hundreds of them, all resolving to a handful of datasets; without this the
893
+ # directory scan and tracker read repeat for every one of them.
894
+ _QC_FIGURES_DONE = set()
895
+
896
+
897
+ def _tracker_read(data_dir, key):
898
+ """One key out of .downloaded_datasets.json, or None."""
899
+ path = os.path.join(data_dir, ".downloaded_datasets.json")
900
+ with FileLock(path + ".lock"):
901
+ if os.path.exists(path):
902
+ try:
903
+ with open(path, "r") as f:
904
+ return json.load(f).get(key)
905
+ except Exception:
906
+ return None
907
+ return None
908
+
909
+
910
+ def _tracker_write(data_dir, key, value):
911
+ """Set one key in .downloaded_datasets.json, preserving the rest."""
912
+ path = os.path.join(data_dir, ".downloaded_datasets.json")
913
+ with FileLock(path + ".lock"):
914
+ current = {}
915
+ if os.path.exists(path):
916
+ try:
917
+ with open(path, "r") as f:
918
+ current = json.load(f)
919
+ except Exception:
920
+ current = {}
921
+ current[key] = value
922
+ with open(path, "w") as f:
923
+ json.dump(current, f)
924
+
925
+
926
+ def _try_ensure_qc_figures(dataset_name, requested, data_dir, num_proc):
927
+ """_ensure_qc_figures, but a failure warns instead of aborting the load.
928
+
929
+ The figures are review material -- nothing in this loader reads them and no
930
+ task needs them -- so a transient Hub error or a half-written archive must not
931
+ take down a dataset that is otherwise fine. It would otherwise do exactly
932
+ that: _info() runs inside DatasetBuilder.__init__, so raising here blocks even
933
+ a fully cached local dataset from loading at all.
934
+
935
+ Swallowing is safe here in a way it is NOT at step 3.2, which deliberately
936
+ lets failures out. That one guards the completion marker: a swallowed error
937
+ there would stamp "installed" onto a dataset with no images, and every later
938
+ run would trust it. Here the tracker entry is written last and only on a clean
939
+ pass, so a failure simply leaves it unwritten and the next load retries.
940
+ """
941
+ try:
942
+ _ensure_qc_figures(dataset_name, requested, data_dir, num_proc)
943
+ except Exception as exc:
944
+ logger.warning(
945
+ "QC figures for %s could not be fetched (%s: %s). The dataset itself "
946
+ "is unaffected; the next load retries. Set "
947
+ "MedVision_DOWNLOAD_QC_FIGURES=False to stop trying.",
948
+ dataset_name, type(exc).__name__, exc,
949
+ )
950
+
951
+
952
+ def _ensure_qc_figures(dataset_name, requested, data_dir, num_proc):
953
+ """Fetch the per-slice QC figures for one dataset, if they are not current.
954
+
955
+ Called from _info(), not from _split_generators: datasets consults the Arrow
956
+ cache after _info() and short-circuits _split_generators when it hits, so a
957
+ fetch placed there runs on a config's first build and never again. _info()
958
+ runs on every load, warm cache or cold.
959
+
960
+ Until v1.4.0 the figures shipped inside Datasets/<name>.zip. They are ~99% of
961
+ that payload -- 298 GB of PNG against 3 GB of annotation -- nothing in this
962
+ loader reads them, and they pushed BraTS24.zip to 72.6 GB and MSD.zip to
963
+ 51.4 GB, past HuggingFace's 50 GB per-file limit, which is a hard publish
964
+ failure (HTTP 422). They now ship as Datasets/<name>_fig.zip, or
965
+ <name>_fig.partNN.zip where a single archive would again clear 50 GB.
966
+
967
+ The archives carry the SAME arcnames the figures had inside the dataset
968
+ archive, so restoring them is the same extractall into the same root: every
969
+ figure lands back at the path it used to occupy. Shards are independent zips,
970
+ not `zip -s` volumes, so they extract in any order and a missing one costs
971
+ only its own figures.
972
+ """
973
+ _memo = (data_dir, dataset_name, requested)
974
+ if _memo in _QC_FIGURES_DONE:
975
+ return
976
+ force = (
977
+ os.environ.get("MedVision_FORCE_DOWNLOAD_DATA", "False").lower() == "true"
978
+ )
979
+ dataset_dir = os.path.join(data_dir, "Datasets", dataset_name)
980
+ # _split_generators creates the data root, but this can run before it -- and
981
+ # from _info(), which runs before _split_generators exists to be reached at
982
+ # all. The locks below are created INSIDE data_dir, and filelock only happens
983
+ # to make their parents; that is not a documented guarantee, so do not depend
984
+ # on the version installed.
985
+ os.makedirs(data_dir, exist_ok=True)
986
+
987
+ # Datasets/<name>_fig.zip is ONE shared path per dataset and HF's builder lock
988
+ # is per CONFIG, so two configs of one dataset would otherwise download the
989
+ # same gigabytes twice into the same staging path and race at os.remove.
990
+ # Lock order is always zip-lock -> tracker-lock, matching step 3.1.
991
+ with FileLock(os.path.join(data_dir, f".{dataset_name}_fig.zip.lock")):
992
+ _tracked = _tracker_read(data_dir, f"qc_figures_{dataset_name}")
993
+
994
+ # Which figures this request wants. Figures are generated with the
995
+ # biometry plans and carry their version, so the biometry resolution is
996
+ # what decides whether what is on disk is current -- whatever task type
997
+ # the config loads. Resolved per DATASET, exactly as annotations are: a
998
+ # release that did not regenerate this dataset leaves the version
999
+ # unchanged and must not invalidate its figures. Keying on the release
1000
+ # version instead would re-pull all 295 GB on every release.
1001
+ target = _resolve(_declared_versions(dataset_name, "biometry"), requested)
1002
+
1003
+ if target is None:
1004
+ # No biometry annotations, so no QC figures are published for this
1005
+ # dataset. Any truthy entry means the Hub was already asked; keep
1006
+ # taking that answer rather than re-querying on every load.
1007
+ current = bool(_tracked)
1008
+ else:
1009
+ # The tracker settles it only when it names a version at least as new
1010
+ # as the one wanted. A legacy `true` names none, so it falls through
1011
+ # to the disk -- which is version-aware, and so can still skip the
1012
+ # download when the figures really are there. That keeps the
1013
+ # pre-v1.4.0 installs (figures shipped inside Datasets/<name>.zip, no
1014
+ # key ever written) from re-pulling a set they already hold.
1015
+ current = (
1016
+ _is_version(_tracked)
1017
+ and _version_tuple(_tracked) >= _version_tuple(target)
1018
+ ) or _figures_current(dataset_dir, target)
1019
+
1020
+ stamp = target if target is not None else True
1021
+
1022
+ if current and not force:
1023
+ logger.info(
1024
+ " - QC figures for %s already cover annotation v%s; skipping",
1025
+ dataset_name, target,
1026
+ )
1027
+ if _tracked != stamp:
1028
+ _tracker_write(data_dir, f"qc_figures_{dataset_name}", stamp)
1029
+ _QC_FIGURES_DONE.add(_memo)
1030
+ return
1031
+
1032
+ logger.info("Downloading QC figures for %s...", dataset_name)
1033
+ _datasets_root = os.path.join(data_dir, "Datasets")
1034
+ snapshot_download(
1035
+ repo_id="YongchengYAO/MedVision",
1036
+ repo_type="dataset",
1037
+ allow_patterns=[
1038
+ f"Datasets/{dataset_name}_fig.zip",
1039
+ f"Datasets/{dataset_name}_fig.part*.zip",
1040
+ ],
1041
+ local_dir=data_dir,
1042
+ max_workers=num_proc,
1043
+ )
1044
+ _fig_zips = sorted(
1045
+ glob.glob(os.path.join(_datasets_root, f"{dataset_name}_fig.zip"))
1046
+ + glob.glob(os.path.join(_datasets_root, f"{dataset_name}_fig.part*.zip"))
1047
+ )
1048
+ # Roughly half the datasets have no figures at all. Record the attempt
1049
+ # anyway so a figure-less dataset does not re-query the Hub on every
1050
+ # single load; MedVision_FORCE_DOWNLOAD_DATA is the way back if figures
1051
+ # are published for it later.
1052
+ if not _fig_zips:
1053
+ logger.info(" - No QC figures are published for %s", dataset_name)
1054
+ else:
1055
+ for _fig_zip in _fig_zips:
1056
+ with zipfile.ZipFile(_fig_zip, "r") as zip_ref:
1057
+ zip_ref.extractall(_datasets_root)
1058
+ os.remove(_fig_zip)
1059
+ logger.info(
1060
+ " - QC figures restored to %s from %d archive(s)",
1061
+ dataset_dir, len(_fig_zips),
1062
+ )
1063
+ # Written last, and only on a clean pass: a crash mid-extract leaves the
1064
+ # entry untouched, so the next load redoes the whole download and
1065
+ # extractall overwrites whatever landed. The value is the annotation
1066
+ # version these figures belong to, so a later release that regenerates
1067
+ # this dataset supersedes it; True only where the dataset publishes no
1068
+ # biometry at all and there is no version to name.
1069
+ _tracker_write(data_dir, f"qc_figures_{dataset_name}", stamp)
1070
+ _QC_FIGURES_DONE.add(_memo)
1071
+
1072
+
1073
  class MedVisionConfig(BuilderConfig):
1074
  """BuilderConfig for MedVision."""
1075
 
 
9944
  split="test",
9945
  ),
9946
  # DEEP-PSMA:Tumor-Lesion-Size:Task01
9947
+ MedVisionConfig(
9948
+ name="DEEP-PSMA_TumorLesionSize_Task01_Sagittal_Train",
9949
+ dataset_name="DEEP-PSMA",
9950
+ taskType="Tumor-Lesion-Size",
9951
+ taskID="01",
9952
+ imageType="2D",
9953
+ features_dict=features_dict_TumorLesionSize,
9954
+ imageSliceType="sagittal",
9955
+ split="train",
9956
+ ),
9957
+ MedVisionConfig(
9958
+ name="DEEP-PSMA_TumorLesionSize_Task01_Sagittal_Test",
9959
+ dataset_name="DEEP-PSMA",
9960
+ taskType="Tumor-Lesion-Size",
9961
+ taskID="01",
9962
+ imageType="2D",
9963
+ features_dict=features_dict_TumorLesionSize,
9964
+ imageSliceType="sagittal",
9965
+ split="test",
9966
+ ),
9967
+ MedVisionConfig(
9968
+ name="DEEP-PSMA_TumorLesionSize_Task01_Coronal_Train",
9969
+ dataset_name="DEEP-PSMA",
9970
+ taskType="Tumor-Lesion-Size",
9971
+ taskID="01",
9972
+ imageType="2D",
9973
+ features_dict=features_dict_TumorLesionSize,
9974
+ imageSliceType="coronal",
9975
+ split="train",
9976
+ ),
9977
+ MedVisionConfig(
9978
+ name="DEEP-PSMA_TumorLesionSize_Task01_Coronal_Test",
9979
+ dataset_name="DEEP-PSMA",
9980
+ taskType="Tumor-Lesion-Size",
9981
+ taskID="01",
9982
+ imageType="2D",
9983
+ features_dict=features_dict_TumorLesionSize,
9984
+ imageSliceType="coronal",
9985
+ split="test",
9986
+ ),
9987
  MedVisionConfig(
9988
  name="DEEP-PSMA_TumorLesionSize_Task01_Axial_Train",
9989
  dataset_name="DEEP-PSMA",
 
10005
  split="test",
10006
  ),
10007
  # DEEP-PSMA:Tumor-Lesion-Size:Task02
10008
+ MedVisionConfig(
10009
+ name="DEEP-PSMA_TumorLesionSize_Task02_Sagittal_Train",
10010
+ dataset_name="DEEP-PSMA",
10011
+ taskType="Tumor-Lesion-Size",
10012
+ taskID="02",
10013
+ imageType="2D",
10014
+ features_dict=features_dict_TumorLesionSize,
10015
+ imageSliceType="sagittal",
10016
+ split="train",
10017
+ ),
10018
+ MedVisionConfig(
10019
+ name="DEEP-PSMA_TumorLesionSize_Task02_Sagittal_Test",
10020
+ dataset_name="DEEP-PSMA",
10021
+ taskType="Tumor-Lesion-Size",
10022
+ taskID="02",
10023
+ imageType="2D",
10024
+ features_dict=features_dict_TumorLesionSize,
10025
+ imageSliceType="sagittal",
10026
+ split="test",
10027
+ ),
10028
+ MedVisionConfig(
10029
+ name="DEEP-PSMA_TumorLesionSize_Task02_Coronal_Train",
10030
+ dataset_name="DEEP-PSMA",
10031
+ taskType="Tumor-Lesion-Size",
10032
+ taskID="02",
10033
+ imageType="2D",
10034
+ features_dict=features_dict_TumorLesionSize,
10035
+ imageSliceType="coronal",
10036
+ split="train",
10037
+ ),
10038
+ MedVisionConfig(
10039
+ name="DEEP-PSMA_TumorLesionSize_Task02_Coronal_Test",
10040
+ dataset_name="DEEP-PSMA",
10041
+ taskType="Tumor-Lesion-Size",
10042
+ taskID="02",
10043
+ imageType="2D",
10044
+ features_dict=features_dict_TumorLesionSize,
10045
+ imageSliceType="coronal",
10046
+ split="test",
10047
+ ),
10048
  MedVisionConfig(
10049
  name="DEEP-PSMA_TumorLesionSize_Task02_Axial_Train",
10050
  dataset_name="DEEP-PSMA",
 
10371
  split="test",
10372
  ),
10373
  # LNQ2023:Tumor-Lesion-Size:Task01
10374
+ MedVisionConfig(
10375
+ name="LNQ2023_TumorLesionSize_Task01_Sagittal_Train",
10376
+ dataset_name="LNQ2023",
10377
+ taskType="Tumor-Lesion-Size",
10378
+ taskID="01",
10379
+ imageType="2D",
10380
+ features_dict=features_dict_TumorLesionSize,
10381
+ imageSliceType="sagittal",
10382
+ split="train",
10383
+ ),
10384
+ MedVisionConfig(
10385
+ name="LNQ2023_TumorLesionSize_Task01_Sagittal_Test",
10386
+ dataset_name="LNQ2023",
10387
+ taskType="Tumor-Lesion-Size",
10388
+ taskID="01",
10389
+ imageType="2D",
10390
+ features_dict=features_dict_TumorLesionSize,
10391
+ imageSliceType="sagittal",
10392
+ split="test",
10393
+ ),
10394
+ MedVisionConfig(
10395
+ name="LNQ2023_TumorLesionSize_Task01_Coronal_Train",
10396
+ dataset_name="LNQ2023",
10397
+ taskType="Tumor-Lesion-Size",
10398
+ taskID="01",
10399
+ imageType="2D",
10400
+ features_dict=features_dict_TumorLesionSize,
10401
+ imageSliceType="coronal",
10402
+ split="train",
10403
+ ),
10404
+ MedVisionConfig(
10405
+ name="LNQ2023_TumorLesionSize_Task01_Coronal_Test",
10406
+ dataset_name="LNQ2023",
10407
+ taskType="Tumor-Lesion-Size",
10408
+ taskID="01",
10409
+ imageType="2D",
10410
+ features_dict=features_dict_TumorLesionSize,
10411
+ imageSliceType="coronal",
10412
+ split="test",
10413
+ ),
10414
  MedVisionConfig(
10415
  name="LNQ2023_TumorLesionSize_Task01_Axial_Train",
10416
  dataset_name="LNQ2023",
 
11588
  _paused_versions(self.config.dataset_name, _kind),
11589
  )
11590
 
11591
+ # QC figures, opt-in and off by default. This sits in _info() rather than
11592
+ # in _split_generators for the same reason the pause gate above does: this
11593
+ # is the only point EVERY load passes through. datasets calls _info() from
11594
+ # DatasetBuilder.__init__, before the cache directory is consulted, while a
11595
+ # config that already has an Arrow cache never reaches _split_generators at
11596
+ # all. Fetching figures there meant they were obtained on a config's first
11597
+ # build and never again, so a machine holding stale figures could not get
11598
+ # the current ones by any means short of deleting its cache.
11599
+ #
11600
+ # Ordering against the data download is not a concern: the figure archives
11601
+ # extract into Datasets/<name>/ on their own, and the version they are
11602
+ # checked against comes from _ANNOTATION_INDEX, which touches neither disk
11603
+ # nor network. Everything here is behind the opt-in flag, so the default
11604
+ # path is unchanged -- including MedVision_PLANNER_VERSION, which is only
11605
+ # required (via _normalize_requested) once the flag is on, and is required
11606
+ # for the load itself regardless.
11607
+ # Deferred when the dataset's own files are not on disk yet, because that
11608
+ # is a first install: no Arrow cache can exist for a config that has never
11609
+ # been built, so _split_generators is guaranteed to run and its call site
11610
+ # fetches the figures AFTER step 3.3. That ordering matters -- the
11611
+ # reorientation pass globs "<dataset_dir>/**/*.nii.gz" recursively, and
11612
+ # figures extracted before it turn that into a walk over hundreds of
11613
+ # thousands of PNGs per dataset. Nothing is modified (only .nii.gz
11614
+ # matches), it is purely wasted stat traffic.
11615
+ #
11616
+ # Conversely, a warm cache implies the dataset was built successfully,
11617
+ # which implies its files ARE on disk -- so the branch that skips
11618
+ # _split_generators is exactly the branch this one covers. A version bump
11619
+ # satisfies both: it changes planner_version in the config fingerprint, so
11620
+ # the cache is cold and both call sites fire, with _QC_FIGURES_DONE making
11621
+ # the second a no-op.
11622
+ #
11623
+ # Not covered: a data directory deleted while its HF cache is kept. That
11624
+ # state already yields rows whose image_file paths do not exist, and
11625
+ # MedVision_FORCE_DOWNLOAD_DATA=True rebuilds out of it.
11626
+ if (
11627
+ os.environ.get("MedVision_DOWNLOAD_QC_FIGURES", "False").lower()
11628
+ == "true"
11629
+ ) and os.path.isdir(
11630
+ os.path.join(_data_root(), "Datasets", self.config.dataset_name)
11631
+ ):
11632
+ _try_ensure_qc_figures(
11633
+ self.config.dataset_name,
11634
+ _normalize_requested(
11635
+ os.environ.get("MedVision_PLANNER_VERSION"), self.config.version
11636
+ ),
11637
+ _data_root(),
11638
+ self.config.num_proc,
11639
+ )
11640
+
11641
  # Define dataset information including feature schema
11642
  dataset_description = f"You are using the configuration <{self.config.name}> of the <{self.config.dataset_name}> dataset."
11643
  return DatasetInfo(
 
12046
  _discover_versions(dataset_dir, _kind),
12047
  )
12048
 
12049
+ # 3.5 QC figures -- one of TWO call sites, and the one that serves a first
12050
+ # install. It runs here, after step 3.3, so the reorientation glob above
12051
+ # does not walk the figure tree. _info() holds the other call site and
12052
+ # covers the case this method cannot: a config with a warm Arrow cache
12053
+ # never reaches _split_generators at all, so a fetch placed only here ran
12054
+ # on a config's first build and never again -- which is what made stale
12055
+ # figures impossible to refresh. _QC_FIGURES_DONE keeps whichever call
12056
+ # comes second from repeating the work.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12057
  if download_qc_figures:
12058
+ _try_ensure_qc_figures(
12059
+ dataset_name, _requested, MedVision_data_dir, self.config.num_proc
12060
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12061
 
12062
  # 4. Get the benchmark planner file - this is config specific but should use existing files if possible
12063
  # NOTE: MUST NOT move the import to the front, as the "medvision_ds" package may not be installed yet at the beginning