| """Download the dataset from HuggingFace, unzip, and build a case manifest. |
| |
| Usage: |
| python -m toothcanal.download --config configs/default.yaml |
| |
| On AutoDL (China) you may want a mirror: |
| export HF_ENDPOINT=https://hf-mirror.com |
| """ |
| import os, glob, zipfile, argparse, re |
| from .utils import load_config, ensure_dir, numeric_id, write_json |
|
|
|
|
| def _safe_extract(zip_path, dest): |
| """Extract a zip, fixing common CJK filename mojibake (cp437 -> gbk/utf-8).""" |
| with zipfile.ZipFile(zip_path) as zf: |
| for info in zf.infolist(): |
| name = info.filename |
| raw = name.encode("cp437", errors="ignore") |
| for enc in ("gbk", "utf-8"): |
| try: |
| name = raw.decode(enc) |
| break |
| except Exception: |
| continue |
| target = os.path.join(dest, name) |
| if info.is_dir() or name.endswith("/"): |
| ensure_dir(target) |
| continue |
| ensure_dir(os.path.dirname(target)) |
| with zf.open(info) as src, open(target, "wb") as out: |
| out.write(src.read()) |
|
|
|
|
| def download_and_extract(cfg, only_substrings=None): |
| from huggingface_hub import HfApi, hf_hub_download |
| repo = cfg["paths"]["hf_repo"] |
| raw_dir = ensure_dir(cfg["paths"]["raw_dir"]) |
|
|
| api = HfApi() |
| files = api.list_repo_files(repo_id=repo, repo_type="dataset") |
| zips = [f for f in files if f.lower().endswith(".zip")] |
| skips = cfg["paths"].get("skip_zip_substrings", []) |
| zips = [f for f in zips if not any(s in f for s in skips)] |
| if only_substrings: |
| zips = [f for f in zips if any(s in f for s in only_substrings)] |
| print(f"[download] using {len(zips)} zip files (skipped {skips}, only={only_substrings}): {zips}") |
|
|
| for zf in zips: |
| print(f"[download] fetching {zf} ...") |
| local = hf_hub_download(repo_id=repo, repo_type="dataset", filename=zf, |
| local_dir=os.path.join(raw_dir, "_zips")) |
| print(f"[download] extracting {os.path.basename(local)} ...") |
| _safe_extract(local, raw_dir) |
| return raw_dir |
|
|
|
|
| def _build_image_from_dicom(folder): |
| """Read all *.dcm in `folder`, write image_from_dicom.nii.gz, return its path.""" |
| import SimpleITK as sitk, glob as _g |
| dcm_files = sorted(_g.glob(os.path.join(folder, "*.dcm"))) |
| if len(dcm_files) < 8: |
| return None |
| reader = sitk.ImageSeriesReader() |
| try: |
| ids = reader.GetGDCMSeriesIDs(folder) |
| if ids: |
| |
| best_files, best_n = None, -1 |
| for sid in ids: |
| fnames = reader.GetGDCMSeriesFileNames(folder, sid) |
| if len(fnames) > best_n: |
| best_n, best_files = len(fnames), fnames |
| reader.SetFileNames(best_files) |
| else: |
| reader.SetFileNames(dcm_files) |
| img = reader.Execute() |
| except Exception: |
| return None |
| out = os.path.join(folder, "image_from_dicom.nii.gz") |
| sitk.WriteImage(img, out) |
| return out |
|
|
|
|
| def _pick_label_in(folder): |
| """Among nii.gz files in `folder` (excluding image_from_dicom), pick the most |
| likely label: prefer the canonical filename if present, else the LARGEST file |
| (the duplicate 01.nii.gz / 31.nii.gz pair are usually the same content, but |
| sometimes 01.nii.gz is a symlink/older copy).""" |
| canonical = os.path.join(folder, "zzz21_tooth_mask_3ik3_label_adjust.nii.gz") |
| if os.path.exists(canonical): |
| return canonical |
| cands = [p for p in glob.glob(os.path.join(folder, "*.nii.gz")) |
| if os.path.basename(p) != "image_from_dicom.nii.gz"] |
| if not cands: |
| return None |
| |
| return max(cands, key=lambda p: os.path.getsize(os.path.realpath(p))) |
|
|
|
|
| def _series_uid_dir_to_case_name(folder, raw_dir): |
| """Pick the case-folder name by scanning relpath segments. The DEEPEST segment |
| that is purely numeric (optionally followed by trailing dashes) and in 1..40 |
| is the case folder. Earlier batch folders like '1-20' are NOT pure-numeric |
| (they contain a dash between two digits) so they won't match `\\d+-*`.""" |
| rel = os.path.relpath(folder, raw_dir).split(os.sep) |
| chosen = None |
| for seg in rel: |
| m = re.fullmatch(r"0*(\d+)-*", seg) |
| if m and 1 <= int(m.group(1)) <= 40: |
| chosen = seg |
| return chosen or os.path.basename(os.path.dirname(folder)) |
|
|
|
|
| def _find_label_for(folder, raw_dir, case_num): |
| """Look for the label .nii.gz file for this case. Strategy: |
| 1. Same folder as the DICOMs. |
| 2. Walk up to the CASE folder (whose name starts with case_num) and |
| search every .nii.gz inside it (excluding image_from_dicom). |
| 3. If still nothing, look in sibling 'case/' summary folders one level |
| up from the case (e.g. data/raw/21-30/21-30/zzz027.nii.gz). |
| """ |
| canonical = "zzz21_tooth_mask_3ik3_label_adjust.nii.gz" |
|
|
| def _ok(p): |
| return os.path.basename(p) != "image_from_dicom.nii.gz" |
|
|
| |
| here = [p for p in glob.glob(os.path.join(folder, "*.nii.gz")) if _ok(p)] |
| if here: |
| return max(here, key=lambda p: os.path.getsize(os.path.realpath(p))) |
|
|
| |
| cur = folder |
| while True: |
| parent = os.path.dirname(cur) |
| if parent == raw_dir or parent == cur: |
| break |
| cur = parent |
| m = re.match(r"0*(\d+)", os.path.basename(cur)) |
| if m and int(m.group(1)) == case_num: |
| cands = [p for p in glob.glob(os.path.join(cur, "**", "*.nii.gz"), |
| recursive=True) if _ok(p)] |
| if cands: |
| |
| preferred = [p for p in cands if str(case_num) in os.path.basename(p) |
| or canonical in os.path.basename(p)] |
| pool = preferred or cands |
| return max(pool, key=lambda p: os.path.getsize(os.path.realpath(p))) |
| break |
| return None |
|
|
|
|
| def discover_cases(raw_dir): |
| """Find all CBCT cases under raw_dir. A case = the directory directly |
| containing the DICOM slices (>=8 .dcm files), OR a directory with an |
| explicit image_from_dicom.nii.gz. Labels are searched in the same folder, |
| then up the directory tree to the case-numbered ancestor.""" |
| cases = {} |
| explicit_imgs = glob.glob(os.path.join(raw_dir, "**", "image_from_dicom.nii.gz"), |
| recursive=True) |
| candidate_dirs = set() |
| for p in explicit_imgs: |
| candidate_dirs.add(os.path.dirname(p)) |
| |
| for folder, dirs, files in os.walk(raw_dir): |
| |
| parts = folder.split(os.sep) |
| if any(seg.startswith(".") or seg == "_zips" for seg in parts): |
| dirs[:] = [] |
| continue |
| n_dcm = sum(1 for f in files if f.lower().endswith(".dcm")) |
| if n_dcm >= 8: |
| candidate_dirs.add(folder) |
|
|
| for folder in sorted(candidate_dirs): |
| |
| |
| |
| |
| |
| rel = os.path.relpath(folder, raw_dir).split(os.sep) |
| case_num = -1 |
| case_name = None |
| for seg in rel: |
| m = re.fullmatch(r"0*(\d+)-*", seg) |
| if m and 1 <= int(m.group(1)) <= 40: |
| case_num = int(m.group(1)) |
| case_name = seg |
| if case_num < 0: |
| print(f"[discover] cannot infer case number from {folder}; skipping") |
| continue |
|
|
| |
| |
| prev = cases.get(case_name) |
| n_dcm = sum(1 for f in os.listdir(folder) if f.lower().endswith(".dcm")) |
| if prev is not None and prev.get("n_dcm", 0) >= n_dcm and prev.get("has_real_dcm", True): |
| continue |
|
|
| |
| img_path = os.path.join(folder, "image_from_dicom.nii.gz") |
| if not os.path.exists(img_path): |
| if n_dcm >= 8: |
| print(f"[discover] {case_name}: building image_from_dicom.nii.gz " |
| f"from {n_dcm} DICOM slices in {folder} ...") |
| built = _build_image_from_dicom(folder) |
| if built is None: |
| print(f"[discover] {folder}: DICOM read failed, skipping.") |
| continue |
| img_path = built |
| else: |
| continue |
|
|
| label = _find_label_for(folder, raw_dir, case_num) |
| if label is None: |
| print(f"[discover] {case_name}: no label .nii.gz found anywhere in " |
| f"its subtree, skipping.") |
| continue |
| cases[case_name] = dict(image=img_path, label=label, num=case_num, |
| n_dcm=n_dcm, has_real_dcm=True) |
|
|
| cases = {k: {kk: vv for kk, vv in v.items() if kk not in ("n_dcm", "has_real_dcm")} |
| for k, v in sorted(cases.items(), key=lambda kv: kv[1]["num"])} |
| print(f"[discover] found {len(cases)} cases: {[c for c in cases]}") |
| return cases |
|
|
|
|
| def main(): |
| ap = argparse.ArgumentParser() |
| ap.add_argument("--config", default="configs/default.yaml") |
| ap.add_argument("--skip_download", action="store_true", |
| help="only (re)build manifest from already-extracted raw_dir") |
| ap.add_argument("--only_zips", nargs="*", default=None, |
| help="only fetch zips whose name contains any of these substrings " |
| "(e.g. --only_zips 31-35 for the smoke test)") |
| args = ap.parse_args() |
| cfg = load_config(args.config) |
|
|
| if not args.skip_download: |
| download_and_extract(cfg, only_substrings=args.only_zips) |
|
|
| cases = discover_cases(cfg["paths"]["raw_dir"]) |
| if not cases: |
| raise SystemExit("No cases found. Check raw_dir / extraction.") |
| write_json(cases, os.path.join(cfg["paths"]["raw_dir"], "manifest.json")) |
| print(f"[download] manifest written with {len(cases)} cases.") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|