flexray-mlx 0.2.4__tar.gz → 0.2.6__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,38 @@
1
+ # MedMLX standard
2
+ __pycache__/
3
+ *.py[cod]
4
+ *.egg-info/
5
+ .venv
6
+ build/
7
+ dist/
8
+ .pytest_cache/
9
+ .ruff_cache/
10
+ .mypy_cache/
11
+ .hypothesis/
12
+ .coverage
13
+ htmlcov/
14
+ .DS_Store
15
+ # Never commit secrets (Hugging Face tokens)
16
+ .env
17
+ # Never commit data or weights
18
+ /data/
19
+ /work/
20
+ /weights/
21
+ /models/
22
+ /checkpoints/
23
+ /outputs/
24
+ *.nii
25
+ *.nii.gz
26
+ *.dcm
27
+ *.nrrd
28
+ *.mha
29
+ *.mhd
30
+ *.safetensors
31
+ *.pt
32
+ *.pth
33
+ *.ckpt
34
+ *.bin
35
+ *.h5
36
+ *.npy
37
+ *.npz
38
+ !tests/fixtures/**/*.npz
@@ -0,0 +1,178 @@
1
+ Metadata-Version: 2.5
2
+ Name: flexray-mlx
3
+ Version: 0.2.6
4
+ Summary: Segment anatomical structures in radiographs with FleXray and native MLX
5
+ Project-URL: Homepage, https://medmlx.org
6
+ Project-URL: Documentation, https://github.com/MedMLX/flexray-mlx/blob/v0.2.6/README.md
7
+ Project-URL: Repository, https://github.com/MedMLX/flexray-mlx
8
+ Project-URL: Issues, https://github.com/MedMLX/flexray-mlx/issues
9
+ Project-URL: Weights, https://huggingface.co/MedMLX/flexray-mlx
10
+ Project-URL: MedMLX, https://github.com/MedMLX/medmlx
11
+ Author: Joseph Sandoval, Alfredo Sandoval Jr.
12
+ License-Expression: Apache-2.0 AND MIT AND BSD-3-Clause
13
+ License-File: LICENSE
14
+ License-File: THIRD_PARTY_NOTICES.md
15
+ Keywords: apple-silicon,flexray,medical-imaging,metal,mlx,radiograph,segmentation,x-ray
16
+ Classifier: Development Status :: 4 - Beta
17
+ Classifier: Intended Audience :: Developers
18
+ Classifier: Intended Audience :: Science/Research
19
+ Classifier: Operating System :: MacOS :: MacOS X
20
+ Classifier: Programming Language :: Python :: 3
21
+ Classifier: Programming Language :: Python :: 3 :: Only
22
+ Classifier: Programming Language :: Python :: 3.13
23
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
24
+ Classifier: Topic :: Scientific/Engineering :: Image Processing
25
+ Classifier: Topic :: Scientific/Engineering :: Medical Science Apps.
26
+ Requires-Python: <3.14,>=3.13
27
+ Requires-Dist: medmlx-core==0.2.6
28
+ Requires-Dist: mlx==0.32.4; platform_system == 'Darwin' and platform_machine == 'arm64'
29
+ Requires-Dist: numpy<3,>=2.0
30
+ Requires-Dist: pillow<14,>=13
31
+ Requires-Dist: pydicom<4,>=3
32
+ Requires-Dist: pyyaml<7,>=6
33
+ Requires-Dist: safetensors<1,>=0.6
34
+ Provides-Extra: dev
35
+ Requires-Dist: pyright==1.1.414; extra == 'dev'
36
+ Requires-Dist: pytest<10,>=8.4; extra == 'dev'
37
+ Requires-Dist: ruff<1,>=0.13; extra == 'dev'
38
+ Description-Content-Type: text/markdown
39
+
40
+ <div align="center">
41
+
42
+ # flexray-mlx
43
+
44
+ Segment anatomical structures in radiographs with FleXray and native MLX.
45
+
46
+ [![PyPI](https://img.shields.io/pypi/v/flexray-mlx)](https://pypi.org/project/flexray-mlx/)
47
+ [![Python](https://img.shields.io/pypi/pyversions/flexray-mlx)](https://pypi.org/project/flexray-mlx/)
48
+ [![License](https://img.shields.io/badge/License-Apache_2.0-blue)](https://github.com/MedMLX/flexray-mlx/blob/v0.2.6/LICENSE)
49
+ [![Apple Silicon](https://img.shields.io/badge/Apple_Silicon-MLX-black?logo=apple)](https://github.com/ml-explore/mlx)
50
+ [![Hugging Face](https://img.shields.io/badge/%F0%9F%A4%97_Hugging_Face-weights-yellow)](https://huggingface.co/MedMLX/flexray-mlx)
51
+ [![MedMLX](https://img.shields.io/badge/MedMLX-runtime-A51C30)](https://github.com/MedMLX/medmlx)
52
+
53
+ [Model weights](https://huggingface.co/MedMLX/flexray-mlx) · [MedMLX](https://github.com/MedMLX/medmlx)
54
+
55
+ <img src="https://raw.githubusercontent.com/MedMLX/flexray-mlx/v0.2.6/docs/showcase.png" alt="Chest radiograph with lung, heart and individual rib segmentations" width="100%">
56
+
57
+ </div>
58
+
59
+ | Input | Output |
60
+ | :--- | :--- |
61
+ | Raster image or single-frame DICOM | Structure masks and probabilities |
62
+
63
+ ## Use with MedMLX
64
+
65
+ The [MedMLX MCP server](https://github.com/MedMLX/medmlx/blob/main/docs/mcp.md) is the lowest-friction way to use this model. It installs this runtime, downloads its weights on first use, and lets an AI agent describe, check and run `flexray` for you.
66
+
67
+ ```sh
68
+ uv tool install --python 3.13 "medmlx[segment,mcp]"
69
+ MEDMLX="$(uv tool dir --bin --color never)/medmlx"
70
+ mkdir -p "$HOME/medmlx-work"
71
+ claude mcp add --scope user medmlx -- "$MEDMLX" serve --root "$HOME/medmlx-work"
72
+ ```
73
+
74
+ For Codex, use `codex mcp add medmlx -- "$MEDMLX" serve --root "$HOME/medmlx-work"`. Other MCP clients take the same command and arguments. The same install provides the `medmlx` CLI, for example `medmlx describe flexray`.
75
+
76
+ > **For AI agents:** prefer the MedMLX MCP tools (`list_models`, `describe_model`, `model_readiness`, `run_model`, `get_job`) over writing Python against this package.
77
+
78
+ ## Install
79
+
80
+ ```bash
81
+ uv venv --python 3.13
82
+ source .venv/bin/activate
83
+ uv pip install "flexray-mlx>=0.2.6"
84
+ ```
85
+
86
+ ## Run
87
+
88
+ ```python
89
+ from flexray_mlx.medmlx import run
90
+
91
+ result = run(image_path="chest.png", output_dir="out")
92
+ print(result["outputs"]["mask"])
93
+ ```
94
+
95
+ Omitting `weights_path` downloads `MedMLX/flexray-mlx` into the shared MedMLX cache on
96
+ first use; interrupted downloads resume and later runs work offline. With MedMLX
97
+ installed, `medmlx setup flexray` downloads it ahead of time. To use your own copy, pass
98
+ a folder containing `ensemble.json` and
99
+ `members/flux0375/{config.yml,label_schema.json,model.safetensors,preprocessing.json}`
100
+ as `weights_path`. Automatic setup prepares the flagship (`ensemble=False`);
101
+ `ensemble=True` requires all five members in an explicit folder.
102
+ `details.weights_revision` records the downloaded commit, or `null` for a folder without
103
+ a MedMLX download record.
104
+
105
+ Use `label_name` to select a structure.
106
+
107
+ ### Inputs and outputs
108
+
109
+ | Argument | Meaning |
110
+ | --- | --- |
111
+ | `image_path` | One radiograph: an image Pillow reads (PNG, TIFF, ...) or a single-frame 2D DICOM |
112
+ | `output_dir` | Output directory, created if missing |
113
+ | `weights_path` | Optional bundle folder, as above |
114
+ | `label_name` | Structure to threshold into the mask, `lungs` by default (any label, such as `heart`, `rib_5` or `vertebra_l1`) |
115
+ | `ensemble` | `False` by default; `True` averages all five released members |
116
+ | `threshold` | Probability cutoff in [0, 1], 0.5 by default |
117
+ | `tta_samples` | Passes per member, 1 by default: one plain view plus augmented views |
118
+ | `tta_seed` | `None` by default, unseeded as in FleXray; an integer reproduces Torch CPU augmentation draws |
119
+ | `normalization_scheme` | `None` keeps the bundle's; or `none`, `minmax`, `percentile_minmax` or `standardize` |
120
+ | `overwrite` | `False` by default; existing outputs are replaced only when `True` |
121
+
122
+ DICOM files end in `.dcm` or `.dicom` (any case) or have `DICM` at byte 128. Accepting
123
+ a file does not mean the model suits its modality. Output paths must differ from each
124
+ other, the input and the bundle files, including links, even with `overwrite`.
125
+
126
+ | Output | File | Content |
127
+ | --- | --- | --- |
128
+ | `mask` | `source_image_label.png` | uint8 0/1 mask of the selected structure on the source pixel grid |
129
+ | `display_source` | `source_image.png` | 8-bit grayscale source the mask overlays |
130
+ | `probabilities` | `probabilities.npy` | float32 61×256×256 sigmoid probabilities on the padded model grid |
131
+ | `prediction` | `prediction.json` | Labels, selected channel, threshold, members and content box |
132
+
133
+ FleXray thresholds on the model grid and exports no source-grid images; the PNGs are a
134
+ MedMLX addition. The mask is thresholded first, then cropped to the content box and
135
+ restored to the source size with nearest-neighbour resampling, so no new decisions come
136
+ from interpolation. `run` returns `{"outputs": {...}, "details": {...}}`; `details`
137
+ repeats the label and channel, threshold, members, TTA passes, seed, normalization,
138
+ source size, content box and mask pixel count. Missing or incompatible assets raise
139
+ `AssetNotReadyError`; invalid inputs or existing outputs raise `InvalidInputError`;
140
+ non-finite probabilities raise `ModelExecutionError` before anything is written.
141
+
142
+ The [published bundle](https://huggingface.co/MedMLX/flexray-mlx/tree/722d8341570e8b9e1196cf50e57892da84974fcc)
143
+ holds only `flux0375`; its `ensemble.json` still lists all five members in order
144
+ (`flux0375`, `flux000`, `flux025`, `flux050`, `flux075`). For `ensemble=True`, use the
145
+ [upstream snapshot](https://huggingface.co/VictorButoi/flexray/tree/6b63ddf09cfdff99aea494e3738cf243a4e22cdb)
146
+ with all five member folders.
147
+
148
+ Augmented views follow FleXray's `tta_v3` chain: flips, inversion, CLAHE or gamma,
149
+ contrast, sharpness and Gaussian noise. Gamma on negative normalized pixels can produce
150
+ NaN, which the runner rejects. The released weights were trained with percentile
151
+ normalization; other schemes are not validated.
152
+
153
+ ### Python API
154
+
155
+ ```python
156
+ from pathlib import Path
157
+
158
+ import numpy as np
159
+ from flexray_mlx import FleXrayMlxModel
160
+
161
+ model = FleXrayMlxModel(Path("flexray/members/flux0375"))
162
+ logits = model(np.zeros((1, 1, 256, 256), dtype=np.float32)) # Bx1x256x256 -> Bx61x256x256
163
+ ```
164
+
165
+ The member folder needs the released `config.yml` and `model.safetensors`; loading
166
+ converts convolution weights to MLX layout and every tensor to float32, keeping the
167
+ names. Inputs are prepared images; preparation, sigmoid, ensembling, TTA and
168
+ source-grid restoration are the caller's. `flexray_mlx.tta.predict_with_tta(forward_fn,
169
+ images, tta_samples=..., seed=..., normalizer=...)` takes one or more forward callables
170
+ and already normalized float32 BxCxHxW images, and returns `(logits, probabilities)`;
171
+ pass the `normalize` method of `flexray_mlx.medmlx.ImagePreprocessing` as `normalizer`
172
+ to follow the bundle. Inference needs Apple Silicon with Metal and has no CPU fallback.
173
+
174
+ ## License
175
+
176
+ [Apache-2.0](https://github.com/MedMLX/flexray-mlx/blob/v0.2.6/LICENSE). See [third-party notices](https://github.com/MedMLX/flexray-mlx/blob/v0.2.6/THIRD_PARTY_NOTICES.md). Model weights retain their publisher terms. FleXray weights are noncommercial (CC-BY-NC-4.0).
177
+
178
+ For research and education. Outputs require human review.
@@ -0,0 +1,139 @@
1
+ <div align="center">
2
+
3
+ # flexray-mlx
4
+
5
+ Segment anatomical structures in radiographs with FleXray and native MLX.
6
+
7
+ [![PyPI](https://img.shields.io/pypi/v/flexray-mlx)](https://pypi.org/project/flexray-mlx/)
8
+ [![Python](https://img.shields.io/pypi/pyversions/flexray-mlx)](https://pypi.org/project/flexray-mlx/)
9
+ [![License](https://img.shields.io/badge/License-Apache_2.0-blue)](https://github.com/MedMLX/flexray-mlx/blob/v0.2.6/LICENSE)
10
+ [![Apple Silicon](https://img.shields.io/badge/Apple_Silicon-MLX-black?logo=apple)](https://github.com/ml-explore/mlx)
11
+ [![Hugging Face](https://img.shields.io/badge/%F0%9F%A4%97_Hugging_Face-weights-yellow)](https://huggingface.co/MedMLX/flexray-mlx)
12
+ [![MedMLX](https://img.shields.io/badge/MedMLX-runtime-A51C30)](https://github.com/MedMLX/medmlx)
13
+
14
+ [Model weights](https://huggingface.co/MedMLX/flexray-mlx) · [MedMLX](https://github.com/MedMLX/medmlx)
15
+
16
+ <img src="https://raw.githubusercontent.com/MedMLX/flexray-mlx/v0.2.6/docs/showcase.png" alt="Chest radiograph with lung, heart and individual rib segmentations" width="100%">
17
+
18
+ </div>
19
+
20
+ | Input | Output |
21
+ | :--- | :--- |
22
+ | Raster image or single-frame DICOM | Structure masks and probabilities |
23
+
24
+ ## Use with MedMLX
25
+
26
+ The [MedMLX MCP server](https://github.com/MedMLX/medmlx/blob/main/docs/mcp.md) is the lowest-friction way to use this model. It installs this runtime, downloads its weights on first use, and lets an AI agent describe, check and run `flexray` for you.
27
+
28
+ ```sh
29
+ uv tool install --python 3.13 "medmlx[segment,mcp]"
30
+ MEDMLX="$(uv tool dir --bin --color never)/medmlx"
31
+ mkdir -p "$HOME/medmlx-work"
32
+ claude mcp add --scope user medmlx -- "$MEDMLX" serve --root "$HOME/medmlx-work"
33
+ ```
34
+
35
+ For Codex, use `codex mcp add medmlx -- "$MEDMLX" serve --root "$HOME/medmlx-work"`. Other MCP clients take the same command and arguments. The same install provides the `medmlx` CLI, for example `medmlx describe flexray`.
36
+
37
+ > **For AI agents:** prefer the MedMLX MCP tools (`list_models`, `describe_model`, `model_readiness`, `run_model`, `get_job`) over writing Python against this package.
38
+
39
+ ## Install
40
+
41
+ ```bash
42
+ uv venv --python 3.13
43
+ source .venv/bin/activate
44
+ uv pip install "flexray-mlx>=0.2.6"
45
+ ```
46
+
47
+ ## Run
48
+
49
+ ```python
50
+ from flexray_mlx.medmlx import run
51
+
52
+ result = run(image_path="chest.png", output_dir="out")
53
+ print(result["outputs"]["mask"])
54
+ ```
55
+
56
+ Omitting `weights_path` downloads `MedMLX/flexray-mlx` into the shared MedMLX cache on
57
+ first use; interrupted downloads resume and later runs work offline. With MedMLX
58
+ installed, `medmlx setup flexray` downloads it ahead of time. To use your own copy, pass
59
+ a folder containing `ensemble.json` and
60
+ `members/flux0375/{config.yml,label_schema.json,model.safetensors,preprocessing.json}`
61
+ as `weights_path`. Automatic setup prepares the flagship (`ensemble=False`);
62
+ `ensemble=True` requires all five members in an explicit folder.
63
+ `details.weights_revision` records the downloaded commit, or `null` for a folder without
64
+ a MedMLX download record.
65
+
66
+ Use `label_name` to select a structure.
67
+
68
+ ### Inputs and outputs
69
+
70
+ | Argument | Meaning |
71
+ | --- | --- |
72
+ | `image_path` | One radiograph: an image Pillow reads (PNG, TIFF, ...) or a single-frame 2D DICOM |
73
+ | `output_dir` | Output directory, created if missing |
74
+ | `weights_path` | Optional bundle folder, as above |
75
+ | `label_name` | Structure to threshold into the mask, `lungs` by default (any label, such as `heart`, `rib_5` or `vertebra_l1`) |
76
+ | `ensemble` | `False` by default; `True` averages all five released members |
77
+ | `threshold` | Probability cutoff in [0, 1], 0.5 by default |
78
+ | `tta_samples` | Passes per member, 1 by default: one plain view plus augmented views |
79
+ | `tta_seed` | `None` by default, unseeded as in FleXray; an integer reproduces Torch CPU augmentation draws |
80
+ | `normalization_scheme` | `None` keeps the bundle's; or `none`, `minmax`, `percentile_minmax` or `standardize` |
81
+ | `overwrite` | `False` by default; existing outputs are replaced only when `True` |
82
+
83
+ DICOM files end in `.dcm` or `.dicom` (any case) or have `DICM` at byte 128. Accepting
84
+ a file does not mean the model suits its modality. Output paths must differ from each
85
+ other, the input and the bundle files, including links, even with `overwrite`.
86
+
87
+ | Output | File | Content |
88
+ | --- | --- | --- |
89
+ | `mask` | `source_image_label.png` | uint8 0/1 mask of the selected structure on the source pixel grid |
90
+ | `display_source` | `source_image.png` | 8-bit grayscale source the mask overlays |
91
+ | `probabilities` | `probabilities.npy` | float32 61×256×256 sigmoid probabilities on the padded model grid |
92
+ | `prediction` | `prediction.json` | Labels, selected channel, threshold, members and content box |
93
+
94
+ FleXray thresholds on the model grid and exports no source-grid images; the PNGs are a
95
+ MedMLX addition. The mask is thresholded first, then cropped to the content box and
96
+ restored to the source size with nearest-neighbour resampling, so no new decisions come
97
+ from interpolation. `run` returns `{"outputs": {...}, "details": {...}}`; `details`
98
+ repeats the label and channel, threshold, members, TTA passes, seed, normalization,
99
+ source size, content box and mask pixel count. Missing or incompatible assets raise
100
+ `AssetNotReadyError`; invalid inputs or existing outputs raise `InvalidInputError`;
101
+ non-finite probabilities raise `ModelExecutionError` before anything is written.
102
+
103
+ The [published bundle](https://huggingface.co/MedMLX/flexray-mlx/tree/722d8341570e8b9e1196cf50e57892da84974fcc)
104
+ holds only `flux0375`; its `ensemble.json` still lists all five members in order
105
+ (`flux0375`, `flux000`, `flux025`, `flux050`, `flux075`). For `ensemble=True`, use the
106
+ [upstream snapshot](https://huggingface.co/VictorButoi/flexray/tree/6b63ddf09cfdff99aea494e3738cf243a4e22cdb)
107
+ with all five member folders.
108
+
109
+ Augmented views follow FleXray's `tta_v3` chain: flips, inversion, CLAHE or gamma,
110
+ contrast, sharpness and Gaussian noise. Gamma on negative normalized pixels can produce
111
+ NaN, which the runner rejects. The released weights were trained with percentile
112
+ normalization; other schemes are not validated.
113
+
114
+ ### Python API
115
+
116
+ ```python
117
+ from pathlib import Path
118
+
119
+ import numpy as np
120
+ from flexray_mlx import FleXrayMlxModel
121
+
122
+ model = FleXrayMlxModel(Path("flexray/members/flux0375"))
123
+ logits = model(np.zeros((1, 1, 256, 256), dtype=np.float32)) # Bx1x256x256 -> Bx61x256x256
124
+ ```
125
+
126
+ The member folder needs the released `config.yml` and `model.safetensors`; loading
127
+ converts convolution weights to MLX layout and every tensor to float32, keeping the
128
+ names. Inputs are prepared images; preparation, sigmoid, ensembling, TTA and
129
+ source-grid restoration are the caller's. `flexray_mlx.tta.predict_with_tta(forward_fn,
130
+ images, tta_samples=..., seed=..., normalizer=...)` takes one or more forward callables
131
+ and already normalized float32 BxCxHxW images, and returns `(logits, probabilities)`;
132
+ pass the `normalize` method of `flexray_mlx.medmlx.ImagePreprocessing` as `normalizer`
133
+ to follow the bundle. Inference needs Apple Silicon with Metal and has no CPU fallback.
134
+
135
+ ## License
136
+
137
+ [Apache-2.0](https://github.com/MedMLX/flexray-mlx/blob/v0.2.6/LICENSE). See [third-party notices](https://github.com/MedMLX/flexray-mlx/blob/v0.2.6/THIRD_PARTY_NOTICES.md). Model weights retain their publisher terms. FleXray weights are noncommercial (CC-BY-NC-4.0).
138
+
139
+ For research and education. Outputs require human review.
@@ -4,17 +4,41 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "flexray-mlx"
7
- version = "0.2.4"
8
- description = "Native MLX implementation of FleXray"
7
+ version = "0.2.6"
8
+ description = "Segment anatomical structures in radiographs with FleXray and native MLX"
9
9
  readme = "README.md"
10
- requires-python = ">=3.13,<3.15"
11
- classifiers = ["Operating System :: MacOS :: MacOS X"]
10
+ requires-python = ">=3.13,<3.14"
11
+ classifiers = [
12
+ "Development Status :: 4 - Beta",
13
+ "Intended Audience :: Developers",
14
+ "Intended Audience :: Science/Research",
15
+ "Operating System :: MacOS :: MacOS X",
16
+ "Programming Language :: Python :: 3",
17
+ "Programming Language :: Python :: 3 :: Only",
18
+ "Programming Language :: Python :: 3.13",
19
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
20
+ "Topic :: Scientific/Engineering :: Image Processing",
21
+ "Topic :: Scientific/Engineering :: Medical Science Apps.",
22
+ ]
23
+ keywords = [
24
+ "mlx",
25
+ "apple-silicon",
26
+ "metal",
27
+ "medical-imaging",
28
+ "radiograph",
29
+ "x-ray",
30
+ "segmentation",
31
+ "flexray",
32
+ ]
12
33
  license = "Apache-2.0 AND MIT AND BSD-3-Clause"
13
34
  license-files = ["LICENSE", "THIRD_PARTY_NOTICES.md"]
14
- authors = [{ name = "Joseph Sandoval" }, { name = "Alfredo Sandoval Jr." }]
35
+ authors = [
36
+ { name = "Joseph Sandoval" },
37
+ { name = "Alfredo Sandoval Jr." },
38
+ ]
15
39
  dependencies = [
16
- "medmlx-core==0.2.5",
17
- "mlx>=0.32.4,<1",
40
+ "medmlx-core==0.2.6",
41
+ "mlx==0.32.4; platform_system == 'Darwin' and platform_machine == 'arm64'",
18
42
  "numpy>=2.0,<3",
19
43
  "pillow>=13,<14",
20
44
  "pydicom>=3,<4",
@@ -23,7 +47,12 @@ dependencies = [
23
47
  ]
24
48
 
25
49
  [project.urls]
26
- Homepage = "https://huggingface.co/MedMLX/flexray-mlx"
50
+ Homepage = "https://medmlx.org"
51
+ Documentation = "https://github.com/MedMLX/flexray-mlx/blob/v0.2.6/README.md"
52
+ Repository = "https://github.com/MedMLX/flexray-mlx"
53
+ Issues = "https://github.com/MedMLX/flexray-mlx/issues"
54
+ Weights = "https://huggingface.co/MedMLX/flexray-mlx"
55
+ MedMLX = "https://github.com/MedMLX/medmlx"
27
56
 
28
57
  [project.entry-points."medmlx.models"]
29
58
  flexray = "flexray_mlx.medmlx:MODEL"
@@ -48,6 +77,7 @@ markers = ["mlx: requires native MLX execution (Metal on Apple Silicon)"]
48
77
 
49
78
  [tool.uv]
50
79
  environments = ["sys_platform == 'darwin' and platform_machine == 'arm64'"]
80
+ required-environments = ["sys_platform == 'darwin' and platform_machine == 'arm64'"]
51
81
 
52
82
  [tool.ruff]
53
83
  line-length = 100
@@ -9,7 +9,7 @@ if TYPE_CHECKING:
9
9
 
10
10
  __all__ = ["FleXrayMlxModel"]
11
11
 
12
- __version__ = "0.2.4"
12
+ __version__ = "0.2.6"
13
13
 
14
14
 
15
15
  def __getattr__(name: str) -> object:
@@ -11,6 +11,7 @@ from __future__ import annotations
11
11
 
12
12
  import json
13
13
  import math
14
+ import os
14
15
  import warnings
15
16
  from collections.abc import Mapping, Sequence
16
17
  from dataclasses import dataclass, replace
@@ -60,10 +61,10 @@ _BUNDLE_FILES = (
60
61
  "preprocessing.json",
61
62
  )
62
63
  _WEIGHTS_HINT = (
63
- "Pass weights_path pointing to the FleXray release snapshot directory "
64
- "(huggingface.co/VictorButoi/flexray, revision 6b63ddf09cfdff99aea494e3738cf243a4e22cdb) "
65
- "holding ensemble.json and members/<name>/{config.yml,model.safetensors,"
66
- "label_schema.json,preprocessing.json}."
64
+ "Omit weights_path to download MedMLX/flexray-mlx (the flux0375 flagship), or pass a "
65
+ "FleXray snapshot directory holding ensemble.json and members/<name>/{config.yml,"
66
+ "model.safetensors,label_schema.json,preprocessing.json}. The five-member ensemble is "
67
+ "huggingface.co/VictorButoi/flexray at revision 6b63ddf09cfdff99aea494e3738cf243a4e22cdb."
67
68
  )
68
69
 
69
70
  DEFAULT_IMAGE_SIZE = (256, 256)
@@ -1076,9 +1077,10 @@ def run(
1076
1077
  normalization_scheme: Override the bundle's normalization with ``none``,
1077
1078
  ``minmax``, ``percentile_minmax`` or ``standardize``. None keeps the
1078
1079
  bundle contract. Standardize uses sample std and adds bundle epsilon.
1079
- overwrite: Replace existing outputs instead of refusing. Output paths
1080
- must remain separate from each other, the input radiograph and the
1081
- documented model bundle files, including their file aliases.
1080
+ overwrite: Replace existing outputs instead of refusing; they are replaced
1081
+ only after every new output is written. Output paths must remain
1082
+ separate from each other, the input radiograph and the documented
1083
+ model bundle files, including their file aliases.
1082
1084
 
1083
1085
  Returns:
1084
1086
  ``outputs`` maps ``mask`` to ``source_image_label.png`` (uint8 0/1 on the
@@ -1103,7 +1105,7 @@ def run(
1103
1105
  output file is written.
1104
1106
  """
1105
1107
 
1106
- source_path = Path(image_path)
1108
+ source_path = Path(image_path).expanduser()
1107
1109
  if not source_path.is_file():
1108
1110
  raise InvalidInputError(f"Missing FleXray input radiograph: {source_path}")
1109
1111
  source_path = source_path.resolve()
@@ -1129,7 +1131,9 @@ def run(
1129
1131
  raise InvalidInputError(
1130
1132
  f"normalization_scheme must be one of {sorted(_NORMALIZATION_SCHEMES)}, or None"
1131
1133
  )
1132
- output = Path(output_dir).resolve()
1134
+ output = Path(output_dir).expanduser().resolve()
1135
+ if output.exists() and not output.is_dir():
1136
+ raise InvalidInputError(f"FleXray output_dir is not a directory: {output}")
1133
1137
  names = (DISPLAY_NAME, MASK_NAME, PROBABILITIES_NAME, PREDICTION_NAME)
1134
1138
  destinations = tuple(output / name for name in names)
1135
1139
  # resolve() catches symlink aliases and samefile() catches hard links.
@@ -1138,20 +1142,6 @@ def run(
1138
1142
  for path in destinations
1139
1143
  ):
1140
1144
  raise InvalidInputError("FleXray outputs must be separate from the input radiograph")
1141
- weights_root = (
1142
- weights_dir("flexray") if weights_path is None else Path(weights_path).expanduser()
1143
- )
1144
- model_assets = (
1145
- weights_root / "ensemble.json",
1146
- *(weights_root / "members" / member / name for member in MEMBERS for name in _BUNDLE_FILES),
1147
- )
1148
- if any(
1149
- path.resolve() == asset.resolve()
1150
- or (path.exists() and asset.exists() and path.samefile(asset))
1151
- for path in destinations
1152
- for asset in model_assets
1153
- ):
1154
- raise InvalidInputError("FleXray outputs must be separate from each model asset")
1155
1145
  if any(
1156
1146
  first.resolve() == second.resolve()
1157
1147
  or (first.exists() and second.exists() and first.samefile(second))
@@ -1164,11 +1154,6 @@ def run(
1164
1154
  f"FleXray outputs already exist: {', '.join(existing)}; "
1165
1155
  "pass overwrite=True to replace them"
1166
1156
  )
1167
-
1168
- admitted = admit_bundle(weights_root, ensemble=ensemble)
1169
- labels = admitted.labels
1170
- if label_name not in labels:
1171
- raise InvalidInputError(f"Unknown FleXray anatomy label: {label_name}")
1172
1157
  try:
1173
1158
  source = display_image(source_path)
1174
1159
  except InvalidInputError:
@@ -1176,6 +1161,26 @@ def run(
1176
1161
  raise
1177
1162
  except _input_errors() as error:
1178
1163
  raise InvalidInputError(f"Unreadable FleXray radiograph {source_path}: {error}") from error
1164
+
1165
+ # Every argument the bundle does not define is checked; only now may weights download.
1166
+ weights_root = (
1167
+ weights_dir("flexray") if weights_path is None else Path(weights_path).expanduser()
1168
+ )
1169
+ model_assets = (
1170
+ weights_root / "ensemble.json",
1171
+ *(weights_root / "members" / member / name for member in MEMBERS for name in _BUNDLE_FILES),
1172
+ )
1173
+ if any(
1174
+ path.resolve() == asset.resolve()
1175
+ or (path.exists() and asset.exists() and path.samefile(asset))
1176
+ for path in destinations
1177
+ for asset in model_assets
1178
+ ):
1179
+ raise InvalidInputError("FleXray outputs must be separate from each model asset")
1180
+ admitted = admit_bundle(weights_root, ensemble=ensemble)
1181
+ labels = admitted.labels
1182
+ if label_name not in labels:
1183
+ raise InvalidInputError(f"Unknown FleXray anatomy label: {label_name}")
1179
1184
  metadata = _read_json(admitted.bundles[0] / "preprocessing.json")
1180
1185
  try:
1181
1186
  preprocessing = ImagePreprocessing.from_metadata(cast(Mapping[str, object], metadata))
@@ -1221,9 +1226,6 @@ def run(
1221
1226
  mask_path = output / MASK_NAME
1222
1227
  probabilities_path = output / PROBABILITIES_NAME
1223
1228
  prediction_path = output / PREDICTION_NAME
1224
- source.save(display_path)
1225
- mask.save(mask_path)
1226
- np.save(probabilities_path, probabilities, allow_pickle=False)
1227
1229
  members = [bundle.name for bundle in admitted.bundles]
1228
1230
  record = {
1229
1231
  "schema_version": PREDICTION_SCHEMA,
@@ -1244,7 +1246,19 @@ def run(
1244
1246
  "probability_mode": "multilabel",
1245
1247
  "overlay_is_source_grid": True,
1246
1248
  }
1247
- prediction_path.write_text(json.dumps(record, indent=2) + "\n", encoding="utf-8")
1249
+ # Write beside the targets and rename once all four exist, so a failed run keeps
1250
+ # earlier outputs. The temporary names keep the suffixes the writers read.
1251
+ partial = {name: output / f".{os.getpid()}.{name}" for name in names}
1252
+ try:
1253
+ source.save(partial[DISPLAY_NAME])
1254
+ mask.save(partial[MASK_NAME])
1255
+ np.save(partial[PROBABILITIES_NAME], probabilities, allow_pickle=False)
1256
+ partial[PREDICTION_NAME].write_text(json.dumps(record, indent=2) + "\n", encoding="utf-8")
1257
+ for name, temporary in partial.items():
1258
+ os.replace(temporary, output / name)
1259
+ finally:
1260
+ for temporary in partial.values():
1261
+ temporary.unlink(missing_ok=True)
1248
1262
  return {
1249
1263
  "outputs": {
1250
1264
  "mask": mask_path.as_posix(),
@@ -1,26 +0,0 @@
1
- __pycache__/
2
- *.py[cod]
3
- .venv/
4
- *.egg-info/
5
- dist/
6
- build/
7
- .pytest_cache/
8
- .ruff_cache/
9
-
10
- # Checkpoints and converted weights are never committed.
11
- checkpoints/
12
- weights/
13
- *.safetensors
14
- *.npz
15
- !tests/fixtures/*.npz
16
- !tests/fixtures/*/*.npz
17
- *.pt
18
- *.pth
19
- *.ckpt
20
-
21
- # Imaging data is never committed.
22
- data/
23
- *.nii
24
- *.nii.gz
25
- *.dcm
26
- .DS_Store
@@ -1,67 +0,0 @@
1
- Metadata-Version: 2.5
2
- Name: flexray-mlx
3
- Version: 0.2.4
4
- Summary: Native MLX implementation of FleXray
5
- Project-URL: Homepage, https://huggingface.co/MedMLX/flexray-mlx
6
- Author: Joseph Sandoval, Alfredo Sandoval Jr.
7
- License-Expression: Apache-2.0 AND MIT AND BSD-3-Clause
8
- License-File: LICENSE
9
- License-File: THIRD_PARTY_NOTICES.md
10
- Classifier: Operating System :: MacOS :: MacOS X
11
- Requires-Python: <3.15,>=3.13
12
- Requires-Dist: medmlx-core==0.2.5
13
- Requires-Dist: mlx<1,>=0.32.4
14
- Requires-Dist: numpy<3,>=2.0
15
- Requires-Dist: pillow<14,>=13
16
- Requires-Dist: pydicom<4,>=3
17
- Requires-Dist: pyyaml<7,>=6
18
- Requires-Dist: safetensors<1,>=0.6
19
- Provides-Extra: dev
20
- Requires-Dist: pyright==1.1.414; extra == 'dev'
21
- Requires-Dist: pytest<10,>=8.4; extra == 'dev'
22
- Requires-Dist: ruff<1,>=0.13; extra == 'dev'
23
- Description-Content-Type: text/markdown
24
-
25
- # flexray-mlx
26
-
27
- Segment anatomical structures in radiographs with FleXray and native MLX.
28
-
29
- [Docs](https://github.com/MedMLX/flexray-mlx/blob/main/docs/technical.md) · [Model weights](https://huggingface.co/MedMLX/flexray-mlx) · [MedMLX](https://github.com/MedMLX)
30
-
31
- | Input | Output |
32
- | :--- | :--- |
33
- | Raster image or single-frame DICOM | Structure masks and probabilities |
34
-
35
- **Apple Silicon · Metal · Python 3.13 / 3.14** · [uv](https://docs.astral.sh/uv/)
36
-
37
- ## Install
38
-
39
- ```bash
40
- uv venv --python 3.13
41
- source .venv/bin/activate
42
- uv pip install "flexray-mlx>=0.2.3"
43
- ```
44
-
45
- ## Run
46
-
47
- ```python
48
- from flexray_mlx.medmlx import run
49
-
50
- result = run(image_path="chest.png", output_dir="out")
51
- print(result["outputs"]["mask"])
52
- ```
53
-
54
- Omitting `weights_path` downloads `MedMLX/flexray-mlx` once and reuses its local cache.
55
- An explicit `weights_path` selects your own model folder, containing `ensemble.json`
56
- and `members/flux0375/{config.yml,label_schema.json,model.safetensors,preprocessing.json}`.
57
- Use `label_name` to select a structure. Automatic setup prepares the flagship
58
- (`ensemble=False`); `ensemble=True` requires all five members in an explicit folder.
59
-
60
- Downloaded commits are returned in `details.weights_revision`; explicit local
61
- weights report `null` unless the folder carries a MedMLX download revision.
62
-
63
- ## License
64
-
65
- [Apache-2.0](https://github.com/MedMLX/flexray-mlx/blob/main/LICENSE). See [third-party notices](https://github.com/MedMLX/flexray-mlx/blob/main/THIRD_PARTY_NOTICES.md). Model weights retain their publisher terms. FleXray weights are noncommercial (CC-BY-NC-4.0).
66
-
67
- For research and education. Outputs require human review.
@@ -1,43 +0,0 @@
1
- # flexray-mlx
2
-
3
- Segment anatomical structures in radiographs with FleXray and native MLX.
4
-
5
- [Docs](https://github.com/MedMLX/flexray-mlx/blob/main/docs/technical.md) · [Model weights](https://huggingface.co/MedMLX/flexray-mlx) · [MedMLX](https://github.com/MedMLX)
6
-
7
- | Input | Output |
8
- | :--- | :--- |
9
- | Raster image or single-frame DICOM | Structure masks and probabilities |
10
-
11
- **Apple Silicon · Metal · Python 3.13 / 3.14** · [uv](https://docs.astral.sh/uv/)
12
-
13
- ## Install
14
-
15
- ```bash
16
- uv venv --python 3.13
17
- source .venv/bin/activate
18
- uv pip install "flexray-mlx>=0.2.3"
19
- ```
20
-
21
- ## Run
22
-
23
- ```python
24
- from flexray_mlx.medmlx import run
25
-
26
- result = run(image_path="chest.png", output_dir="out")
27
- print(result["outputs"]["mask"])
28
- ```
29
-
30
- Omitting `weights_path` downloads `MedMLX/flexray-mlx` once and reuses its local cache.
31
- An explicit `weights_path` selects your own model folder, containing `ensemble.json`
32
- and `members/flux0375/{config.yml,label_schema.json,model.safetensors,preprocessing.json}`.
33
- Use `label_name` to select a structure. Automatic setup prepares the flagship
34
- (`ensemble=False`); `ensemble=True` requires all five members in an explicit folder.
35
-
36
- Downloaded commits are returned in `details.weights_revision`; explicit local
37
- weights report `null` unless the folder carries a MedMLX download revision.
38
-
39
- ## License
40
-
41
- [Apache-2.0](https://github.com/MedMLX/flexray-mlx/blob/main/LICENSE). See [third-party notices](https://github.com/MedMLX/flexray-mlx/blob/main/THIRD_PARTY_NOTICES.md). Model weights retain their publisher terms. FleXray weights are noncommercial (CC-BY-NC-4.0).
42
-
43
- For research and education. Outputs require human review.
File without changes