Metadata-Version: 2.5
Name: flexible-unet-mlx
Version: 0.3.0
Summary: Segment surgical tools in RGB endoscopy frames with FlexibleUNet and native MLX
Project-URL: Homepage, https://medmlx.org
Project-URL: Documentation, https://github.com/MedMLX/flexible-unet-mlx/blob/v0.3.0/README.md
Project-URL: Repository, https://github.com/MedMLX/flexible-unet-mlx
Project-URL: Issues, https://github.com/MedMLX/flexible-unet-mlx/issues
Project-URL: Weights, https://huggingface.co/MedMLX/flexible-unet-effnetb2-mlx
Project-URL: MedMLX, https://github.com/MedMLX/medmlx
Author: Joseph Sandoval, Alfredo Sandoval Jr.
License-Expression: Apache-2.0
License-File: LICENSE
License-File: THIRD_PARTY_NOTICES.md
Keywords: apple-silicon,endoscopy,medical-imaging,metal,mlx,monai,segmentation,surgical-tools
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: Operating System :: MacOS :: MacOS X
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Scientific/Engineering :: Image Processing
Classifier: Topic :: Scientific/Engineering :: Medical Science Apps.
Requires-Python: <3.14,>=3.13
Requires-Dist: medmlx-core<0.4,>=0.3
Requires-Dist: mlx==0.32.4; platform_system == 'Darwin' and platform_machine == 'arm64'
Requires-Dist: numpy<3,>=2.0
Requires-Dist: pillow<14,>=13
Provides-Extra: dev
Requires-Dist: pyright==1.1.414; extra == 'dev'
Requires-Dist: pytest<10,>=8.4; extra == 'dev'
Requires-Dist: ruff<1,>=0.13; extra == 'dev'
Requires-Dist: safetensors<1,>=0.6; extra == 'dev'
Requires-Dist: torch<2.14,>=2.13; extra == 'dev'
Description-Content-Type: text/markdown

<div align="center">

# flexible-unet-mlx

Segment surgical tools in RGB endoscopy frames with FlexibleUNet and native MLX.

[![PyPI](https://img.shields.io/pypi/v/flexible-unet-mlx)](https://pypi.org/project/flexible-unet-mlx/)
[![Python](https://img.shields.io/pypi/pyversions/flexible-unet-mlx)](https://pypi.org/project/flexible-unet-mlx/)
[![License](https://img.shields.io/badge/License-Apache_2.0-blue)](https://github.com/MedMLX/flexible-unet-mlx/blob/v0.3.0/LICENSE)
[![Apple Silicon](https://img.shields.io/badge/Apple_Silicon-MLX-black?logo=apple)](https://github.com/ml-explore/mlx)
[![Hugging Face](https://img.shields.io/badge/%F0%9F%A4%97_Hugging_Face-weights-yellow)](https://huggingface.co/MedMLX/flexible-unet-effnetb2-mlx)
[![MedMLX](https://img.shields.io/badge/MedMLX-runtime-A51C30)](https://github.com/MedMLX/medmlx)

<img src="https://raw.githubusercontent.com/MedMLX/flexible-unet-mlx/main/docs/example.jpg" alt="Endoscopy frame and the predicted surgical instrument mask with the reference outline" width="100%">

<sub>Frame and reference outline from [Kvasir-Instrument](https://datasets.simula.no/kvasir-instrument/), for research and education.</sub>

</div>

| Input | Output |
| :--- | :--- |
| RGB image | Tool mask at the original size |

| Model | Weights download | Peak MLX memory | Measured on |
| :--- | ---: | ---: | :--- |
| `flexible-unet` | 46 MB | 0.27 GB | 768×576 endoscopy frame |

## Install

```bash
uv venv --python 3.13
source .venv/bin/activate
uv pip install "flexible-unet-mlx>=0.3.0"
```

## Run

```python
from flexible_unet_mlx import run

result = run(image_path="frame.jpg", output_dir="out")
print(result["outputs"]["mask"])
```

Weights download from `MedMLX/flexible-unet-effnetb2-mlx` on first use; `medmlx setup flexible-unet`
downloads them ahead of time. For local weights, pass the folder containing
`flexibleunet.safetensors` as `weights_path`.

To segment a sequence of frames with one loaded network, use `load_model`. Each
`model.run` call takes the same image, output and overwrite arguments as `run`:

```python
from flexible_unet_mlx import load_model

with load_model() as model:
    for frame in ["frame1", "frame2"]:
        model.run(image_path=f"{frame}.jpg", output_dir=f"out/{frame}")
```

### Inputs and outputs

| Argument | Meaning |
| --- | --- |
| `image_path` | One RGB image Pillow can read; the bundle used JPEG |
| `output_dir` | Directory for `mask.png`, created if missing |
| `weights_path` | Optional folder containing `flexibleunet.safetensors` |
| `overwrite` | `False` by default; an existing mask is replaced only when `True` |

This 2D model reads images, not NIfTI volumes.

- **Mask:** `out/mask.png`, an 8-bit grayscale mask at the original frame size: 255
  for tools and 0 for background.
- **Return value:** `{"outputs": {"mask": path}, "artifacts": {"mask": ...}, "details": {...}}`:
  the `mask` artifact names the labels and the frame grid it is on, and `details` holds run
  metadata.

| Error | Raised when |
| :--- | :--- |
| `InvalidInputError` | A frame is invalid |
| `AssetNotReadyError` | Weights are missing or mismatched |
| `ModelExecutionError` | Inference fails |
| `MissingDependencyError` | The native runtime is missing |

### Python API

```python
from pathlib import Path

import numpy as np
from flexible_unet_mlx import forward_patch, load_network

network = load_network(Path("flexibleunet.safetensors"))
logits = forward_patch(network, np.zeros((1, 3, 736, 480), dtype=np.float32))
```

- `forward_patch` takes finite float32 `(B, 3, 736, 480)` frames, whose spatial axes are
  width and height as the bundle's reader returns them, and returns raw
  `(B, 2, 736, 480)` logits; channel 1 is the tool class.
- Preprocessing and postprocessing are the caller's. `FlexibleUNet(weights, mx=mx)` runs
  on MLX arrays directly.
- `load_network` checks names, shapes, dtypes and finite values.
- Inference requires Apple Silicon with Metal.

## Use with MedMLX

Use the [MedMLX MCP server](https://github.com/MedMLX/medmlx/blob/main/docs/mcp.md) to run `flexible-unet` from an MCP client. Weights download on first use.

```sh
uv tool install --python 3.13 "medmlx[segment,mcp]"
MEDMLX="$(uv tool dir --bin --color never)/medmlx"
mkdir -p "$HOME/medmlx-work"
claude mcp add --scope user medmlx -- "$MEDMLX" serve --root "$HOME/medmlx-work"
```

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 flexible-unet`.

> **For AI agents:** prefer the MedMLX MCP tools (`list_models`, `describe_model`, `model_readiness`, `run_model`, `get_job`) over writing Python against this package.

## License

[Apache-2.0](https://github.com/MedMLX/flexible-unet-mlx/blob/v0.3.0/LICENSE). See [third-party notices](https://github.com/MedMLX/flexible-unet-mlx/blob/v0.3.0/THIRD_PARTY_NOTICES.md). Model weights retain their publisher terms.
