"""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: # pick the largest series (most slices) 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 # follow symlinks; pick the one with the largest real size 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" # 1. same folder 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))) # 2. walk up to the case folder 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: # prefer one whose filename contains the case number 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)) # any directory with >=8 .dcm files is a DICOM series for folder, dirs, files in os.walk(raw_dir): # skip hidden and the HF cache 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): # derive a stable case id and a numeric case number from the path. # The path may look like raw/1-20/01-/20230519// so the FIRST # segment with a number (`1-20`) is the batch folder, not the case. We want # the DEEPEST segment whose name parses as a single number in 1..40 — that's # the actual case folder. 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) # purely numeric + trailing dashes if m and 1 <= int(m.group(1)) <= 40: case_num = int(m.group(1)) case_name = seg # keep updating -> deepest wins if case_num < 0: print(f"[discover] cannot infer case number from {folder}; skipping") continue # if multiple series exist under the same case (rare here), keep only the # largest one (most DICOM slices) 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 # build image_from_dicom if not already present 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()