hasagi 0.1.0b1__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.
hasagi-0.1.0b1/LICENSE ADDED
@@ -0,0 +1,50 @@
1
+ HASAGI Noncommercial License
2
+
3
+ Scope
4
+
5
+ This license applies to the HASAGI Python code, its documentation and
6
+ tests, and the two bundled ONNX models, layers_fp32.onnx and
7
+ discernibility_fp32.onnx, including their HASAGI-trained parameters.
8
+ Together these are the "Materials."
9
+
10
+ Noncommercial research and teaching
11
+
12
+ The HASAGI rights holders permit you to download, install, run, study,
13
+ and adapt the Materials, free of charge, solely for noncommercial
14
+ research or teaching. You may make working copies and fine-tune the
15
+ models for those purposes. You may publish research findings and share
16
+ a link to an authorized HASAGI download. Supplying copies of the
17
+ Materials alongside those findings requires the permission described
18
+ below.
19
+
20
+ Commercial use and redistribution
21
+
22
+ Obtain prior written authorization from the applicable HASAGI rights
23
+ holders or their authorized representative before either of the following:
24
+
25
+ 1. Using the Materials for a commercial purpose, including incorporating
26
+ them into a commercial product or operating a paid inference service.
27
+ 2. Redistributing any of the Materials to another person or organization,
28
+ in original or modified form, for any purpose, with or without a fee.
29
+ This includes sending a model to a collaborator, mirroring a package,
30
+ or distributing fine-tuned weights. The same rule applies to research
31
+ and classroom distribution.
32
+
33
+ With any authorized redistribution, retain this license, the accompanying
34
+ THIRD_PARTY_NOTICES, and applicable attribution notices. Identify any
35
+ changes you have made.
36
+
37
+ Third-party rights
38
+
39
+ Each HASAGI rights holder grants permission only for rights they control.
40
+ Third-party material remains subject to its own terms. In particular,
41
+ the upstream Apache License, Version 2.0, and its notices are reproduced
42
+ in THIRD_PARTY_NOTICES. Rights granted directly under those terms remain
43
+ available to recipients.
44
+
45
+ Warranty and liability
46
+
47
+ The Materials are supplied as is. To the extent permitted by applicable
48
+ law, the rights holders disclaim warranties, including merchantability,
49
+ fitness for a particular purpose, and noninfringement, and disclaim
50
+ liability for damages arising from use of the Materials.
@@ -0,0 +1,3 @@
1
+ exclude README.md
2
+ exclude tests/test_*.py
3
+ include tests/test_hasagi_predictor.py
@@ -0,0 +1,105 @@
1
+ Metadata-Version: 2.4
2
+ Name: hasagi
3
+ Version: 0.1.0b1
4
+ Summary: CPU inference for corneal IVCM tissue layers and nerve discernibility
5
+ License-Expression: LicenseRef-HASAGI-Noncommercial AND Apache-2.0
6
+ Requires-Python: >=3.10
7
+ Description-Content-Type: text/markdown
8
+ License-File: LICENSE
9
+ License-File: THIRD_PARTY_NOTICES
10
+ Requires-Dist: numpy
11
+ Requires-Dist: onnxruntime
12
+ Requires-Dist: Pillow>=9.1
13
+ Dynamic: license-file
14
+
15
+ # HASAGI
16
+
17
+ HASAGI identifies tissue layers and grades nerve discernibility in single-frame corneal in vivo confocal microscopy (IVCM) images. Both ONNX models run offline on the CPU.
18
+
19
+ ## License
20
+
21
+ The HASAGI Noncommercial License permits use and adaptation of the Python
22
+ code and both ONNX models for noncommercial research or teaching. Commercial
23
+ use and any redistribution, including sharing copies for free with collaborators
24
+ or students, require prior written authorization from the applicable HASAGI
25
+ rights holders or their authorized representative. You may share a link to an
26
+ authorized download. See `LICENSE` for the full terms and `THIRD_PARTY_NOTICES`
27
+ for upstream licenses and attribution.
28
+
29
+ ## Installation
30
+
31
+ Requires Python 3.10 or later.
32
+
33
+ ```bash
34
+ # From the source directory
35
+ python -m pip install .
36
+ ```
37
+
38
+ Once the beta is available on PyPI, install it with `python -m pip install hasagi==0.1.0b1`.
39
+
40
+ ## Usage
41
+
42
+ Create one predictor and reuse it across images. The constructor loads both models. The optional `num_threads` argument sets the number of CPU threads available to each ONNX session for computing an operator (default 4).
43
+
44
+ ```python
45
+ from PIL import Image
46
+ from hasagi import HASAGIPredictor
47
+
48
+ predictor = HASAGIPredictor(num_threads=4)
49
+ with Image.open("frame.png") as image:
50
+ result = predictor.predict(image, resize_mode="resize")
51
+
52
+ print(result.labels, result.grade, result.score)
53
+ ```
54
+
55
+ For a 384 × 384 frame, either task can also run on its own.
56
+
57
+ ```python
58
+ with Image.open("frame.png") as image:
59
+ layers = predictor.predict(image, predict_score=False)
60
+ score = predictor.predict(image, predict_layers=False)
61
+ ```
62
+
63
+ ## Batch inference
64
+
65
+ `predict_batch()` accepts a list, tuple, or generator of images. Each enabled model runs once per batch. The final batch can be smaller. To process a directory one batch at a time, reuse the predictor above.
66
+
67
+ ```python
68
+ from pathlib import Path
69
+
70
+ def read_images(paths):
71
+ for path in paths:
72
+ with Image.open(path) as image:
73
+ yield image
74
+
75
+ paths = sorted(Path("frames").glob("*.png"))
76
+ results = predictor.predict_batch(read_images(paths), batch_size=8, resize_mode="resize")
77
+ for path, result in zip(paths, results):
78
+ print(path.name, result.labels, result.grade, result.score)
79
+ ```
80
+
81
+ ## Prediction parameters
82
+
83
+ | Parameter | Default | Behavior |
84
+ | --- | --- | --- |
85
+ | `image` / `images` | Required | Pass one PIL image or NumPy array to `predict()`, or an iterable of images to `predict_batch()`. |
86
+ | `batch_size` | `8` | Maximum images per model call in `predict_batch()`. Larger batches use more memory. |
87
+ | `predict_layers` | `True` | Identify all matching layers. |
88
+ | `predict_score` | `True` | Grade nerve discernibility regardless of the predicted layers. |
89
+ | `resize_mode` | `"crop"` | `"crop"` takes the top-left 384 × 384 pixels and requires both dimensions to be at least 384. `"resize"` scales the whole image to 384 × 384 using bilinear interpolation. |
90
+
91
+ Pass options by keyword. Both `num_threads` and `batch_size` must be positive integers. Disabling both tasks raises `ValueError`. For an invalid image, the batch error identifies its zero-based index.
92
+
93
+ NumPy arrays use `(H, W)` or channels-last grayscale, RGB, or RGBA layout. Supply `uint8` pixels, finite floats in `[0, 1]`, or `uint16` grayscale (values above 255 are clipped).
94
+
95
+ ## Return value
96
+
97
+ `predict()` returns a `HASAGIPrediction` dataclass. `predict_batch()` returns a list of these results in input order, or `[]` for empty input. Fields for a disabled task are `None`.
98
+
99
+ | Field | Type when enabled | Meaning |
100
+ | --- | --- | --- |
101
+ | `labels` | `tuple[str, ...]` | Layers with probability ≥ 0.5, or `("other",)` if none reach the threshold. |
102
+ | `layer_probabilities` | `dict[str, float]` | Independent probabilities for `sbnp` (subbasal nerve plexus), `epithelium`, `stroma`, and `other`. |
103
+ | `score` | `float` | Nerve discernibility on a 0–100 scale. Higher scores indicate clearer nerves. |
104
+ | `grade` | `str` | One of `poor`, `fair`, `good`, or `excellent`. |
105
+ | `grade_probabilities` | `dict[str, float]` | Probability of each of the four grades. |
@@ -0,0 +1,91 @@
1
+ # HASAGI
2
+
3
+ HASAGI identifies tissue layers and grades nerve discernibility in single-frame corneal in vivo confocal microscopy (IVCM) images. Both ONNX models run offline on the CPU.
4
+
5
+ ## License
6
+
7
+ The HASAGI Noncommercial License permits use and adaptation of the Python
8
+ code and both ONNX models for noncommercial research or teaching. Commercial
9
+ use and any redistribution, including sharing copies for free with collaborators
10
+ or students, require prior written authorization from the applicable HASAGI
11
+ rights holders or their authorized representative. You may share a link to an
12
+ authorized download. See `LICENSE` for the full terms and `THIRD_PARTY_NOTICES`
13
+ for upstream licenses and attribution.
14
+
15
+ ## Installation
16
+
17
+ Requires Python 3.10 or later.
18
+
19
+ ```bash
20
+ # From the source directory
21
+ python -m pip install .
22
+ ```
23
+
24
+ Once the beta is available on PyPI, install it with `python -m pip install hasagi==0.1.0b1`.
25
+
26
+ ## Usage
27
+
28
+ Create one predictor and reuse it across images. The constructor loads both models. The optional `num_threads` argument sets the number of CPU threads available to each ONNX session for computing an operator (default 4).
29
+
30
+ ```python
31
+ from PIL import Image
32
+ from hasagi import HASAGIPredictor
33
+
34
+ predictor = HASAGIPredictor(num_threads=4)
35
+ with Image.open("frame.png") as image:
36
+ result = predictor.predict(image, resize_mode="resize")
37
+
38
+ print(result.labels, result.grade, result.score)
39
+ ```
40
+
41
+ For a 384 × 384 frame, either task can also run on its own.
42
+
43
+ ```python
44
+ with Image.open("frame.png") as image:
45
+ layers = predictor.predict(image, predict_score=False)
46
+ score = predictor.predict(image, predict_layers=False)
47
+ ```
48
+
49
+ ## Batch inference
50
+
51
+ `predict_batch()` accepts a list, tuple, or generator of images. Each enabled model runs once per batch. The final batch can be smaller. To process a directory one batch at a time, reuse the predictor above.
52
+
53
+ ```python
54
+ from pathlib import Path
55
+
56
+ def read_images(paths):
57
+ for path in paths:
58
+ with Image.open(path) as image:
59
+ yield image
60
+
61
+ paths = sorted(Path("frames").glob("*.png"))
62
+ results = predictor.predict_batch(read_images(paths), batch_size=8, resize_mode="resize")
63
+ for path, result in zip(paths, results):
64
+ print(path.name, result.labels, result.grade, result.score)
65
+ ```
66
+
67
+ ## Prediction parameters
68
+
69
+ | Parameter | Default | Behavior |
70
+ | --- | --- | --- |
71
+ | `image` / `images` | Required | Pass one PIL image or NumPy array to `predict()`, or an iterable of images to `predict_batch()`. |
72
+ | `batch_size` | `8` | Maximum images per model call in `predict_batch()`. Larger batches use more memory. |
73
+ | `predict_layers` | `True` | Identify all matching layers. |
74
+ | `predict_score` | `True` | Grade nerve discernibility regardless of the predicted layers. |
75
+ | `resize_mode` | `"crop"` | `"crop"` takes the top-left 384 × 384 pixels and requires both dimensions to be at least 384. `"resize"` scales the whole image to 384 × 384 using bilinear interpolation. |
76
+
77
+ Pass options by keyword. Both `num_threads` and `batch_size` must be positive integers. Disabling both tasks raises `ValueError`. For an invalid image, the batch error identifies its zero-based index.
78
+
79
+ NumPy arrays use `(H, W)` or channels-last grayscale, RGB, or RGBA layout. Supply `uint8` pixels, finite floats in `[0, 1]`, or `uint16` grayscale (values above 255 are clipped).
80
+
81
+ ## Return value
82
+
83
+ `predict()` returns a `HASAGIPrediction` dataclass. `predict_batch()` returns a list of these results in input order, or `[]` for empty input. Fields for a disabled task are `None`.
84
+
85
+ | Field | Type when enabled | Meaning |
86
+ | --- | --- | --- |
87
+ | `labels` | `tuple[str, ...]` | Layers with probability ≥ 0.5, or `("other",)` if none reach the threshold. |
88
+ | `layer_probabilities` | `dict[str, float]` | Independent probabilities for `sbnp` (subbasal nerve plexus), `epithelium`, `stroma`, and `other`. |
89
+ | `score` | `float` | Nerve discernibility on a 0–100 scale. Higher scores indicate clearer nerves. |
90
+ | `grade` | `str` | One of `poor`, `fair`, `good`, or `excellent`. |
91
+ | `grade_probabilities` | `dict[str, float]` | Probability of each of the four grades. |
@@ -0,0 +1,226 @@
1
+ HASAGI third-party notices
2
+
3
+ EfficientNetV2-B0 pretrained backbone
4
+
5
+ Both HASAGI models use the tf_efficientnetv2_b0.in1k backbone. Mingxing
6
+ Tan and Quoc V. Le are the authors of EfficientNetV2. The upstream model
7
+ was trained on ImageNet-1k in TensorFlow and ported to PyTorch by Ross
8
+ Wightman. The timm model card identifies its license as Apache-2.0.
9
+
10
+ Model card: https://huggingface.co/timm/tf_efficientnetv2_b0.in1k
11
+ Upstream checkpoint: tf_efficientnetv2_b0-c7cc451f.pth
12
+ SHA-256: c7cc451f8f3450d815ed5dda9a0f78cb82b97a363e40b23ff9ed4955a6f27e54
13
+
14
+ HASAGI modifications
15
+
16
+ HASAGI combined features from four backbone stages using a task-specific
17
+ attention and classification head, trained separate models for tissue
18
+ layers and nerve discernibility, and exported both to ONNX with dynamic
19
+ batch sizes. The resulting files are models/layers_fp32.onnx and
20
+ models/discernibility_fp32.onnx within the hasagi Python package.
21
+ The accompanying LICENSE describes the terms for the HASAGI materials.
22
+
23
+ Upstream license and attribution
24
+
25
+
26
+ Apache License
27
+ Version 2.0, January 2004
28
+ http://www.apache.org/licenses/
29
+
30
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
31
+
32
+ 1. Definitions.
33
+
34
+ "License" shall mean the terms and conditions for use, reproduction,
35
+ and distribution as defined by Sections 1 through 9 of this document.
36
+
37
+ "Licensor" shall mean the copyright owner or entity authorized by
38
+ the copyright owner that is granting the License.
39
+
40
+ "Legal Entity" shall mean the union of the acting entity and all
41
+ other entities that control, are controlled by, or are under common
42
+ control with that entity. For the purposes of this definition,
43
+ "control" means (i) the power, direct or indirect, to cause the
44
+ direction or management of such entity, whether by contract or
45
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
46
+ outstanding shares, or (iii) beneficial ownership of such entity.
47
+
48
+ "You" (or "Your") shall mean an individual or Legal Entity
49
+ exercising permissions granted by this License.
50
+
51
+ "Source" form shall mean the preferred form for making modifications,
52
+ including but not limited to software source code, documentation
53
+ source, and configuration files.
54
+
55
+ "Object" form shall mean any form resulting from mechanical
56
+ transformation or translation of a Source form, including but
57
+ not limited to compiled object code, generated documentation,
58
+ and conversions to other media types.
59
+
60
+ "Work" shall mean the work of authorship, whether in Source or
61
+ Object form, made available under the License, as indicated by a
62
+ copyright notice that is included in or attached to the work
63
+ (an example is provided in the Appendix below).
64
+
65
+ "Derivative Works" shall mean any work, whether in Source or Object
66
+ form, that is based on (or derived from) the Work and for which the
67
+ editorial revisions, annotations, elaborations, or other modifications
68
+ represent, as a whole, an original work of authorship. For the purposes
69
+ of this License, Derivative Works shall not include works that remain
70
+ separable from, or merely link (or bind by name) to the interfaces of,
71
+ the Work and Derivative Works thereof.
72
+
73
+ "Contribution" shall mean any work of authorship, including
74
+ the original version of the Work and any modifications or additions
75
+ to that Work or Derivative Works thereof, that is intentionally
76
+ submitted to Licensor for inclusion in the Work by the copyright owner
77
+ or by an individual or Legal Entity authorized to submit on behalf of
78
+ the copyright owner. For the purposes of this definition, "submitted"
79
+ means any form of electronic, verbal, or written communication sent
80
+ to the Licensor or its representatives, including but not limited to
81
+ communication on electronic mailing lists, source code control systems,
82
+ and issue tracking systems that are managed by, or on behalf of, the
83
+ Licensor for the purpose of discussing and improving the Work, but
84
+ excluding communication that is conspicuously marked or otherwise
85
+ designated in writing by the copyright owner as "Not a Contribution."
86
+
87
+ "Contributor" shall mean Licensor and any individual or Legal Entity
88
+ on behalf of whom a Contribution has been received by Licensor and
89
+ subsequently incorporated within the Work.
90
+
91
+ 2. Grant of Copyright License. Subject to the terms and conditions of
92
+ this License, each Contributor hereby grants to You a perpetual,
93
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
94
+ copyright license to reproduce, prepare Derivative Works of,
95
+ publicly display, publicly perform, sublicense, and distribute the
96
+ Work and such Derivative Works in Source or Object form.
97
+
98
+ 3. Grant of Patent License. Subject to the terms and conditions of
99
+ this License, each Contributor hereby grants to You a perpetual,
100
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
101
+ (except as stated in this section) patent license to make, have made,
102
+ use, offer to sell, sell, import, and otherwise transfer the Work,
103
+ where such license applies only to those patent claims licensable
104
+ by such Contributor that are necessarily infringed by their
105
+ Contribution(s) alone or by combination of their Contribution(s)
106
+ with the Work to which such Contribution(s) was submitted. If You
107
+ institute patent litigation against any entity (including a
108
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
109
+ or a Contribution incorporated within the Work constitutes direct
110
+ or contributory patent infringement, then any patent licenses
111
+ granted to You under this License for that Work shall terminate
112
+ as of the date such litigation is filed.
113
+
114
+ 4. Redistribution. You may reproduce and distribute copies of the
115
+ Work or Derivative Works thereof in any medium, with or without
116
+ modifications, and in Source or Object form, provided that You
117
+ meet the following conditions:
118
+
119
+ (a) You must give any other recipients of the Work or
120
+ Derivative Works a copy of this License; and
121
+
122
+ (b) You must cause any modified files to carry prominent notices
123
+ stating that You changed the files; and
124
+
125
+ (c) You must retain, in the Source form of any Derivative Works
126
+ that You distribute, all copyright, patent, trademark, and
127
+ attribution notices from the Source form of the Work,
128
+ excluding those notices that do not pertain to any part of
129
+ the Derivative Works; and
130
+
131
+ (d) If the Work includes a "NOTICE" text file as part of its
132
+ distribution, then any Derivative Works that You distribute must
133
+ include a readable copy of the attribution notices contained
134
+ within such NOTICE file, excluding those notices that do not
135
+ pertain to any part of the Derivative Works, in at least one
136
+ of the following places: within a NOTICE text file distributed
137
+ as part of the Derivative Works; within the Source form or
138
+ documentation, if provided along with the Derivative Works; or,
139
+ within a display generated by the Derivative Works, if and
140
+ wherever such third-party notices normally appear. The contents
141
+ of the NOTICE file are for informational purposes only and
142
+ do not modify the License. You may add Your own attribution
143
+ notices within Derivative Works that You distribute, alongside
144
+ or as an addendum to the NOTICE text from the Work, provided
145
+ that such additional attribution notices cannot be construed
146
+ as modifying the License.
147
+
148
+ You may add Your own copyright statement to Your modifications and
149
+ may provide additional or different license terms and conditions
150
+ for use, reproduction, or distribution of Your modifications, or
151
+ for any such Derivative Works as a whole, provided Your use,
152
+ reproduction, and distribution of the Work otherwise complies with
153
+ the conditions stated in this License.
154
+
155
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
156
+ any Contribution intentionally submitted for inclusion in the Work
157
+ by You to the Licensor shall be under the terms and conditions of
158
+ this License, without any additional terms or conditions.
159
+ Notwithstanding the above, nothing herein shall supersede or modify
160
+ the terms of any separate license agreement you may have executed
161
+ with Licensor regarding such Contributions.
162
+
163
+ 6. Trademarks. This License does not grant permission to use the trade
164
+ names, trademarks, service marks, or product names of the Licensor,
165
+ except as required for reasonable and customary use in describing the
166
+ origin of the Work and reproducing the content of the NOTICE file.
167
+
168
+ 7. Disclaimer of Warranty. Unless required by applicable law or
169
+ agreed to in writing, Licensor provides the Work (and each
170
+ Contributor provides its Contributions) on an "AS IS" BASIS,
171
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
172
+ implied, including, without limitation, any warranties or conditions
173
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
174
+ PARTICULAR PURPOSE. You are solely responsible for determining the
175
+ appropriateness of using or redistributing the Work and assume any
176
+ risks associated with Your exercise of permissions under this License.
177
+
178
+ 8. Limitation of Liability. In no event and under no legal theory,
179
+ whether in tort (including negligence), contract, or otherwise,
180
+ unless required by applicable law (such as deliberate and grossly
181
+ negligent acts) or agreed to in writing, shall any Contributor be
182
+ liable to You for damages, including any direct, indirect, special,
183
+ incidental, or consequential damages of any character arising as a
184
+ result of this License or out of the use or inability to use the
185
+ Work (including but not limited to damages for loss of goodwill,
186
+ work stoppage, computer failure or malfunction, or any and all
187
+ other commercial damages or losses), even if such Contributor
188
+ has been advised of the possibility of such damages.
189
+
190
+ 9. Accepting Warranty or Additional Liability. While redistributing
191
+ the Work or Derivative Works thereof, You may choose to offer,
192
+ and charge a fee for, acceptance of support, warranty, indemnity,
193
+ or other liability obligations and/or rights consistent with this
194
+ License. However, in accepting such obligations, You may act only
195
+ on Your own behalf and on Your sole responsibility, not on behalf
196
+ of any other Contributor, and only if You agree to indemnify,
197
+ defend, and hold each Contributor harmless for any liability
198
+ incurred by, or claims asserted against, such Contributor by reason
199
+ of your accepting any such warranty or additional liability.
200
+
201
+ END OF TERMS AND CONDITIONS
202
+
203
+ APPENDIX: How to apply the Apache License to your work.
204
+
205
+ To apply the Apache License to your work, attach the following
206
+ boilerplate notice, with the fields enclosed by brackets "{}"
207
+ replaced with your own identifying information. (Don't include
208
+ the brackets!) The text should be enclosed in the appropriate
209
+ comment syntax for the file format. We also recommend that a
210
+ file or class name and description of purpose be included on the
211
+ same "printed page" as the copyright notice for easier
212
+ identification within third-party archives.
213
+
214
+ Copyright 2019 Ross Wightman
215
+
216
+ Licensed under the Apache License, Version 2.0 (the "License");
217
+ you may not use this file except in compliance with the License.
218
+ You may obtain a copy of the License at
219
+
220
+ http://www.apache.org/licenses/LICENSE-2.0
221
+
222
+ Unless required by applicable law or agreed to in writing, software
223
+ distributed under the License is distributed on an "AS IS" BASIS,
224
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
225
+ See the License for the specific language governing permissions and
226
+ limitations under the License.
@@ -0,0 +1,24 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77.0.3"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "hasagi"
7
+ version = "0.1.0b1"
8
+ description = "CPU inference for corneal IVCM tissue layers and nerve discernibility"
9
+ readme = "README.pypi.md"
10
+ license = "LicenseRef-HASAGI-Noncommercial AND Apache-2.0"
11
+ license-files = ["LICENSE", "THIRD_PARTY_NOTICES"]
12
+ requires-python = ">=3.10"
13
+ dependencies = ["numpy", "onnxruntime", "Pillow>=9.1"]
14
+
15
+ [tool.setuptools]
16
+ package-dir = {"" = "src"}
17
+ packages = ["hasagi"]
18
+ include-package-data = false
19
+
20
+ [tool.setuptools.package-data]
21
+ hasagi = ["models/*.onnx"]
22
+
23
+ [tool.pytest.ini_options]
24
+ pythonpath = ["src"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,5 @@
1
+ """HASAGI inference for single-frame corneal IVCM images."""
2
+
3
+ from .predictor import HASAGIPrediction, HASAGIPredictor
4
+
5
+ __all__ = ["HASAGIPrediction", "HASAGIPredictor"]
@@ -0,0 +1,174 @@
1
+ from collections.abc import Iterable, Iterator
2
+ from dataclasses import dataclass
3
+ from itertools import islice
4
+ from numbers import Integral
5
+ from pathlib import Path
6
+ from typing import Literal
7
+
8
+ import numpy as np
9
+ import onnxruntime as ort
10
+ from PIL import Image
11
+
12
+ _SIDE = 384
13
+ _LAYERS = ("sbnp", "epithelium", "stroma", "other")
14
+ _GRADES = ("poor", "fair", "good", "excellent")
15
+ _MEAN = np.array([0.485, 0.456, 0.406], dtype=np.float32)[:, None, None]
16
+ _STD = np.array([0.229, 0.224, 0.225], dtype=np.float32)[:, None, None]
17
+
18
+
19
+ @dataclass(frozen=True)
20
+ class HASAGIPrediction:
21
+ """Selected layers, a 0–100 discernibility score, and named probabilities.
22
+
23
+ Fields for a disabled prediction task are None.
24
+ """
25
+
26
+ labels: tuple[str, ...] | None
27
+ layer_probabilities: dict[str, float] | None
28
+ score: float | None
29
+ grade: str | None
30
+ grade_probabilities: dict[str, float] | None
31
+
32
+
33
+ def _from_array(array: np.ndarray) -> Image.Image:
34
+ if array.ndim == 3 and array.shape[2] == 1:
35
+ array = array[:, :, 0]
36
+ if array.ndim != 2 and not (array.ndim == 3 and array.shape[2] in (3, 4)):
37
+ raise ValueError("Expected a grayscale, RGB or RGBA array in H×W or H×W×C layout.")
38
+ if array.size == 0:
39
+ raise ValueError("Expected a nonempty image.")
40
+ if np.issubdtype(array.dtype, np.floating):
41
+ if not np.isfinite(array).all() or array.min() < 0 or array.max() > 1:
42
+ raise ValueError("Floating-point images must contain finite values in [0, 1].")
43
+ array = np.rint(array * 255).astype(np.uint8)
44
+ elif array.ndim == 2 and array.dtype.kind == "u" and array.dtype.itemsize == 2:
45
+ array = array.clip(0, 255).astype(np.uint8)
46
+ elif array.dtype != np.uint8:
47
+ raise ValueError("Expected uint8, uint16 grayscale, or floating-point pixels in [0, 1].")
48
+ return Image.fromarray(array)
49
+
50
+
51
+ def _model_input(image: Image.Image | np.ndarray, resize_mode: str) -> np.ndarray:
52
+ if isinstance(image, np.ndarray):
53
+ image = _from_array(image)
54
+ elif not isinstance(image, Image.Image):
55
+ raise TypeError("image must be a PIL.Image.Image or a numpy.ndarray.")
56
+ if getattr(image, "n_frames", 1) != 1 or min(image.size) < 1:
57
+ raise ValueError("Expected a nonempty, single-frame image.")
58
+ if image.mode == "F":
59
+ image = _from_array(np.asarray(image))
60
+ if resize_mode == "crop":
61
+ if min(image.size) < _SIDE:
62
+ raise ValueError("crop requires both image dimensions to be at least 384 pixels.")
63
+ if image.size != (_SIDE, _SIDE):
64
+ image = image.crop((0, 0, _SIDE, _SIDE))
65
+ gray = image.convert("L")
66
+ if gray.size != (_SIDE, _SIDE):
67
+ gray = gray.resize((_SIDE, _SIDE), Image.Resampling.BILINEAR)
68
+ pixels = np.asarray(gray, dtype=np.float32) / 255.0
69
+ return (pixels - _MEAN) / _STD
70
+
71
+
72
+ def _inputs(images: Iterable[Image.Image | np.ndarray], resize_mode: str) -> Iterator[np.ndarray]:
73
+ iterator = iter(images)
74
+ index = 0
75
+ while True:
76
+ try:
77
+ image = next(iterator)
78
+ pixels = _model_input(image, resize_mode)
79
+ except StopIteration:
80
+ return
81
+ except (TypeError, ValueError, OSError) as exc:
82
+ raise type(exc)(f"images[{index}]: {exc}") from exc
83
+ yield pixels
84
+ index += 1
85
+
86
+
87
+ def _positive_integer(value: int, name: str) -> int:
88
+ if isinstance(value, bool) or not isinstance(value, Integral) or value < 1:
89
+ raise ValueError(f"{name} must be a positive integer.")
90
+ return int(value)
91
+
92
+
93
+ def _logits(session: ort.InferenceSession, pixels: np.ndarray) -> np.ndarray:
94
+ output = session.run(["logits"], {"images": pixels})[0]
95
+ if output.shape != (len(pixels), 4) or not np.isfinite(output).all():
96
+ raise ValueError("Expected four finite logits per image from the HASAGI model.")
97
+ return output.astype(np.float64)
98
+
99
+
100
+ def _prediction(layer_logits: np.ndarray | None, grade_logits: np.ndarray | None) -> HASAGIPrediction:
101
+ labels = layer_probabilities = None
102
+ if layer_logits is not None:
103
+ probabilities = np.exp(-np.logaddexp(0, -layer_logits))
104
+ layer_probabilities = dict(zip(_LAYERS, probabilities.tolist()))
105
+ labels = tuple(name for name, p in layer_probabilities.items() if p >= 0.5) or ("other",)
106
+
107
+ score = grade = grade_probabilities = None
108
+ if grade_logits is not None:
109
+ weights = np.exp(grade_logits - grade_logits.max())
110
+ probabilities = weights / weights.sum()
111
+ grade_probabilities = dict(zip(_GRADES, probabilities.tolist()))
112
+ grade = _GRADES[grade_logits.argmax()]
113
+ score = float(np.dot(probabilities, (0, 1, 2, 3)) * 100 / 3)
114
+ return HASAGIPrediction(labels, layer_probabilities, score, grade, grade_probabilities)
115
+
116
+
117
+ class HASAGIPredictor:
118
+ """Load both bundled ONNX models once and reuse their CPU sessions."""
119
+
120
+ def __init__(self, *, num_threads: int = 4) -> None:
121
+ models = Path(__file__).parent / "models"
122
+ options = ort.SessionOptions()
123
+ options.intra_op_num_threads = _positive_integer(num_threads, "num_threads")
124
+ options.inter_op_num_threads = 1
125
+ self._layers = ort.InferenceSession(
126
+ str(models / "layers_fp32.onnx"), options, providers=["CPUExecutionProvider"]
127
+ )
128
+ self._grades = ort.InferenceSession(
129
+ str(models / "discernibility_fp32.onnx"), options, providers=["CPUExecutionProvider"]
130
+ )
131
+
132
+ def predict(
133
+ self,
134
+ image: Image.Image | np.ndarray,
135
+ *,
136
+ predict_layers: bool = True,
137
+ predict_score: bool = True,
138
+ resize_mode: Literal["crop", "resize"] = "crop",
139
+ ) -> HASAGIPrediction:
140
+ """Run each enabled model independently on a single image.
141
+
142
+ Arrays use grayscale, RGB or RGBA order. Supply uint8 pixels, uint16
143
+ grayscale (clipped to 255), or floating-point pixels in [0, 1].
144
+ Crop takes the upper-left 384×384 pixels. Resize uses bilinear
145
+ interpolation over the whole image. Enable at least one task.
146
+ """
147
+ return self.predict_batch(
148
+ (image,), batch_size=1, predict_layers=predict_layers,
149
+ predict_score=predict_score, resize_mode=resize_mode,
150
+ )[0]
151
+
152
+ def predict_batch(
153
+ self,
154
+ images: Iterable[Image.Image | np.ndarray],
155
+ *,
156
+ batch_size: int = 8,
157
+ predict_layers: bool = True,
158
+ predict_score: bool = True,
159
+ resize_mode: Literal["crop", "resize"] = "crop",
160
+ ) -> list[HASAGIPrediction]:
161
+ """Process successive batches and return one result per image in input order."""
162
+ batch_size = _positive_integer(batch_size, "batch_size")
163
+ if not (predict_layers or predict_score):
164
+ raise ValueError("Enable at least one of predict_layers or predict_score.")
165
+ if resize_mode not in ("crop", "resize"):
166
+ raise ValueError("resize_mode must be 'crop' or 'resize'.")
167
+ inputs = _inputs(images, resize_mode)
168
+ results = []
169
+ while batch := list(islice(inputs, batch_size)):
170
+ pixels = np.stack(batch)
171
+ layers = _logits(self._layers, pixels) if predict_layers else [None] * len(batch)
172
+ grades = _logits(self._grades, pixels) if predict_score else [None] * len(batch)
173
+ results.extend(_prediction(layer, grade) for layer, grade in zip(layers, grades))
174
+ return results
@@ -0,0 +1,105 @@
1
+ Metadata-Version: 2.4
2
+ Name: hasagi
3
+ Version: 0.1.0b1
4
+ Summary: CPU inference for corneal IVCM tissue layers and nerve discernibility
5
+ License-Expression: LicenseRef-HASAGI-Noncommercial AND Apache-2.0
6
+ Requires-Python: >=3.10
7
+ Description-Content-Type: text/markdown
8
+ License-File: LICENSE
9
+ License-File: THIRD_PARTY_NOTICES
10
+ Requires-Dist: numpy
11
+ Requires-Dist: onnxruntime
12
+ Requires-Dist: Pillow>=9.1
13
+ Dynamic: license-file
14
+
15
+ # HASAGI
16
+
17
+ HASAGI identifies tissue layers and grades nerve discernibility in single-frame corneal in vivo confocal microscopy (IVCM) images. Both ONNX models run offline on the CPU.
18
+
19
+ ## License
20
+
21
+ The HASAGI Noncommercial License permits use and adaptation of the Python
22
+ code and both ONNX models for noncommercial research or teaching. Commercial
23
+ use and any redistribution, including sharing copies for free with collaborators
24
+ or students, require prior written authorization from the applicable HASAGI
25
+ rights holders or their authorized representative. You may share a link to an
26
+ authorized download. See `LICENSE` for the full terms and `THIRD_PARTY_NOTICES`
27
+ for upstream licenses and attribution.
28
+
29
+ ## Installation
30
+
31
+ Requires Python 3.10 or later.
32
+
33
+ ```bash
34
+ # From the source directory
35
+ python -m pip install .
36
+ ```
37
+
38
+ Once the beta is available on PyPI, install it with `python -m pip install hasagi==0.1.0b1`.
39
+
40
+ ## Usage
41
+
42
+ Create one predictor and reuse it across images. The constructor loads both models. The optional `num_threads` argument sets the number of CPU threads available to each ONNX session for computing an operator (default 4).
43
+
44
+ ```python
45
+ from PIL import Image
46
+ from hasagi import HASAGIPredictor
47
+
48
+ predictor = HASAGIPredictor(num_threads=4)
49
+ with Image.open("frame.png") as image:
50
+ result = predictor.predict(image, resize_mode="resize")
51
+
52
+ print(result.labels, result.grade, result.score)
53
+ ```
54
+
55
+ For a 384 × 384 frame, either task can also run on its own.
56
+
57
+ ```python
58
+ with Image.open("frame.png") as image:
59
+ layers = predictor.predict(image, predict_score=False)
60
+ score = predictor.predict(image, predict_layers=False)
61
+ ```
62
+
63
+ ## Batch inference
64
+
65
+ `predict_batch()` accepts a list, tuple, or generator of images. Each enabled model runs once per batch. The final batch can be smaller. To process a directory one batch at a time, reuse the predictor above.
66
+
67
+ ```python
68
+ from pathlib import Path
69
+
70
+ def read_images(paths):
71
+ for path in paths:
72
+ with Image.open(path) as image:
73
+ yield image
74
+
75
+ paths = sorted(Path("frames").glob("*.png"))
76
+ results = predictor.predict_batch(read_images(paths), batch_size=8, resize_mode="resize")
77
+ for path, result in zip(paths, results):
78
+ print(path.name, result.labels, result.grade, result.score)
79
+ ```
80
+
81
+ ## Prediction parameters
82
+
83
+ | Parameter | Default | Behavior |
84
+ | --- | --- | --- |
85
+ | `image` / `images` | Required | Pass one PIL image or NumPy array to `predict()`, or an iterable of images to `predict_batch()`. |
86
+ | `batch_size` | `8` | Maximum images per model call in `predict_batch()`. Larger batches use more memory. |
87
+ | `predict_layers` | `True` | Identify all matching layers. |
88
+ | `predict_score` | `True` | Grade nerve discernibility regardless of the predicted layers. |
89
+ | `resize_mode` | `"crop"` | `"crop"` takes the top-left 384 × 384 pixels and requires both dimensions to be at least 384. `"resize"` scales the whole image to 384 × 384 using bilinear interpolation. |
90
+
91
+ Pass options by keyword. Both `num_threads` and `batch_size` must be positive integers. Disabling both tasks raises `ValueError`. For an invalid image, the batch error identifies its zero-based index.
92
+
93
+ NumPy arrays use `(H, W)` or channels-last grayscale, RGB, or RGBA layout. Supply `uint8` pixels, finite floats in `[0, 1]`, or `uint16` grayscale (values above 255 are clipped).
94
+
95
+ ## Return value
96
+
97
+ `predict()` returns a `HASAGIPrediction` dataclass. `predict_batch()` returns a list of these results in input order, or `[]` for empty input. Fields for a disabled task are `None`.
98
+
99
+ | Field | Type when enabled | Meaning |
100
+ | --- | --- | --- |
101
+ | `labels` | `tuple[str, ...]` | Layers with probability ≥ 0.5, or `("other",)` if none reach the threshold. |
102
+ | `layer_probabilities` | `dict[str, float]` | Independent probabilities for `sbnp` (subbasal nerve plexus), `epithelium`, `stroma`, and `other`. |
103
+ | `score` | `float` | Nerve discernibility on a 0–100 scale. Higher scores indicate clearer nerves. |
104
+ | `grade` | `str` | One of `poor`, `fair`, `good`, or `excellent`. |
105
+ | `grade_probabilities` | `dict[str, float]` | Probability of each of the four grades. |
@@ -0,0 +1,15 @@
1
+ LICENSE
2
+ MANIFEST.in
3
+ README.pypi.md
4
+ THIRD_PARTY_NOTICES
5
+ pyproject.toml
6
+ src/hasagi/__init__.py
7
+ src/hasagi/predictor.py
8
+ src/hasagi.egg-info/PKG-INFO
9
+ src/hasagi.egg-info/SOURCES.txt
10
+ src/hasagi.egg-info/dependency_links.txt
11
+ src/hasagi.egg-info/requires.txt
12
+ src/hasagi.egg-info/top_level.txt
13
+ src/hasagi/models/discernibility_fp32.onnx
14
+ src/hasagi/models/layers_fp32.onnx
15
+ tests/test_hasagi_predictor.py
@@ -0,0 +1,3 @@
1
+ numpy
2
+ onnxruntime
3
+ Pillow>=9.1
@@ -0,0 +1 @@
1
+ hasagi
@@ -0,0 +1,134 @@
1
+ from unittest.mock import patch
2
+
3
+ import numpy as np
4
+ import pytest
5
+ from PIL import Image
6
+
7
+ from hasagi import HASAGIPrediction, HASAGIPredictor
8
+
9
+
10
+ @pytest.fixture(scope="module")
11
+ def predictor():
12
+ return HASAGIPredictor()
13
+
14
+
15
+ @pytest.fixture(scope="module")
16
+ def rgb():
17
+ return np.random.default_rng(42).integers(0, 256, (420, 460, 3), dtype=np.uint8)
18
+
19
+
20
+ def test_independent_predictions(predictor, rgb):
21
+ both = predictor.predict(rgb)
22
+ assert isinstance(both, HASAGIPrediction)
23
+ assert set(both.layer_probabilities) == {"sbnp", "epithelium", "stroma", "other"}
24
+ assert all(0 <= p <= 1 for p in both.layer_probabilities.values())
25
+ assert set(both.grade_probabilities) == {"poor", "fair", "good", "excellent"}
26
+ assert sum(both.grade_probabilities.values()) == pytest.approx(1)
27
+ assert both.grade == max(both.grade_probabilities, key=both.grade_probabilities.get)
28
+ p = both.grade_probabilities
29
+ assert both.score == pytest.approx(100 * (p["fair"] + 2*p["good"] + 3*p["excellent"]) / 3)
30
+
31
+ with patch.object(predictor._grades, "run", side_effect=AssertionError("grade model ran")):
32
+ layers = predictor.predict(rgb, predict_score=False)
33
+ assert layers == HASAGIPrediction(both.labels, both.layer_probabilities, None, None, None)
34
+ with patch.object(predictor._layers, "run", side_effect=AssertionError("layer model ran")):
35
+ score = predictor.predict(rgb, predict_layers=False)
36
+ assert score == HASAGIPrediction(None, None, both.score, both.grade, both.grade_probabilities)
37
+ with pytest.raises(ValueError, match="at least one"):
38
+ predictor.predict(rgb, predict_layers=False, predict_score=False)
39
+
40
+
41
+ @pytest.mark.parametrize(("logits", "labels"), [
42
+ ([-2, -2, -2, -2], ("other",)),
43
+ ([0, -2, 2, -2], ("sbnp", "stroma")),
44
+ ])
45
+ def test_score_also_runs_for_other_and_mixed_layers(predictor, rgb, logits, labels):
46
+ output = np.array([logits], dtype=np.float32)
47
+ with patch.object(predictor._layers, "run", return_value=[output]):
48
+ result = predictor.predict(rgb)
49
+ assert result.labels == labels
50
+ assert 0 <= result.score <= 100
51
+
52
+
53
+ def test_crop_uses_top_left(predictor, rgb):
54
+ assert predictor.predict(rgb) == predictor.predict(Image.fromarray(rgb[:384, :384]))
55
+
56
+
57
+ def test_resize_uses_whole_image(predictor, rgb):
58
+ image = Image.fromarray(rgb[:160])
59
+ expected = image.convert("L").resize((384, 384), Image.Resampling.BILINEAR)
60
+ assert predictor.predict(image, resize_mode="resize") == predictor.predict(expected)
61
+
62
+
63
+ def test_grayscale_array_formats(predictor, rgb):
64
+ gray = rgb[:384, :384, 0]
65
+ expected = predictor.predict(gray)
66
+ assert predictor.predict(gray[..., None]) == expected
67
+ assert predictor.predict(gray.astype(np.float32) / 255) == expected
68
+ wide = gray.astype(np.uint16)
69
+ wide[gray == 255] = 1024
70
+ assert predictor.predict(wide) == expected
71
+
72
+
73
+ @pytest.mark.parametrize(("image", "mode", "error"), [
74
+ (np.zeros((383, 400), np.uint8), "crop", "at least 384"),
75
+ (np.zeros((400, 383), np.uint8), "crop", "at least 384"),
76
+ (np.zeros((384, 384), np.uint8), "pad", "resize_mode"),
77
+ (np.empty((0, 400), np.uint8), "resize", "nonempty"),
78
+ (np.zeros((3, 384, 384), np.uint8), "resize", "layout"),
79
+ (np.array([[np.nan]]), "resize", "finite"),
80
+ ])
81
+ def test_invalid_inputs(predictor, image, mode, error):
82
+ with pytest.raises(ValueError, match=error):
83
+ predictor.predict(image, resize_mode=mode)
84
+
85
+
86
+ @pytest.mark.parametrize("predict_layers,predict_score", [(True, True), (True, False), (False, True)])
87
+ def test_batch_matches_single_and_runs_once_per_chunk(predictor, predict_layers, predict_score):
88
+ images = [np.full((200 + i, 384), i * 50, dtype=np.uint8) for i in range(5)]
89
+ options = dict(predict_layers=predict_layers, predict_score=predict_score, resize_mode="resize")
90
+ expected = [predictor.predict(im, **options) for im in images]
91
+ with (
92
+ patch.object(predictor._layers, "run", wraps=predictor._layers.run) as layers,
93
+ patch.object(predictor._grades, "run", wraps=predictor._grades.run) as grades,
94
+ ):
95
+ actual = predictor.predict_batch(iter(images), batch_size=2, **options)
96
+ for model, enabled in ((layers, predict_layers), (grades, predict_score)):
97
+ shapes = [call.args[1]["images"].shape[0] for call in model.call_args_list]
98
+ assert shapes == ([2, 2, 1] if enabled else [])
99
+ assert len(actual) == len(expected)
100
+ for a, e in zip(actual, expected):
101
+ assert (a.labels, a.grade) == (e.labels, e.grade)
102
+ if predict_layers:
103
+ assert a.layer_probabilities == pytest.approx(e.layer_probabilities, abs=1e-5)
104
+ else:
105
+ assert a.layer_probabilities is None
106
+ if predict_score:
107
+ assert a.score == pytest.approx(e.score, abs=1e-3)
108
+ assert a.grade_probabilities == pytest.approx(e.grade_probabilities, abs=1e-5)
109
+ else:
110
+ assert a.score is a.grade_probabilities is None
111
+
112
+
113
+ def test_threads_and_empty_batch():
114
+ predictor = HASAGIPredictor(num_threads=2)
115
+ for session in (predictor._layers, predictor._grades):
116
+ assert session.get_session_options().intra_op_num_threads == 2
117
+ assert predictor.predict_batch([]) == []
118
+ with pytest.raises(ValueError, match="at least one"):
119
+ predictor.predict_batch([], predict_layers=False, predict_score=False)
120
+ with pytest.raises(ValueError, match="resize_mode"):
121
+ predictor.predict_batch([], resize_mode="pad")
122
+
123
+
124
+ @pytest.mark.parametrize("value", [False, 0, -1, 1.5])
125
+ def test_positive_integer_parameters(predictor, value):
126
+ with pytest.raises(ValueError, match="num_threads"):
127
+ HASAGIPredictor(num_threads=value)
128
+ with pytest.raises(ValueError, match="batch_size"):
129
+ predictor.predict_batch([], batch_size=value)
130
+
131
+
132
+ def test_batch_error_index(predictor, rgb):
133
+ with pytest.raises(ValueError, match=r"images\[3\].*at least 384"):
134
+ predictor.predict_batch([rgb, rgb, rgb, rgb[:10]], batch_size=2)