File size: 10,662 Bytes
08764e9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
"""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/<series_uid>/  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()