mammofm 0.1.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.
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,80 @@
1
+ Custom Academic License for Model Weights
2
+ (Based on CC BY-NC 4.0)
3
+
4
+ 1. Overview
5
+ This license governs the use of the accompanying model weights, code, and associated materials (“Model”).
6
+ This license is based on the Creative Commons Attribution-NonCommercial 4.0 International License, with additional restrictions specific to machine learning models.
7
+ By accessing, downloading, or using the Model, you agree to the terms below.
8
+ 2. Permitted Use
9
+ The Model may be used solely for non-commercial academic research purposes.
10
+
11
+ Permitted users include:
12
+ - Academic institutions
13
+ - Non-profit research organizations
14
+ Allowed activities:
15
+ - Research use
16
+ - Evaluation and benchmarking
17
+ - Fine-tuning or linear probing for academic research only
18
+
19
+ 3. Prohibited Use
20
+ The following uses are strictly prohibited:
21
+
22
+ 3.1 Commercial Use
23
+ - Any commercial use
24
+ - Any use by for-profit entities without prior written approval
25
+ - Use in products, services, or revenue-generating activities
26
+
27
+ 3.2 Industry Research Without Approval
28
+ - Any use by industry, including internal research, evaluation, or development, without explicit prior written permission
29
+
30
+ 3.3 Clinical and Medical Use
31
+ - Any clinical deployment
32
+ - Any diagnostic or treatment use
33
+ - Any use in medical decision-making systems
34
+
35
+ 4. Restrictions on Model Use
36
+
37
+ 4.1 Redistribution
38
+ - Redistribution of the Model weights, in whole or in part, is not permitted
39
+
40
+ 4.2 Hosting and Serving
41
+ - Hosting, serving, or making the Model available through an API, SaaS platform, web service, or other remote access mechanism is not permitted
42
+
43
+ 4.3 Distillation and Model Extraction
44
+ - Distillation, compression, extraction, imitation, or transfer of knowledge from the Model to create, train, initialize, or improve another model is not permitted
45
+
46
+ 5. Derivative Works
47
+ Derivative models are allowed only under the following conditions:
48
+ - They must be used solely for non-commercial academic research
49
+ - They must not be shared publicly or redistributed
50
+ - They must inherit this same license in full
51
+ - They must not be used to circumvent restrictions in this license
52
+
53
+ 6. Attribution
54
+ Any use of the Model must include:
55
+ - Proper citation of the associated publication(s)
56
+ - Acknowledgment of the original authors and institution(s)
57
+ Example acknowledgment:
58
+ “This work uses [MODEL NAME] developed by [AUTHORS], [INSTITUTION].”
59
+ 7. Access Control
60
+ The Licensor reserves the right to:
61
+ - Restrict access to the Model
62
+ - Require user registration or approval
63
+ - Revoke access in case of misuse or violation of this license
64
+
65
+ 8. No Warranty
66
+ The Model is provided “as is”, without warranty of any kind, express or implied, including but not limited to warranties of merchantability, fitness for a particular purpose, or non-infringement.
67
+ The authors and licensors make no guarantees regarding performance, safety, legality, or correctness.
68
+
69
+ 9. Limitation of Liability
70
+ In no event shall the authors, licensors, or affiliated institutions be liable for any claim, damages, or other liability arising from, out of, or in connection with the Model or its use or misuse.
71
+
72
+ 10. Termination
73
+ Any violation of this license results in immediate termination of all rights granted under this license.
74
+ Upon termination, the user must cease all use of the Model and destroy all copies in their possession or control.
75
+
76
+ 11. Contact for Permissions
77
+ For commercial use, industry research, or other exceptions, contact:
78
+ contact:
79
+ Kayhan Batmanghelich
80
+ email: batman@bu.edu
@@ -0,0 +1,17 @@
1
+ include pyproject.toml LICENSE.txt LICENSE_WEIGHTS.txt
2
+ include docs/python-package.md
3
+ exclude README.md
4
+ recursive-include src/mammofm *.py *.json LICENSE* NOTICE*
5
+ prune src/codebase
6
+ prune src/preprocessing
7
+ prune src/scripts
8
+ prune src/nltk_data
9
+ prune src/zs_prompts
10
+ prune Test
11
+ prune tests
12
+ prune doc
13
+ prune .git
14
+ prune .idea
15
+ prune .codex
16
+ prune .claude
17
+ global-exclude *.pyc *.pyo .DS_Store .env *.pth *.pt *.tar *.zip *.dcm *.dicom *.png
mammofm-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,312 @@
1
+ Metadata-Version: 2.4
2
+ Name: mammofm
3
+ Version: 0.1.0
4
+ Summary: Research-only mammography diagnosis and image features with Mammo-FM
5
+ Author: Batman Lab
6
+ Project-URL: Homepage, https://github.com/batmanlab/Mammo-FM
7
+ Project-URL: Documentation, https://github.com/batmanlab/Mammo-FM/blob/main/docs/python-package.md
8
+ Project-URL: Checkpoints, https://huggingface.co/batmanLab/Mammo-FM
9
+ Keywords: mammography,Mammo-FM,medical-imaging,research
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Intended Audience :: Science/Research
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.10
14
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
15
+ Requires-Python: >=3.10
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE.txt
18
+ License-File: LICENSE_WEIGHTS.txt
19
+ License-File: src/mammofm/_vendor/LICENSE-EFFICIENTNET.txt
20
+ Requires-Dist: torch<3,>=2.6
21
+ Requires-Dist: numpy<3,>=1.24
22
+ Requires-Dist: Pillow<13,>=9
23
+ Requires-Dist: opencv-python-headless<5,>=4.8
24
+ Requires-Dist: pydicom<4,>=2.4
25
+ Requires-Dist: huggingface-hub<1,>=0.27
26
+ Requires-Dist: transformers<5,>=4.48
27
+ Requires-Dist: safetensors>=0.4
28
+ Provides-Extra: dicom
29
+ Requires-Dist: pylibjpeg<3,>=2; extra == "dicom"
30
+ Requires-Dist: pylibjpeg-libjpeg<3,>=2; extra == "dicom"
31
+ Requires-Dist: pylibjpeg-openjpeg<3,>=2; extra == "dicom"
32
+ Provides-Extra: dev
33
+ Requires-Dist: build>=1.2; extra == "dev"
34
+ Requires-Dist: twine>=6; extra == "dev"
35
+ Dynamic: license-file
36
+
37
+ # mammofm Python package
38
+
39
+ Local, single-image inference with Mammo-FM. This first package provides
40
+ `mammofm.diagnosis` and `mammofm.features`. Prognosis and report generation are
41
+ not exposed by this release; use the repository's separate workflows for now.
42
+
43
+ **Research only.** Outputs are uncalibrated model scores, not clinical diagnoses
44
+ or validated patient-level disease probabilities. Read the repository's
45
+ `LICENSE.txt` and `LICENSE_WEIGHTS.txt`; packaging does not change their terms.
46
+ Images stay on your machine. The package has no report-generation API key,
47
+ telemetry, image upload, or remote inference service.
48
+
49
+ ## Contents
50
+
51
+ - [Installation](#installation)
52
+ - [Diagnosis](#diagnosis)
53
+ - [Supported tasks and missing models](#supported-tasks-and-missing-models)
54
+ - [Image features](#image-features)
55
+ - [DICOM and PNG preprocessing](#dicom-and-png-preprocessing)
56
+ - [Checkpoints, caching, and offline use](#checkpoints-caching-and-offline-use)
57
+ - [API reference](#api-reference)
58
+ - [Testing and publishing](#testing-and-publishing)
59
+
60
+ ## Installation
61
+
62
+ Python 3.10+ and PyTorch 2.6+ are required. CPU inference is supported; a compatible
63
+ CUDA-enabled PyTorch installation is recommended for repeated inference. Install
64
+ the appropriate PyTorch build for your machine before installing this package.
65
+
66
+ From the repository root, before the first PyPI publication:
67
+
68
+ ```bash
69
+ python -m pip install .
70
+ # Include decoders for compressed mammography DICOMs:
71
+ python -m pip install '.[dicom]'
72
+ ```
73
+
74
+ The distribution name is `mammofm`. **Once the maintainer publishes it to PyPI**, users can run:
75
+
76
+ ```bash
77
+ python -m pip install 'mammofm[dicom]'
78
+ # For preprocessed PNGs and uncompressed DICOMs only:
79
+ python -m pip install mammofm
80
+ ```
81
+
82
+ These are the intended public installation commands, not a claim that a PyPI
83
+ release has already been published. No model weights or patient data are bundled
84
+ in the wheel or source distribution.
85
+
86
+ On a shared CPU host with a low process/thread limit, set these before starting
87
+ Python to bound numerical and tokenizer worker pools:
88
+
89
+ ```bash
90
+ export OMP_NUM_THREADS=2 MKL_NUM_THREADS=2 OPENBLAS_NUM_THREADS=2
91
+ export TOKENIZERS_PARALLELISM=false TORCHINDUCTOR_COMPILE_THREADS=1
92
+ ```
93
+
94
+ You can additionally set `cv2.setNumThreads(2)` in your application. The package
95
+ does not change process-wide thread settings. The latter PyTorch setting avoids
96
+ an import-time compiler worker pool in some Transformers versions even though
97
+ Mammo-FM uses eager, noncompiled inference.
98
+
99
+ ## Diagnosis
100
+
101
+ ```python
102
+ import json
103
+ import mammofm as mf
104
+
105
+ output = mf.diagnosis('/data/mammogram.dcm', 'vindr')
106
+ print(json.dumps(output, indent=2, allow_nan=False))
107
+
108
+ # A preprocessed PNG uses the same API.
109
+ output = mf.diagnosis('/data/mammogram.png', 'nlbreast')
110
+ ```
111
+
112
+ `output` is a Python dictionary that can be directly serialized to JSON. Its
113
+ top-level prediction groups are `zero_shot`, `linear_probe`, and `full_finetune`.
114
+ Each maps task names to positive-class probabilities (Python floats) or `None`
115
+ (`null` in JSON) when that specific model has not been released.
116
+
117
+ ```python
118
+ output['zero_shot']['mass']
119
+ output['linear_probe']['mass']
120
+ output['full_finetune']['mass']
121
+ output['unavailable'] # Reasons for unavailable fields; never substitute zeros.
122
+ output['metadata'] # Input processing, pinned checkpoint identities, semantics.
123
+ ```
124
+
125
+ Only binary positive-class scores are returned, not hard labels or a clinical
126
+ threshold. Classifiers use sigmoid. Zero-shot preserves the official evaluator:
127
+ normalize individual projected prompt embeddings, average within negative and
128
+ positive classes, compute cosine similarity to each mean, and apply a two-class
129
+ softmax. **The checkpoint's learned logit scale is not multiplied into these
130
+ scores**, matching the original evaluation.
131
+
132
+ To avoid unnecessary models or downloads:
133
+
134
+ ```python
135
+ output = mf.diagnosis('/data/mammogram.png', 'rsna', methods=['linear_probe'])
136
+ print(mf.availability('rsna')) # Does not load or download any weights.
137
+ ```
138
+
139
+ Missing published models produce a warning and explicit null fields. Use
140
+ `strict=True` to raise `MissingModelError` before any model download if any
141
+ requested task/method is unavailable. Download failures, invalid inputs,
142
+ checkpoint mismatches, and actual inference failures always raise errors rather
143
+ than masquerading as a missing model.
144
+
145
+ ## Supported tasks and missing models
146
+
147
+ Registry pinned to HF revision `5e07ca4c4e88cd118b0c2cfaacadddfe69f30026`:
148
+
149
+ | Dataset argument | Task key | Zero-shot | Linear probe | Full finetune |
150
+ | --- | --- | --- | --- | --- |
151
+ | `rsna` | `cancer` | Available | Available | Available |
152
+ | `rsna` | `invasive_cancer` | Not released | Not released | Not released |
153
+ | `vindr` | `abnormality` | Available, historical surrogate | Available | Available |
154
+ | `vindr` | `mass` | Available | Available | Available |
155
+ | `vindr` | `suspicious_calcification` | Available | Available | Available |
156
+ | `nlbreast` | `cancer` | Available | Available | Available |
157
+
158
+ NL-Breast aliases such as `nl_breast` and `NL-Breast` are accepted. Unknown
159
+ diagnosis datasets are rejected. RSNA cancer is **not** an invasive-cancer
160
+ substitute. CMMD and LUMINA diagnosis are deferred and rejected by this release;
161
+ only RSNA, VinDr, and NL-Breast are enabled.
162
+
163
+ VinDr abnormality means **BI-RADS 4/5 versus 1/2**, with BI-RADS 3 excluded in
164
+ evaluation. It does not mean any finding or pathology-confirmed cancer. Its
165
+ historical zero-shot surrogate uses the original `cancer` / `no cancer` prompts;
166
+ this limitation is also recorded in the output metadata.
167
+
168
+ ## Image features
169
+
170
+ ```python
171
+ import numpy as np
172
+ import mammofm as mf
173
+
174
+ output = mf.features('/data/mammogram.dcm', 'rsna')
175
+ spatial = output['before_pooling']
176
+ pooled = output['after_pooling']
177
+ print(spatial.shape) # (1, 2048, 48, 29) at the standard image size
178
+ print(pooled.shape) # (1, 2048)
179
+ np.savez('/outputs/image_features.npz', before_pooling=spatial, after_pooling=pooled)
180
+
181
+ # An unknown or omitted dataset uses general min-max DICOM preprocessing.
182
+ output = mf.features('/data/mammogram.png', 'my_dataset')
183
+ output = mf.features('/data/mammogram.dcm')
184
+ ```
185
+
186
+ The arrays are full float32 CPU NumPy arrays, retaining the batch dimension.
187
+ They are the final image-encoder spatial map and its global average-pooled
188
+ vector, **before the CLIP projection and L2 normalization**. Feature arrays are
189
+ not automatically converted to enormous JSON lists. `metadata` identifies the
190
+ checkpoint and preprocessing. Use `.tolist()` explicitly if JSON is required.
191
+
192
+ Both feature extraction and zero-shot use the requested
193
+ [`Mammo-FM_ASU_Trained_CLIP.tar`](https://huggingface.co/batmanLab/Mammo-FM/blob/5e07ca4c4e88cd118b0c2cfaacadddfe69f30026/Mammo-FM_ASU_Trained_CLIP.tar).
194
+ At this pinned revision it is byte-identical to the Batmanlab CLIP release:
195
+ SHA-256 `58ae959de52d563acc1d43f50571498eddcd4fb7ca599e706540fdd319e3599b`.
196
+ The classifier paths load their own complete released encoder+head weights;
197
+ fine-tuned encoders are not replaced with the ASU encoder.
198
+
199
+ ## DICOM and PNG preprocessing
200
+
201
+ `img` is a local path to one single-frame grayscale DICOM or an already
202
+ preprocessed 8-bit PNG. RGB PNGs are also accepted. Color/multiframe DICOMs,
203
+ 16-bit PNGs, and transparent PNGs are rejected rather than silently altered.
204
+
205
+ | Dataset | DICOM intensity route |
206
+ | --- | --- |
207
+ | RSNA, VinDr | Original CPU-style min-max scaling |
208
+ | NL-Breast | DICOM rescale + window center/width; 1st/99th-percentile fallback |
209
+ | Unknown/omitted dataset in `features` | General min-max preprocessing |
210
+
211
+ DICOMs use the unified converter's five-pixel border removal, MONOCHROME1
212
+ correction, original breast-cropping heuristic, and `INTER_AREA` resize to
213
+ 1520H x 912W. Conversion is **in memory**; no temporary PNG or DICOM metadata is
214
+ written. PNGs skip this contrast/cropping pipeline. PNG input should already
215
+ have the intended breast preprocessing; being a PNG does not establish that.
216
+
217
+ All inputs then receive the model's RGB conversion, branch-specific resize
218
+ when needed (`INTER_LINEAR`), per-image min-max normalization and
219
+ `(x - 0.3089279) / 0.25053555408335154`. Constant images are handled without NaNs.
220
+
221
+ All enabled branches use **1520H x 912W**. For arbitrary PNG sizes, this resize
222
+ is a package standardization step; the original non-CMMD loaders expected
223
+ already-preprocessed PNG dimensions and did not apply it. Image preprocessing
224
+ does not update detection boxes, perform anatomical segmentation or anonymize
225
+ burned-in text. No patient identifiers or source paths are included in results.
226
+
227
+ The shared image operations preserve the original CPU conventions, not a
228
+ guarantee of byte-identical behavior for every legacy GPU/decoder path.
229
+
230
+ ## Checkpoints, caching, and offline use
231
+
232
+ The first relevant inference downloads weights from the public
233
+ [`batmanLab/Mammo-FM`](https://huggingface.co/batmanLab/Mammo-FM) repository. The
234
+ ASU joint checkpoint is about 2.15 GB; each classifier is downloaded separately
235
+ only when requested. No HF token is required for this pinned public release.
236
+
237
+ ```python
238
+ model = mf.MammoFM(device='cuda', cache_dir='/models/huggingface')
239
+ result = model.diagnosis('/data/image.png', 'vindr')
240
+ features = model.features('/data/image.png', 'vindr')
241
+ model.clear_cache() # Release this client's model references; keep disk cache.
242
+ ```
243
+
244
+ For offline use, first download the published assets, preserving their HF
245
+ relative paths. Then use:
246
+
247
+ ```python
248
+ model = mf.MammoFM(device='cpu', model_dir='/models/Mammo-FM', local_files_only=True)
249
+ output = model.diagnosis('/data/image.png', 'nlbreast')
250
+ ```
251
+
252
+ The base checkpoint sits directly under `model_dir`; classifiers remain under
253
+ `linear_probe_mammo_FM_image_encoder/...` and `fullfinetune_mammo_FM_image_encoder/...`.
254
+ Zero-shot also requires `config.json`, `tokenizer.json`, `tokenizer_config.json`,
255
+ and `special_tokens_map.json` under `text_encoders/modernbert_mlm_5epochs/`.
256
+ It does **not** require that directory's separate MLM initialization weights:
257
+ fine-tuned text weights are already in the joint CLIP checkpoint.
258
+
259
+ `MAMMOFM_MODEL_DIR` and `MAMMOFM_CACHE_DIR` provide optional environment defaults.
260
+ Otherwise, downloads use the standard Hugging Face cache, not the codebase.
261
+ Every asset is pinned to a revision and SHA-256 checked before loading. Model
262
+ loading is strict; there is no silent random-weight or ImageNet-weight fallback.
263
+
264
+ ## API reference
265
+
266
+ ```python
267
+ mf.diagnosis(img, dataset, *, methods=None, strict=False, device=None,
268
+ cache_dir=None, model_dir=None, local_files_only=False)
269
+ mf.features(img, dataset=None, *, device=None, cache_dir=None,
270
+ model_dir=None, local_files_only=False)
271
+ mf.availability(dataset=None)
272
+ mf.clear_cache()
273
+
274
+ mf.MammoFM(*, device=None, cache_dir=None, model_dir=None,
275
+ local_files_only=False, prompt_batch_size=32)
276
+ ```
277
+
278
+ `device=None` selects CUDA when available, otherwise CPU. `methods` selects
279
+ `zero_shot`, `linear_probe`, and/or `full_finetune`. All three are requested by
280
+ default. A reusable client caches its encoder, CLIP model, prompt prototypes,
281
+ and at most two classifier models in memory. For parallel workers, construct
282
+ one client per worker; clients are not promised to be thread-safe.
283
+
284
+ ## Testing and publishing
285
+
286
+ Synthetic tests do not need private data, downloaded checkpoints or GPUs:
287
+
288
+ ```bash
289
+ python -m unittest discover -s tests/package -p 'test_*.py'
290
+ ```
291
+
292
+ Build and check release artifacts from a clean checkout:
293
+
294
+ ```bash
295
+ python -m pip install '.[dev]'
296
+ python -m build
297
+ python -m twine check dist/*
298
+ ```
299
+
300
+ Before publishing, inspect both archives: they must contain only the inference
301
+ package, public prompts, documentation, packaging metadata and license notices.
302
+ Do not include weights, images, private CSVs, test-inference artifacts, secrets,
303
+ editor/assistant files, or the original training code tree. Run an installed-wheel
304
+ smoke test outside the repository so accidental checkout imports cannot pass.
305
+
306
+ PyPI publication is a separate maintainer action requiring project ownership
307
+ and an authenticated upload or trusted-publishing configuration. Do not embed
308
+ upload tokens in the repository. Only after release review and publication:
309
+
310
+ ```bash
311
+ python -m twine upload dist/*
312
+ ```