totalsegmentator-mlx 0.2.0__tar.gz → 0.4.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 (26) hide show
  1. {totalsegmentator_mlx-0.2.0 → totalsegmentator_mlx-0.4.0}/PKG-INFO +43 -63
  2. {totalsegmentator_mlx-0.2.0 → totalsegmentator_mlx-0.4.0}/README.md +40 -60
  3. {totalsegmentator_mlx-0.2.0 → totalsegmentator_mlx-0.4.0}/pyproject.toml +3 -3
  4. totalsegmentator_mlx-0.4.0/src/totalsegmentator_mlx/__init__.py +21 -0
  5. {totalsegmentator_mlx-0.2.0 → totalsegmentator_mlx-0.4.0}/src/totalsegmentator_mlx/__main__.py +1 -1
  6. totalsegmentator_mlx-0.4.0/src/totalsegmentator_mlx/cli.py +37 -0
  7. totalsegmentator_mlx-0.4.0/src/totalsegmentator_mlx/engine.py +225 -0
  8. {totalsegmentator_mlx-0.2.0 → totalsegmentator_mlx-0.4.0}/src/totalsegmentator_mlx/geometry.py +29 -68
  9. totalsegmentator_mlx-0.4.0/src/totalsegmentator_mlx/imageio.py +122 -0
  10. totalsegmentator_mlx-0.4.0/src/totalsegmentator_mlx/medmlx.py +295 -0
  11. {totalsegmentator_mlx-0.2.0 → totalsegmentator_mlx-0.4.0}/src/totalsegmentator_mlx/models.py +2 -2
  12. {totalsegmentator_mlx-0.2.0 → totalsegmentator_mlx-0.4.0}/src/totalsegmentator_mlx/output.py +2 -39
  13. totalsegmentator_mlx-0.4.0/src/totalsegmentator_mlx/pipeline.py +337 -0
  14. {totalsegmentator_mlx-0.2.0 → totalsegmentator_mlx-0.4.0}/src/totalsegmentator_mlx/resampling.py +36 -15
  15. totalsegmentator_mlx-0.2.0/src/totalsegmentator_mlx/__init__.py +0 -27
  16. totalsegmentator_mlx-0.2.0/src/totalsegmentator_mlx/cli.py +0 -104
  17. totalsegmentator_mlx-0.2.0/src/totalsegmentator_mlx/engine.py +0 -254
  18. totalsegmentator_mlx-0.2.0/src/totalsegmentator_mlx/imageio.py +0 -53
  19. totalsegmentator_mlx-0.2.0/src/totalsegmentator_mlx/medmlx.py +0 -108
  20. totalsegmentator_mlx-0.2.0/src/totalsegmentator_mlx/pipeline.py +0 -464
  21. {totalsegmentator_mlx-0.2.0 → totalsegmentator_mlx-0.4.0}/.gitignore +0 -0
  22. {totalsegmentator_mlx-0.2.0 → totalsegmentator_mlx-0.4.0}/LICENSE +0 -0
  23. {totalsegmentator_mlx-0.2.0 → totalsegmentator_mlx-0.4.0}/THIRD_PARTY_NOTICES.md +0 -0
  24. {totalsegmentator_mlx-0.2.0 → totalsegmentator_mlx-0.4.0}/src/totalsegmentator_mlx/labels.py +0 -0
  25. {totalsegmentator_mlx-0.2.0 → totalsegmentator_mlx-0.4.0}/src/totalsegmentator_mlx/localization.py +0 -0
  26. {totalsegmentator_mlx-0.2.0 → totalsegmentator_mlx-0.4.0}/src/totalsegmentator_mlx/py.typed +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.4.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[nifti]<0.4,>=0.3.2
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.11,>=0.10.0
31
31
  Requires-Dist: numpy<3,>=2.0
32
32
  Requires-Dist: scipy==1.18.1
33
33
  Provides-Extra: dev
@@ -44,14 +44,14 @@ 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.4.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)
51
51
 
52
- <img src="docs/example.png" alt="TotalSegmentator standard-mode (1.5 mm) 3D surfaces and axial CT segmentation" width="100%">
52
+ <img src="https://raw.githubusercontent.com/MedMLX/totalsegmentator-mlx/main/docs/example.png" alt="TotalSegmentator standard-mode (1.5 mm) 3D surfaces and axial CT segmentation" width="100%">
53
53
 
54
- Standard mode (1.5 mm): 3D surfaces from [autoPET-III](https://huggingface.co/datasets/YongchengYAO/autoPET-III-Lite) and axial CT from [AMOS22](https://zenodo.org/records/7262581). Surfaces and contours are smoothed for display.
54
+ <sub>Standard mode (1.5 mm): 3D surfaces from <a href="https://huggingface.co/datasets/YongchengYAO/autoPET-III-Lite">autoPET-III</a> and axial CT from <a href="https://zenodo.org/records/7262581">AMOS22</a>. Surfaces and contours are smoothed for display.</sub>
55
55
 
56
56
  </div>
57
57
 
@@ -68,43 +68,52 @@ 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.4.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"])
81
81
  ```
82
82
 
83
- Weights download from `MedMLX/totalsegmentator-mlx` on first use. Use `medmlx setup totalsegmentator` to download ahead of time. For local weights, pass the downloaded bundle folder as `weights_path`.
83
+ Weights download from `MedMLX/totalsegmentator-mlx` on first use; `medmlx setup totalsegmentator`
84
+ downloads them ahead of time. For local weights, pass the downloaded bundle folder as
85
+ `weights_path`.
84
86
 
85
87
  ### Inputs and outputs
86
88
 
87
89
  | Argument | Meaning |
88
90
  | --- | --- |
89
91
  | `image_path` | One finite 3D CT in NIfTI-1 or NIfTI-2, in Hounsfield units |
90
- | `output_dir` | Directory for `mask.nii.gz` |
92
+ | `output_dir` | Directory for `mask.nii.gz` (and the probability files) |
91
93
  | `weights_path` | Optional root of the model folders below |
92
94
  | `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 |
95
+ | `classes` | Structure names to keep after inference; label IDs stay global |
96
+ | `model_part` | One standard part: `organs`, `vertebrae`, `cardiac`, `muscles` or `ribs` |
94
97
  | `roi_subset` | Locate these structures, crop to them plus 20 mm and drop other labels |
95
98
  | `robust_crop` | Locate `roi_subset` with the 3 mm model instead of the 6 mm one |
96
99
  | `body_seg` | Crop to the Dataset300 body model plus 3 mm |
97
- | `overwrite` | `False` by default; an existing mask is never replaced |
100
+ | `force_split` | Use upstream's three overlapping slabs even for smaller volumes |
101
+ | `probabilities` | Also write `probabilities.npz` and `probabilities.pkl` for one uncropped model |
102
+ | `overwrite` | `False` by default; existing outputs are replaced only when `True` |
98
103
 
99
104
  - **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
105
+ structures. `roi_subset` cannot be combined with `classes`, `model_part` or `body_seg`, and
101
106
  `robust_crop` requires `roi_subset`. Cropped regions are restored by zero filling; an
102
107
  empty localization returns an empty mask.
103
- - **Units:** spatial units must be millimetres or unspecified.
108
+ - **Units:** spatial units may be millimeters, meters, microns or unspecified.
104
109
  - **Mask:** a uint8 NIfTI-1 with global labels 1–117 (0 background) on the input grid,
105
110
  with the upstream label table as a header extension.
106
- - **Return value:** `{"outputs": {"mask": path}, "details": {...}}`, with run metadata in
107
- `details`.
111
+ - **Probabilities:** float32 local-label probabilities on the model reader's grid, with
112
+ nnU-Net's geometry and crop properties in the `.pkl` beside them.
113
+ - **Return value:** `{"outputs": {"mask": path}, "artifacts": {"mask": ...}, "details": {...}}`,
114
+ plus the `probabilities` and `probability_properties` roles when requested. The mask
115
+ artifact is a label map on the input grid whose labels are the structures the run can
116
+ write; `details` holds run metadata.
108
117
  - **Errors:** invalid inputs raise `InvalidInputError`; missing or mismatched weights
109
118
  raise `AssetNotReadyError`.
110
119
 
@@ -122,61 +131,33 @@ single model folder can be passed directly when only that dataset is needed.
122
131
  | `298/` | 6 mm total model | `coarse`; `roi_subset` |
123
132
  | `300/` | 6 mm body model | `body_seg` |
124
133
 
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:
134
+ ### Several CTs
145
135
 
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
136
+ `run` loads each network for its part and releases it before the next one. To
137
+ segment several CTs, load the model once; its networks stay loaded until it closes:
155
138
 
156
139
  ```python
157
- from totalsegmentator_mlx import segment
140
+ from totalsegmentator_mlx import load_model
158
141
 
159
- labels = segment("ct.nii.gz", model_dir="models", mode="fast") # nibabel image, uint8
142
+ with load_model() as model:
143
+ for name in ("ct1", "ct2"):
144
+ model.run(image_path=f"{name}.nii.gz", output_dir=name)
160
145
  ```
161
146
 
162
- `segment` takes the command-line options as keyword arguments, plus an optional
163
- `output_path`. It never downloads weights.
147
+ `model.run` takes the same arguments as `run` except `weights_path`. Standard
148
+ mode with crops keeps up to eight networks loaded.
164
149
 
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
150
+ ### Command line
170
151
 
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()
152
+ ```bash
153
+ totalsegmentator-mlx predict --image-path ct.nii.gz --output-dir out
174
154
  ```
175
155
 
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.
156
+ `predict` takes each argument above as a flag with hyphens (`--image-path`, `--output-dir`,
157
+ `--weights-path`, `--mode`, `--classes`, `--model-part`, `--roi-subset`, `--robust-crop`,
158
+ `--body-seg`, `--force-split`, `--probabilities`, `--overwrite`; each switch also has a
159
+ `--no-` form) and prints the run result as JSON.
160
+ `totalsegmentator-mlx labels` prints the label IDs.
180
161
 
181
162
  ### Limits
182
163
 
@@ -185,7 +166,6 @@ to `configure_predictor_cache()` restores the eight-model policy.
185
166
  - Models use `3d_fullres`, fold 0, without mirroring.
186
167
  - Input and output are NIfTI. Other TotalSegmentator tasks and its extra export,
187
168
  statistics and training options are unsupported.
188
- - Inference requires Apple Silicon with Metal.
189
169
 
190
170
  ## Use with MedMLX
191
171
 
@@ -204,4 +184,4 @@ For Codex, use `codex mcp add medmlx -- "$MEDMLX" serve --root "$HOME/medmlx-wor
204
184
 
205
185
  ## License
206
186
 
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.
187
+ [Apache-2.0](https://github.com/MedMLX/totalsegmentator-mlx/blob/v0.4.0/LICENSE). See [third-party notices](https://github.com/MedMLX/totalsegmentator-mlx/blob/v0.4.0/THIRD_PARTY_NOTICES.md). Model weights retain their publisher terms.
@@ -6,14 +6,14 @@ 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.4.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)
13
13
 
14
- <img src="docs/example.png" alt="TotalSegmentator standard-mode (1.5 mm) 3D surfaces and axial CT segmentation" width="100%">
14
+ <img src="https://raw.githubusercontent.com/MedMLX/totalsegmentator-mlx/main/docs/example.png" alt="TotalSegmentator standard-mode (1.5 mm) 3D surfaces and axial CT segmentation" width="100%">
15
15
 
16
- Standard mode (1.5 mm): 3D surfaces from [autoPET-III](https://huggingface.co/datasets/YongchengYAO/autoPET-III-Lite) and axial CT from [AMOS22](https://zenodo.org/records/7262581). Surfaces and contours are smoothed for display.
16
+ <sub>Standard mode (1.5 mm): 3D surfaces from <a href="https://huggingface.co/datasets/YongchengYAO/autoPET-III-Lite">autoPET-III</a> and axial CT from <a href="https://zenodo.org/records/7262581">AMOS22</a>. Surfaces and contours are smoothed for display.</sub>
17
17
 
18
18
  </div>
19
19
 
@@ -30,43 +30,52 @@ 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.4.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"])
43
43
  ```
44
44
 
45
- Weights download from `MedMLX/totalsegmentator-mlx` on first use. Use `medmlx setup totalsegmentator` to download ahead of time. For local weights, pass the downloaded bundle folder as `weights_path`.
45
+ Weights download from `MedMLX/totalsegmentator-mlx` on first use; `medmlx setup totalsegmentator`
46
+ downloads them ahead of time. For local weights, pass the downloaded bundle folder as
47
+ `weights_path`.
46
48
 
47
49
  ### Inputs and outputs
48
50
 
49
51
  | Argument | Meaning |
50
52
  | --- | --- |
51
53
  | `image_path` | One finite 3D CT in NIfTI-1 or NIfTI-2, in Hounsfield units |
52
- | `output_dir` | Directory for `mask.nii.gz` |
54
+ | `output_dir` | Directory for `mask.nii.gz` (and the probability files) |
53
55
  | `weights_path` | Optional root of the model folders below |
54
56
  | `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 |
57
+ | `classes` | Structure names to keep after inference; label IDs stay global |
58
+ | `model_part` | One standard part: `organs`, `vertebrae`, `cardiac`, `muscles` or `ribs` |
56
59
  | `roi_subset` | Locate these structures, crop to them plus 20 mm and drop other labels |
57
60
  | `robust_crop` | Locate `roi_subset` with the 3 mm model instead of the 6 mm one |
58
61
  | `body_seg` | Crop to the Dataset300 body model plus 3 mm |
59
- | `overwrite` | `False` by default; an existing mask is never replaced |
62
+ | `force_split` | Use upstream's three overlapping slabs even for smaller volumes |
63
+ | `probabilities` | Also write `probabilities.npz` and `probabilities.pkl` for one uncropped model |
64
+ | `overwrite` | `False` by default; existing outputs are replaced only when `True` |
60
65
 
61
66
  - **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
67
+ structures. `roi_subset` cannot be combined with `classes`, `model_part` or `body_seg`, and
63
68
  `robust_crop` requires `roi_subset`. Cropped regions are restored by zero filling; an
64
69
  empty localization returns an empty mask.
65
- - **Units:** spatial units must be millimetres or unspecified.
70
+ - **Units:** spatial units may be millimeters, meters, microns or unspecified.
66
71
  - **Mask:** a uint8 NIfTI-1 with global labels 1–117 (0 background) on the input grid,
67
72
  with the upstream label table as a header extension.
68
- - **Return value:** `{"outputs": {"mask": path}, "details": {...}}`, with run metadata in
69
- `details`.
73
+ - **Probabilities:** float32 local-label probabilities on the model reader's grid, with
74
+ nnU-Net's geometry and crop properties in the `.pkl` beside them.
75
+ - **Return value:** `{"outputs": {"mask": path}, "artifacts": {"mask": ...}, "details": {...}}`,
76
+ plus the `probabilities` and `probability_properties` roles when requested. The mask
77
+ artifact is a label map on the input grid whose labels are the structures the run can
78
+ write; `details` holds run metadata.
70
79
  - **Errors:** invalid inputs raise `InvalidInputError`; missing or mismatched weights
71
80
  raise `AssetNotReadyError`.
72
81
 
@@ -84,61 +93,33 @@ single model folder can be passed directly when only that dataset is needed.
84
93
  | `298/` | 6 mm total model | `coarse`; `roi_subset` |
85
94
  | `300/` | 6 mm body model | `body_seg` |
86
95
 
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:
96
+ ### Several CTs
107
97
 
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
98
+ `run` loads each network for its part and releases it before the next one. To
99
+ segment several CTs, load the model once; its networks stay loaded until it closes:
117
100
 
118
101
  ```python
119
- from totalsegmentator_mlx import segment
102
+ from totalsegmentator_mlx import load_model
120
103
 
121
- labels = segment("ct.nii.gz", model_dir="models", mode="fast") # nibabel image, uint8
104
+ with load_model() as model:
105
+ for name in ("ct1", "ct2"):
106
+ model.run(image_path=f"{name}.nii.gz", output_dir=name)
122
107
  ```
123
108
 
124
- `segment` takes the command-line options as keyword arguments, plus an optional
125
- `output_path`. It never downloads weights.
109
+ `model.run` takes the same arguments as `run` except `weights_path`. Standard
110
+ mode with crops keeps up to eight networks loaded.
126
111
 
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
112
+ ### Command line
132
113
 
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()
114
+ ```bash
115
+ totalsegmentator-mlx predict --image-path ct.nii.gz --output-dir out
136
116
  ```
137
117
 
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.
118
+ `predict` takes each argument above as a flag with hyphens (`--image-path`, `--output-dir`,
119
+ `--weights-path`, `--mode`, `--classes`, `--model-part`, `--roi-subset`, `--robust-crop`,
120
+ `--body-seg`, `--force-split`, `--probabilities`, `--overwrite`; each switch also has a
121
+ `--no-` form) and prints the run result as JSON.
122
+ `totalsegmentator-mlx labels` prints the label IDs.
142
123
 
143
124
  ### Limits
144
125
 
@@ -147,7 +128,6 @@ to `configure_predictor_cache()` restores the eight-model policy.
147
128
  - Models use `3d_fullres`, fold 0, without mirroring.
148
129
  - Input and output are NIfTI. Other TotalSegmentator tasks and its extra export,
149
130
  statistics and training options are unsupported.
150
- - Inference requires Apple Silicon with Metal.
151
131
 
152
132
  ## Use with MedMLX
153
133
 
@@ -166,4 +146,4 @@ For Codex, use `codex mcp add medmlx -- "$MEDMLX" serve --root "$HOME/medmlx-wor
166
146
 
167
147
  ## License
168
148
 
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.
149
+ [Apache-2.0](https://github.com/MedMLX/totalsegmentator-mlx/blob/v0.4.0/LICENSE). See [third-party notices](https://github.com/MedMLX/totalsegmentator-mlx/blob/v0.4.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.4.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[nifti]>=0.3.2,<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.10.0,<0.11",
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)
@@ -3,4 +3,4 @@
3
3
  from totalsegmentator_mlx.cli import main
4
4
 
5
5
  if __name__ == "__main__":
6
- main()
6
+ raise SystemExit(main())
@@ -0,0 +1,37 @@
1
+ """Command-line entry point: ``predict`` is generated from ``run``, ``labels`` is hand-written."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import logging
7
+ import sys
8
+ from collections.abc import Sequence
9
+ from importlib.metadata import version
10
+
11
+ from medmlx_core.cli import add_options, call, execute
12
+
13
+ from totalsegmentator_mlx.labels import LABELS
14
+ from totalsegmentator_mlx.medmlx import run
15
+
16
+ _PROG = "totalsegmentator-mlx"
17
+
18
+
19
+ def main(argv: Sequence[str] | None = None) -> int:
20
+ """Run ``predict`` or ``labels`` and return the exit status.
21
+
22
+ ``predict`` has one option per ``run`` argument, logs stages on stderr and prints the
23
+ run result as JSON; ``labels`` prints the global label ID-to-name table as JSON.
24
+ """
25
+ parser = argparse.ArgumentParser(
26
+ prog=_PROG, description="Native TotalSegmentator v2 CT inference on Metal"
27
+ )
28
+ parser.add_argument("--version", action="version", version=version(_PROG))
29
+ subparsers = parser.add_subparsers(dest="command", required=True)
30
+ predict = subparsers.add_parser("predict", help="Segment a NIfTI CT on its original grid")
31
+ add_options(predict, run)
32
+ subparsers.add_parser("labels", help="Print released global label IDs as JSON")
33
+ arguments = parser.parse_args(argv)
34
+ if arguments.command == "labels":
35
+ return execute(_PROG, lambda: LABELS)
36
+ logging.basicConfig(stream=sys.stderr, level=logging.INFO, format="%(message)s")
37
+ return execute(_PROG, lambda: call(run, arguments))