Metadata-Version: 2.4
Name: mammofm
Version: 0.1.0
Summary: Research-only mammography diagnosis and image features with Mammo-FM
Author: Batman Lab
Project-URL: Homepage, https://github.com/batmanlab/Mammo-FM
Project-URL: Documentation, https://github.com/batmanlab/Mammo-FM/blob/main/docs/python-package.md
Project-URL: Checkpoints, https://huggingface.co/batmanLab/Mammo-FM
Keywords: mammography,Mammo-FM,medical-imaging,research
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Science/Research
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE.txt
License-File: LICENSE_WEIGHTS.txt
License-File: src/mammofm/_vendor/LICENSE-EFFICIENTNET.txt
Requires-Dist: torch<3,>=2.6
Requires-Dist: numpy<3,>=1.24
Requires-Dist: Pillow<13,>=9
Requires-Dist: opencv-python-headless<5,>=4.8
Requires-Dist: pydicom<4,>=2.4
Requires-Dist: huggingface-hub<1,>=0.27
Requires-Dist: transformers<5,>=4.48
Requires-Dist: safetensors>=0.4
Provides-Extra: dicom
Requires-Dist: pylibjpeg<3,>=2; extra == "dicom"
Requires-Dist: pylibjpeg-libjpeg<3,>=2; extra == "dicom"
Requires-Dist: pylibjpeg-openjpeg<3,>=2; extra == "dicom"
Provides-Extra: dev
Requires-Dist: build>=1.2; extra == "dev"
Requires-Dist: twine>=6; extra == "dev"
Dynamic: license-file

# mammofm Python package

Local, single-image inference with Mammo-FM. This first package provides
`mammofm.diagnosis` and `mammofm.features`. Prognosis and report generation are
not exposed by this release; use the repository's separate workflows for now.

**Research only.** Outputs are uncalibrated model scores, not clinical diagnoses
or validated patient-level disease probabilities. Read the repository's
`LICENSE.txt` and `LICENSE_WEIGHTS.txt`; packaging does not change their terms.
Images stay on your machine. The package has no report-generation API key,
telemetry, image upload, or remote inference service.

## Contents

- [Installation](#installation)
- [Diagnosis](#diagnosis)
- [Supported tasks and missing models](#supported-tasks-and-missing-models)
- [Image features](#image-features)
- [DICOM and PNG preprocessing](#dicom-and-png-preprocessing)
- [Checkpoints, caching, and offline use](#checkpoints-caching-and-offline-use)
- [API reference](#api-reference)
- [Testing and publishing](#testing-and-publishing)

## Installation

Python 3.10+ and PyTorch 2.6+ are required. CPU inference is supported; a compatible
CUDA-enabled PyTorch installation is recommended for repeated inference. Install
the appropriate PyTorch build for your machine before installing this package.

From the repository root, before the first PyPI publication:

```bash
python -m pip install .
# Include decoders for compressed mammography DICOMs:
python -m pip install '.[dicom]'
```

The distribution name is `mammofm`. **Once the maintainer publishes it to PyPI**, users can run:

```bash
python -m pip install 'mammofm[dicom]'
# For preprocessed PNGs and uncompressed DICOMs only:
python -m pip install mammofm
```

These are the intended public installation commands, not a claim that a PyPI
release has already been published. No model weights or patient data are bundled
in the wheel or source distribution.

On a shared CPU host with a low process/thread limit, set these before starting
Python to bound numerical and tokenizer worker pools:

```bash
export OMP_NUM_THREADS=2 MKL_NUM_THREADS=2 OPENBLAS_NUM_THREADS=2
export TOKENIZERS_PARALLELISM=false TORCHINDUCTOR_COMPILE_THREADS=1
```

You can additionally set `cv2.setNumThreads(2)` in your application. The package
does not change process-wide thread settings. The latter PyTorch setting avoids
an import-time compiler worker pool in some Transformers versions even though
Mammo-FM uses eager, noncompiled inference.

## Diagnosis

```python
import json
import mammofm as mf

output = mf.diagnosis('/data/mammogram.dcm', 'vindr')
print(json.dumps(output, indent=2, allow_nan=False))

# A preprocessed PNG uses the same API.
output = mf.diagnosis('/data/mammogram.png', 'nlbreast')
```

`output` is a Python dictionary that can be directly serialized to JSON. Its
top-level prediction groups are `zero_shot`, `linear_probe`, and `full_finetune`.
Each maps task names to positive-class probabilities (Python floats) or `None`
(`null` in JSON) when that specific model has not been released.

```python
output['zero_shot']['mass']
output['linear_probe']['mass']
output['full_finetune']['mass']
output['unavailable']  # Reasons for unavailable fields; never substitute zeros.
output['metadata']     # Input processing, pinned checkpoint identities, semantics.
```

Only binary positive-class scores are returned, not hard labels or a clinical
threshold. Classifiers use sigmoid. Zero-shot preserves the official evaluator:
normalize individual projected prompt embeddings, average within negative and
positive classes, compute cosine similarity to each mean, and apply a two-class
softmax. **The checkpoint's learned logit scale is not multiplied into these
scores**, matching the original evaluation.

To avoid unnecessary models or downloads:

```python
output = mf.diagnosis('/data/mammogram.png', 'rsna', methods=['linear_probe'])
print(mf.availability('rsna'))  # Does not load or download any weights.
```

Missing published models produce a warning and explicit null fields. Use
`strict=True` to raise `MissingModelError` before any model download if any
requested task/method is unavailable. Download failures, invalid inputs,
checkpoint mismatches, and actual inference failures always raise errors rather
than masquerading as a missing model.

## Supported tasks and missing models

Registry pinned to HF revision `5e07ca4c4e88cd118b0c2cfaacadddfe69f30026`:

| Dataset argument | Task key | Zero-shot | Linear probe | Full finetune |
| --- | --- | --- | --- | --- |
| `rsna` | `cancer` | Available | Available | Available |
| `rsna` | `invasive_cancer` | Not released | Not released | Not released |
| `vindr` | `abnormality` | Available, historical surrogate | Available | Available |
| `vindr` | `mass` | Available | Available | Available |
| `vindr` | `suspicious_calcification` | Available | Available | Available |
| `nlbreast` | `cancer` | Available | Available | Available |

NL-Breast aliases such as `nl_breast` and `NL-Breast` are accepted. Unknown
diagnosis datasets are rejected. RSNA cancer is **not** an invasive-cancer
substitute. CMMD and LUMINA diagnosis are deferred and rejected by this release;
only RSNA, VinDr, and NL-Breast are enabled.

VinDr abnormality means **BI-RADS 4/5 versus 1/2**, with BI-RADS 3 excluded in
evaluation. It does not mean any finding or pathology-confirmed cancer. Its
historical zero-shot surrogate uses the original `cancer` / `no cancer` prompts;
this limitation is also recorded in the output metadata.

## Image features

```python
import numpy as np
import mammofm as mf

output = mf.features('/data/mammogram.dcm', 'rsna')
spatial = output['before_pooling']
pooled = output['after_pooling']
print(spatial.shape)  # (1, 2048, 48, 29) at the standard image size
print(pooled.shape)   # (1, 2048)
np.savez('/outputs/image_features.npz', before_pooling=spatial, after_pooling=pooled)

# An unknown or omitted dataset uses general min-max DICOM preprocessing.
output = mf.features('/data/mammogram.png', 'my_dataset')
output = mf.features('/data/mammogram.dcm')
```

The arrays are full float32 CPU NumPy arrays, retaining the batch dimension.
They are the final image-encoder spatial map and its global average-pooled
vector, **before the CLIP projection and L2 normalization**. Feature arrays are
not automatically converted to enormous JSON lists. `metadata` identifies the
checkpoint and preprocessing. Use `.tolist()` explicitly if JSON is required.

Both feature extraction and zero-shot use the requested
[`Mammo-FM_ASU_Trained_CLIP.tar`](https://huggingface.co/batmanLab/Mammo-FM/blob/5e07ca4c4e88cd118b0c2cfaacadddfe69f30026/Mammo-FM_ASU_Trained_CLIP.tar).
At this pinned revision it is byte-identical to the Batmanlab CLIP release:
SHA-256 `58ae959de52d563acc1d43f50571498eddcd4fb7ca599e706540fdd319e3599b`.
The classifier paths load their own complete released encoder+head weights;
fine-tuned encoders are not replaced with the ASU encoder.

## DICOM and PNG preprocessing

`img` is a local path to one single-frame grayscale DICOM or an already
preprocessed 8-bit PNG. RGB PNGs are also accepted. Color/multiframe DICOMs,
16-bit PNGs, and transparent PNGs are rejected rather than silently altered.

| Dataset | DICOM intensity route |
| --- | --- |
| RSNA, VinDr | Original CPU-style min-max scaling |
| NL-Breast | DICOM rescale + window center/width; 1st/99th-percentile fallback |
| Unknown/omitted dataset in `features` | General min-max preprocessing |

DICOMs use the unified converter's five-pixel border removal, MONOCHROME1
correction, original breast-cropping heuristic, and `INTER_AREA` resize to
1520H x 912W. Conversion is **in memory**; no temporary PNG or DICOM metadata is
written. PNGs skip this contrast/cropping pipeline. PNG input should already
have the intended breast preprocessing; being a PNG does not establish that.

All inputs then receive the model's RGB conversion, branch-specific resize
when needed (`INTER_LINEAR`), per-image min-max normalization and
`(x - 0.3089279) / 0.25053555408335154`. Constant images are handled without NaNs.

All enabled branches use **1520H x 912W**. For arbitrary PNG sizes, this resize
is a package standardization step; the original non-CMMD loaders expected
already-preprocessed PNG dimensions and did not apply it. Image preprocessing
does not update detection boxes, perform anatomical segmentation or anonymize
burned-in text. No patient identifiers or source paths are included in results.

The shared image operations preserve the original CPU conventions, not a
guarantee of byte-identical behavior for every legacy GPU/decoder path.

## Checkpoints, caching, and offline use

The first relevant inference downloads weights from the public
[`batmanLab/Mammo-FM`](https://huggingface.co/batmanLab/Mammo-FM) repository. The
ASU joint checkpoint is about 2.15 GB; each classifier is downloaded separately
only when requested. No HF token is required for this pinned public release.

```python
model = mf.MammoFM(device='cuda', cache_dir='/models/huggingface')
result = model.diagnosis('/data/image.png', 'vindr')
features = model.features('/data/image.png', 'vindr')
model.clear_cache()  # Release this client's model references; keep disk cache.
```

For offline use, first download the published assets, preserving their HF
relative paths. Then use:

```python
model = mf.MammoFM(device='cpu', model_dir='/models/Mammo-FM', local_files_only=True)
output = model.diagnosis('/data/image.png', 'nlbreast')
```

The base checkpoint sits directly under `model_dir`; classifiers remain under
`linear_probe_mammo_FM_image_encoder/...` and `fullfinetune_mammo_FM_image_encoder/...`.
Zero-shot also requires `config.json`, `tokenizer.json`, `tokenizer_config.json`,
and `special_tokens_map.json` under `text_encoders/modernbert_mlm_5epochs/`.
It does **not** require that directory's separate MLM initialization weights:
fine-tuned text weights are already in the joint CLIP checkpoint.

`MAMMOFM_MODEL_DIR` and `MAMMOFM_CACHE_DIR` provide optional environment defaults.
Otherwise, downloads use the standard Hugging Face cache, not the codebase.
Every asset is pinned to a revision and SHA-256 checked before loading. Model
loading is strict; there is no silent random-weight or ImageNet-weight fallback.

## API reference

```python
mf.diagnosis(img, dataset, *, methods=None, strict=False, device=None,
             cache_dir=None, model_dir=None, local_files_only=False)
mf.features(img, dataset=None, *, device=None, cache_dir=None,
            model_dir=None, local_files_only=False)
mf.availability(dataset=None)
mf.clear_cache()

mf.MammoFM(*, device=None, cache_dir=None, model_dir=None,
           local_files_only=False, prompt_batch_size=32)
```

`device=None` selects CUDA when available, otherwise CPU. `methods` selects
`zero_shot`, `linear_probe`, and/or `full_finetune`. All three are requested by
default. A reusable client caches its encoder, CLIP model, prompt prototypes,
and at most two classifier models in memory. For parallel workers, construct
one client per worker; clients are not promised to be thread-safe.

## Testing and publishing

Synthetic tests do not need private data, downloaded checkpoints or GPUs:

```bash
python -m unittest discover -s tests/package -p 'test_*.py'
```

Build and check release artifacts from a clean checkout:

```bash
python -m pip install '.[dev]'
python -m build
python -m twine check dist/*
```

Before publishing, inspect both archives: they must contain only the inference
package, public prompts, documentation, packaging metadata and license notices.
Do not include weights, images, private CSVs, test-inference artifacts, secrets,
editor/assistant files, or the original training code tree. Run an installed-wheel
smoke test outside the repository so accidental checkout imports cannot pass.

PyPI publication is a separate maintainer action requiring project ownership
and an authenticated upload or trusted-publishing configuration. Do not embed
upload tokens in the repository. Only after release review and publication:

```bash
python -m twine upload dist/*
```
