totalsegmentator-mlx 0.2.0__tar.gz → 0.3.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (24) hide show
  1. {totalsegmentator_mlx-0.2.0 → totalsegmentator_mlx-0.3.0}/PKG-INFO +36 -58
  2. {totalsegmentator_mlx-0.2.0 → totalsegmentator_mlx-0.3.0}/README.md +33 -55
  3. {totalsegmentator_mlx-0.2.0 → totalsegmentator_mlx-0.3.0}/pyproject.toml +3 -3
  4. totalsegmentator_mlx-0.3.0/src/totalsegmentator_mlx/__init__.py +21 -0
  5. {totalsegmentator_mlx-0.2.0 → totalsegmentator_mlx-0.3.0}/src/totalsegmentator_mlx/cli.py +27 -20
  6. totalsegmentator_mlx-0.3.0/src/totalsegmentator_mlx/engine.py +171 -0
  7. totalsegmentator_mlx-0.3.0/src/totalsegmentator_mlx/medmlx.py +294 -0
  8. {totalsegmentator_mlx-0.2.0 → totalsegmentator_mlx-0.3.0}/src/totalsegmentator_mlx/output.py +2 -39
  9. totalsegmentator_mlx-0.3.0/src/totalsegmentator_mlx/pipeline.py +315 -0
  10. totalsegmentator_mlx-0.2.0/src/totalsegmentator_mlx/__init__.py +0 -27
  11. totalsegmentator_mlx-0.2.0/src/totalsegmentator_mlx/engine.py +0 -254
  12. totalsegmentator_mlx-0.2.0/src/totalsegmentator_mlx/medmlx.py +0 -108
  13. totalsegmentator_mlx-0.2.0/src/totalsegmentator_mlx/pipeline.py +0 -464
  14. {totalsegmentator_mlx-0.2.0 → totalsegmentator_mlx-0.3.0}/.gitignore +0 -0
  15. {totalsegmentator_mlx-0.2.0 → totalsegmentator_mlx-0.3.0}/LICENSE +0 -0
  16. {totalsegmentator_mlx-0.2.0 → totalsegmentator_mlx-0.3.0}/THIRD_PARTY_NOTICES.md +0 -0
  17. {totalsegmentator_mlx-0.2.0 → totalsegmentator_mlx-0.3.0}/src/totalsegmentator_mlx/__main__.py +0 -0
  18. {totalsegmentator_mlx-0.2.0 → totalsegmentator_mlx-0.3.0}/src/totalsegmentator_mlx/geometry.py +0 -0
  19. {totalsegmentator_mlx-0.2.0 → totalsegmentator_mlx-0.3.0}/src/totalsegmentator_mlx/imageio.py +0 -0
  20. {totalsegmentator_mlx-0.2.0 → totalsegmentator_mlx-0.3.0}/src/totalsegmentator_mlx/labels.py +0 -0
  21. {totalsegmentator_mlx-0.2.0 → totalsegmentator_mlx-0.3.0}/src/totalsegmentator_mlx/localization.py +0 -0
  22. {totalsegmentator_mlx-0.2.0 → totalsegmentator_mlx-0.3.0}/src/totalsegmentator_mlx/models.py +0 -0
  23. {totalsegmentator_mlx-0.2.0 → totalsegmentator_mlx-0.3.0}/src/totalsegmentator_mlx/py.typed +0 -0
  24. {totalsegmentator_mlx-0.2.0 → totalsegmentator_mlx-0.3.0}/src/totalsegmentator_mlx/resampling.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: totalsegmentator-mlx
3
- Version: 0.2.0
3
+ Version: 0.3.0
4
4
  Summary: Segment 117 CT structures with TotalSegmentator v2 in native MLX
5
5
  Project-URL: Homepage, https://medmlx.org
6
6
  Project-URL: Documentation, https://github.com/MedMLX/totalsegmentator-mlx/blob/v0.2.0/README.md
@@ -24,10 +24,10 @@ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
24
24
  Classifier: Topic :: Scientific/Engineering :: Image Processing
25
25
  Classifier: Topic :: Scientific/Engineering :: Medical Science Apps.
26
26
  Requires-Python: <3.14,>=3.13
27
- Requires-Dist: medmlx-core<0.3,>=0.2.6
27
+ Requires-Dist: medmlx-core<0.4,>=0.3
28
28
  Requires-Dist: mlx==0.32.4; platform_system == 'Darwin' and platform_machine == 'arm64'
29
29
  Requires-Dist: nibabel<6,>=5.3
30
- Requires-Dist: nnunet-mlx<0.9,>=0.8.0
30
+ Requires-Dist: nnunet-mlx<0.10,>=0.9.0
31
31
  Requires-Dist: numpy<3,>=2.0
32
32
  Requires-Dist: scipy==1.18.1
33
33
  Provides-Extra: dev
@@ -44,7 +44,7 @@ Segment 117 CT structures with TotalSegmentator v2 in native MLX. Includes stand
44
44
 
45
45
  [![PyPI](https://img.shields.io/pypi/v/totalsegmentator-mlx)](https://pypi.org/project/totalsegmentator-mlx/)
46
46
  [![Python](https://img.shields.io/pypi/pyversions/totalsegmentator-mlx)](https://pypi.org/project/totalsegmentator-mlx/)
47
- [![License](https://img.shields.io/badge/License-Apache_2.0-blue)](https://github.com/MedMLX/totalsegmentator-mlx/blob/v0.2.0/LICENSE)
47
+ [![License](https://img.shields.io/badge/License-Apache_2.0-blue)](https://github.com/MedMLX/totalsegmentator-mlx/blob/v0.3.0/LICENSE)
48
48
  [![Apple Silicon](https://img.shields.io/badge/Apple_Silicon-MLX-black?logo=apple)](https://github.com/ml-explore/mlx)
49
49
  [![Hugging Face](https://img.shields.io/badge/%F0%9F%A4%97_Hugging_Face-weights-yellow)](https://huggingface.co/MedMLX/totalsegmentator-mlx)
50
50
  [![MedMLX](https://img.shields.io/badge/MedMLX-runtime-A51C30)](https://github.com/MedMLX/medmlx)
@@ -68,13 +68,13 @@ Standard mode (1.5 mm): 3D surfaces from [autoPET-III](https://huggingface.co/da
68
68
  ```bash
69
69
  uv venv --python 3.13
70
70
  source .venv/bin/activate
71
- uv pip install "totalsegmentator-mlx>=0.2.0"
71
+ uv pip install "totalsegmentator-mlx>=0.3.0"
72
72
  ```
73
73
 
74
74
  ## Run
75
75
 
76
76
  ```python
77
- from totalsegmentator_mlx.medmlx import run
77
+ from totalsegmentator_mlx import run
78
78
 
79
79
  result = run(image_path="ct.nii.gz", output_dir="out")
80
80
  print(result["outputs"]["mask"])
@@ -87,24 +87,31 @@ Weights download from `MedMLX/totalsegmentator-mlx` on first use. Use `medmlx se
87
87
  | Argument | Meaning |
88
88
  | --- | --- |
89
89
  | `image_path` | One finite 3D CT in NIfTI-1 or NIfTI-2, in Hounsfield units |
90
- | `output_dir` | Directory for `mask.nii.gz` |
90
+ | `output_dir` | Directory for `mask.nii.gz` (and the probability files) |
91
91
  | `weights_path` | Optional root of the model folders below |
92
92
  | `mode` | `standard` (default, five 1.5 mm parts), `fast` (3 mm model, upstream `--fast`) or `coarse` (6 mm model, upstream `--fastest`) |
93
- | `prompt` | Structure names to keep after inference; label IDs stay global |
93
+ | `classes` | Structure names to keep after inference; label IDs stay global |
94
+ | `model_part` | One standard part: `organs`, `vertebrae`, `cardiac`, `muscles` or `ribs` |
94
95
  | `roi_subset` | Locate these structures, crop to them plus 20 mm and drop other labels |
95
96
  | `robust_crop` | Locate `roi_subset` with the 3 mm model instead of the 6 mm one |
96
97
  | `body_seg` | Crop to the Dataset300 body model plus 3 mm |
97
- | `overwrite` | `False` by default; an existing mask is never replaced |
98
+ | `force_split` | Use upstream's three overlapping slabs even for smaller volumes |
99
+ | `probabilities` | Also write `probabilities.npz` and `probabilities.pkl` for one uncropped model |
100
+ | `overwrite` | `False` by default; existing outputs are never replaced |
98
101
 
99
102
  - **Cropping:** with `roi_subset`, standard mode runs only the parts that contain those
100
- structures. `roi_subset` cannot be combined with `prompt` or `body_seg`, and
103
+ structures. `roi_subset` cannot be combined with `classes`, `model_part` or `body_seg`, and
101
104
  `robust_crop` requires `roi_subset`. Cropped regions are restored by zero filling; an
102
105
  empty localization returns an empty mask.
103
106
  - **Units:** spatial units must be millimetres or unspecified.
104
107
  - **Mask:** a uint8 NIfTI-1 with global labels 1–117 (0 background) on the input grid,
105
108
  with the upstream label table as a header extension.
106
- - **Return value:** `{"outputs": {"mask": path}, "details": {...}}`, with run metadata in
107
- `details`.
109
+ - **Probabilities:** float32 local-label probabilities on the model reader's grid, with
110
+ nnU-Net's geometry and crop properties in the `.pkl` beside them.
111
+ - **Return value:** `{"outputs": {"mask": path}, "artifacts": {"mask": ...}, "details": {...}}`,
112
+ plus the `probabilities` and `probability_properties` roles when requested. The mask
113
+ artifact is a label map on the input grid whose labels are the structures the run can
114
+ write; `details` holds run metadata.
108
115
  - **Errors:** invalid inputs raise `InvalidInputError`; missing or mismatched weights
109
116
  raise `AssetNotReadyError`.
110
117
 
@@ -122,61 +129,32 @@ single model folder can be passed directly when only that dataset is needed.
122
129
  | `298/` | 6 mm total model | `coarse`; `roi_subset` |
123
130
  | `300/` | 6 mm body model | `body_seg` |
124
131
 
125
- ### Command line
126
-
127
- Download the [safetensors model bundle](https://huggingface.co/MedMLX/totalsegmentator-mlx),
128
- then segment:
129
-
130
- ```bash
131
- python - <<'PY'
132
- from huggingface_hub import snapshot_download
133
-
134
- snapshot_download(
135
- "MedMLX/totalsegmentator-mlx",
136
- revision="6c03d6f90ccf53f224c3985cbdecf1eaa96555af",
137
- local_dir="models",
138
- )
139
- PY
140
- totalsegmentator-mlx predict -i ct.nii.gz -o mask.nii.gz --model-dir models
141
- ```
142
-
143
- `predict` takes the runner options as flags (`--mode`, `--organ` for `prompt`,
144
- `--roi-subset`, `--robust-crop`, `--body-seg`, `--overwrite`) and adds three more:
132
+ ### Several CTs
145
133
 
146
- | Flag | Effect |
147
- | :--- | :--- |
148
- | `--model-part` | Runs one standard part: `organs`, `vertebrae`, `cardiac`, `muscles` or `ribs` |
149
- | `--force-split` | Uses upstream's three overlapping slabs |
150
- | `--probabilities-path probabilities.npz` | Also exports local-label probabilities for one unsplit, uncropped model |
151
-
152
- `totalsegmentator-mlx labels` prints the label IDs.
153
-
154
- ### Python API
134
+ `run` loads each network for its part and releases it before the next one. To
135
+ segment several CTs, load the model once; its networks stay loaded until it closes:
155
136
 
156
137
  ```python
157
- from totalsegmentator_mlx import segment
138
+ from totalsegmentator_mlx import load_model
158
139
 
159
- labels = segment("ct.nii.gz", model_dir="models", mode="fast") # nibabel image, uint8
140
+ with load_model() as model:
141
+ for name in ("ct1", "ct2"):
142
+ model.run(image_path=f"{name}.nii.gz", output_dir=name)
160
143
  ```
161
144
 
162
- `segment` takes the command-line options as keyword arguments, plus an optional
163
- `output_path`. It never downloads weights.
145
+ `model.run` takes the same arguments as `run` except `weights_path`. Standard
146
+ mode with crops keeps up to eight networks loaded.
164
147
 
165
- For a long-lived Python process, the default cache retains up to eight model
166
- predictors. Set an explicit policy before a job when memory takes priority:
167
-
168
- ```python
169
- from totalsegmentator_mlx import configure_predictor_cache, clear_predictor_cache
148
+ ### Command line
170
149
 
171
- configure_predictor_cache(max_entries=1, max_bytes=2 * 1024**3)
172
- # Run segment(...) calls with one retained network at a time.
173
- clear_predictor_cache()
150
+ ```bash
151
+ totalsegmentator-mlx predict -i ct.nii.gz -o out
174
152
  ```
175
153
 
176
- The byte budget covers retained model state; inference scratch and MLX's free
177
- allocator cache are separate. A model exceeding the budget runs uncached.
178
- `predictor_cache_info()` reports these counters separately. Passing no limits
179
- to `configure_predictor_cache()` restores the eight-model policy.
154
+ `predict` takes the arguments above as flags (`--weights`, `--mode`, `--classes`,
155
+ `--model-part`, `--roi-subset`, `--robust-crop`, `--body-seg`, `--force-split`,
156
+ `--probabilities`, `--overwrite`) and prints the output paths.
157
+ `totalsegmentator-mlx labels` prints the label IDs.
180
158
 
181
159
  ### Limits
182
160
 
@@ -204,4 +182,4 @@ For Codex, use `codex mcp add medmlx -- "$MEDMLX" serve --root "$HOME/medmlx-wor
204
182
 
205
183
  ## License
206
184
 
207
- [Apache-2.0](https://github.com/MedMLX/totalsegmentator-mlx/blob/v0.2.0/LICENSE). See [third-party notices](https://github.com/MedMLX/totalsegmentator-mlx/blob/v0.2.0/THIRD_PARTY_NOTICES.md). Model weights retain their publisher terms.
185
+ [Apache-2.0](https://github.com/MedMLX/totalsegmentator-mlx/blob/v0.3.0/LICENSE). See [third-party notices](https://github.com/MedMLX/totalsegmentator-mlx/blob/v0.3.0/THIRD_PARTY_NOTICES.md). Model weights retain their publisher terms.
@@ -6,7 +6,7 @@ Segment 117 CT structures with TotalSegmentator v2 in native MLX. Includes stand
6
6
 
7
7
  [![PyPI](https://img.shields.io/pypi/v/totalsegmentator-mlx)](https://pypi.org/project/totalsegmentator-mlx/)
8
8
  [![Python](https://img.shields.io/pypi/pyversions/totalsegmentator-mlx)](https://pypi.org/project/totalsegmentator-mlx/)
9
- [![License](https://img.shields.io/badge/License-Apache_2.0-blue)](https://github.com/MedMLX/totalsegmentator-mlx/blob/v0.2.0/LICENSE)
9
+ [![License](https://img.shields.io/badge/License-Apache_2.0-blue)](https://github.com/MedMLX/totalsegmentator-mlx/blob/v0.3.0/LICENSE)
10
10
  [![Apple Silicon](https://img.shields.io/badge/Apple_Silicon-MLX-black?logo=apple)](https://github.com/ml-explore/mlx)
11
11
  [![Hugging Face](https://img.shields.io/badge/%F0%9F%A4%97_Hugging_Face-weights-yellow)](https://huggingface.co/MedMLX/totalsegmentator-mlx)
12
12
  [![MedMLX](https://img.shields.io/badge/MedMLX-runtime-A51C30)](https://github.com/MedMLX/medmlx)
@@ -30,13 +30,13 @@ Standard mode (1.5 mm): 3D surfaces from [autoPET-III](https://huggingface.co/da
30
30
  ```bash
31
31
  uv venv --python 3.13
32
32
  source .venv/bin/activate
33
- uv pip install "totalsegmentator-mlx>=0.2.0"
33
+ uv pip install "totalsegmentator-mlx>=0.3.0"
34
34
  ```
35
35
 
36
36
  ## Run
37
37
 
38
38
  ```python
39
- from totalsegmentator_mlx.medmlx import run
39
+ from totalsegmentator_mlx import run
40
40
 
41
41
  result = run(image_path="ct.nii.gz", output_dir="out")
42
42
  print(result["outputs"]["mask"])
@@ -49,24 +49,31 @@ Weights download from `MedMLX/totalsegmentator-mlx` on first use. Use `medmlx se
49
49
  | Argument | Meaning |
50
50
  | --- | --- |
51
51
  | `image_path` | One finite 3D CT in NIfTI-1 or NIfTI-2, in Hounsfield units |
52
- | `output_dir` | Directory for `mask.nii.gz` |
52
+ | `output_dir` | Directory for `mask.nii.gz` (and the probability files) |
53
53
  | `weights_path` | Optional root of the model folders below |
54
54
  | `mode` | `standard` (default, five 1.5 mm parts), `fast` (3 mm model, upstream `--fast`) or `coarse` (6 mm model, upstream `--fastest`) |
55
- | `prompt` | Structure names to keep after inference; label IDs stay global |
55
+ | `classes` | Structure names to keep after inference; label IDs stay global |
56
+ | `model_part` | One standard part: `organs`, `vertebrae`, `cardiac`, `muscles` or `ribs` |
56
57
  | `roi_subset` | Locate these structures, crop to them plus 20 mm and drop other labels |
57
58
  | `robust_crop` | Locate `roi_subset` with the 3 mm model instead of the 6 mm one |
58
59
  | `body_seg` | Crop to the Dataset300 body model plus 3 mm |
59
- | `overwrite` | `False` by default; an existing mask is never replaced |
60
+ | `force_split` | Use upstream's three overlapping slabs even for smaller volumes |
61
+ | `probabilities` | Also write `probabilities.npz` and `probabilities.pkl` for one uncropped model |
62
+ | `overwrite` | `False` by default; existing outputs are never replaced |
60
63
 
61
64
  - **Cropping:** with `roi_subset`, standard mode runs only the parts that contain those
62
- structures. `roi_subset` cannot be combined with `prompt` or `body_seg`, and
65
+ structures. `roi_subset` cannot be combined with `classes`, `model_part` or `body_seg`, and
63
66
  `robust_crop` requires `roi_subset`. Cropped regions are restored by zero filling; an
64
67
  empty localization returns an empty mask.
65
68
  - **Units:** spatial units must be millimetres or unspecified.
66
69
  - **Mask:** a uint8 NIfTI-1 with global labels 1–117 (0 background) on the input grid,
67
70
  with the upstream label table as a header extension.
68
- - **Return value:** `{"outputs": {"mask": path}, "details": {...}}`, with run metadata in
69
- `details`.
71
+ - **Probabilities:** float32 local-label probabilities on the model reader's grid, with
72
+ nnU-Net's geometry and crop properties in the `.pkl` beside them.
73
+ - **Return value:** `{"outputs": {"mask": path}, "artifacts": {"mask": ...}, "details": {...}}`,
74
+ plus the `probabilities` and `probability_properties` roles when requested. The mask
75
+ artifact is a label map on the input grid whose labels are the structures the run can
76
+ write; `details` holds run metadata.
70
77
  - **Errors:** invalid inputs raise `InvalidInputError`; missing or mismatched weights
71
78
  raise `AssetNotReadyError`.
72
79
 
@@ -84,61 +91,32 @@ single model folder can be passed directly when only that dataset is needed.
84
91
  | `298/` | 6 mm total model | `coarse`; `roi_subset` |
85
92
  | `300/` | 6 mm body model | `body_seg` |
86
93
 
87
- ### Command line
88
-
89
- Download the [safetensors model bundle](https://huggingface.co/MedMLX/totalsegmentator-mlx),
90
- then segment:
91
-
92
- ```bash
93
- python - <<'PY'
94
- from huggingface_hub import snapshot_download
95
-
96
- snapshot_download(
97
- "MedMLX/totalsegmentator-mlx",
98
- revision="6c03d6f90ccf53f224c3985cbdecf1eaa96555af",
99
- local_dir="models",
100
- )
101
- PY
102
- totalsegmentator-mlx predict -i ct.nii.gz -o mask.nii.gz --model-dir models
103
- ```
104
-
105
- `predict` takes the runner options as flags (`--mode`, `--organ` for `prompt`,
106
- `--roi-subset`, `--robust-crop`, `--body-seg`, `--overwrite`) and adds three more:
94
+ ### Several CTs
107
95
 
108
- | Flag | Effect |
109
- | :--- | :--- |
110
- | `--model-part` | Runs one standard part: `organs`, `vertebrae`, `cardiac`, `muscles` or `ribs` |
111
- | `--force-split` | Uses upstream's three overlapping slabs |
112
- | `--probabilities-path probabilities.npz` | Also exports local-label probabilities for one unsplit, uncropped model |
113
-
114
- `totalsegmentator-mlx labels` prints the label IDs.
115
-
116
- ### Python API
96
+ `run` loads each network for its part and releases it before the next one. To
97
+ segment several CTs, load the model once; its networks stay loaded until it closes:
117
98
 
118
99
  ```python
119
- from totalsegmentator_mlx import segment
100
+ from totalsegmentator_mlx import load_model
120
101
 
121
- labels = segment("ct.nii.gz", model_dir="models", mode="fast") # nibabel image, uint8
102
+ with load_model() as model:
103
+ for name in ("ct1", "ct2"):
104
+ model.run(image_path=f"{name}.nii.gz", output_dir=name)
122
105
  ```
123
106
 
124
- `segment` takes the command-line options as keyword arguments, plus an optional
125
- `output_path`. It never downloads weights.
107
+ `model.run` takes the same arguments as `run` except `weights_path`. Standard
108
+ mode with crops keeps up to eight networks loaded.
126
109
 
127
- For a long-lived Python process, the default cache retains up to eight model
128
- predictors. Set an explicit policy before a job when memory takes priority:
129
-
130
- ```python
131
- from totalsegmentator_mlx import configure_predictor_cache, clear_predictor_cache
110
+ ### Command line
132
111
 
133
- configure_predictor_cache(max_entries=1, max_bytes=2 * 1024**3)
134
- # Run segment(...) calls with one retained network at a time.
135
- clear_predictor_cache()
112
+ ```bash
113
+ totalsegmentator-mlx predict -i ct.nii.gz -o out
136
114
  ```
137
115
 
138
- The byte budget covers retained model state; inference scratch and MLX's free
139
- allocator cache are separate. A model exceeding the budget runs uncached.
140
- `predictor_cache_info()` reports these counters separately. Passing no limits
141
- to `configure_predictor_cache()` restores the eight-model policy.
116
+ `predict` takes the arguments above as flags (`--weights`, `--mode`, `--classes`,
117
+ `--model-part`, `--roi-subset`, `--robust-crop`, `--body-seg`, `--force-split`,
118
+ `--probabilities`, `--overwrite`) and prints the output paths.
119
+ `totalsegmentator-mlx labels` prints the label IDs.
142
120
 
143
121
  ### Limits
144
122
 
@@ -166,4 +144,4 @@ For Codex, use `codex mcp add medmlx -- "$MEDMLX" serve --root "$HOME/medmlx-wor
166
144
 
167
145
  ## License
168
146
 
169
- [Apache-2.0](https://github.com/MedMLX/totalsegmentator-mlx/blob/v0.2.0/LICENSE). See [third-party notices](https://github.com/MedMLX/totalsegmentator-mlx/blob/v0.2.0/THIRD_PARTY_NOTICES.md). Model weights retain their publisher terms.
147
+ [Apache-2.0](https://github.com/MedMLX/totalsegmentator-mlx/blob/v0.3.0/LICENSE). See [third-party notices](https://github.com/MedMLX/totalsegmentator-mlx/blob/v0.3.0/THIRD_PARTY_NOTICES.md). Model weights retain their publisher terms.
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "totalsegmentator-mlx"
7
- version = "0.2.0"
7
+ version = "0.3.0"
8
8
  description = "Segment 117 CT structures with TotalSegmentator v2 in native MLX"
9
9
  readme = "README.md"
10
10
  classifiers = [
@@ -36,9 +36,9 @@ authors = [
36
36
  { name = "Alfredo Sandoval Jr." },
37
37
  ]
38
38
  dependencies = [
39
- "medmlx-core>=0.2.6,<0.3",
39
+ "medmlx-core>=0.3,<0.4",
40
40
  "mlx==0.32.4; platform_system == 'Darwin' and platform_machine == 'arm64'",
41
- "nnunet-mlx>=0.8.0,<0.9",
41
+ "nnunet-mlx>=0.9.0,<0.10",
42
42
  "nibabel>=5.3,<6",
43
43
  "numpy>=2.0,<3",
44
44
  "scipy==1.18.1",
@@ -0,0 +1,21 @@
1
+ """TotalSegmentator v2 ``total`` CT inference on Apple Silicon (MLX), research software.
2
+
3
+ ``run`` runs a CT through the native workflow and writes uint8 global label IDs
4
+ (1-117) on the input grid; ``load_model`` keeps the networks loaded across CTs. Both
5
+ load on first access, so importing the package does not import the MLX engine.
6
+ """
7
+
8
+ from importlib import import_module
9
+ from typing import TYPE_CHECKING
10
+
11
+ if TYPE_CHECKING:
12
+ from totalsegmentator_mlx.medmlx import load_model, run
13
+
14
+ __all__ = ["load_model", "run"]
15
+
16
+
17
+ def __getattr__(name: str) -> object:
18
+ """Load the public operation lazily on first access."""
19
+ if name not in __all__:
20
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
21
+ return getattr(import_module(f"{__name__}.medmlx"), name)
@@ -4,6 +4,7 @@ from __future__ import annotations
4
4
 
5
5
  import argparse
6
6
  import json
7
+ import logging
7
8
  import sys
8
9
  from pathlib import Path
9
10
  from typing import TYPE_CHECKING, cast
@@ -21,18 +22,18 @@ class Arguments(argparse.Namespace):
21
22
  """
22
23
 
23
24
  command: str
24
- input_path: Path
25
- output_path: Path
26
- model_dir: Path
25
+ image_path: Path
26
+ output_dir: Path
27
+ weights_path: Path | None
27
28
  mode: str
28
29
  model_part: str | None
29
- organ: list[str] | None
30
+ classes: list[str] | None
30
31
  roi_subset: list[str] | None
31
32
  robust_crop: bool
32
33
  body_seg: bool
33
34
  force_split: bool
34
35
  overwrite: bool
35
- probabilities_path: Path | None
36
+ probabilities: bool
36
37
 
37
38
 
38
39
  def _parser() -> argparse.ArgumentParser:
@@ -40,9 +41,11 @@ def _parser() -> argparse.ArgumentParser:
40
41
  parser = argparse.ArgumentParser(description="Native TotalSegmentator v2 CT inference on Metal")
41
42
  subparsers = parser.add_subparsers(dest="command", required=True)
42
43
  predict = subparsers.add_parser("predict", help="Segment a NIfTI CT on its original grid")
43
- predict.add_argument("-i", "--input", dest="input_path", type=Path, required=True)
44
- predict.add_argument("-o", "--output", dest="output_path", type=Path, required=True)
45
- predict.add_argument("--model-dir", type=Path, required=True)
44
+ predict.add_argument("-i", "--image", dest="image_path", type=Path, required=True)
45
+ predict.add_argument("-o", "--output-dir", type=Path, required=True)
46
+ predict.add_argument(
47
+ "--weights", dest="weights_path", type=Path, help="Weights folder; default downloads"
48
+ )
46
49
  predict.add_argument(
47
50
  "--mode",
48
51
  choices=["standard", *QUALITY_MODELS],
@@ -50,7 +53,9 @@ def _parser() -> argparse.ArgumentParser:
50
53
  help="standard: five 1.5 mm parts; fast: 3 mm model; coarse: 6 mm model (upstream fastest)",
51
54
  )
52
55
  predict.add_argument("--model-part", choices=list(MODEL_PARTS))
53
- predict.add_argument("--organ", nargs="+", help="Filter canonical organ names after inference")
56
+ predict.add_argument(
57
+ "--classes", nargs="+", help="Keep these canonical structure names after inference"
58
+ )
54
59
  predict.add_argument(
55
60
  "--roi-subset",
56
61
  nargs="+",
@@ -64,7 +69,9 @@ def _parser() -> argparse.ArgumentParser:
64
69
  )
65
70
  predict.add_argument("--force-split", action="store_true")
66
71
  predict.add_argument("--overwrite", action="store_true")
67
- predict.add_argument("--probabilities-path", type=Path)
72
+ predict.add_argument(
73
+ "--probabilities", action="store_true", help="Also write probabilities.npz and .pkl"
74
+ )
68
75
  subparsers.add_parser("labels", help="Print released global label IDs as JSON")
69
76
  return parser
70
77
 
@@ -74,31 +81,31 @@ def main(argv: list[str] | None = None) -> None:
74
81
 
75
82
  Exceptions that are ``OSError``, ``ValueError``, ``RuntimeError`` or ``ImportError``
76
83
  (which includes the ``medmlx_core`` errors) are reported on stderr with exit status 2.
77
- ``predict`` prints the output path on success.
84
+ ``predict`` reports stages on stderr and prints the output paths as JSON on success.
78
85
  """
79
86
  parser = _parser()
80
87
  args = parser.parse_args(argv, namespace=Arguments())
81
88
  if args.command == "labels":
82
89
  print(json.dumps(LABELS, indent=2))
83
90
  return
91
+ logging.basicConfig(stream=sys.stderr, level=logging.INFO, format="%(message)s")
84
92
  try:
85
- from totalsegmentator_mlx.pipeline import segment
93
+ from totalsegmentator_mlx.medmlx import run
86
94
 
87
- segment(
88
- args.input_path,
89
- model_dir=args.model_dir,
90
- output_path=args.output_path,
95
+ result = run(
96
+ image_path=args.image_path,
97
+ output_dir=args.output_dir,
98
+ weights_path=args.weights_path,
99
+ classes=args.classes,
91
100
  mode=cast("Mode", args.mode),
92
101
  model_part=args.model_part,
93
- prompt=args.organ,
94
102
  roi_subset=args.roi_subset,
95
103
  robust_crop=args.robust_crop,
96
104
  body_seg=args.body_seg,
97
105
  force_split=args.force_split,
106
+ probabilities=args.probabilities,
98
107
  overwrite=args.overwrite,
99
- probabilities_path=args.probabilities_path,
100
- progress=lambda message: print(message, file=sys.stderr, flush=True),
101
108
  )
102
- print(args.output_path)
109
+ print(json.dumps(result["outputs"], indent=2))
103
110
  except (OSError, ValueError, RuntimeError, ImportError) as error:
104
111
  parser.exit(2, f"{parser.prog}: {error}\n")
@@ -0,0 +1,171 @@
1
+ """Delegate each CT network to the public nnunet-mlx Metal inference boundary."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import sys
6
+ from collections.abc import Sequence
7
+ from dataclasses import replace
8
+ from pathlib import Path
9
+ from threading import RLock
10
+ from typing import TYPE_CHECKING, Protocol, cast
11
+
12
+ import nibabel as nib
13
+ from medmlx_core.errors import ModelExecutionError
14
+
15
+ from totalsegmentator_mlx.labels import BODY_MODEL
16
+ from totalsegmentator_mlx.models import ARITHMETIC, SOURCE_PROFILE, TASK_SPACING
17
+
18
+ if TYPE_CHECKING:
19
+ from nnunet_mlx import ModelFolderPredictor, NiftiPrediction
20
+
21
+ _runtime_lock = RLock()
22
+
23
+ type ModelIdentity = tuple[tuple[int, int, int, int, int] | None, ...]
24
+
25
+
26
+ class _Memory(Protocol):
27
+ """MLX's free-buffer cache control."""
28
+
29
+ def clear_cache(self) -> None: ...
30
+
31
+
32
+ class Networks:
33
+ """Fold-0 networks on Metal, owned by one ``run`` call or one loaded model.
34
+
35
+ With ``retain=False`` (one-shot ``run``) a network is loaded for one model's
36
+ slabs and released, with MLX's free-buffer cache, before the next model loads, so
37
+ one network is resident at a time. With ``retain=True`` (``load_model``) every
38
+ network used stays loaded until :meth:`close`. Prediction holds a process-wide
39
+ lock because all networks share the one Metal device.
40
+ """
41
+
42
+ def __init__(self, *, retain: bool) -> None:
43
+ """Start with no network loaded; each loads on first use."""
44
+ self._retain = retain
45
+ self._loaded: dict[tuple[Path, int], ModelFolderPredictor] = {}
46
+
47
+ def predict_images(
48
+ self, images: Sequence[nib.Nifti1Image], folder: Path, task_id: int
49
+ ) -> list[nib.Nifti1Image]:
50
+ """Return each image's local labels on its own grid, in order.
51
+
52
+ ``images`` are float32 CT on the model grid (1.5, 3 or 6 mm); labels are the
53
+ model's own IDs (``model_labels(task_id)``), not yet merged into global IDs.
54
+ """
55
+ with _runtime_lock:
56
+ predictor = self._network(folder, task_id)
57
+ try:
58
+ return [predictor.predict_nifti(image) for image in images]
59
+ finally:
60
+ del predictor
61
+ self._release()
62
+
63
+ def predict_probabilities(
64
+ self, image: nib.Nifti1Image, folder: Path, task_id: int
65
+ ) -> NiftiPrediction:
66
+ """Return labels plus reader-grid probabilities and properties for one image."""
67
+ with _runtime_lock:
68
+ predictor = self._network(folder, task_id)
69
+ try:
70
+ return predictor.predict_nifti_probabilities(image)
71
+ finally:
72
+ del predictor
73
+ self._release()
74
+
75
+ def close(self) -> None:
76
+ """Release every retained network and MLX's free-buffer cache."""
77
+ with _runtime_lock:
78
+ self._loaded.clear()
79
+ _clear_mlx_cache()
80
+
81
+ def _network(self, folder: Path, task_id: int) -> ModelFolderPredictor:
82
+ key = folder.resolve(), task_id
83
+ predictor = self._loaded.get(key)
84
+ if predictor is None:
85
+ predictor = load_predictor(*key)
86
+ if self._retain:
87
+ self._loaded[key] = predictor
88
+ return predictor
89
+
90
+ def _release(self) -> None:
91
+ if not self._retain:
92
+ _clear_mlx_cache()
93
+
94
+
95
+ def _clear_mlx_cache() -> None:
96
+ """Return MLX's free buffers to the system; a no-op before MLX is imported."""
97
+ module = sys.modules.get("mlx.core")
98
+ if module is not None:
99
+ cast(_Memory, module).clear_cache()
100
+
101
+
102
+ def _model_identity(folder: Path) -> ModelIdentity:
103
+ """Identify the model files by inode, size and times, to detect edits during loading."""
104
+ paths = (
105
+ folder / "plans.json",
106
+ folder / "dataset.json",
107
+ folder / "fold_0/checkpoint_final/state.json",
108
+ folder / "fold_0/checkpoint_final/weights.safetensors",
109
+ folder / "conversion.json",
110
+ )
111
+ identities: list[tuple[int, int, int, int, int] | None] = []
112
+ for path in paths:
113
+ if path.name == "conversion.json" and not path.exists():
114
+ identities.append(None)
115
+ continue
116
+ info = path.stat()
117
+ identities.append(
118
+ (info.st_dev, info.st_ino, info.st_size, info.st_mtime_ns, info.st_ctime_ns)
119
+ )
120
+ return tuple(identities)
121
+
122
+
123
+ def _step_fraction(task_id: int) -> float:
124
+ """Return upstream's tile step: 0.8 below a 3 mm grid and 0.5 otherwise."""
125
+ return 0.8 if TASK_SPACING[task_id] < 3.0 else 0.5
126
+
127
+
128
+ def load_predictor(folder: Path, task_id: int) -> ModelFolderPredictor:
129
+ """Load one fold-0 model onto Metal with TotalSegmentator's inference settings.
130
+
131
+ Raises:
132
+ ModelExecutionError: Metal is unavailable, the model does not take one CT channel,
133
+ a non-body model carries test-time mirroring axes, or the model files changed
134
+ while loading.
135
+ """
136
+ identity = _model_identity(folder)
137
+ predictor = _load_predictor(folder, task_id)
138
+ if _model_identity(folder) != identity:
139
+ raise ModelExecutionError("Model files changed while loading; retry with stable assets")
140
+ return predictor
141
+
142
+
143
+ def _load_predictor(folder: Path, task_id: int) -> ModelFolderPredictor:
144
+ """Build the predictor; ``load_predictor`` checks the files around this call."""
145
+ from nnunet_mlx import ModelFolderPredictor, load_model_bundle
146
+ from nnunet_mlx.runtime import runtime_info
147
+
148
+ if runtime_info().backend != "metal":
149
+ raise ModelExecutionError("TotalSegmentator requires an Apple Metal GPU")
150
+ bundle = load_model_bundle(
151
+ folder,
152
+ configuration="3d_fullres",
153
+ folds=[0],
154
+ source_profile=SOURCE_PROFILE,
155
+ arithmetic=ARITHMETIC,
156
+ )
157
+ if bundle.image_channels != 1 or bundle.input_channels != 1:
158
+ raise ModelExecutionError("CT models require exactly one CT input channel")
159
+ if task_id == BODY_MODEL:
160
+ # The body model was trained with mirroring; upstream predicts it without TTA.
161
+ bundle = replace(bundle, mirroring_axes=())
162
+ elif bundle.mirroring_axes:
163
+ raise ModelExecutionError("TotalSegmentator CT requires a no-mirroring model bundle")
164
+ # Upstream nnU-Net blends every model's tiles in float16; float32 blending
165
+ # changed 549 voxels of AMOS22 case amos_0008 against the upstream standard pipeline.
166
+ return ModelFolderPredictor(
167
+ bundle,
168
+ step_fraction=_step_fraction(task_id),
169
+ compile_models=False,
170
+ accumulation="nnunet-fp16",
171
+ )