MitakaKuma commited on
Commit
dc0b89d
·
verified ·
1 Parent(s): 15947ca

Update collection metadata and safe collectors

Browse files
LICENSES/source_terms.md CHANGED
@@ -4,6 +4,8 @@ This file tracks the source terms that govern public mirroring and derived
4
  NIfTI conversion. It is not legal advice. When a source has ambiguous or
5
  conflicting terms, raw scans are not mirrored until the terms are resolved.
6
 
 
 
7
  | Dataset | Source | Current handling |
8
  |---|---|---|
9
  | LIDC-IDRI | TCIA public collection: https://www.cancerimagingarchive.net/collection/lidc-idri/ | OK to collect with attribution and TCIA policy notes |
@@ -15,6 +17,11 @@ conflicting terms, raw scans are not mirrored until the terms are resolved.
15
  | MIDRC | MIDRC Data Use Agreement: https://www.midrc.org/midrc-data-use-agreement | Do not mirror raw or converted scans; DUA requires separate users to access through MIDRC and prohibits distribution without written permission |
16
  | LTRC | NHLBI BioLINCC: https://biolincc.nhlbi.nih.gov/studies/ltrc/ | Do not mirror raw scans publicly; access requires BioLINCC login/request and is limited to lung disease research |
17
 
 
 
 
 
 
18
  ## Standard User Obligations
19
 
20
  Users must not attempt to identify or contact patients represented in these
 
4
  NIfTI conversion. It is not legal advice. When a source has ambiguous or
5
  conflicting terms, raw scans are not mirrored until the terms are resolved.
6
 
7
+ Last reviewed against the linked source pages: 2026-06-28 UTC.
8
+
9
  | Dataset | Source | Current handling |
10
  |---|---|---|
11
  | LIDC-IDRI | TCIA public collection: https://www.cancerimagingarchive.net/collection/lidc-idri/ | OK to collect with attribution and TCIA policy notes |
 
17
  | MIDRC | MIDRC Data Use Agreement: https://www.midrc.org/midrc-data-use-agreement | Do not mirror raw or converted scans; DUA requires separate users to access through MIDRC and prohibits distribution without written permission |
18
  | LTRC | NHLBI BioLINCC: https://biolincc.nhlbi.nih.gov/studies/ltrc/ | Do not mirror raw scans publicly; access requires BioLINCC login/request and is limited to lung disease research |
19
 
20
+ The machine-readable enforcement policy is in
21
+ `manifests/source_datasets.csv`. Collector scripts refuse scan uploads unless
22
+ that registry explicitly permits mirroring. Metadata-only preparation does not
23
+ override a source agreement.
24
+
25
  ## Standard User Obligations
26
 
27
  Users must not attempt to identify or contact patients represented in these
README.md CHANGED
@@ -39,6 +39,20 @@ data/
39
  Each scan directory contains only `ct.nii.gz`. Provenance, source identifiers,
40
  checksums, and conversion metadata are stored in `manifests/`.
41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
  ## Planned Public CT Sources
43
 
44
  | Dataset | Planned scans from paper | Status policy |
 
39
  Each scan directory contains only `ct.nii.gz`. Provenance, source identifiers,
40
  checksums, and conversion metadata are stored in `manifests/`.
41
 
42
+ ## Safe Collection
43
+
44
+ Collection is fail-closed: commands are dry runs unless `--execute` is supplied,
45
+ executed batches default to one case, and all collectors share a lock. Temporary
46
+ data is capped at 20 GiB across `.hf_tmp`, while at least 100 GiB of filesystem
47
+ free space is reserved and checked throughout every download and extraction.
48
+ LUNA16 extracts one scan at a time instead of unpacking a complete subset.
49
+
50
+ Credentials are read only from supported Hugging Face environment variables.
51
+ Never put API tokens in commands, files, logs, notebooks, or issue text.
52
+
53
+ See `docs/collection_plan.md` for source gates and safe dry-run commands. Run
54
+ `python scripts/collection_status.py` for an offline readiness check.
55
+
56
  ## Planned Public CT Sources
57
 
58
  | Dataset | Planned scans from paper | Status policy |
docs/collection_plan.md ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Collection Plan
2
+
3
+ This workspace prepares the eight public cohorts listed in the SUMI paper while
4
+ failing closed on storage and redistribution policy. A paper cohort count is a
5
+ target, not permission to mirror a source.
6
+
7
+ ## Safety Defaults
8
+
9
+ - Collection commands are dry runs unless `--execute` is supplied.
10
+ - Executed batches default to one CT volume.
11
+ - All bundled collectors share one advisory lock, so they cannot stage large
12
+ downloads concurrently.
13
+ - Staging is capped at 20 GiB across `.hf_tmp`, with at least 100 GiB of free
14
+ filesystem space reserved. Both limits are checked before and during writes.
15
+ - Temporary archives, extracted source images, and converted CTs are removed
16
+ after each bounded batch. LUNA16 extracts only one scan from a subset archive
17
+ at a time.
18
+ - A CT and its JSONL manifest update are uploaded in one Hugging Face commit.
19
+
20
+ Do not lower `--min-free-gb` or raise `--max-local-gb` while other disk-heavy
21
+ jobs are active.
22
+
23
+ ## Source Matrix
24
+
25
+ | Dataset | Preparation | Permitted action |
26
+ |---|---|---|
27
+ | LIDC-IDRI | Ready | Bounded TCIA upload with attribution |
28
+ | LUNA16 | Canary passed | Bounded batches; one scan extracted at a time |
29
+ | NLST | Collector ready, selection unresolved | Catalog only until the exact 422-series allowlist is reviewed |
30
+ | DSB17 | Terms unresolved | Metadata/instructions only |
31
+ | LNDb19 | Record text and metadata conflict; record text says no derivatives | Metadata/instructions only |
32
+ | LTRC | BioLINCC request and agreement required | Metadata/instructions only |
33
+ | MIDRC | Redistribution prohibited without written permission | Metadata/instructions only |
34
+ | RSNA-STR | Redistribution expressly prohibited | Metadata/instructions only |
35
+
36
+ The machine-readable policy gate is `manifests/source_datasets.csv`. The
37
+ collectors refuse execution when that registry does not explicitly allow the
38
+ requested source.
39
+
40
+ ## Safe Commands
41
+
42
+ Plan the next LIDC-IDRI case without downloading scan data:
43
+
44
+ ```bash
45
+ python scripts/tcia_collect_upload.py \
46
+ --collection LIDC-IDRI \
47
+ --dataset-name LIDC-IDRI
48
+ ```
49
+
50
+ Execute one LIDC-IDRI case only after reviewing the dry run:
51
+
52
+ ```bash
53
+ python scripts/tcia_collect_upload.py \
54
+ --collection LIDC-IDRI \
55
+ --dataset-name LIDC-IDRI \
56
+ --max-cases 1 \
57
+ --execute
58
+ ```
59
+
60
+ Plan a LUNA16 subset-0 smoke test without downloading its 6.8 GB archive:
61
+
62
+ ```bash
63
+ python scripts/luna16_collect_upload.py --subset 0 --max-cases 1
64
+ ```
65
+
66
+ NLST execution is intentionally impossible until
67
+ `manifests/NLST_selection.csv` contains reviewed TCIA Series Instance UIDs:
68
+
69
+ ```bash
70
+ python scripts/tcia_collect_upload.py \
71
+ --collection NLST \
72
+ --dataset-name NLST \
73
+ --series-allowlist manifests/NLST_selection.csv \
74
+ --max-cases 1
75
+ ```
76
+
77
+ After the allowlist and its provenance are reviewed, add `--execute`.
manifests/NLST_selection.csv ADDED
@@ -0,0 +1 @@
 
 
1
+ series_uid,selection_reason,source_reference
manifests/progress.md CHANGED
@@ -1,14 +1,26 @@
1
  # Collection Progress
2
 
3
- Last updated: 2026-06-26 UTC
4
 
5
  | Dataset | Uploaded CT volumes | Notes |
6
  |---|---:|---|
7
- | LIDC-IDRI | 5 | First storage-safe TCIA batch uploaded as `data/LIDC-IDRI_00000001` through `data/LIDC-IDRI_00000005` |
8
- | LUNA16 | 0 | Collector script prepared; next step is a one-subset or smoke-test upload |
9
- | NLST | 0 | Public TCIA/IDC source confirmed; paper subset selection still needs to be fixed before upload |
10
  | LNDb19 | 0 | Hold converted NIfTI upload until license conflict is resolved |
11
  | DSB17 | 0 | Hold converted NIfTI upload until Kaggle/TCIA source terms are resolved |
12
  | RSNA-STR | 0 | Raw/converted mirroring blocked by no-redistribution term |
13
  | MIDRC | 0 | Raw/converted mirroring blocked by DUA redistribution restriction |
14
  | LTRC | 0 | Raw mirroring blocked pending BioLINCC access/permission |
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  # Collection Progress
2
 
3
+ Last updated: 2026-06-28 UTC
4
 
5
  | Dataset | Uploaded CT volumes | Notes |
6
  |---|---:|---|
7
+ | LIDC-IDRI | 5 | Live inventory verified; collector now uses bounded writes and atomic CT+manifest commits |
8
+ | LUNA16 | 1 | Subset-0 canary passed as `data/LUNA16_00000001`; archive and extracted source were cleaned |
9
+ | NLST | 0 | Collector and allowlist schema prepared; exact 422-series selection still requires review |
10
  | LNDb19 | 0 | Hold converted NIfTI upload until license conflict is resolved |
11
  | DSB17 | 0 | Hold converted NIfTI upload until Kaggle/TCIA source terms are resolved |
12
  | RSNA-STR | 0 | Raw/converted mirroring blocked by no-redistribution term |
13
  | MIDRC | 0 | Raw/converted mirroring blocked by DUA redistribution restriction |
14
  | LTRC | 0 | Raw mirroring blocked pending BioLINCC access/permission |
15
+
16
+ ## Preparation State
17
+
18
+ - All collection commands default to dry-run mode and one-case batches.
19
+ - A shared collection lock prevents bundled collectors from staging in parallel.
20
+ - Staging is capped at 20 GiB with a 100 GiB filesystem free-space reserve.
21
+ - LUNA16 now extracts one scan from a subset archive at a time.
22
+ - The first LUNA16 canary passed checksum, conversion, atomic upload, remote
23
+ manifest reconciliation, and staging cleanup checks.
24
+ - Restricted sources are policy-gated to metadata/instructions only.
25
+ - Offline storage, conversion, policy, and credential-leak tests are available
26
+ under `tests/`.
manifests/source_datasets.csv CHANGED
@@ -1,9 +1,9 @@
1
- dataset,planned_scans,source_primary,license_status,mirror_policy
2
- DSB17,1596,Kaggle Data Science Bowl 2017,under_review,manifest_until_terms_verified
3
- LIDC-IDRI,1018,TCIA LIDC-IDRI,cc_by_3_tcia_policy,mirror_allowed_with_attribution
4
- LNDb19,324,Zenodo LNDb Dataset,conflicting_cc_by_vs_cc_by_nc_nd,hold_converted_nifti
5
- LTRC,1496,NHLBI BioLINCC LTRC,access_controlled_biolincc,manifest_only_without_permission
6
- LUNA16,854,Grand Challenge/Zenodo LUNA16,cc_by_4,mirror_allowed_with_attribution
7
- MIDRC,10496,MIDRC Data Commons,redistribution_prohibited_without_permission,manifest_only
8
- NLST,422,TCIA/IDC NLST,public_tcia_policy,mirror_selected_public_ct_with_attribution
9
- RSNA-STR,1110,Kaggle/AWS RSNA STR Pulmonary Embolism Detection,redistribution_prohibited,manifest_only
 
1
+ dataset,planned_scans,source_primary,license_status,mirror_policy,preparation_status,collector,required_selection
2
+ DSB17,1596,Kaggle Data Science Bowl 2017,under_review,manifest_until_terms_verified,blocked_terms_review,none,
3
+ LIDC-IDRI,1018,TCIA LIDC-IDRI,cc_by_3_tcia_policy,mirror_allowed_with_attribution,ready_bounded_batches,scripts/tcia_collect_upload.py,
4
+ LNDb19,324,Zenodo LNDb Dataset,conflicting_cc_by_vs_cc_by_nc_nd,hold_converted_nifti,blocked_license_conflict,none,
5
+ LTRC,1496,NHLBI BioLINCC LTRC,access_controlled_biolincc,manifest_only_without_permission,access_request_required,none,
6
+ LUNA16,854,Grand Challenge/Zenodo LUNA16,cc_by_4,mirror_allowed_with_attribution,canary_passed_bounded_batches_ready,scripts/luna16_collect_upload.py,
7
+ MIDRC,10496,MIDRC Data Commons,redistribution_prohibited_without_permission,manifest_only,manifest_only_no_redistribution,none,
8
+ NLST,422,TCIA/IDC NLST,public_tcia_policy,mirror_selected_public_ct_with_attribution,selection_required,scripts/tcia_collect_upload.py,manifests/NLST_selection.csv
9
+ RSNA-STR,1110,Kaggle/AWS RSNA STR Pulmonary Embolism Detection,redistribution_prohibited,manifest_only,manifest_only_no_redistribution,none,
scripts/collection_status.py ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Report and validate SUMI OpenCT collection readiness without network I/O."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import csv
8
+ import json
9
+ from pathlib import Path
10
+
11
+
12
+ EXPECTED_DATASETS = {
13
+ "DSB17",
14
+ "LIDC-IDRI",
15
+ "LNDb19",
16
+ "LTRC",
17
+ "LUNA16",
18
+ "MIDRC",
19
+ "NLST",
20
+ "RSNA-STR",
21
+ }
22
+ MIRROR_ALLOWED = {
23
+ "mirror_allowed_with_attribution",
24
+ "mirror_selected_public_ct_with_attribution",
25
+ }
26
+
27
+
28
+ def read_jsonl(path: Path) -> list[dict]:
29
+ if not path.exists():
30
+ return []
31
+ rows: list[dict] = []
32
+ with path.open(encoding="utf-8") as f:
33
+ for line_number, line in enumerate(f, start=1):
34
+ if not line.strip():
35
+ continue
36
+ try:
37
+ value = json.loads(line)
38
+ except json.JSONDecodeError as exc:
39
+ raise RuntimeError(f"Invalid JSON at {path}:{line_number}: {exc}") from exc
40
+ if not isinstance(value, dict):
41
+ raise RuntimeError(f"Expected an object at {path}:{line_number}")
42
+ rows.append(value)
43
+ return rows
44
+
45
+
46
+ def count_csv_rows(path: Path) -> int:
47
+ if not path.exists():
48
+ return 0
49
+ with path.open(newline="", encoding="utf-8") as f:
50
+ return sum(1 for _ in csv.DictReader(f))
51
+
52
+
53
+ def collect_status(root: Path) -> tuple[list[dict], list[str]]:
54
+ registry_path = root / "manifests/source_datasets.csv"
55
+ with registry_path.open(newline="", encoding="utf-8") as f:
56
+ registry = list(csv.DictReader(f))
57
+
58
+ errors: list[str] = []
59
+ names = {row.get("dataset", "") for row in registry}
60
+ if names != EXPECTED_DATASETS:
61
+ errors.append(
62
+ f"registry datasets differ: missing={sorted(EXPECTED_DATASETS - names)}, "
63
+ f"unexpected={sorted(names - EXPECTED_DATASETS)}"
64
+ )
65
+
66
+ status: list[dict] = []
67
+ for source in registry:
68
+ dataset = source["dataset"]
69
+ planned = int(source["planned_scans"])
70
+ manifest_path = root / f"manifests/{dataset}.jsonl"
71
+ manifest = read_jsonl(manifest_path)
72
+ folders = [str(row.get("folder", "")) for row in manifest]
73
+ source_uids = [str(row.get("source_series_uid", "")) for row in manifest]
74
+
75
+ if len(folders) != len(set(folders)):
76
+ errors.append(f"{dataset}: duplicate folder in {manifest_path}")
77
+ if any(not value for value in folders):
78
+ errors.append(f"{dataset}: manifest row missing folder")
79
+ if len(source_uids) != len(set(source_uids)):
80
+ errors.append(f"{dataset}: duplicate source_series_uid in {manifest_path}")
81
+ if any(not value for value in source_uids):
82
+ errors.append(f"{dataset}: manifest row missing source_series_uid")
83
+ if len(manifest) > planned:
84
+ errors.append(f"{dataset}: {len(manifest)} uploads exceed planned count {planned}")
85
+
86
+ collector = source.get("collector", "")
87
+ if collector and collector != "none" and not (root / collector).is_file():
88
+ errors.append(f"{dataset}: collector does not exist: {collector}")
89
+ policy = source.get("mirror_policy", "")
90
+ if policy not in MIRROR_ALLOWED and manifest:
91
+ errors.append(f"{dataset}: restricted source has {len(manifest)} uploaded manifest rows")
92
+
93
+ selection_path = source.get("required_selection", "")
94
+ selection_rows = count_csv_rows(root / selection_path) if selection_path else None
95
+ status.append(
96
+ {
97
+ "dataset": dataset,
98
+ "planned": planned,
99
+ "uploaded": len(manifest),
100
+ "preparation_status": source.get("preparation_status", ""),
101
+ "mirror_policy": policy,
102
+ "selection_rows": selection_rows,
103
+ }
104
+ )
105
+ return status, errors
106
+
107
+
108
+ def main() -> None:
109
+ parser = argparse.ArgumentParser()
110
+ parser.add_argument("--root", type=Path, default=Path("."))
111
+ parser.add_argument("--json", action="store_true")
112
+ args = parser.parse_args()
113
+
114
+ root = args.root.resolve()
115
+ status, errors = collect_status(root)
116
+ if args.json:
117
+ print(json.dumps({"sources": status, "errors": errors}, indent=2, sort_keys=True))
118
+ else:
119
+ print(f"{'dataset':<12} {'planned':>8} {'uploaded':>8} preparation")
120
+ for row in status:
121
+ selection = row["selection_rows"]
122
+ suffix = f" (selection rows: {selection})" if selection is not None else ""
123
+ print(
124
+ f"{row['dataset']:<12} {row['planned']:>8} {row['uploaded']:>8} "
125
+ f"{row['preparation_status']}{suffix}"
126
+ )
127
+ print(
128
+ f"{'TOTAL':<12} {sum(row['planned'] for row in status):>8} "
129
+ f"{sum(row['uploaded'] for row in status):>8}"
130
+ )
131
+ print("validation: " + ("OK" if not errors else "FAILED"))
132
+ for error in errors:
133
+ print(f"- {error}")
134
+
135
+ if errors:
136
+ raise SystemExit(1)
137
+
138
+
139
+ if __name__ == "__main__":
140
+ main()
scripts/luna16_collect_upload.py CHANGED
@@ -9,21 +9,38 @@ Use `--max-cases` for small smoke tests before full collection.
9
  from __future__ import annotations
10
 
11
  import argparse
 
12
  import hashlib
13
  import json
14
  import os
15
  import re
16
- import shutil
17
  import tempfile
18
  import zipfile
19
- from pathlib import Path
20
 
21
  import nibabel as nib
22
  import numpy as np
23
  import requests
24
- from huggingface_hub import HfApi
25
  from tqdm import tqdm
26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
 
28
  TOKEN_KEYS = (
29
  "HF_TOKEN",
@@ -73,22 +90,6 @@ def default_repo_id(api: HfApi, token: str, repo_name: str) -> str:
73
  return f"{namespace}/{repo_name}"
74
 
75
 
76
- def bytes_in_tree(path: Path) -> int:
77
- if not path.exists():
78
- return 0
79
- return sum(p.stat().st_size for p in path.rglob("*") if p.is_file())
80
-
81
-
82
- def enforce_staging_limit(path: Path, max_local_gb: float) -> None:
83
- used = bytes_in_tree(path)
84
- limit = int(max_local_gb * 1024**3)
85
- if used > limit:
86
- raise RuntimeError(
87
- f"Staging directory {path} uses {used / 1024**3:.2f} GiB, "
88
- f"above the configured {max_local_gb:.2f} GiB limit."
89
- )
90
-
91
-
92
  def md5_file(path: Path) -> str:
93
  h = hashlib.md5()
94
  with path.open("rb") as f:
@@ -105,30 +106,48 @@ def sha256_file(path: Path) -> str:
105
  return h.hexdigest()
106
 
107
 
108
- def download(url: str, out_path: Path) -> None:
109
  with requests.get(url, stream=True, timeout=300) as resp:
110
  resp.raise_for_status()
111
  total = int(resp.headers.get("content-length") or 0)
112
- with out_path.open("wb") as f, tqdm(total=total, unit="B", unit_scale=True, desc=out_path.name) as bar:
113
- for chunk in resp.iter_content(chunk_size=1024 * 1024):
114
- if chunk:
115
- f.write(chunk)
116
- bar.update(len(chunk))
 
 
 
 
 
 
 
 
 
 
117
 
118
 
119
  def parse_mhd(path: Path) -> dict[str, str]:
120
- fields: dict[str, str] = {}
121
  with path.open("r", encoding="utf-8") as f:
122
- for line in f:
123
- if "=" not in line:
124
- continue
125
- key, value = line.split("=", 1)
126
- fields[key.strip()] = value.strip()
 
 
 
 
 
127
  return fields
128
 
129
 
130
- def convert_mhd_to_nifti(mhd_path: Path, raw_path: Path, out_path: Path) -> dict[str, object]:
131
- fields = parse_mhd(mhd_path)
 
 
 
 
132
  dims = [int(v) for v in fields["DimSize"].split()]
133
  spacing = [float(v) for v in fields.get("ElementSpacing", "1 1 1").split()]
134
  offset = [float(v) for v in fields.get("Offset", "0 0 0").split()]
@@ -156,6 +175,9 @@ def convert_mhd_to_nifti(mhd_path: Path, raw_path: Path, out_path: Path) -> dict
156
  image.header.set_xyzt_units("mm")
157
  image.header["cal_min"] = float(np.nanmin(data_xyz))
158
  image.header["cal_max"] = float(np.nanmax(data_xyz))
 
 
 
159
  nib.save(image, str(out_path))
160
  return {
161
  "shape": list(map(int, data_xyz.shape)),
@@ -164,138 +186,310 @@ def convert_mhd_to_nifti(mhd_path: Path, raw_path: Path, out_path: Path) -> dict
164
  }
165
 
166
 
 
 
 
 
 
 
 
 
 
167
  def existing_indices(api: HfApi, repo_id: str, dataset_name: str, token: str) -> set[int]:
168
- try:
169
- files = api.list_repo_files(repo_id=repo_id, repo_type="dataset", token=token)
170
- except Exception:
171
- return set()
172
  pattern = re.compile(rf"^data/{re.escape(dataset_name)}_(\d{{8}})/ct\.nii\.gz$")
173
  return {int(match.group(1)) for path in files if (match := pattern.match(path))}
174
 
175
 
176
- def append_jsonl(path: Path, row: dict) -> None:
177
- path.parent.mkdir(parents=True, exist_ok=True)
178
- with path.open("a", encoding="utf-8") as f:
179
- f.write(json.dumps(row, sort_keys=True) + "\n")
180
-
181
-
182
- def read_manifest_values(path: Path, key: str) -> set[str]:
183
  if not path.exists():
184
- return set()
185
- values: set[str] = set()
186
  with path.open("r", encoding="utf-8") as f:
187
- for line in f:
188
  line = line.strip()
189
  if not line:
190
  continue
191
  try:
192
  row = json.loads(line)
193
- except json.JSONDecodeError:
194
- continue
195
- value = row.get(key)
196
- if value:
197
- values.add(str(value))
198
- return values
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
199
 
200
 
201
  def main() -> None:
202
- parser = argparse.ArgumentParser()
 
 
203
  parser.add_argument("--dataset-name", default="LUNA16")
204
  parser.add_argument("--repo-id", default=None)
205
  parser.add_argument("--repo-name", default="SUMI-OpenCT")
206
  parser.add_argument("--work-dir", default=".hf_tmp/luna16")
 
 
207
  parser.add_argument("--max-local-gb", type=float, default=20.0)
 
208
  parser.add_argument("--subset", type=int, choices=range(10), action="append")
209
- parser.add_argument("--max-cases", type=int, default=None)
210
  parser.add_argument("--start-index", type=int, default=None)
 
 
 
 
 
 
211
  args = parser.parse_args()
212
 
213
- token = get_token()
214
- api = HfApi(token=token)
215
- repo_id = args.repo_id or default_repo_id(api, token, args.repo_name)
 
 
 
 
 
216
  work_dir = Path(args.work_dir).resolve()
217
  work_dir.mkdir(parents=True, exist_ok=True)
218
  subsets = args.subset if args.subset is not None else list(range(10))
219
- existing = existing_indices(api, repo_id, args.dataset_name, token)
220
- index = args.start_index or ((max(existing) + 1) if existing else 1)
221
- processed = 0
222
- manifest_path = Path("manifests") / f"{args.dataset_name}.jsonl"
223
- processed_source_uids = read_manifest_values(manifest_path, "source_series_uid")
224
-
225
- for subset_id in subsets:
226
- if args.max_cases is not None and processed >= args.max_cases:
227
- break
228
- url, expected_md5 = LUNA16_FILES[subset_id]
229
- with tempfile.TemporaryDirectory(dir=work_dir) as tmp:
230
- tmp_dir = Path(tmp)
231
- zip_path = tmp_dir / f"subset{subset_id}.zip"
232
- extract_dir = tmp_dir / "extract"
233
- download(url, zip_path)
234
- enforce_staging_limit(work_dir, args.max_local_gb)
235
- actual_md5 = md5_file(zip_path)
236
- if actual_md5 != expected_md5:
237
- raise RuntimeError(f"MD5 mismatch for subset{subset_id}: {actual_md5} != {expected_md5}")
238
-
239
- with zipfile.ZipFile(zip_path) as zf:
240
- zf.extractall(extract_dir)
241
- enforce_staging_limit(work_dir, args.max_local_gb)
242
-
243
- mhd_files = sorted(extract_dir.rglob("*.mhd"))
244
- for mhd_path in mhd_files:
245
- if args.max_cases is not None and processed >= args.max_cases:
246
- break
247
- fields = parse_mhd(mhd_path)
248
- raw_name = fields["ElementDataFile"]
249
- raw_path = mhd_path.parent / raw_name
250
- if not raw_path.exists():
251
- raise RuntimeError(f"Missing raw file {raw_path}")
252
- if mhd_path.stem in processed_source_uids:
253
- continue
254
-
255
- folder_name = f"{args.dataset_name}_{index:08d}"
256
- case_dir = tmp_dir / folder_name
257
- case_dir.mkdir(parents=True, exist_ok=True)
258
- ct_path = case_dir / "ct.nii.gz"
259
- conversion = convert_mhd_to_nifti(mhd_path, raw_path, ct_path)
260
- digest = sha256_file(ct_path)
261
- size_bytes = ct_path.stat().st_size
262
-
263
- api.upload_folder(
264
- repo_id=repo_id,
265
- repo_type="dataset",
266
- folder_path=str(case_dir),
267
- path_in_repo=f"data/{folder_name}",
268
- token=token,
269
- commit_message=f"Add {folder_name}",
270
- )
271
- row = {
272
- "dataset": args.dataset_name,
273
- "folder": folder_name,
274
- "path": f"data/{folder_name}/ct.nii.gz",
275
- "source": "LUNA16",
276
- "source_subset": subset_id,
277
- "source_series_uid": mhd_path.stem,
278
- "source_mhd": str(mhd_path.relative_to(extract_dir)),
279
- "sha256": digest,
280
- "size_bytes": size_bytes,
281
- **conversion,
282
- }
283
- append_jsonl(manifest_path, row)
284
- processed_source_uids.add(mhd_path.stem)
285
- api.upload_file(
286
- repo_id=repo_id,
287
- repo_type="dataset",
288
- path_or_fileobj=str(manifest_path),
289
- path_in_repo=f"manifests/{args.dataset_name}.jsonl",
290
- token=token,
291
- commit_message=f"Update {args.dataset_name} manifest",
292
- )
293
- shutil.rmtree(case_dir, ignore_errors=True)
294
- processed += 1
295
- index += 1
296
-
297
- enforce_staging_limit(work_dir, args.max_local_gb)
298
- print(f"Uploaded {processed} {args.dataset_name} cases to {repo_id}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
299
 
300
 
301
  if __name__ == "__main__":
 
9
  from __future__ import annotations
10
 
11
  import argparse
12
+ import csv
13
  import hashlib
14
  import json
15
  import os
16
  import re
 
17
  import tempfile
18
  import zipfile
19
+ from pathlib import Path, PurePosixPath
20
 
21
  import nibabel as nib
22
  import numpy as np
23
  import requests
24
+ from huggingface_hub import CommitOperationAdd, HfApi
25
  from tqdm import tqdm
26
 
27
+ try:
28
+ from .storage_guard import (
29
+ StorageBudget,
30
+ copy_bounded,
31
+ exclusive_collection_lock,
32
+ extract_member_bounded,
33
+ validated_zip_member,
34
+ )
35
+ except ImportError: # Support `python scripts/luna16_collect_upload.py`.
36
+ from storage_guard import ( # type: ignore[no-redef]
37
+ StorageBudget,
38
+ copy_bounded,
39
+ exclusive_collection_lock,
40
+ extract_member_bounded,
41
+ validated_zip_member,
42
+ )
43
+
44
 
45
  TOKEN_KEYS = (
46
  "HF_TOKEN",
 
90
  return f"{namespace}/{repo_name}"
91
 
92
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93
  def md5_file(path: Path) -> str:
94
  h = hashlib.md5()
95
  with path.open("rb") as f:
 
106
  return h.hexdigest()
107
 
108
 
109
+ def download(url: str, out_path: Path, budget: StorageBudget) -> None:
110
  with requests.get(url, stream=True, timeout=300) as resp:
111
  resp.raise_for_status()
112
  total = int(resp.headers.get("content-length") or 0)
113
+ with tqdm(
114
+ total=total,
115
+ unit="B",
116
+ unit_scale=True,
117
+ desc=out_path.name,
118
+ mininterval=10.0,
119
+ ) as bar:
120
+ copy_bounded(
121
+ resp.raw,
122
+ out_path,
123
+ budget,
124
+ expected_bytes=total or None,
125
+ context=f"downloading {out_path.name}",
126
+ on_chunk=bar.update,
127
+ )
128
 
129
 
130
  def parse_mhd(path: Path) -> dict[str, str]:
 
131
  with path.open("r", encoding="utf-8") as f:
132
+ return parse_mhd_text(f.read())
133
+
134
+
135
+ def parse_mhd_text(text: str) -> dict[str, str]:
136
+ fields: dict[str, str] = {}
137
+ for line in text.splitlines():
138
+ if "=" not in line:
139
+ continue
140
+ key, value = line.split("=", 1)
141
+ fields[key.strip()] = value.strip()
142
  return fields
143
 
144
 
145
+ def convert_mhd_fields_to_nifti(
146
+ fields: dict[str, str],
147
+ raw_path: Path,
148
+ out_path: Path,
149
+ budget: StorageBudget | None = None,
150
+ ) -> dict[str, object]:
151
  dims = [int(v) for v in fields["DimSize"].split()]
152
  spacing = [float(v) for v in fields.get("ElementSpacing", "1 1 1").split()]
153
  offset = [float(v) for v in fields.get("Offset", "0 0 0").split()]
 
175
  image.header.set_xyzt_units("mm")
176
  image.header["cal_min"] = float(np.nanmin(data_xyz))
177
  image.header["cal_max"] = float(np.nanmax(data_xyz))
178
+ if budget is not None:
179
+ worst_case_bytes = int(data_xyz.nbytes * 1.01) + 1024 * 1024
180
+ budget.check(worst_case_bytes, context="writing converted LUNA16 NIfTI")
181
  nib.save(image, str(out_path))
182
  return {
183
  "shape": list(map(int, data_xyz.shape)),
 
186
  }
187
 
188
 
189
+ def convert_mhd_to_nifti(
190
+ mhd_path: Path,
191
+ raw_path: Path,
192
+ out_path: Path,
193
+ budget: StorageBudget | None = None,
194
+ ) -> dict[str, object]:
195
+ return convert_mhd_fields_to_nifti(parse_mhd(mhd_path), raw_path, out_path, budget)
196
+
197
+
198
  def existing_indices(api: HfApi, repo_id: str, dataset_name: str, token: str) -> set[int]:
199
+ files = api.list_repo_files(repo_id=repo_id, repo_type="dataset", token=token)
 
 
 
200
  pattern = re.compile(rf"^data/{re.escape(dataset_name)}_(\d{{8}})/ct\.nii\.gz$")
201
  return {int(match.group(1)) for path in files if (match := pattern.match(path))}
202
 
203
 
204
+ def read_manifest_rows(path: Path) -> list[dict]:
 
 
 
 
 
 
205
  if not path.exists():
206
+ return []
207
+ rows: list[dict] = []
208
  with path.open("r", encoding="utf-8") as f:
209
+ for line_number, line in enumerate(f, start=1):
210
  line = line.strip()
211
  if not line:
212
  continue
213
  try:
214
  row = json.loads(line)
215
+ except json.JSONDecodeError as exc:
216
+ raise RuntimeError(f"Invalid JSON in {path}:{line_number}: {exc}") from exc
217
+ if not isinstance(row, dict):
218
+ raise RuntimeError(f"Expected an object in {path}:{line_number}")
219
+ rows.append(row)
220
+ return rows
221
+
222
+
223
+ def sync_remote_manifest(repo_id: str, dataset_name: str, token: str, local_path: Path) -> list[dict]:
224
+ remote_path = f"manifests/{dataset_name}.jsonl"
225
+ url = f"https://huggingface.co/datasets/{repo_id}/resolve/main/{remote_path}"
226
+ response = requests.get(url, headers={"Authorization": f"Bearer {token}"}, timeout=120)
227
+ if response.status_code == 404:
228
+ return read_manifest_rows(local_path)
229
+ response.raise_for_status()
230
+
231
+ remote_rows: list[dict] = []
232
+ for line_number, line in enumerate(response.text.splitlines(), start=1):
233
+ if not line.strip():
234
+ continue
235
+ try:
236
+ row = json.loads(line)
237
+ except json.JSONDecodeError as exc:
238
+ raise RuntimeError(
239
+ f"Invalid JSON in remote {remote_path}:{line_number}: {exc}"
240
+ ) from exc
241
+ if not isinstance(row, dict):
242
+ raise RuntimeError(f"Expected an object in remote {remote_path}:{line_number}")
243
+ remote_rows.append(row)
244
+
245
+ local_rows = read_manifest_rows(local_path)
246
+ remote_uids = {str(row.get("source_series_uid")) for row in remote_rows}
247
+ local_only = {
248
+ str(row.get("source_series_uid"))
249
+ for row in local_rows
250
+ if str(row.get("source_series_uid")) not in remote_uids
251
+ }
252
+ if local_only:
253
+ raise RuntimeError(
254
+ f"Local manifest has {len(local_only)} source UID(s) absent from the remote manifest; "
255
+ "refusing to overwrite divergent state."
256
+ )
257
+
258
+ canonical = "".join(json.dumps(row, sort_keys=True) + "\n" for row in remote_rows)
259
+ current = local_path.read_text(encoding="utf-8") if local_path.exists() else ""
260
+ if canonical != current:
261
+ local_path.parent.mkdir(parents=True, exist_ok=True)
262
+ with tempfile.NamedTemporaryFile(
263
+ mode="w",
264
+ encoding="utf-8",
265
+ dir=local_path.parent,
266
+ prefix=f".{local_path.name}.",
267
+ suffix=".sync",
268
+ delete=False,
269
+ ) as tmp:
270
+ tmp.write(canonical)
271
+ tmp_path = Path(tmp.name)
272
+ os.replace(tmp_path, local_path)
273
+ return remote_rows
274
+
275
+
276
+ def create_manifest_candidate(path: Path, rows: list[dict], row: dict) -> Path:
277
+ path.parent.mkdir(parents=True, exist_ok=True)
278
+ with tempfile.NamedTemporaryFile(
279
+ mode="w",
280
+ encoding="utf-8",
281
+ dir=path.parent,
282
+ prefix=f".{path.name}.",
283
+ suffix=".pending",
284
+ delete=False,
285
+ ) as tmp:
286
+ for existing in rows:
287
+ tmp.write(json.dumps(existing, sort_keys=True) + "\n")
288
+ tmp.write(json.dumps(row, sort_keys=True) + "\n")
289
+ return Path(tmp.name)
290
+
291
+
292
+ def assert_mirroring_policy(dataset_name: str, policy_path: Path) -> None:
293
+ with policy_path.open(newline="", encoding="utf-8") as f:
294
+ rows = {row["dataset"]: row for row in csv.DictReader(f)}
295
+ if dataset_name not in rows:
296
+ raise RuntimeError(f"{dataset_name} is not present in {policy_path}")
297
+ policy = rows[dataset_name].get("mirror_policy", "")
298
+ if policy != "mirror_allowed_with_attribution":
299
+ raise RuntimeError(
300
+ f"Refusing to mirror {dataset_name}: registry policy is {policy!r}, not an allowed policy."
301
+ )
302
+
303
+
304
+ def luna_members(zf: zipfile.ZipFile) -> list[str]:
305
+ return sorted(info.filename for info in zf.infolist() if info.filename.lower().endswith(".mhd"))
306
+
307
+
308
+ def mhd_and_raw_member(zf: zipfile.ZipFile, mhd_member: str) -> tuple[dict[str, str], str]:
309
+ info = validated_zip_member(zf, mhd_member)
310
+ fields = parse_mhd_text(zf.read(info).decode("utf-8"))
311
+ raw_name = fields.get("ElementDataFile")
312
+ if not raw_name or raw_name.upper() == "LOCAL":
313
+ raise RuntimeError(f"Unsupported ElementDataFile in {mhd_member}: {raw_name!r}")
314
+ raw_path = PurePosixPath(mhd_member).parent / PurePosixPath(raw_name)
315
+ if raw_path.is_absolute() or ".." in raw_path.parts:
316
+ raise RuntimeError(f"Unsafe raw member path in {mhd_member}: {raw_name}")
317
+ raw_member = raw_path.as_posix()
318
+ validated_zip_member(zf, raw_member)
319
+ return fields, raw_member
320
 
321
 
322
  def main() -> None:
323
+ parser = argparse.ArgumentParser(
324
+ description="Plan or upload a bounded LUNA16 batch with strict storage guards."
325
+ )
326
  parser.add_argument("--dataset-name", default="LUNA16")
327
  parser.add_argument("--repo-id", default=None)
328
  parser.add_argument("--repo-name", default="SUMI-OpenCT")
329
  parser.add_argument("--work-dir", default=".hf_tmp/luna16")
330
+ parser.add_argument("--staging-root", default=".hf_tmp")
331
+ parser.add_argument("--lock-file", default=".hf_tmp/collection.lock")
332
  parser.add_argument("--max-local-gb", type=float, default=20.0)
333
+ parser.add_argument("--min-free-gb", type=float, default=100.0)
334
  parser.add_argument("--subset", type=int, choices=range(10), action="append")
335
+ parser.add_argument("--max-cases", type=int, default=1)
336
  parser.add_argument("--start-index", type=int, default=None)
337
+ parser.add_argument("--policy-file", type=Path, default=Path("manifests/source_datasets.csv"))
338
+ parser.add_argument(
339
+ "--execute",
340
+ action="store_true",
341
+ help="Actually download and upload. Without this flag, print a plan only.",
342
+ )
343
  args = parser.parse_args()
344
 
345
+ if args.max_cases <= 0:
346
+ parser.error("--max-cases must be positive")
347
+
348
+ budget = StorageBudget.from_gib(
349
+ Path(args.staging_root),
350
+ max_local_gib=args.max_local_gb,
351
+ min_free_gib=args.min_free_gb,
352
+ )
353
  work_dir = Path(args.work_dir).resolve()
354
  work_dir.mkdir(parents=True, exist_ok=True)
355
  subsets = args.subset if args.subset is not None else list(range(10))
356
+
357
+ if not args.execute:
358
+ print(
359
+ f"DRY RUN: subsets={subsets}; would process at most {args.max_cases} case(s); "
360
+ f"staging cap={args.max_local_gb:.1f} GiB; free-space reserve={args.min_free_gb:.1f} GiB."
361
+ )
362
+ print("Re-run with --execute to download and upload. No archive was downloaded.")
363
+ return
364
+
365
+ assert_mirroring_policy(args.dataset_name, args.policy_file)
366
+ token = get_token()
367
+ api = HfApi(token=token)
368
+ repo_id = args.repo_id or default_repo_id(api, token, args.repo_name)
369
+
370
+ with exclusive_collection_lock(Path(args.lock_file)):
371
+ budget.check(context="starting LUNA16 collection")
372
+ manifest_path = Path("manifests") / f"{args.dataset_name}.jsonl"
373
+ manifest_rows = sync_remote_manifest(repo_id, args.dataset_name, token, manifest_path)
374
+ processed_source_uids = {
375
+ str(row["source_series_uid"])
376
+ for row in manifest_rows
377
+ if row.get("source_series_uid")
378
+ }
379
+ if len(processed_source_uids) != len(manifest_rows):
380
+ raise RuntimeError("Manifest contains missing or duplicate source_series_uid values")
381
+
382
+ existing = existing_indices(api, repo_id, args.dataset_name, token)
383
+ manifested_indices = {
384
+ int(match.group(1))
385
+ for row in manifest_rows
386
+ if (match := re.fullmatch(rf"{re.escape(args.dataset_name)}_(\d{{8}})", str(row.get("folder", ""))))
387
+ }
388
+ orphan_data = existing - manifested_indices
389
+ missing_data = manifested_indices - existing
390
+ if orphan_data or missing_data:
391
+ raise RuntimeError(
392
+ "Remote data/manifest mismatch; refusing automatic resume. "
393
+ f"orphan data indices={sorted(orphan_data)}, missing data indices={sorted(missing_data)}"
394
+ )
395
+
396
+ index = args.start_index or ((max(existing) + 1) if existing else 1)
397
+ if index in existing:
398
+ raise RuntimeError(f"Requested start index {index} already exists")
399
+ processed = 0
400
+
401
+ for subset_id in subsets:
402
+ if processed >= args.max_cases:
403
+ break
404
+ budget.check(context=f"starting LUNA16 subset{subset_id}")
405
+ url, expected_md5 = LUNA16_FILES[subset_id]
406
+ with tempfile.TemporaryDirectory(dir=work_dir) as tmp:
407
+ tmp_dir = Path(tmp)
408
+ zip_path = tmp_dir / f"subset{subset_id}.zip"
409
+ download(url, zip_path, budget)
410
+ actual_md5 = md5_file(zip_path)
411
+ if actual_md5 != expected_md5:
412
+ raise RuntimeError(
413
+ f"MD5 mismatch for subset{subset_id}: {actual_md5} != {expected_md5}"
414
+ )
415
+
416
+ with zipfile.ZipFile(zip_path) as zf:
417
+ members = luna_members(zf)
418
+ if not members:
419
+ raise RuntimeError(f"No MHD files found in subset{subset_id}")
420
+ for mhd_member in members:
421
+ if processed >= args.max_cases:
422
+ break
423
+ source_uid = PurePosixPath(mhd_member).stem
424
+ if source_uid in processed_source_uids:
425
+ continue
426
+
427
+ fields, raw_member = mhd_and_raw_member(zf, mhd_member)
428
+ folder_name = f"{args.dataset_name}_{index:08d}"
429
+ with tempfile.TemporaryDirectory(dir=tmp_dir, prefix="case-") as case_tmp:
430
+ case_tmp_dir = Path(case_tmp)
431
+ raw_path = case_tmp_dir / PurePosixPath(raw_member).name
432
+ case_dir = case_tmp_dir / folder_name
433
+ case_dir.mkdir(parents=True, exist_ok=True)
434
+ ct_path = case_dir / "ct.nii.gz"
435
+
436
+ extract_member_bounded(zf, raw_member, raw_path, budget)
437
+ conversion = convert_mhd_fields_to_nifti(
438
+ fields, raw_path, ct_path, budget
439
+ )
440
+ digest = sha256_file(ct_path)
441
+ size_bytes = ct_path.stat().st_size
442
+ row = {
443
+ "dataset": args.dataset_name,
444
+ "folder": folder_name,
445
+ "path": f"data/{folder_name}/ct.nii.gz",
446
+ "source": "LUNA16",
447
+ "source_subset": subset_id,
448
+ "source_series_uid": source_uid,
449
+ "source_mhd": mhd_member,
450
+ "sha256": digest,
451
+ "size_bytes": size_bytes,
452
+ **conversion,
453
+ }
454
+
455
+ original_digest = sha256_file(manifest_path) if manifest_path.exists() else None
456
+ candidate = create_manifest_candidate(manifest_path, manifest_rows, row)
457
+ try:
458
+ api.create_commit(
459
+ repo_id=repo_id,
460
+ repo_type="dataset",
461
+ token=token,
462
+ commit_message=f"Add {folder_name} with manifest",
463
+ operations=[
464
+ CommitOperationAdd(
465
+ path_in_repo=f"data/{folder_name}/ct.nii.gz",
466
+ path_or_fileobj=str(ct_path),
467
+ ),
468
+ CommitOperationAdd(
469
+ path_in_repo=f"manifests/{args.dataset_name}.jsonl",
470
+ path_or_fileobj=str(candidate),
471
+ ),
472
+ ],
473
+ )
474
+ current_digest = (
475
+ sha256_file(manifest_path) if manifest_path.exists() else None
476
+ )
477
+ if current_digest != original_digest:
478
+ raise RuntimeError(
479
+ "Remote commit succeeded, but the local manifest changed "
480
+ "concurrently; leaving it untouched for reconciliation."
481
+ )
482
+ os.replace(candidate, manifest_path)
483
+ finally:
484
+ candidate.unlink(missing_ok=True)
485
+
486
+ manifest_rows.append(row)
487
+ processed_source_uids.add(source_uid)
488
+ processed += 1
489
+ index += 1
490
+ budget.check(context="finishing LUNA16 case")
491
+
492
+ print(f"Uploaded {processed} {args.dataset_name} case(s) to {repo_id}")
493
 
494
 
495
  if __name__ == "__main__":
scripts/storage_guard.py ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Shared, fail-closed storage guards for collection scripts.
3
+
4
+ The guards enforce both a workspace staging cap and a filesystem free-space
5
+ reserve. Checks happen before and during writes so a misleading or missing
6
+ Content-Length cannot fill the disk. A workspace-wide advisory lock prevents
7
+ the bundled collectors from staging large archives concurrently.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import fcntl
13
+ import os
14
+ import shutil
15
+ import zipfile
16
+ from contextlib import contextmanager
17
+ from dataclasses import dataclass
18
+ from pathlib import Path, PurePosixPath
19
+ from typing import BinaryIO, Callable, Iterator
20
+
21
+
22
+ GIB = 1024**3
23
+ COPY_CHUNK_BYTES = 1024 * 1024
24
+
25
+
26
+ class StorageLimitError(RuntimeError):
27
+ """Raised before a write would violate a configured storage limit."""
28
+
29
+
30
+ def bytes_in_tree(path: Path) -> int:
31
+ """Return allocated file sizes below *path* without following symlinks."""
32
+
33
+ if not path.exists():
34
+ return 0
35
+ total = 0
36
+ for item in path.rglob("*"):
37
+ if item.is_file() and not item.is_symlink():
38
+ total += item.stat().st_size
39
+ return total
40
+
41
+
42
+ @dataclass(frozen=True)
43
+ class StorageBudget:
44
+ """A staging-directory cap plus a whole-filesystem free-space reserve."""
45
+
46
+ staging_root: Path
47
+ max_local_bytes: int
48
+ min_free_bytes: int
49
+
50
+ @classmethod
51
+ def from_gib(
52
+ cls,
53
+ staging_root: Path,
54
+ max_local_gib: float,
55
+ min_free_gib: float,
56
+ ) -> "StorageBudget":
57
+ if max_local_gib <= 0:
58
+ raise ValueError("max_local_gib must be positive")
59
+ if min_free_gib < 0:
60
+ raise ValueError("min_free_gib cannot be negative")
61
+ root = staging_root.resolve()
62
+ root.mkdir(parents=True, exist_ok=True)
63
+ return cls(
64
+ staging_root=root,
65
+ max_local_bytes=int(max_local_gib * GIB),
66
+ min_free_bytes=int(min_free_gib * GIB),
67
+ )
68
+
69
+ def check(self, additional_bytes: int = 0, context: str = "operation") -> None:
70
+ """Fail if writing *additional_bytes* would exceed either limit."""
71
+
72
+ if additional_bytes < 0:
73
+ raise ValueError("additional_bytes cannot be negative")
74
+ staged = bytes_in_tree(self.staging_root)
75
+ if staged + additional_bytes > self.max_local_bytes:
76
+ raise StorageLimitError(
77
+ f"Refusing {context}: staging would use "
78
+ f"{(staged + additional_bytes) / GIB:.2f} GiB, above the "
79
+ f"{self.max_local_bytes / GIB:.2f} GiB cap at {self.staging_root}."
80
+ )
81
+
82
+ free = shutil.disk_usage(self.staging_root).free
83
+ if free - additional_bytes < self.min_free_bytes:
84
+ raise StorageLimitError(
85
+ f"Refusing {context}: projected filesystem free space is "
86
+ f"{max(0, free - additional_bytes) / GIB:.2f} GiB, below the "
87
+ f"{self.min_free_bytes / GIB:.2f} GiB reserve."
88
+ )
89
+
90
+
91
+ def copy_bounded(
92
+ source: BinaryIO,
93
+ destination: Path,
94
+ budget: StorageBudget,
95
+ *,
96
+ expected_bytes: int | None = None,
97
+ context: str = "write",
98
+ on_chunk: Callable[[int], None] | None = None,
99
+ ) -> int:
100
+ """Copy a binary stream while checking the budget before every chunk."""
101
+
102
+ if expected_bytes is not None:
103
+ budget.check(expected_bytes, context=context)
104
+ else:
105
+ budget.check(context=context)
106
+
107
+ destination.parent.mkdir(parents=True, exist_ok=True)
108
+ written = 0
109
+ try:
110
+ with destination.open("wb") as output:
111
+ while True:
112
+ chunk = source.read(COPY_CHUNK_BYTES)
113
+ if not chunk:
114
+ break
115
+ budget.check(len(chunk), context=context)
116
+ output.write(chunk)
117
+ written += len(chunk)
118
+ if on_chunk is not None:
119
+ on_chunk(len(chunk))
120
+ except BaseException:
121
+ destination.unlink(missing_ok=True)
122
+ raise
123
+
124
+ if expected_bytes is not None and written != expected_bytes:
125
+ destination.unlink(missing_ok=True)
126
+ raise RuntimeError(
127
+ f"Incomplete {context}: wrote {written} bytes, expected {expected_bytes}."
128
+ )
129
+ return written
130
+
131
+
132
+ def validated_zip_member(zf: zipfile.ZipFile, member_name: str) -> zipfile.ZipInfo:
133
+ """Resolve a regular ZIP member and reject traversal or link-like entries."""
134
+
135
+ path = PurePosixPath(member_name)
136
+ if path.is_absolute() or ".." in path.parts:
137
+ raise RuntimeError(f"Unsafe ZIP member path: {member_name}")
138
+ info = zf.getinfo(member_name)
139
+ if info.is_dir():
140
+ raise RuntimeError(f"Expected a file, found ZIP directory: {member_name}")
141
+ unix_mode = info.external_attr >> 16
142
+ if unix_mode and (unix_mode & 0o170000) not in (0, 0o100000):
143
+ raise RuntimeError(f"Refusing non-regular ZIP member: {member_name}")
144
+ return info
145
+
146
+
147
+ def extract_member_bounded(
148
+ zf: zipfile.ZipFile,
149
+ member_name: str,
150
+ destination: Path,
151
+ budget: StorageBudget,
152
+ ) -> int:
153
+ """Extract one regular ZIP member with traversal and storage checks."""
154
+
155
+ info = validated_zip_member(zf, member_name)
156
+ with zf.open(info, "r") as source:
157
+ return copy_bounded(
158
+ source,
159
+ destination,
160
+ budget,
161
+ expected_bytes=info.file_size,
162
+ context=f"extracting {member_name}",
163
+ )
164
+
165
+
166
+ @contextmanager
167
+ def exclusive_collection_lock(lock_path: Path) -> Iterator[None]:
168
+ """Prevent bundled collectors from running large staging jobs together."""
169
+
170
+ path = lock_path.resolve()
171
+ path.parent.mkdir(parents=True, exist_ok=True)
172
+ with path.open("a+", encoding="utf-8") as lock_file:
173
+ try:
174
+ fcntl.flock(lock_file.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
175
+ except BlockingIOError as exc:
176
+ lock_file.seek(0)
177
+ owner = lock_file.read().strip() or "another process"
178
+ raise RuntimeError(f"Collection lock {path} is held by {owner}.") from exc
179
+
180
+ lock_file.seek(0)
181
+ lock_file.truncate()
182
+ lock_file.write(f"pid={os.getpid()}")
183
+ lock_file.flush()
184
+ try:
185
+ yield
186
+ finally:
187
+ lock_file.seek(0)
188
+ lock_file.truncate()
189
+ lock_file.flush()
190
+ fcntl.flock(lock_file.fileno(), fcntl.LOCK_UN)
scripts/tcia_collect_upload.py CHANGED
@@ -18,19 +18,33 @@ import hashlib
18
  import json
19
  import os
20
  import re
21
- import shutil
22
  import tempfile
23
  import zipfile
24
  from dataclasses import dataclass
25
- from pathlib import Path
26
  from typing import Iterable
27
 
28
  import nibabel as nib
29
  import numpy as np
30
  import requests
31
- from huggingface_hub import HfApi
32
  from tqdm import tqdm
33
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
  try:
35
  import pydicom
36
  except ImportError as exc: # pragma: no cover - dependency guard
@@ -73,26 +87,6 @@ def default_repo_id(api: HfApi, token: str, repo_name: str) -> str:
73
  return f"{namespace}/{repo_name}"
74
 
75
 
76
- def bytes_in_tree(path: Path) -> int:
77
- if not path.exists():
78
- return 0
79
- total = 0
80
- for item in path.rglob("*"):
81
- if item.is_file():
82
- total += item.stat().st_size
83
- return total
84
-
85
-
86
- def enforce_staging_limit(path: Path, max_local_gb: float) -> None:
87
- used = bytes_in_tree(path)
88
- limit = int(max_local_gb * 1024**3)
89
- if used > limit:
90
- raise RuntimeError(
91
- f"Staging directory {path} uses {used / 1024**3:.2f} GiB, "
92
- f"above the configured {max_local_gb:.2f} GiB limit."
93
- )
94
-
95
-
96
  def request_json(endpoint: str, params: dict[str, str | int]) -> list[dict]:
97
  resp = requests.get(f"{TCIA_BASE}/{endpoint}", params=params, timeout=120)
98
  resp.raise_for_status()
@@ -119,10 +113,7 @@ def load_series(collection: str, modality: str = "CT") -> list[SeriesInfo]:
119
 
120
 
121
  def existing_indices(api: HfApi, repo_id: str, repo_type: str, dataset_name: str, token: str) -> set[int]:
122
- try:
123
- files = api.list_repo_files(repo_id=repo_id, repo_type=repo_type, token=token)
124
- except Exception:
125
- return set()
126
  pattern = re.compile(rf"^data/{re.escape(dataset_name)}_(\d{{8}})/ct\.nii\.gz$")
127
  indices: set[int] = set()
128
  for path in files:
@@ -138,27 +129,39 @@ def next_index(existing: set[int], requested_start: int | None = None) -> int:
138
  return (max(existing) + 1) if existing else 1
139
 
140
 
141
- def download_series_zip(series_uid: str, out_path: Path) -> None:
142
  params = {"SeriesInstanceUID": series_uid}
143
  with requests.get(f"{TCIA_BASE}/getImage", params=params, stream=True, timeout=300) as resp:
144
  resp.raise_for_status()
145
  total = int(resp.headers.get("content-length") or 0)
146
- with out_path.open("wb") as f, tqdm(
147
  total=total,
148
  unit="B",
149
  unit_scale=True,
150
  desc=f"download {series_uid[-12:]}",
 
151
  ) as bar:
152
- for chunk in resp.iter_content(chunk_size=1024 * 1024):
153
- if chunk:
154
- f.write(chunk)
155
- bar.update(len(chunk))
 
 
 
 
156
 
157
 
158
- def extract_zip(zip_path: Path, out_dir: Path) -> list[Path]:
 
159
  with zipfile.ZipFile(zip_path) as zf:
160
- zf.extractall(out_dir)
161
- return [p for p in out_dir.rglob("*") if p.is_file()]
 
 
 
 
 
 
162
 
163
 
164
  def read_dicom_slices(paths: Iterable[Path]) -> list:
@@ -185,7 +188,11 @@ def slice_position(ds, normal: np.ndarray) -> float:
185
  return float(getattr(ds, "InstanceNumber", 0))
186
 
187
 
188
- def dicom_to_nifti(dicom_paths: Iterable[Path], out_path: Path) -> dict[str, object]:
 
 
 
 
189
  slices = read_dicom_slices(dicom_paths)
190
  first = slices[0]
191
  orientation = np.asarray([float(v) for v in first.ImageOrientationPatient], dtype=float)
@@ -198,6 +205,7 @@ def dicom_to_nifti(dicom_paths: Iterable[Path], out_path: Path) -> dict[str, obj
198
  normal = normal / norm
199
 
200
  slices.sort(key=lambda ds: slice_position(ds, normal))
 
201
  positions = [slice_position(ds, normal) for ds in slices]
202
  diffs = np.diff(positions)
203
  if len(diffs):
@@ -235,6 +243,9 @@ def dicom_to_nifti(dicom_paths: Iterable[Path], out_path: Path) -> dict[str, obj
235
  image.header.set_xyzt_units("mm")
236
  image.header["cal_min"] = float(np.nanmin(data))
237
  image.header["cal_max"] = float(np.nanmax(data))
 
 
 
238
  nib.save(image, str(out_path))
239
 
240
  return {
@@ -253,31 +264,131 @@ def sha256_file(path: Path) -> str:
253
  return h.hexdigest()
254
 
255
 
256
- def append_jsonl(path: Path, row: dict) -> None:
257
- path.parent.mkdir(parents=True, exist_ok=True)
258
- with path.open("a", encoding="utf-8") as f:
259
- f.write(json.dumps(row, sort_keys=True) + "\n")
260
-
261
-
262
- def read_manifest_values(path: Path, key: str) -> set[str]:
263
  if not path.exists():
264
- return set()
265
- values: set[str] = set()
266
  with path.open("r", encoding="utf-8") as f:
267
- for line in f:
268
  line = line.strip()
269
  if not line:
270
  continue
271
  try:
272
  row = json.loads(line)
273
- except json.JSONDecodeError:
274
- continue
275
- value = row.get(key)
276
- if value:
277
- values.add(str(value))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
278
  return values
279
 
280
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
281
  def write_series_catalog(path: Path, series: list[SeriesInfo]) -> None:
282
  path.parent.mkdir(parents=True, exist_ok=True)
283
  with path.open("w", newline="", encoding="utf-8") as f:
@@ -299,113 +410,196 @@ def write_series_catalog(path: Path, series: list[SeriesInfo]) -> None:
299
 
300
 
301
  def main() -> None:
302
- parser = argparse.ArgumentParser()
 
 
303
  parser.add_argument("--collection", required=True, help="TCIA collection name, e.g. LIDC-IDRI.")
304
  parser.add_argument("--dataset-name", required=True, help="Folder prefix, e.g. LIDC-IDRI.")
305
  parser.add_argument("--repo-id", default=None)
306
  parser.add_argument("--repo-name", default="SUMI-OpenCT")
307
  parser.add_argument("--work-dir", default=".hf_tmp/tcia")
308
- parser.add_argument("--max-local-gb", type=float, default=25.0)
309
- parser.add_argument("--max-cases", type=int, default=None)
 
 
 
 
 
 
 
 
310
  parser.add_argument("--start-index", type=int, default=None)
311
- parser.add_argument("--skip-existing", action="store_true")
 
312
  parser.add_argument("--metadata-only", action="store_true")
 
 
 
 
 
313
  args = parser.parse_args()
314
 
315
- token = get_token()
316
- api = HfApi(token=token)
317
- repo_id = args.repo_id or default_repo_id(api, token, args.repo_name)
318
- work_dir = Path(args.work_dir).resolve() / args.dataset_name
319
- work_dir.mkdir(parents=True, exist_ok=True)
320
 
321
- series = load_series(args.collection)
322
- catalog_path = Path("manifests") / f"{args.dataset_name}_tcia_series.csv"
323
- write_series_catalog(catalog_path, series)
324
- api.upload_file(
325
- repo_id=repo_id,
326
- repo_type="dataset",
327
- path_or_fileobj=str(catalog_path),
328
- path_in_repo=f"manifests/{catalog_path.name}",
329
- token=token,
330
- commit_message=f"Add {args.dataset_name} TCIA series catalog",
331
  )
332
- if args.metadata_only:
333
- print(f"Wrote metadata for {len(series)} series")
334
- return
335
-
336
- existing = existing_indices(api, repo_id, "dataset", args.dataset_name, token)
337
- index = next_index(existing, args.start_index)
338
- processed = 0
339
- manifest_path = Path("manifests") / f"{args.dataset_name}.jsonl"
340
- processed_source_uids = read_manifest_values(manifest_path, "source_series_uid")
341
-
342
- for item in series:
343
- if args.max_cases is not None and processed >= args.max_cases:
344
- break
345
- if item.series_uid in processed_source_uids:
346
- continue
347
- if args.skip_existing and index in existing:
348
- index += 1
349
- continue
350
 
351
- folder_name = f"{args.dataset_name}_{index:08d}"
352
- with tempfile.TemporaryDirectory(dir=work_dir) as tmp:
353
- tmp_dir = Path(tmp)
354
- zip_path = tmp_dir / "series.zip"
355
- extract_dir = tmp_dir / "dicom"
356
- case_dir = tmp_dir / folder_name
357
- case_dir.mkdir(parents=True, exist_ok=True)
358
- ct_path = case_dir / "ct.nii.gz"
359
-
360
- download_series_zip(item.series_uid, zip_path)
361
- enforce_staging_limit(work_dir, args.max_local_gb)
362
- dicom_files = extract_zip(zip_path, extract_dir)
363
- enforce_staging_limit(work_dir, args.max_local_gb)
364
- conversion = dicom_to_nifti(dicom_files, ct_path)
365
- digest = sha256_file(ct_path)
366
- size_bytes = ct_path.stat().st_size
367
-
368
- api.upload_folder(
369
- repo_id=repo_id,
370
- repo_type="dataset",
371
- folder_path=str(case_dir),
372
- path_in_repo=f"data/{folder_name}",
373
- token=token,
374
- commit_message=f"Add {folder_name}",
375
  )
376
-
377
- row = {
378
- "dataset": args.dataset_name,
379
- "folder": folder_name,
380
- "path": f"data/{folder_name}/ct.nii.gz",
381
- "source_collection": item.collection,
382
- "source_patient_id": item.patient_id,
383
- "source_study_uid": item.study_uid,
384
- "source_series_uid": item.series_uid,
385
- "source_image_count": item.image_count,
386
- "source_manufacturer": item.manufacturer,
387
- "source_model": item.model,
388
- "sha256": digest,
389
- "size_bytes": size_bytes,
390
- **conversion,
391
- }
392
- append_jsonl(manifest_path, row)
393
- processed_source_uids.add(item.series_uid)
394
- api.upload_file(
395
- repo_id=repo_id,
396
- repo_type="dataset",
397
- path_or_fileobj=str(manifest_path),
398
- path_in_repo=f"manifests/{args.dataset_name}.jsonl",
399
- token=token,
400
- commit_message=f"Update {args.dataset_name} manifest",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
401
  )
402
 
403
- shutil.rmtree(work_dir / "__pycache__", ignore_errors=True)
404
- processed += 1
405
- index += 1
406
- enforce_staging_limit(work_dir, args.max_local_gb)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
407
 
408
- print(f"Uploaded {processed} {args.dataset_name} cases to {repo_id}")
409
 
410
 
411
  if __name__ == "__main__":
 
18
  import json
19
  import os
20
  import re
 
21
  import tempfile
22
  import zipfile
23
  from dataclasses import dataclass
24
+ from pathlib import Path, PurePosixPath
25
  from typing import Iterable
26
 
27
  import nibabel as nib
28
  import numpy as np
29
  import requests
30
+ from huggingface_hub import CommitOperationAdd, HfApi
31
  from tqdm import tqdm
32
 
33
+ try:
34
+ from .storage_guard import (
35
+ StorageBudget,
36
+ copy_bounded,
37
+ exclusive_collection_lock,
38
+ extract_member_bounded,
39
+ )
40
+ except ImportError: # Support `python scripts/tcia_collect_upload.py`.
41
+ from storage_guard import ( # type: ignore[no-redef]
42
+ StorageBudget,
43
+ copy_bounded,
44
+ exclusive_collection_lock,
45
+ extract_member_bounded,
46
+ )
47
+
48
  try:
49
  import pydicom
50
  except ImportError as exc: # pragma: no cover - dependency guard
 
87
  return f"{namespace}/{repo_name}"
88
 
89
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90
  def request_json(endpoint: str, params: dict[str, str | int]) -> list[dict]:
91
  resp = requests.get(f"{TCIA_BASE}/{endpoint}", params=params, timeout=120)
92
  resp.raise_for_status()
 
113
 
114
 
115
  def existing_indices(api: HfApi, repo_id: str, repo_type: str, dataset_name: str, token: str) -> set[int]:
116
+ files = api.list_repo_files(repo_id=repo_id, repo_type=repo_type, token=token)
 
 
 
117
  pattern = re.compile(rf"^data/{re.escape(dataset_name)}_(\d{{8}})/ct\.nii\.gz$")
118
  indices: set[int] = set()
119
  for path in files:
 
129
  return (max(existing) + 1) if existing else 1
130
 
131
 
132
+ def download_series_zip(series_uid: str, out_path: Path, budget: StorageBudget) -> None:
133
  params = {"SeriesInstanceUID": series_uid}
134
  with requests.get(f"{TCIA_BASE}/getImage", params=params, stream=True, timeout=300) as resp:
135
  resp.raise_for_status()
136
  total = int(resp.headers.get("content-length") or 0)
137
+ with tqdm(
138
  total=total,
139
  unit="B",
140
  unit_scale=True,
141
  desc=f"download {series_uid[-12:]}",
142
+ mininterval=10.0,
143
  ) as bar:
144
+ copy_bounded(
145
+ resp.raw,
146
+ out_path,
147
+ budget,
148
+ expected_bytes=total or None,
149
+ context=f"downloading TCIA series {series_uid}",
150
+ on_chunk=bar.update,
151
+ )
152
 
153
 
154
+ def extract_zip(zip_path: Path, out_dir: Path, budget: StorageBudget) -> list[Path]:
155
+ files: list[Path] = []
156
  with zipfile.ZipFile(zip_path) as zf:
157
+ for info in zf.infolist():
158
+ if info.is_dir():
159
+ continue
160
+ rel = PurePosixPath(info.filename)
161
+ target = out_dir.joinpath(*rel.parts)
162
+ extract_member_bounded(zf, info.filename, target, budget)
163
+ files.append(target)
164
+ return files
165
 
166
 
167
  def read_dicom_slices(paths: Iterable[Path]) -> list:
 
188
  return float(getattr(ds, "InstanceNumber", 0))
189
 
190
 
191
+ def dicom_to_nifti(
192
+ dicom_paths: Iterable[Path],
193
+ out_path: Path,
194
+ budget: StorageBudget | None = None,
195
+ ) -> dict[str, object]:
196
  slices = read_dicom_slices(dicom_paths)
197
  first = slices[0]
198
  orientation = np.asarray([float(v) for v in first.ImageOrientationPatient], dtype=float)
 
205
  normal = normal / norm
206
 
207
  slices.sort(key=lambda ds: slice_position(ds, normal))
208
+ first = slices[0]
209
  positions = [slice_position(ds, normal) for ds in slices]
210
  diffs = np.diff(positions)
211
  if len(diffs):
 
243
  image.header.set_xyzt_units("mm")
244
  image.header["cal_min"] = float(np.nanmin(data))
245
  image.header["cal_max"] = float(np.nanmax(data))
246
+ if budget is not None:
247
+ worst_case_bytes = int(data.nbytes * 1.01) + 1024 * 1024
248
+ budget.check(worst_case_bytes, context="writing converted TCIA NIfTI")
249
  nib.save(image, str(out_path))
250
 
251
  return {
 
264
  return h.hexdigest()
265
 
266
 
267
+ def read_manifest_rows(path: Path) -> list[dict]:
 
 
 
 
 
 
268
  if not path.exists():
269
+ return []
270
+ rows: list[dict] = []
271
  with path.open("r", encoding="utf-8") as f:
272
+ for line_number, line in enumerate(f, start=1):
273
  line = line.strip()
274
  if not line:
275
  continue
276
  try:
277
  row = json.loads(line)
278
+ except json.JSONDecodeError as exc:
279
+ raise RuntimeError(f"Invalid JSON in {path}:{line_number}: {exc}") from exc
280
+ if not isinstance(row, dict):
281
+ raise RuntimeError(f"Expected an object in {path}:{line_number}")
282
+ rows.append(row)
283
+ return rows
284
+
285
+
286
+ def sync_remote_manifest(
287
+ repo_id: str,
288
+ dataset_name: str,
289
+ token: str,
290
+ local_path: Path,
291
+ ) -> list[dict]:
292
+ """Use the remote manifest as authority and refuse divergent local state."""
293
+
294
+ remote_path = f"manifests/{dataset_name}.jsonl"
295
+ url = f"https://huggingface.co/datasets/{repo_id}/resolve/main/{remote_path}"
296
+ response = requests.get(url, headers={"Authorization": f"Bearer {token}"}, timeout=120)
297
+ if response.status_code == 404:
298
+ return read_manifest_rows(local_path)
299
+ response.raise_for_status()
300
+
301
+ remote_rows: list[dict] = []
302
+ for line_number, line in enumerate(response.text.splitlines(), start=1):
303
+ if not line.strip():
304
+ continue
305
+ try:
306
+ row = json.loads(line)
307
+ except json.JSONDecodeError as exc:
308
+ raise RuntimeError(
309
+ f"Invalid JSON in remote {remote_path}:{line_number}: {exc}"
310
+ ) from exc
311
+ if not isinstance(row, dict):
312
+ raise RuntimeError(f"Expected an object in remote {remote_path}:{line_number}")
313
+ remote_rows.append(row)
314
+
315
+ local_rows = read_manifest_rows(local_path)
316
+ remote_uids = {str(row.get("source_series_uid")) for row in remote_rows}
317
+ local_only = {
318
+ str(row.get("source_series_uid"))
319
+ for row in local_rows
320
+ if str(row.get("source_series_uid")) not in remote_uids
321
+ }
322
+ if local_only:
323
+ raise RuntimeError(
324
+ f"Local manifest has {len(local_only)} source UID(s) absent from the remote manifest; "
325
+ "refusing to overwrite divergent state."
326
+ )
327
+
328
+ canonical = "".join(json.dumps(row, sort_keys=True) + "\n" for row in remote_rows)
329
+ current = local_path.read_text(encoding="utf-8") if local_path.exists() else ""
330
+ if canonical != current:
331
+ local_path.parent.mkdir(parents=True, exist_ok=True)
332
+ with tempfile.NamedTemporaryFile(
333
+ mode="w",
334
+ encoding="utf-8",
335
+ dir=local_path.parent,
336
+ prefix=f".{local_path.name}.",
337
+ suffix=".sync",
338
+ delete=False,
339
+ ) as tmp:
340
+ tmp.write(canonical)
341
+ tmp_path = Path(tmp.name)
342
+ os.replace(tmp_path, local_path)
343
+ return remote_rows
344
+
345
+
346
+ def create_manifest_candidate(path: Path, rows: list[dict], row: dict) -> Path:
347
+ """Create the next manifest beside the canonical file for an atomic swap."""
348
+
349
+ path.parent.mkdir(parents=True, exist_ok=True)
350
+ with tempfile.NamedTemporaryFile(
351
+ mode="w",
352
+ encoding="utf-8",
353
+ dir=path.parent,
354
+ prefix=f".{path.name}.",
355
+ suffix=".pending",
356
+ delete=False,
357
+ ) as tmp:
358
+ for existing in rows:
359
+ tmp.write(json.dumps(existing, sort_keys=True) + "\n")
360
+ tmp.write(json.dumps(row, sort_keys=True) + "\n")
361
+ return Path(tmp.name)
362
+
363
+
364
+ def read_series_allowlist(path: Path) -> set[str]:
365
+ """Read a CSV with a required `series_uid` column."""
366
+
367
+ with path.open(newline="", encoding="utf-8") as f:
368
+ reader = csv.DictReader(f)
369
+ if not reader.fieldnames or "series_uid" not in reader.fieldnames:
370
+ raise RuntimeError(f"{path} must contain a series_uid column")
371
+ values = {str(row["series_uid"]).strip() for row in reader if row.get("series_uid")}
372
+ if not values:
373
+ raise RuntimeError(f"{path} contains no series UIDs")
374
  return values
375
 
376
 
377
+ def assert_mirroring_policy(dataset_name: str, policy_path: Path) -> None:
378
+ """Fail closed unless the source registry explicitly permits mirroring."""
379
+
380
+ with policy_path.open(newline="", encoding="utf-8") as f:
381
+ rows = {row["dataset"]: row for row in csv.DictReader(f)}
382
+ if dataset_name not in rows:
383
+ raise RuntimeError(f"{dataset_name} is not present in {policy_path}")
384
+ policy = rows[dataset_name].get("mirror_policy", "")
385
+ allowed = {"mirror_allowed_with_attribution", "mirror_selected_public_ct_with_attribution"}
386
+ if policy not in allowed:
387
+ raise RuntimeError(
388
+ f"Refusing to mirror {dataset_name}: registry policy is {policy!r}, not an allowed policy."
389
+ )
390
+
391
+
392
  def write_series_catalog(path: Path, series: list[SeriesInfo]) -> None:
393
  path.parent.mkdir(parents=True, exist_ok=True)
394
  with path.open("w", newline="", encoding="utf-8") as f:
 
410
 
411
 
412
  def main() -> None:
413
+ parser = argparse.ArgumentParser(
414
+ description="Catalog TCIA series or upload a bounded, policy-approved batch."
415
+ )
416
  parser.add_argument("--collection", required=True, help="TCIA collection name, e.g. LIDC-IDRI.")
417
  parser.add_argument("--dataset-name", required=True, help="Folder prefix, e.g. LIDC-IDRI.")
418
  parser.add_argument("--repo-id", default=None)
419
  parser.add_argument("--repo-name", default="SUMI-OpenCT")
420
  parser.add_argument("--work-dir", default=".hf_tmp/tcia")
421
+ parser.add_argument("--staging-root", default=".hf_tmp")
422
+ parser.add_argument("--lock-file", default=".hf_tmp/collection.lock")
423
+ parser.add_argument("--max-local-gb", type=float, default=20.0)
424
+ parser.add_argument("--min-free-gb", type=float, default=100.0)
425
+ parser.add_argument(
426
+ "--max-cases",
427
+ type=int,
428
+ default=1,
429
+ help="Bounded batch size; defaults to one case.",
430
+ )
431
  parser.add_argument("--start-index", type=int, default=None)
432
+ parser.add_argument("--series-allowlist", type=Path, default=None)
433
+ parser.add_argument("--policy-file", type=Path, default=Path("manifests/source_datasets.csv"))
434
  parser.add_argument("--metadata-only", action="store_true")
435
+ parser.add_argument(
436
+ "--execute",
437
+ action="store_true",
438
+ help="Actually upload. Without this flag, the command only prepares local metadata and a plan.",
439
+ )
440
  args = parser.parse_args()
441
 
442
+ if args.max_cases <= 0:
443
+ parser.error("--max-cases must be positive")
444
+ if args.dataset_name.upper() == "NLST" and not args.metadata_only and args.series_allowlist is None:
445
+ parser.error("NLST data collection requires --series-allowlist; full-collection download is forbidden")
 
446
 
447
+ budget = StorageBudget.from_gib(
448
+ Path(args.staging_root),
449
+ max_local_gib=args.max_local_gb,
450
+ min_free_gib=args.min_free_gb,
 
 
 
 
 
 
451
  )
452
+ work_dir = Path(args.work_dir).resolve() / args.dataset_name
453
+ work_dir.mkdir(parents=True, exist_ok=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
454
 
455
+ with exclusive_collection_lock(Path(args.lock_file)):
456
+ budget.check(context="starting TCIA collection")
457
+ all_series = load_series(args.collection)
458
+ catalog_path = Path("manifests") / f"{args.dataset_name}_tcia_series.csv"
459
+ write_series_catalog(catalog_path, all_series)
460
+
461
+ selected_series = all_series
462
+ if args.series_allowlist is not None:
463
+ allowed_uids = read_series_allowlist(args.series_allowlist)
464
+ by_uid = {item.series_uid: item for item in all_series}
465
+ missing = allowed_uids - by_uid.keys()
466
+ if missing:
467
+ raise RuntimeError(
468
+ f"Allowlist contains {len(missing)} UID(s) absent from TCIA collection {args.collection}."
469
+ )
470
+ selected_series = [item for item in all_series if item.series_uid in allowed_uids]
471
+
472
+ if not args.execute:
473
+ local_rows = read_manifest_rows(Path("manifests") / f"{args.dataset_name}.jsonl")
474
+ completed = {str(row.get("source_series_uid")) for row in local_rows}
475
+ pending = [item for item in selected_series if item.series_uid not in completed]
476
+ print(
477
+ f"DRY RUN: cataloged {len(all_series)} series; selected {len(selected_series)}; "
478
+ f"pending {len(pending)}; would process at most {min(args.max_cases, len(pending))}."
479
  )
480
+ print("Re-run with --execute to upload. No scan data was downloaded.")
481
+ return
482
+
483
+ if not args.metadata_only:
484
+ assert_mirroring_policy(args.dataset_name, args.policy_file)
485
+ token = get_token()
486
+ api = HfApi(token=token)
487
+ repo_id = args.repo_id or default_repo_id(api, token, args.repo_name)
488
+ api.upload_file(
489
+ repo_id=repo_id,
490
+ repo_type="dataset",
491
+ path_or_fileobj=str(catalog_path),
492
+ path_in_repo=f"manifests/{catalog_path.name}",
493
+ token=token,
494
+ commit_message=f"Update {args.dataset_name} TCIA series catalog",
495
+ )
496
+ if args.metadata_only:
497
+ print(f"Uploaded metadata for {len(all_series)} series to {repo_id}")
498
+ return
499
+
500
+ manifest_path = Path("manifests") / f"{args.dataset_name}.jsonl"
501
+ manifest_rows = sync_remote_manifest(repo_id, args.dataset_name, token, manifest_path)
502
+ processed_source_uids = {
503
+ str(row["source_series_uid"])
504
+ for row in manifest_rows
505
+ if row.get("source_series_uid")
506
+ }
507
+ if len(processed_source_uids) != len(manifest_rows):
508
+ raise RuntimeError("Manifest contains missing or duplicate source_series_uid values")
509
+
510
+ existing = existing_indices(api, repo_id, "dataset", args.dataset_name, token)
511
+ manifested_indices = {
512
+ int(match.group(1))
513
+ for row in manifest_rows
514
+ if (match := re.fullmatch(rf"{re.escape(args.dataset_name)}_(\d{{8}})", str(row.get("folder", ""))))
515
+ }
516
+ orphan_data = existing - manifested_indices
517
+ missing_data = manifested_indices - existing
518
+ if orphan_data or missing_data:
519
+ raise RuntimeError(
520
+ "Remote data/manifest mismatch; refusing automatic resume. "
521
+ f"orphan data indices={sorted(orphan_data)}, missing data indices={sorted(missing_data)}"
522
  )
523
 
524
+ index = next_index(existing, args.start_index)
525
+ if index in existing:
526
+ raise RuntimeError(f"Requested start index {index} already exists")
527
+
528
+ processed = 0
529
+ for item in selected_series:
530
+ if processed >= args.max_cases:
531
+ break
532
+ if item.series_uid in processed_source_uids:
533
+ continue
534
+
535
+ budget.check(context=f"starting {item.series_uid}")
536
+ folder_name = f"{args.dataset_name}_{index:08d}"
537
+ with tempfile.TemporaryDirectory(dir=work_dir) as tmp:
538
+ tmp_dir = Path(tmp)
539
+ zip_path = tmp_dir / "series.zip"
540
+ extract_dir = tmp_dir / "dicom"
541
+ case_dir = tmp_dir / folder_name
542
+ case_dir.mkdir(parents=True, exist_ok=True)
543
+ ct_path = case_dir / "ct.nii.gz"
544
+
545
+ download_series_zip(item.series_uid, zip_path, budget)
546
+ dicom_files = extract_zip(zip_path, extract_dir, budget)
547
+ conversion = dicom_to_nifti(dicom_files, ct_path, budget)
548
+ digest = sha256_file(ct_path)
549
+ size_bytes = ct_path.stat().st_size
550
+
551
+ row = {
552
+ "dataset": args.dataset_name,
553
+ "folder": folder_name,
554
+ "path": f"data/{folder_name}/ct.nii.gz",
555
+ "source_collection": item.collection,
556
+ "source_patient_id": item.patient_id,
557
+ "source_study_uid": item.study_uid,
558
+ "source_series_uid": item.series_uid,
559
+ "source_image_count": item.image_count,
560
+ "source_manufacturer": item.manufacturer,
561
+ "source_model": item.model,
562
+ "sha256": digest,
563
+ "size_bytes": size_bytes,
564
+ **conversion,
565
+ }
566
+ original_digest = sha256_file(manifest_path) if manifest_path.exists() else None
567
+ candidate = create_manifest_candidate(manifest_path, manifest_rows, row)
568
+ try:
569
+ api.create_commit(
570
+ repo_id=repo_id,
571
+ repo_type="dataset",
572
+ token=token,
573
+ commit_message=f"Add {folder_name} with manifest",
574
+ operations=[
575
+ CommitOperationAdd(
576
+ path_in_repo=f"data/{folder_name}/ct.nii.gz",
577
+ path_or_fileobj=str(ct_path),
578
+ ),
579
+ CommitOperationAdd(
580
+ path_in_repo=f"manifests/{args.dataset_name}.jsonl",
581
+ path_or_fileobj=str(candidate),
582
+ ),
583
+ ],
584
+ )
585
+ current_digest = sha256_file(manifest_path) if manifest_path.exists() else None
586
+ if current_digest != original_digest:
587
+ raise RuntimeError(
588
+ "Remote commit succeeded, but the local manifest changed concurrently; "
589
+ "leaving it untouched for reconciliation on the next run."
590
+ )
591
+ os.replace(candidate, manifest_path)
592
+ finally:
593
+ candidate.unlink(missing_ok=True)
594
+
595
+ manifest_rows.append(row)
596
+ processed_source_uids.add(item.series_uid)
597
+
598
+ processed += 1
599
+ index += 1
600
+ budget.check(context="finishing TCIA case")
601
 
602
+ print(f"Uploaded {processed} {args.dataset_name} case(s) to {repo_id}")
603
 
604
 
605
  if __name__ == "__main__":