"""ScolioSim helper: the part that runs inside TotalSegmentator's own Python. worker.py weights download the model weights of the 'total' task worker.py check print, as JSON, what PyTorch sees worker.py segment DICOM_DIR OUT [--fast] [--bodies] worker.py share TOTAL BODIES OUT the whole vertebrae shared out again from the vertebral bodies Lines "STAGE n" tell the helper which step of its job has started. """ from __future__ import annotations import json import shutil import sys import tempfile import time import warnings from pathlib import Path # PyTorch's notices about its own deprecated parts say nothing to a doctor warnings.filterwarnings("ignore", category=FutureWarning) LEVELS = [f"vertebrae_T{i}" for i in range(1, 13)] + [f"vertebrae_L{i}" for i in range(1, 6)] + ["vertebrae_S1", "sacrum"] TOTAL = [291, 292, 293, 294, 295, 298] # TotalSegmentator's 'total' task (its totalseg_download_weights table) def say(text: str) -> None: print(text, flush=True) def quiet_stats() -> None: """TotalSegmentator sends anonymous usage statistics unless its config says not to: say not to.""" from totalsegmentator.config import get_totalseg_dir, setup_totalseg config = setup_totalseg() if config.get("send_usage_stats", True) or not config.get("statistics_disclaimer_shown"): config["send_usage_stats"] = False config["statistics_disclaimer_shown"] = True with open(get_totalseg_dir() / "config.json", "w") as f: json.dump(config, f, indent=4) def device() -> str: import torch if torch.cuda.is_available(): props = torch.cuda.get_device_properties(0) say(f"Graphics card: {props.name}, {props.total_memory / 1024 ** 3:.0f} GB.") return "gpu" if getattr(torch.backends, "mps", None) and torch.backends.mps.is_available(): say("Apple silicon: using its graphics.") return "mps" say("No NVIDIA graphics card in use: the processor does the work, which takes longer.") return "cpu" def weights() -> None: quiet_stats() import requests from totalsegmentator.libs import download_pretrained_weights for n, task in enumerate(TOTAL, 1): say(f"Model part {n} of {len(TOTAL)}...") # GitHub, which serves them, now and then answers a busy moment with an error (504): tried again for attempt in range(1, 4): try: download_pretrained_weights(task) break except requests.RequestException as e: if attempt == 3: raise say(f"The download failed ({e.__class__.__name__}); trying again in {15 * attempt} s...") time.sleep(15 * attempt) def check() -> None: import torch from importlib.metadata import version cuda = torch.cuda.is_available() mps = not cuda and bool(getattr(torch.backends, "mps", None) and torch.backends.mps.is_available()) print(json.dumps({ "totalsegmentator": version("TotalSegmentator"), "torch": torch.__version__, "cuda": cuda, "mps": mps, "device": torch.cuda.get_device_name(0) if cuda else "Apple silicon" if mps else None, })) def run_totalsegmentator(where: str, *args, **kwargs) -> str: """TotalSegmentator on the device chosen; if the Apple graphics cannot run it, again on the processor. Returns the device that did the work.""" from totalsegmentator.python_api import totalsegmentator try: totalsegmentator(*args, device=where, **kwargs) return where except Exception as e: # noqa: BLE001 if where != "mps": raise say(f"The Apple graphics could not run it ({str(e)[:200]}); trying again on the processor, which takes longer...") totalsegmentator(*args, device="cpu", **kwargs) return "cpu" def segment(dicom: Path, out: Path, fast: bool, bodies: bool = False) -> None: quiet_stats() started = time.time() where = device() from totalsegmentator.dicom_io import dcm_to_nifti with tempfile.TemporaryDirectory(prefix="scoliosim-ct-") as tmp: say("STAGE 1") say("Converting the series to NIfTI...") ct = Path(tmp) / "ct.nii.gz" try: dcm_to_nifti(dicom, ct) except Exception as e: # noqa: BLE001 say(f"ERROR The series could not be converted: {e}") sys.exit(1) shutil.rmtree(dicom, ignore_errors=True) say("STAGE 2") say("Segmenting with TotalSegmentator...") try: where = run_totalsegmentator(where, ct, out, ml=True, roi_subset=LEVELS, fast=fast, quiet=False) except Exception as e: # noqa: BLE001 text = str(e) if "out of memory" in text.lower(): say("ERROR The graphics card ran out of memory. Try again with the faster, coarser model.") else: say(f"ERROR TotalSegmentator stopped: {text}") sys.exit(1) labels = {"edit-labels.nii.gz": out} if bodies: # Experimental: TotalSegmentator's vertebral bodies task, whose authors report far fewer # neighbouring vertebrae mixed up, used to share the whole vertebrae out again say("Segmenting the vertebral bodies (vertebrae_pp; the first time it downloads about 230 MB)...") pp = Path(tmp) / "bodies.nii.gz" try: run_totalsegmentator(where, ct, pp, ml=True, task="vertebrae_pp", quiet=False) combined = out.parent / "vertebrae-pp.nii.gz" report = share_by_bodies(out, pp, combined) (out.parent / "pp-report.json").write_text(json.dumps(report), encoding="utf-8") labels["edit-labels-pp.nii.gz"] = combined except Exception as e: # noqa: BLE001 - the plain segmentation is still there say(f"The vertebral bodies could not be used: {e}") say("STAGE 3") try: crop_for_editing(ct, labels, out.parent) except Exception as e: # noqa: BLE001 - the segmentation is still good without it say(f"The CT could not be prepared for editing: {e}") say(f"Done in {time.time() - started:.0f} s.") SPINE = [f"vertebrae_T{i}" for i in range(1, 13)] + [f"vertebrae_L{i}" for i in range(1, 6)] def share_by_bodies(total: Path, bodies: Path, out: Path) -> dict: """The whole vertebrae of 'total' shared out again from the vertebral bodies of 'vertebrae_pp'. Each piece that 'total' gave one label (a connected region of T1-L5) is looked at on its own: holding one body of 'vertebrae_pp', it takes that body's level; holding two or more, it is split between them along the shortest paths through its own bone (a watershed seeded with the bodies); holding none, it stays as it was. Paths never cross from one label of 'total' into another: across the facet joints an articular process lies nearer the body below, and flooding the whole spine gave each vertebra's inferior processes to the vertebra underneath. A body that touches a piece only at its edge (under 15% of the largest body in it) does not count. The sacrum and S1 stay as 'total' has them. Returns how much changed, level by level.""" import nibabel as nib import numpy as np from scipy import ndimage from skimage.segmentation import watershed from totalsegmentator.map_to_binary import class_map t_img = nib.load(str(total)) T = np.asanyarray(t_img.dataobj).astype(np.uint8) P = np.asanyarray(nib.load(str(bodies)).dataobj).astype(np.uint8) if P.shape != T.shape: raise ValueError(f"the two segmentations differ in size: {P.shape} and {T.shape}") total_id = {name: i for i, name in class_map["total"].items()} spine_ids = np.array([total_id[n] for n in SPINE], dtype=np.uint8) bone = np.isin(T, spine_ids) found = np.argwhere(bone) if found.size == 0: raise ValueError("no vertebra from T1 to L5 in the segmentation") lo, hi = found.min(0), found.max(0) + 1 box = tuple(slice(int(a), int(b)) for a, b in zip(lo, hi)) b_bone, b_T, b_P = bone[box], T[box], P[box] seeds = np.zeros(b_T.shape, dtype=np.int32) for pid, name in class_map["vertebrae_pp"].items(): if name in total_id and name in SPINE: seeds[(b_P == pid) & b_bone] = total_id[name] if not seeds.any(): raise ValueError("no vertebral body from T1 to L5 was found") shared = b_T.copy() for level in spine_ids: pieces, count = ndimage.label(b_T == level) for n in range(1, count + 1): piece = pieces == n ids, sizes = np.unique(seeds[piece], return_counts=True) keep = [(int(i), int(s)) for i, s in zip(ids, sizes) if i != 0] if not keep: continue largest = max(s for _, s in keep) keep = [i for i, s in keep if s >= 0.15 * largest] if len(keep) == 1: shared[piece] = keep[0] continue # Split between the bodies it holds, through its own bone only where = np.argwhere(piece) lo_p, hi_p = where.min(0), where.max(0) + 1 sub = tuple(slice(int(a), int(b)) for a, b in zip(lo_p, hi_p)) mask = piece[sub] markers = np.where(mask & np.isin(seeds[sub], keep), seeds[sub], 0) split = watershed(np.zeros(mask.shape, dtype=np.uint8), markers=markers, mask=mask, connectivity=1) region = shared[sub] region[mask & (split > 0)] = split[mask & (split > 0)] result = T.copy() region = result[box] region[b_bone] = shared[b_bone] names = class_map["total"] moved = b_bone & (shared != b_T) by_level: dict[str, dict] = {} voxel_ml = float(np.prod(t_img.header.get_zooms()[:3])) / 1000 for i in spine_ids: lost = int(np.count_nonzero(moved & (b_T == i))) won = int(np.count_nonzero(moved & (shared == i))) if lost or won: by_level[names[int(i)].replace("vertebrae_", "")] = {"lostMl": round(lost * voxel_ml, 2), "wonMl": round(won * voxel_ml, 2)} image = nib.Nifti1Image(result, t_img.affine) image.header.extensions.extend(t_img.header.extensions) nib.save(image, str(out)) share = float(np.count_nonzero(moved)) / max(1, int(np.count_nonzero(b_bone))) say(f"The vertebral bodies moved {share * 100:.1f}% of the spine's bone to another vertebra.") return {"movedPercent": round(share * 100, 1), "levels": by_level, "bodies": sorted({class_map["vertebrae_pp"][int(v)].replace("vertebrae_", "") for v in np.unique(P) if v})} def crop_for_editing(ct: Path, labels: dict, into: Path, margin_mm: float = 15, finest_mm: float = 0.8) -> None: """The CT and the labels around the spine only, at no finer than finest_mm: what the page's editor loads. A whole CT is hundreds of MB; the box round the vertebrae, with a margin, is a few tens. Every label map (name in the folder: its file) is cut to the same box as the first.""" import nibabel as nib import numpy as np first = next(iter(labels.values())) seg = nib.load(str(first)) data = np.asanyarray(seg.dataobj) found = np.argwhere(data > 0) if found.size == 0: return zooms = seg.header.get_zooms()[:3] pad = [int(np.ceil(margin_mm / z)) for z in zooms] lo = np.maximum(found.min(0) - pad, 0) hi = np.minimum(found.max(0) + pad + 1, data.shape[:3]) step = [max(1, int(finest_mm // z)) for z in zooms] box = tuple(slice(int(a), int(b), s) for a, b, s in zip(lo, hi, step)) image = nib.load(str(ct)) cropped_ct = image.slicer[box] values = np.asanyarray(cropped_ct.dataobj).astype(np.int16) nib.save(nib.Nifti1Image(values, cropped_ct.affine), str(into / "edit-ct.nii.gz")) for name, path in labels.items(): source = nib.load(str(path)) cropped = source.slicer[box] out = nib.Nifti1Image(np.asanyarray(cropped.dataobj).astype(np.uint8), cropped.affine) out.header.extensions.extend(source.header.extensions) # the names of the labels go with them nib.save(out, str(into / name)) say(f"Prepared for editing: {values.shape[0]} x {values.shape[1]} x {values.shape[2]}.") if __name__ == "__main__": command = sys.argv[1] if len(sys.argv) > 1 else "" if command == "weights": weights() elif command == "check": check() elif command == "segment" and len(sys.argv) >= 4: segment(Path(sys.argv[2]), Path(sys.argv[3]), "--fast" in sys.argv[4:], "--bodies" in sys.argv[4:]) elif command == "share" and len(sys.argv) >= 5: # The sharing alone, on two segmentations already made: worker.py share TOTAL BODIES OUT print(json.dumps(share_by_bodies(Path(sys.argv[2]), Path(sys.argv[3]), Path(sys.argv[4])))) else: sys.exit(__doc__)