File size: 3,547 Bytes
3799002
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Inspect extra_tooth_labels/ and report which case each file maps to + what
preprocess.assemble_label will do.

    python -m toothcanal.inspect_labels --config configs/default.yaml

Use this BEFORE running preprocess on cases 21-30: it tells you which files in
extra_tooth_labels/ are recognized, which case each is mapped to, and whether
the content already contains tooth bodies (overrides HF label) or only teeth /
only canal (needs merging).
"""
import os, re, glob, argparse
import numpy as np
from .utils import load_config, load_nii


def case_candidates(name):
    """Return the set of plausible case numbers (1..40) suggested by filename."""
    import re
    runs = re.findall(r"\d+", name)
    plausible = set()
    for r in runs:
        n = int(r)
        if 1 <= n <= 40:
            plausible.add(n)
        for w in (2, 3):
            for i in range(len(r) - w + 1):
                n = int(r[i:i + w])
                if 1 <= n <= 40:
                    plausible.add(n)
    return sorted(plausible)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--config", default="configs/default.yaml")
    args = ap.parse_args()
    cfg = load_config(args.config)

    extra = cfg["paths"].get("extra_tooth_dir")
    if not extra or not os.path.isdir(extra):
        raise SystemExit(f"extra_tooth_dir not found: {extra}")
    ls = cfg["label_scheme"]
    cands = sorted(glob.glob(os.path.join(extra, "**", "*.nii.gz"), recursive=True))
    if not cands:
        raise SystemExit(f"no .nii.gz files in {extra}")

    print(f"\nInspecting {len(cands)} files in {extra}\n")
    print(f"{'file':50s} {'cases':>14s}  {'shape':>15s}  {'labels':>40s}  verdict")
    print("-" * 145)
    by_case = {}
    for p in cands:
        base = os.path.basename(p)
        guesses = case_candidates(base)
        try:
            vol, _ = load_nii(p)
            vol = np.rint(vol).astype(np.int16)
            uniq = sorted(int(v) for v in np.unique(vol) if v != 0)
        except Exception as e:
            print(f"{base:50s}  READ FAIL: {e}")
            continue
        has_canal = any(ls["canal_lo"] <= v <= ls["canal_hi"] for v in uniq)
        has_body  = any(ls["body_lo"]  <= v <= ls["body_hi"]  for v in uniq)
        if has_canal and has_body:
            verdict = "COMPLETE (will override HF label)"
        elif has_canal and not has_body:
            verdict = "canal-only (won't be used; rename / replace)"
        elif has_body and not has_canal:
            verdict = "body-only (will be merged with HF canal)"
        else:
            verdict = "binary or unknown -> will be merged"
        head = (str(uniq)[:38] + "..") if len(str(uniq)) > 40 else str(uniq)
        cstr = ",".join(str(c) for c in guesses) if guesses else "-"
        print(f"{base[:50]:50s} {cstr:>14s}  {str(vol.shape):>15s}  {head:>40s}  {verdict}")
        for n in guesses:
            by_case.setdefault(n, []).append((base, verdict))

    print("\nPer-case summary (production resolution via find_extra_tooth):")
    from .assemble import find_extra_tooth
    extra_dir = cfg["paths"]["extra_tooth_dir"]
    chosen = {}
    for n in range(1, 41):
        p = find_extra_tooth(n, extra_dir)
        if p:
            chosen[n] = os.path.basename(p)
    for n in sorted(chosen):
        print(f"  case {n:>2}: -> {chosen[n]}")
    missing = [n for n in range(21, 31) if n not in chosen]
    if missing:
        print(f"\n  WARNING: no extra label resolved for cases {missing} in 21-30 range.")


if __name__ == "__main__":
    main()