totalsegmentator-mlx 0.1.1__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.
@@ -0,0 +1,20 @@
1
+ .venv
2
+ .venv-*
3
+ .cache/
4
+ runs/
5
+ __pycache__/
6
+ *.py[cod]
7
+ .pytest_cache/
8
+ .hypothesis/
9
+ .ruff_cache/
10
+ dist/
11
+ build/
12
+ *.egg-info/
13
+ *.nii
14
+ *.nii.gz
15
+ *.pth
16
+ *.safetensors
17
+ *.npz
18
+ *.npy
19
+ # Generated synthetic CT fixtures carry the independent workflow reference.
20
+ !tests/fixtures/*.nii.gz
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,70 @@
1
+ Metadata-Version: 2.5
2
+ Name: totalsegmentator-mlx
3
+ Version: 0.1.1
4
+ Summary: TotalSegmentator v2 CT segmentation with native MLX inference on Apple Silicon
5
+ Project-URL: Homepage, https://github.com/MedMLX/totalsegmentator-mlx
6
+ Project-URL: Documentation, https://github.com/MedMLX/totalsegmentator-mlx/blob/main/docs/technical.md
7
+ Project-URL: Repository, https://github.com/MedMLX/totalsegmentator-mlx
8
+ Project-URL: Issues, https://github.com/MedMLX/totalsegmentator-mlx/issues
9
+ Author: Joseph Sandoval, Alfredo Sandoval Jr.
10
+ License-Expression: Apache-2.0
11
+ License-File: LICENSE
12
+ License-File: THIRD_PARTY_NOTICES.md
13
+ Classifier: Operating System :: MacOS :: MacOS X
14
+ Requires-Python: <3.15,>=3.13
15
+ Requires-Dist: medmlx-core==0.2.3
16
+ Requires-Dist: nibabel<6,>=5.3
17
+ Requires-Dist: nnunet-mlx==0.5.1
18
+ Requires-Dist: numpy<3,>=2.0
19
+ Requires-Dist: scipy==1.18.1
20
+ Provides-Extra: conversion
21
+ Requires-Dist: nnunet-mlx[conversion]; extra == 'conversion'
22
+ Provides-Extra: dev
23
+ Requires-Dist: hypothesis<7,>=6; extra == 'dev'
24
+ Requires-Dist: pyright==1.1.414; extra == 'dev'
25
+ Requires-Dist: pytest<10,>=8.4; extra == 'dev'
26
+ Requires-Dist: ruff<1,>=0.13; extra == 'dev'
27
+ Description-Content-Type: text/markdown
28
+
29
+ # totalsegmentator-mlx
30
+
31
+ Segment 117 CT structures with TotalSegmentator v2 in native MLX. Includes standard, fast and coarse modes.
32
+
33
+ [Docs](https://github.com/MedMLX/totalsegmentator-mlx/blob/main/docs/technical.md) · [MedMLX](https://github.com/MedMLX)
34
+
35
+ ![totalsegmentator-mlx example output](https://raw.githubusercontent.com/MedMLX/totalsegmentator-mlx/main/docs/example.png)
36
+
37
+ *Fast-mode 3D surfaces and an axial slice from an autoPET CT.*
38
+
39
+ | Input | Output |
40
+ | :--- | :--- |
41
+ | 3D CT · NIfTI | Multilabel mask on the input grid |
42
+
43
+ **Apple Silicon · Metal · Python 3.13 / 3.14** · [uv](https://docs.astral.sh/uv/)
44
+
45
+ ## Quick start
46
+
47
+ ```bash
48
+ uv venv --python 3.13 --seed
49
+ source .venv/bin/activate
50
+ python -m pip install "totalsegmentator-mlx[conversion]==0.1.1"
51
+ ```
52
+
53
+ Convert your TotalSegmentator v2 checkpoints once, then segment:
54
+
55
+ ```bash
56
+ totalsegmentator-mlx convert --source-model-dir ~/.totalsegmentator/nnunet/results \
57
+ --output-model-dir models --models organs vertebrae cardiac muscles ribs
58
+ totalsegmentator-mlx predict -i ct.nii.gz -o mask.nii.gz --model-dir models
59
+ ```
60
+
61
+ The PyPI package contains code only. Obtain trusted TotalSegmentator v2 checkpoints
62
+ from [upstream](https://github.com/wasserth/TotalSegmentator) under their publisher
63
+ terms, then convert your local copies. No checkpoints are downloaded automatically.
64
+ Docs cover model folders, modes and cropping.
65
+
66
+ ## License
67
+
68
+ [Apache-2.0](https://github.com/MedMLX/totalsegmentator-mlx/blob/main/LICENSE). See [third-party notices](https://github.com/MedMLX/totalsegmentator-mlx/blob/main/THIRD_PARTY_NOTICES.md). Model weights retain their publisher terms.
69
+
70
+ For research and education. Outputs require human review.
@@ -0,0 +1,42 @@
1
+ # totalsegmentator-mlx
2
+
3
+ Segment 117 CT structures with TotalSegmentator v2 in native MLX. Includes standard, fast and coarse modes.
4
+
5
+ [Docs](https://github.com/MedMLX/totalsegmentator-mlx/blob/main/docs/technical.md) · [MedMLX](https://github.com/MedMLX)
6
+
7
+ ![totalsegmentator-mlx example output](https://raw.githubusercontent.com/MedMLX/totalsegmentator-mlx/main/docs/example.png)
8
+
9
+ *Fast-mode 3D surfaces and an axial slice from an autoPET CT.*
10
+
11
+ | Input | Output |
12
+ | :--- | :--- |
13
+ | 3D CT · NIfTI | Multilabel mask on the input grid |
14
+
15
+ **Apple Silicon · Metal · Python 3.13 / 3.14** · [uv](https://docs.astral.sh/uv/)
16
+
17
+ ## Quick start
18
+
19
+ ```bash
20
+ uv venv --python 3.13 --seed
21
+ source .venv/bin/activate
22
+ python -m pip install "totalsegmentator-mlx[conversion]==0.1.1"
23
+ ```
24
+
25
+ Convert your TotalSegmentator v2 checkpoints once, then segment:
26
+
27
+ ```bash
28
+ totalsegmentator-mlx convert --source-model-dir ~/.totalsegmentator/nnunet/results \
29
+ --output-model-dir models --models organs vertebrae cardiac muscles ribs
30
+ totalsegmentator-mlx predict -i ct.nii.gz -o mask.nii.gz --model-dir models
31
+ ```
32
+
33
+ The PyPI package contains code only. Obtain trusted TotalSegmentator v2 checkpoints
34
+ from [upstream](https://github.com/wasserth/TotalSegmentator) under their publisher
35
+ terms, then convert your local copies. No checkpoints are downloaded automatically.
36
+ Docs cover model folders, modes and cropping.
37
+
38
+ ## License
39
+
40
+ [Apache-2.0](https://github.com/MedMLX/totalsegmentator-mlx/blob/main/LICENSE). See [third-party notices](https://github.com/MedMLX/totalsegmentator-mlx/blob/main/THIRD_PARTY_NOTICES.md). Model weights retain their publisher terms.
41
+
42
+ For research and education. Outputs require human review.
@@ -0,0 +1,46 @@
1
+ # Third-party notices
2
+
3
+ MedMLX-authored additions are licensed under [Apache-2.0](LICENSE).
4
+ The upstream attribution and license notices are retained below.
5
+
6
+ totalsegmentator-mlx extracts the existing MedMLX integration and the
7
+ TotalSegmentator v2 CT outer pipeline into a native model package.
8
+
9
+ TotalSegmentator source and label tables:
10
+ https://github.com/Alfredo-Sandoval/TotalSegmentator
11
+ revision 44310d406805032e7056c8c13a2a37456faeaaf7
12
+ derived from https://github.com/wasserth/TotalSegmentator
13
+ Apache License, Version 2.0 (included as LICENSE).
14
+
15
+ The extracted CT path preserves canonical orientation, cubic 1.5 mm CT
16
+ resampling with int32 staging, ordered five-part global label merging,
17
+ nearest-neighbor label restoration and the NIfTI label table. Other upstream
18
+ tasks, backends and application services are not included.
19
+
20
+ The MedMLX adapter originated in medseg-mlx, by Joseph Sandoval and
21
+ Alfredo Sandoval Jr., under the Apache License, Version 2.0.
22
+
23
+ nnunet-mlx is a separate dependency and retains its own Apache-2.0 and MIT
24
+ notices. Model checkpoint terms are separate from these source-code licenses.
25
+
26
+ Dependencies declared in [pyproject.toml](pyproject.toml) are installed separately
27
+ and retain their respective licenses.
28
+
29
+ ## Historical Medical Segmentation Decathlon labels
30
+
31
+ The inherited Git history contains 32 training masks from the Medical
32
+ Segmentation Decathlon `Task05_Prostate` dataset. Its dataset metadata credits
33
+ Radboud University, Nijmegen Medical Centre. The masks' NIfTI contents are
34
+ unchanged from the dataset's `labelsTr` files.
35
+
36
+ Upstream commit
37
+ [`29ca422`](https://github.com/wasserth/TotalSegmentator/commit/29ca42220288df4e5080fce501f4025453ebc07e)
38
+ added them under `mnt/nvme/nnunet/preprocessed/Task005_Prostate/gt_segmentations/`;
39
+ [`4d6b53d`](https://github.com/wasserth/TotalSegmentator/commit/4d6b53d859063df5c3d7ace0b019b60c27df19e5)
40
+ removed them from the source tree. They remain in the inherited Git history.
41
+
42
+ These masks retain the dataset's
43
+ [Creative Commons Attribution-ShareAlike 4.0 International license](https://creativecommons.org/licenses/by-sa/4.0/).
44
+ Source: [Medical Segmentation Decathlon on the AWS Open Data Registry](https://registry.opendata.aws/msd/)
45
+ and its MONAI-hosted [Task05_Prostate archive](https://msd-for-monai.s3-us-west-2.amazonaws.com/Task05_Prostate.tar),
46
+ accessed 2026-10-24.
@@ -0,0 +1,86 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.27"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "totalsegmentator-mlx"
7
+ version = "0.1.1"
8
+ description = "TotalSegmentator v2 CT segmentation with native MLX inference on Apple Silicon"
9
+ readme = "README.md"
10
+ classifiers = ["Operating System :: MacOS :: MacOS X"]
11
+ requires-python = ">=3.13,<3.15"
12
+ license = "Apache-2.0"
13
+ license-files = ["LICENSE", "THIRD_PARTY_NOTICES.md"]
14
+ authors = [{name = "Joseph Sandoval"}, {name = "Alfredo Sandoval Jr."}]
15
+ dependencies = [
16
+ "medmlx-core==0.2.3",
17
+ "nnunet-mlx==0.5.1",
18
+ "nibabel>=5.3,<6",
19
+ "numpy>=2.0,<3",
20
+ "scipy==1.18.1",
21
+ ]
22
+
23
+ [project.urls]
24
+ Homepage = "https://github.com/MedMLX/totalsegmentator-mlx"
25
+ Documentation = "https://github.com/MedMLX/totalsegmentator-mlx/blob/main/docs/technical.md"
26
+ Repository = "https://github.com/MedMLX/totalsegmentator-mlx"
27
+ Issues = "https://github.com/MedMLX/totalsegmentator-mlx/issues"
28
+
29
+ [project.optional-dependencies]
30
+ conversion = ["nnunet-mlx[conversion]"]
31
+ dev = ["hypothesis>=6,<7", "pyright==1.1.414", "pytest>=8.4,<10", "ruff>=0.13,<1"]
32
+
33
+ [project.scripts]
34
+ totalsegmentator-mlx = "totalsegmentator_mlx.cli:main"
35
+
36
+ [project.entry-points."medmlx.models"]
37
+ totalsegmentator = "totalsegmentator_mlx.medmlx:MODEL"
38
+
39
+ [tool.hatch.metadata]
40
+ allow-direct-references = true
41
+
42
+ [tool.hatch.build.targets.wheel]
43
+ packages = ["src/totalsegmentator_mlx"]
44
+
45
+ [tool.uv]
46
+ constraint-dependencies = ["setuptools>=84.1.0", "filelock>=4.2.1", ]
47
+ environments = ["sys_platform == 'darwin' and platform_machine == 'arm64'"]
48
+ required-environments = ["sys_platform == 'darwin' and platform_machine == 'arm64'"]
49
+
50
+ [tool.pytest.ini_options]
51
+ testpaths = ["tests"]
52
+ addopts = "--strict-config --strict-markers"
53
+
54
+ [tool.ruff]
55
+ target-version = "py313"
56
+ line-length = 100
57
+
58
+ [tool.ruff.lint]
59
+ select = ["E", "F", "I", "UP", "B", "SIM", "RUF", "TID251", "TID252", "ANN401"]
60
+
61
+ [tool.ruff.lint.flake8-tidy-imports]
62
+ ban-relative-imports = "all"
63
+
64
+ [tool.ruff.lint.flake8-tidy-imports.banned-api]
65
+ "typing.Any" = {msg = "Use precise types at external boundaries."}
66
+ "typing_extensions.Any" = {msg = "Use precise types at external boundaries."}
67
+
68
+ [tool.pyright]
69
+ include = ["src", "tests"]
70
+ pythonVersion = "3.13"
71
+ typeCheckingMode = "strict"
72
+ enableTypeIgnoreComments = false
73
+ reportUnnecessaryTypeIgnoreComment = "error"
74
+
75
+ [tool.uv.sources]
76
+ medmlx-core = { git = "https://github.com/MedMLX/medmlx.git", rev = "e765f0a94aa31e8dfcdc599e4a4206eaca84f8b0", subdirectory = "packages/core" }
77
+ nnunet-mlx = { git = "https://github.com/MedMLX/nnunet-mlx.git", rev = "ac07d0047a2f6f2e620b52e9d3a512a64d874b6a" }
78
+
79
+ [tool.hatch.build.targets.sdist]
80
+ only-include = [
81
+ "src/totalsegmentator_mlx",
82
+ "pyproject.toml",
83
+ "README.md",
84
+ "LICENSE",
85
+ "THIRD_PARTY_NOTICES.md",
86
+ ]
@@ -0,0 +1,23 @@
1
+ """TotalSegmentator v2 ``total`` CT inference on Apple Silicon (MLX), research software.
2
+
3
+ ``segment`` runs a CT through the native workflow and returns uint8 global label IDs
4
+ (1-117) on the input grid; ``convert_model`` converts upstream fold-0 checkpoints to
5
+ the layout ``segment`` reads. Names load on first access, so importing the package
6
+ does not import the MLX engine.
7
+ """
8
+
9
+ from importlib import import_module
10
+ from typing import TYPE_CHECKING
11
+
12
+ if TYPE_CHECKING:
13
+ from totalsegmentator_mlx.conversion import convert_model
14
+ from totalsegmentator_mlx.pipeline import segment
15
+
16
+ __all__ = ["convert_model", "segment"]
17
+
18
+
19
+ def __getattr__(name: str) -> object:
20
+ owner = {"segment": "pipeline", "convert_model": "conversion"}.get(name)
21
+ if owner is None:
22
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
23
+ return getattr(import_module(f"{__name__}.{owner}"), name)
@@ -0,0 +1,6 @@
1
+ """Run the installed command through python -m totalsegmentator_mlx."""
2
+
3
+ from totalsegmentator_mlx.cli import main
4
+
5
+ if __name__ == "__main__":
6
+ main()
@@ -0,0 +1,128 @@
1
+ """Lazy command-line entry point for conversion, CT prediction and label discovery."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import sys
8
+ from pathlib import Path
9
+ from typing import TYPE_CHECKING, cast
10
+
11
+ from totalsegmentator_mlx.labels import LABELS, MODEL_PARTS, QUALITY_MODELS
12
+
13
+ if TYPE_CHECKING:
14
+ from totalsegmentator_mlx.models import Mode
15
+
16
+
17
+ class Arguments(argparse.Namespace):
18
+ """Typed namespace for the ``predict``, ``convert`` and ``labels`` subcommands.
19
+
20
+ Only the fields of the chosen subcommand are set by argparse.
21
+ """
22
+
23
+ command: str
24
+ input_path: Path
25
+ output_path: Path
26
+ model_dir: Path
27
+ mode: str
28
+ model_part: str | None
29
+ organ: list[str] | None
30
+ roi_subset: list[str] | None
31
+ robust_crop: bool
32
+ body_seg: bool
33
+ models: list[str] | None
34
+ force_split: bool
35
+ overwrite: bool
36
+ probabilities_path: Path | None
37
+ source_model_dir: Path
38
+ output_model_dir: Path
39
+
40
+
41
+ def _parser() -> argparse.ArgumentParser:
42
+ parser = argparse.ArgumentParser(description="Native TotalSegmentator v2 CT inference on Metal")
43
+ subparsers = parser.add_subparsers(dest="command", required=True)
44
+ predict = subparsers.add_parser("predict", help="Segment a NIfTI CT on its original grid")
45
+ predict.add_argument("-i", "--input", dest="input_path", type=Path, required=True)
46
+ predict.add_argument("-o", "--output", dest="output_path", type=Path, required=True)
47
+ predict.add_argument("--model-dir", type=Path, required=True)
48
+ predict.add_argument(
49
+ "--mode",
50
+ choices=["standard", *QUALITY_MODELS],
51
+ default="standard",
52
+ help="standard: five 1.5 mm parts; fast: 3 mm model; coarse: 6 mm model (upstream fastest)",
53
+ )
54
+ predict.add_argument("--model-part", choices=list(MODEL_PARTS))
55
+ predict.add_argument("--organ", nargs="+", help="Filter canonical organ names after inference")
56
+ predict.add_argument(
57
+ "--roi-subset",
58
+ nargs="+",
59
+ help="Crop to these structures with a rough 6 mm segmentation and run only their parts",
60
+ )
61
+ predict.add_argument(
62
+ "--robust-crop", action="store_true", help="Locate --roi-subset with the 3 mm model"
63
+ )
64
+ predict.add_argument(
65
+ "--body-seg", action="store_true", help="Crop to the body with the Dataset300 model"
66
+ )
67
+ predict.add_argument("--force-split", action="store_true")
68
+ predict.add_argument("--overwrite", action="store_true")
69
+ predict.add_argument("--probabilities-path", type=Path)
70
+ convert = subparsers.add_parser("convert", help="Convert trusted local fold-0 checkpoints")
71
+ convert.add_argument("--source-model-dir", type=Path, required=True)
72
+ convert.add_argument("--output-model-dir", type=Path, required=True)
73
+ convert_models = convert.add_mutually_exclusive_group()
74
+ convert_models.add_argument("--model-part", choices=[*MODEL_PARTS, *QUALITY_MODELS, "body"])
75
+ convert_models.add_argument(
76
+ "--models",
77
+ nargs="+",
78
+ choices=[*MODEL_PARTS, *QUALITY_MODELS, "body"],
79
+ help="Models to convert into one new root (default: the five standard parts)",
80
+ )
81
+ subparsers.add_parser("labels", help="Print released global label IDs as JSON")
82
+ return parser
83
+
84
+
85
+ def main(argv: list[str] | None = None) -> None:
86
+ """Run a subcommand; ``labels`` prints the global ID-to-name table as JSON.
87
+
88
+ Exceptions that are ``OSError``, ``ValueError``, ``RuntimeError`` or ``ImportError``
89
+ (which includes the ``medmlx_core`` errors) are reported on stderr with exit status 2.
90
+ ``predict`` prints the output path on success and ``convert`` the new model root.
91
+ """
92
+ parser = _parser()
93
+ args = parser.parse_args(argv, namespace=Arguments())
94
+ if args.command == "labels":
95
+ print(json.dumps(LABELS, indent=2))
96
+ return
97
+ try:
98
+ if args.command == "convert":
99
+ from totalsegmentator_mlx.conversion import convert_model
100
+
101
+ output = convert_model(
102
+ args.source_model_dir,
103
+ args.output_model_dir,
104
+ model_part=args.model_part,
105
+ models=args.models,
106
+ )
107
+ print(output)
108
+ return
109
+ from totalsegmentator_mlx.pipeline import segment
110
+
111
+ segment(
112
+ args.input_path,
113
+ model_dir=args.model_dir,
114
+ output_path=args.output_path,
115
+ mode=cast("Mode", args.mode),
116
+ model_part=args.model_part,
117
+ prompt=args.organ,
118
+ roi_subset=args.roi_subset,
119
+ robust_crop=args.robust_crop,
120
+ body_seg=args.body_seg,
121
+ force_split=args.force_split,
122
+ overwrite=args.overwrite,
123
+ probabilities_path=args.probabilities_path,
124
+ progress=lambda message: print(message, file=sys.stderr, flush=True),
125
+ )
126
+ print(args.output_path)
127
+ except (OSError, ValueError, RuntimeError, ImportError) as error:
128
+ parser.exit(2, f"{parser.prog}: {error}\n")