bioimageflow-segmentation-tools 0.2.0__tar.gz → 0.3.2__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.
Files changed (38) hide show
  1. {bioimageflow_segmentation_tools-0.2.0 → bioimageflow_segmentation_tools-0.3.2}/PKG-INFO +12 -7
  2. {bioimageflow_segmentation_tools-0.2.0 → bioimageflow_segmentation_tools-0.3.2}/README.md +10 -1
  3. {bioimageflow_segmentation_tools-0.2.0 → bioimageflow_segmentation_tools-0.3.2}/bioimageflow_segmentation_tools/__init__.py +6 -0
  4. bioimageflow_segmentation_tools-0.3.2/bioimageflow_segmentation_tools/instanseg_segmenter.py +386 -0
  5. bioimageflow_segmentation_tools-0.3.2/bioimageflow_segmentation_tools/nagini3d_segmenter.py +420 -0
  6. {bioimageflow_segmentation_tools-0.2.0 → bioimageflow_segmentation_tools-0.3.2}/docs/index.md +12 -3
  7. bioimageflow_segmentation_tools-0.3.2/docs/tools/instanseg_segmenter.md +14 -0
  8. bioimageflow_segmentation_tools-0.3.2/docs/tools/nagini3d_segmenter.md +16 -0
  9. {bioimageflow_segmentation_tools-0.2.0 → bioimageflow_segmentation_tools-0.3.2}/docs/tools/stardist_segmenter.md +1 -0
  10. {bioimageflow_segmentation_tools-0.2.0 → bioimageflow_segmentation_tools-0.3.2}/docs/workflows/bbbc038_segmentation_benchmark.md +2 -2
  11. bioimageflow_segmentation_tools-0.3.2/docs/workflows/instanseg_cell_segmentation.md +6 -0
  12. bioimageflow_segmentation_tools-0.3.2/docs/workflows/nagini3d_caps_segmentation.md +5 -0
  13. {bioimageflow_segmentation_tools-0.2.0 → bioimageflow_segmentation_tools-0.3.2}/pyproject.toml +2 -6
  14. bioimageflow_segmentation_tools-0.3.2/tests/test_instanseg_runtime.py +50 -0
  15. bioimageflow_segmentation_tools-0.3.2/tests/test_model_adapters.py +300 -0
  16. bioimageflow_segmentation_tools-0.3.2/tests/test_model_content_identity.py +171 -0
  17. bioimageflow_segmentation_tools-0.3.2/tests/test_nagini_runtime.py +23 -0
  18. {bioimageflow_segmentation_tools-0.2.0 → bioimageflow_segmentation_tools-0.3.2}/tests/test_schema.py +8 -0
  19. {bioimageflow_segmentation_tools-0.2.0 → bioimageflow_segmentation_tools-0.3.2}/.gitignore +0 -0
  20. {bioimageflow_segmentation_tools-0.2.0 → bioimageflow_segmentation_tools-0.3.2}/LICENSE +0 -0
  21. {bioimageflow_segmentation_tools-0.2.0 → bioimageflow_segmentation_tools-0.3.2}/bioimageflow_segmentation_tools/_arrays.py +0 -0
  22. {bioimageflow_segmentation_tools-0.2.0 → bioimageflow_segmentation_tools-0.3.2}/bioimageflow_segmentation_tools/cellpose_sam.py +0 -0
  23. {bioimageflow_segmentation_tools-0.2.0 → bioimageflow_segmentation_tools-0.3.2}/bioimageflow_segmentation_tools/cellpose_v3.py +0 -0
  24. {bioimageflow_segmentation_tools-0.2.0 → bioimageflow_segmentation_tools-0.3.2}/bioimageflow_segmentation_tools/classical.py +0 -0
  25. {bioimageflow_segmentation_tools-0.2.0 → bioimageflow_segmentation_tools-0.3.2}/bioimageflow_segmentation_tools/stardist_segmenter.py +9 -9
  26. {bioimageflow_segmentation_tools-0.2.0 → bioimageflow_segmentation_tools-0.3.2}/docs/images/README.md +0 -0
  27. {bioimageflow_segmentation_tools-0.2.0 → bioimageflow_segmentation_tools-0.3.2}/docs/tools/cellpose3.md +0 -0
  28. {bioimageflow_segmentation_tools-0.2.0 → bioimageflow_segmentation_tools-0.3.2}/docs/tools/cellpose_sam.md +0 -0
  29. {bioimageflow_segmentation_tools-0.2.0 → bioimageflow_segmentation_tools-0.3.2}/docs/tools/distance_watershed_segment.md +0 -0
  30. {bioimageflow_segmentation_tools-0.2.0 → bioimageflow_segmentation_tools-0.3.2}/docs/tools/filter_labels.md +0 -0
  31. {bioimageflow_segmentation_tools-0.2.0 → bioimageflow_segmentation_tools-0.3.2}/docs/tools/local_threshold_segment.md +0 -0
  32. {bioimageflow_segmentation_tools-0.2.0 → bioimageflow_segmentation_tools-0.3.2}/docs/tools/otsu_threshold_segment.md +0 -0
  33. {bioimageflow_segmentation_tools-0.2.0 → bioimageflow_segmentation_tools-0.3.2}/docs/tools/postprocess_labels.md +0 -0
  34. {bioimageflow_segmentation_tools-0.2.0 → bioimageflow_segmentation_tools-0.3.2}/docs/tools/split_touching_objects.md +0 -0
  35. {bioimageflow_segmentation_tools-0.2.0 → bioimageflow_segmentation_tools-0.3.2}/docs/tools/threshold_segment.md +0 -0
  36. {bioimageflow_segmentation_tools-0.2.0 → bioimageflow_segmentation_tools-0.3.2}/docs/tools/watershed_segment.md +0 -0
  37. {bioimageflow_segmentation_tools-0.2.0 → bioimageflow_segmentation_tools-0.3.2}/tests/conftest.py +0 -0
  38. {bioimageflow_segmentation_tools-0.2.0 → bioimageflow_segmentation_tools-0.3.2}/tests/test_execution.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: bioimageflow-segmentation-tools
3
- Version: 0.2.0
3
+ Version: 0.3.2
4
4
  Summary: Segmentation tools for BioImageFlow
5
5
  Project-URL: Homepage, https://github.com/Inria-SAIRPICO/bioimageflow
6
6
  Project-URL: Documentation, https://bioimageflow.readthedocs.io/latest/
@@ -21,11 +21,7 @@ Classifier: Programming Language :: Python :: 3.12
21
21
  Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
22
22
  Classifier: Topic :: Scientific/Engineering :: Image Processing
23
23
  Requires-Python: >=3.10
24
- Requires-Dist: bioimageflow-core<0.4,>=0.3.0
25
- Requires-Dist: imageio>=2.31.0
26
- Requires-Dist: numpy>=1.23.5
27
- Requires-Dist: scikit-image>=0.21.0
28
- Requires-Dist: scipy>=1.10.0
24
+ Requires-Dist: bioimageflow-core<0.6,>=0.5.0
29
25
  Description-Content-Type: text/markdown
30
26
 
31
27
  # bioimageflow-segmentation-tools
@@ -37,6 +33,8 @@ Segmentation-focused tool package for BioImageFlow.
37
33
  - `Cellpose3`: Cellpose v3 pretrained model wrapper.
38
34
  - `CellposeSAM`: Cellpose-SAM pretrained model wrapper.
39
35
  - `StarDistSegmenter`: StarDist 2D pretrained model wrapper.
36
+ - `InstanSegSegment`: selected-target nuclei or cell segmentation with named or local InstanSeg models.
37
+ - `Nagini3DSegment`: volumetric NAGINI-3D segmentation with probability, parametric surfaces, and curvature outputs.
40
38
  - `ThresholdSegment`: threshold an intensity image and label connected foreground objects.
41
39
  - `OtsuThresholdSegment`: compute a global Otsu threshold and label foreground objects.
42
40
  - `LocalThresholdSegment`: compute a Sauvola local threshold and label foreground objects.
@@ -49,11 +47,18 @@ Segmentation-focused tool package for BioImageFlow.
49
47
  Classical connected-component tools use face connectivity by default and treat `image > threshold` as foreground when `above` is enabled. Label inputs are validated as finite, integral, non-negative arrays, and object counts are based on distinct positive IDs rather than the largest ID.
50
48
  Default label-output paths use TIFF rather than inheriting an input extension that may be lossy or unable to store UInt32 label IDs.
51
49
 
52
- Heavy model dependencies are declared in isolated `EnvironmentSpec` objects and imported only inside `process_row`. Importing this package does not require Cellpose, TensorFlow, StarDist, or other model packages to be installed in the main process.
50
+ Package discovery requires only `bioimageflow-core`.
51
+ Classical image dependencies and heavy model dependencies are declared in worker `EnvironmentSpec` objects and imported only inside `process_row`. Importing this package does not require ImageIO, NumPy, SciPy, scikit-image, Cellpose, TensorFlow, StarDist, or other model packages in the main process.
53
52
  `Cellpose3`, `CellposeSAM`, and `StarDistSegmenter` lazily keep one model per worker-side tool instance.
54
53
  Repeated calls with the same model selection reuse the weights; changing `model_type` or `model_name` replaces the cached model, and `clear_model_cache()` releases it explicitly.
55
54
  Applications can invalidate remote worker caches by stopping the corresponding Wetlands environment.
56
55
 
56
+ ## NAGINI-3D license boundary
57
+
58
+ `Nagini3DSegment` installs and executes the third-party `nagini3D` runtime, which is distributed under AGPL-3.0.
59
+ The BioImageFlow wrapper remains BSD-4-Clause, but downstream distributors must review and comply with NAGINI-3D's license before publishing an environment or product containing that runtime.
60
+ NAGINI model weights and datasets are not bundled in this package.
61
+
57
62
  The former `nnInteractive` wrapper was removed because nnInteractive requires a stateful volumetric inference session; its public point-list-to-2D-mask contract did not represent the upstream API.
58
63
 
59
64
  ## Example
@@ -7,6 +7,8 @@ Segmentation-focused tool package for BioImageFlow.
7
7
  - `Cellpose3`: Cellpose v3 pretrained model wrapper.
8
8
  - `CellposeSAM`: Cellpose-SAM pretrained model wrapper.
9
9
  - `StarDistSegmenter`: StarDist 2D pretrained model wrapper.
10
+ - `InstanSegSegment`: selected-target nuclei or cell segmentation with named or local InstanSeg models.
11
+ - `Nagini3DSegment`: volumetric NAGINI-3D segmentation with probability, parametric surfaces, and curvature outputs.
10
12
  - `ThresholdSegment`: threshold an intensity image and label connected foreground objects.
11
13
  - `OtsuThresholdSegment`: compute a global Otsu threshold and label foreground objects.
12
14
  - `LocalThresholdSegment`: compute a Sauvola local threshold and label foreground objects.
@@ -19,11 +21,18 @@ Segmentation-focused tool package for BioImageFlow.
19
21
  Classical connected-component tools use face connectivity by default and treat `image > threshold` as foreground when `above` is enabled. Label inputs are validated as finite, integral, non-negative arrays, and object counts are based on distinct positive IDs rather than the largest ID.
20
22
  Default label-output paths use TIFF rather than inheriting an input extension that may be lossy or unable to store UInt32 label IDs.
21
23
 
22
- Heavy model dependencies are declared in isolated `EnvironmentSpec` objects and imported only inside `process_row`. Importing this package does not require Cellpose, TensorFlow, StarDist, or other model packages to be installed in the main process.
24
+ Package discovery requires only `bioimageflow-core`.
25
+ Classical image dependencies and heavy model dependencies are declared in worker `EnvironmentSpec` objects and imported only inside `process_row`. Importing this package does not require ImageIO, NumPy, SciPy, scikit-image, Cellpose, TensorFlow, StarDist, or other model packages in the main process.
23
26
  `Cellpose3`, `CellposeSAM`, and `StarDistSegmenter` lazily keep one model per worker-side tool instance.
24
27
  Repeated calls with the same model selection reuse the weights; changing `model_type` or `model_name` replaces the cached model, and `clear_model_cache()` releases it explicitly.
25
28
  Applications can invalidate remote worker caches by stopping the corresponding Wetlands environment.
26
29
 
30
+ ## NAGINI-3D license boundary
31
+
32
+ `Nagini3DSegment` installs and executes the third-party `nagini3D` runtime, which is distributed under AGPL-3.0.
33
+ The BioImageFlow wrapper remains BSD-4-Clause, but downstream distributors must review and comply with NAGINI-3D's license before publishing an environment or product containing that runtime.
34
+ NAGINI model weights and datasets are not bundled in this package.
35
+
27
36
  The former `nnInteractive` wrapper was removed because nnInteractive requires a stateful volumetric inference session; its public point-list-to-2D-mask contract did not represent the upstream API.
28
37
 
29
38
  ## Example
@@ -14,6 +14,8 @@ if TYPE_CHECKING:
14
14
  from .classical import SplitTouchingObjects as SplitTouchingObjects
15
15
  from .classical import ThresholdSegment as ThresholdSegment
16
16
  from .classical import WatershedSegment as WatershedSegment
17
+ from .instanseg_segmenter import InstanSegSegment as InstanSegSegment
18
+ from .nagini3d_segmenter import Nagini3DSegment as Nagini3DSegment
17
19
  from .stardist_segmenter import StarDistSegmenter as StarDistSegmenter
18
20
 
19
21
 
@@ -22,7 +24,9 @@ _EXPORTS = {
22
24
  "Cellpose3": ("cellpose_v3", "Cellpose3"),
23
25
  "DistanceWatershedSegment": ("classical", "DistanceWatershedSegment"),
24
26
  "FilterLabels": ("classical", "FilterLabels"),
27
+ "InstanSegSegment": ("instanseg_segmenter", "InstanSegSegment"),
25
28
  "LocalThresholdSegment": ("classical", "LocalThresholdSegment"),
29
+ "Nagini3DSegment": ("nagini3d_segmenter", "Nagini3DSegment"),
26
30
  "OtsuThresholdSegment": ("classical", "OtsuThresholdSegment"),
27
31
  "PostprocessLabels": ("classical", "PostprocessLabels"),
28
32
  "SplitTouchingObjects": ("classical", "SplitTouchingObjects"),
@@ -36,7 +40,9 @@ __all__ = [
36
40
  "Cellpose3",
37
41
  "DistanceWatershedSegment",
38
42
  "FilterLabels",
43
+ "InstanSegSegment",
39
44
  "LocalThresholdSegment",
45
+ "Nagini3DSegment",
40
46
  "OtsuThresholdSegment",
41
47
  "PostprocessLabels",
42
48
  "SplitTouchingObjects",
@@ -0,0 +1,386 @@
1
+ """Production InstanSeg inference adapter."""
2
+
3
+ from dataclasses import dataclass
4
+ from pathlib import Path
5
+ from typing import Annotated, Any, Literal
6
+
7
+ from bioimageflow_core import (
8
+ Arguments,
9
+ Category,
10
+ Connectable,
11
+ EnvironmentSpec,
12
+ GUIMeta,
13
+ ImageSpec,
14
+ IOModel,
15
+ Layout,
16
+ ProcessingTool,
17
+ RowConsumption,
18
+ Semantic,
19
+ Template,
20
+ )
21
+
22
+ from ._arrays import object_count, validate_image, validate_labels, write_labels
23
+
24
+
25
+ instanseg_env = EnvironmentSpec(
26
+ name="segmentation-instanseg",
27
+ dependencies={
28
+ "python": "3.11",
29
+ "pip": [
30
+ "instanseg-torch==0.1.1",
31
+ "imageio==2.37.3",
32
+ "numpy==2.2.6",
33
+ "scikit-image==0.25.2",
34
+ "tifffile==2025.5.10",
35
+ "torch==2.7.1",
36
+ ],
37
+ },
38
+ )
39
+
40
+
41
+ @dataclass(frozen=True)
42
+ class _CachedModel:
43
+ source: str
44
+ device: str | None
45
+ metadata: tuple[str | None, str | None, str | None]
46
+ model: Any
47
+
48
+
49
+ class InstanSegSegment(ProcessingTool):
50
+ """Segment nuclei or cells with an InstanSeg model."""
51
+
52
+ row_consumption = RowConsumption.MAPPED
53
+ display_name = "InstanSeg"
54
+ documentation = (
55
+ "Segment nuclei or cells in a 2D microscopy image using a named "
56
+ "InstanSeg model or a local model bundle."
57
+ )
58
+ category = Category.SEGMENTATION
59
+ tags = ["segmentation", "instanseg", "nuclei", "cells", "deep learning"]
60
+ environment = instanseg_env
61
+
62
+ def __init__(self) -> None:
63
+ super().__init__()
64
+ self._cached_model: _CachedModel | None = None
65
+
66
+ def clear_model_cache(self) -> None:
67
+ """Release the cached model held by this tool instance."""
68
+ self._cached_model = None
69
+
70
+ def _get_model(
71
+ self,
72
+ model_source: str,
73
+ device: str | None,
74
+ metadata: tuple[str | None, str | None, str | None],
75
+ *,
76
+ named: bool,
77
+ ) -> _CachedModel:
78
+ cached = self._cached_model
79
+ if cached is None or (cached.source, cached.device, cached.metadata) != (
80
+ model_source, device, metadata
81
+ ):
82
+ from instanseg import InstanSeg # type: ignore
83
+
84
+ self.clear_model_cache()
85
+ cached = None
86
+ model = InstanSeg(
87
+ model_type=model_source,
88
+ device=device,
89
+ image_reader="skimage.io",
90
+ verbosity=0,
91
+ )
92
+ if named and metadata[2] is None:
93
+ # Acquisition can establish a previously absent local weight file.
94
+ metadata = _named_model_metadata(model_source)
95
+ cached = _CachedModel(model_source, device, metadata, model)
96
+ self._cached_model = cached
97
+ return cached
98
+
99
+ class Inputs(IOModel):
100
+ input_image: Annotated[
101
+ Path,
102
+ ImageSpec(
103
+ semantics={Semantic.INTENSITY},
104
+ layouts={Layout.PLANAR, Layout.PLANAR_CHANNEL},
105
+ ),
106
+ GUIMeta(
107
+ display_name="Input image",
108
+ description="2D intensity image, optionally with a channel axis.",
109
+ connectable=Connectable.BY_DEFAULT,
110
+ ),
111
+ ]
112
+ model_name: Annotated[
113
+ str,
114
+ GUIMeta(
115
+ display_name="Model name",
116
+ description="Official InstanSeg model name used when model_path is empty.",
117
+ ),
118
+ ] = "fluorescence_nuclei_and_cells"
119
+ model_path: Annotated[
120
+ Path | None,
121
+ GUIMeta(
122
+ display_name="Local model",
123
+ description="Optional local model bundle. Takes precedence over model_name.",
124
+ connectable=Connectable.NEVER,
125
+ ),
126
+ ] = None
127
+ target: Annotated[
128
+ Literal["nuclei", "cells"],
129
+ GUIMeta(
130
+ display_name="Target",
131
+ description="Instance type returned in the single output mask.",
132
+ ),
133
+ ] = "nuclei"
134
+ pixel_size_um: Annotated[
135
+ float | None,
136
+ GUIMeta(
137
+ display_name="Pixel size",
138
+ description="Optional physical pixel size in micrometres.",
139
+ min=0.000001,
140
+ ),
141
+ ] = None
142
+ channel_axis: Annotated[
143
+ Literal["first", "last"],
144
+ GUIMeta(
145
+ display_name="Channel axis",
146
+ description="Location of the channel axis for a three-dimensional array.",
147
+ ),
148
+ ] = "first"
149
+ channel_ids: Annotated[
150
+ list[int] | None,
151
+ GUIMeta(
152
+ display_name="Channels",
153
+ description="Optional zero-based channels passed to InstanSeg in this order.",
154
+ ),
155
+ ] = None
156
+ processing_method: Annotated[
157
+ Literal["auto", "small", "medium"],
158
+ GUIMeta(
159
+ display_name="Processing method",
160
+ description="Whole-image, tiled, or automatically selected inference.",
161
+ ),
162
+ ] = "auto"
163
+ device: Annotated[
164
+ Literal["auto", "cpu", "cuda", "mps"],
165
+ GUIMeta(display_name="Device"),
166
+ ] = "auto"
167
+
168
+ class Outputs(IOModel):
169
+ mask: Annotated[
170
+ Path,
171
+ ImageSpec(semantics={Semantic.LABEL}, layouts={Layout.PLANAR}),
172
+ GUIMeta(display_name="Segmentation mask"),
173
+ ] = Template("{input_image.stem}_instanseg_{target}_mask.tif")
174
+ object_count: Annotated[int, GUIMeta(display_name="Object count")]
175
+ model_source: Annotated[str, GUIMeta(display_name="Model source")]
176
+ model_provenance: Annotated[
177
+ Path,
178
+ GUIMeta(display_name="Model provenance"),
179
+ ] = Template("{input_image.stem}_instanseg_{target}_provenance.json")
180
+
181
+ def process_row(self, arguments: Arguments, *, context: Any = None) -> Any:
182
+ import json
183
+
184
+ import imageio.v3 as iio
185
+ import numpy as np
186
+
187
+ image = validate_image(
188
+ iio.imread(str(arguments.input_image)),
189
+ name="input_image",
190
+ dimensions=(2, 3),
191
+ )
192
+ if image.ndim == 2:
193
+ prepared = image
194
+ channel_count = 1
195
+ else:
196
+ axis = 0 if str(arguments.channel_axis) == "first" else image.ndim - 1
197
+ channel_count = int(image.shape[axis])
198
+ if channel_count < 1:
199
+ raise ValueError("input_image channel axis must not be empty.")
200
+ prepared = np.moveaxis(image, axis, 0)
201
+
202
+ channel_ids = arguments.channel_ids
203
+ if channel_ids is not None:
204
+ if not channel_ids:
205
+ raise ValueError("channel_ids must not be empty when provided.")
206
+ if any(
207
+ isinstance(value, bool)
208
+ or not isinstance(value, (int, np.integer))
209
+ or int(value) < 0
210
+ or int(value) >= channel_count
211
+ for value in channel_ids
212
+ ):
213
+ raise ValueError(
214
+ f"channel_ids must be unique zero-based indices below {channel_count}."
215
+ )
216
+ if len(set(int(value) for value in channel_ids)) != len(channel_ids):
217
+ raise ValueError("channel_ids must not contain duplicates.")
218
+ normalized_channel_ids = [int(value) for value in channel_ids]
219
+ else:
220
+ normalized_channel_ids = None
221
+
222
+ pixel_size = arguments.pixel_size_um
223
+ if pixel_size is not None:
224
+ pixel_size = float(pixel_size)
225
+ if not np.isfinite(pixel_size) or pixel_size <= 0.0:
226
+ raise ValueError("pixel_size_um must be finite and greater than zero.")
227
+
228
+ target = str(arguments.target)
229
+ if target not in {"nuclei", "cells"}:
230
+ raise ValueError("target must be 'nuclei' or 'cells'.")
231
+ processing_method = str(arguments.processing_method)
232
+ if processing_method not in {"auto", "small", "medium"}:
233
+ raise ValueError("processing_method must be 'auto', 'small', or 'medium'.")
234
+ device_name = str(arguments.device)
235
+ if device_name not in {"auto", "cpu", "cuda", "mps"}:
236
+ raise ValueError("device must be 'auto', 'cpu', 'cuda', or 'mps'.")
237
+ device = None if device_name == "auto" else device_name
238
+
239
+ model_path = arguments.model_path
240
+ if model_path is not None:
241
+ local_model = Path(model_path)
242
+ if not local_model.is_dir() or not (local_model / "instanseg.pt").is_file():
243
+ raise ValueError(
244
+ "model_path must be an InstanSeg model directory containing "
245
+ f"instanseg.pt: {local_model}"
246
+ )
247
+ model_source = str(local_model.resolve())
248
+ model_kind = "local"
249
+ model_digest = _digest_path(local_model)
250
+ model_version = None
251
+ model_url = None
252
+ else:
253
+ model_source = str(arguments.model_name).strip()
254
+ if not model_source:
255
+ raise ValueError("model_name must not be empty when model_path is not set.")
256
+ model_kind = "named"
257
+ model_version = None
258
+ model_url = None
259
+ model_digest = None
260
+
261
+ if model_kind == "named":
262
+ model_version, model_url, model_digest = _named_model_metadata(model_source)
263
+ cached = self._get_model(
264
+ model_source, device, (model_version, model_url, model_digest),
265
+ named=model_kind == "named",
266
+ )
267
+ model = cached.model
268
+ model_version, model_url, model_digest = cached.metadata
269
+ cells_and_nuclei = bool(getattr(model.instanseg, "cells_and_nuclei", False))
270
+ if target == "cells" and not cells_and_nuclei:
271
+ raise ValueError(
272
+ "The selected InstanSeg model does not provide cell segmentation."
273
+ )
274
+
275
+ kwargs: dict[str, Any] = {
276
+ "pixel_size": pixel_size,
277
+ "return_image_tensor": False,
278
+ "target": target,
279
+ }
280
+ if normalized_channel_ids is not None:
281
+ kwargs["channel_ids"] = normalized_channel_ids
282
+ method = processing_method
283
+ if method == "auto":
284
+ method = "small" if int(np.prod(prepared.shape)) <= 3 * 1500 * 1500 else "medium"
285
+ if method == "small":
286
+ prediction = model.eval_small_image(prepared, **kwargs)
287
+ else:
288
+ prediction = model.eval_medium_image(prepared, **kwargs)
289
+
290
+ labels = _instanseg_labels(prediction)
291
+ labels = validate_labels(
292
+ labels,
293
+ name="InstanSeg mask",
294
+ dimensions=(2,),
295
+ expected_shape=tuple(int(size) for size in prepared.shape[-2:]),
296
+ )
297
+ mask_path = Path(arguments.mask)
298
+ write_labels(mask_path, labels)
299
+
300
+ provenance = {
301
+ "adapter": "InstanSegSegment",
302
+ "input_sha256": _sha256_file(Path(arguments.input_image)),
303
+ "model_kind": model_kind,
304
+ "model_source": model_source,
305
+ "model_version": model_version,
306
+ "model_url": model_url,
307
+ "model_sha256": model_digest,
308
+ "target": target,
309
+ "pixel_size_um": pixel_size,
310
+ "channel_ids": normalized_channel_ids,
311
+ "processing_method": method,
312
+ "device": device_name,
313
+ }
314
+ provenance_path = Path(arguments.model_provenance)
315
+ provenance_path.parent.mkdir(parents=True, exist_ok=True)
316
+ provenance_path.write_text(json.dumps(provenance, indent=2, sort_keys=True) + "\n")
317
+ return self.Outputs(
318
+ mask=mask_path,
319
+ object_count=object_count(labels),
320
+ model_source=model_source,
321
+ model_provenance=provenance_path,
322
+ )
323
+
324
+
325
+ def _instanseg_labels(prediction: Any) -> Any:
326
+ import numpy as np
327
+
328
+ if hasattr(prediction, "detach"):
329
+ prediction = prediction.detach().cpu().numpy()
330
+ labels = np.asarray(prediction)
331
+ if labels.ndim > 2 and all(size == 1 for size in labels.shape[:-2]):
332
+ labels = labels.reshape(labels.shape[-2:])
333
+ if labels.ndim != 2:
334
+ raise ValueError(
335
+ "InstanSeg selected-target prediction must contain one 2D label image; "
336
+ f"got shape {labels.shape}."
337
+ )
338
+ return labels
339
+
340
+
341
+ def _sha256_file(path: Path) -> str:
342
+ import hashlib
343
+
344
+ digest = hashlib.sha256()
345
+ with path.open("rb") as stream:
346
+ for chunk in iter(lambda: stream.read(1024 * 1024), b""):
347
+ digest.update(chunk)
348
+ return digest.hexdigest()
349
+
350
+
351
+ def _digest_path(path: Path) -> str:
352
+ import hashlib
353
+
354
+ if path.is_file():
355
+ return _sha256_file(path)
356
+ digest = hashlib.sha256()
357
+ for child in sorted(candidate for candidate in path.rglob("*") if candidate.is_file()):
358
+ digest.update(child.relative_to(path).as_posix().encode())
359
+ digest.update(bytes.fromhex(_sha256_file(child)))
360
+ return digest.hexdigest()
361
+
362
+
363
+ def _named_model_metadata(model_name: str) -> tuple[str | None, str | None, str | None]:
364
+ import importlib.resources
365
+ import json
366
+ import os
367
+
368
+ try:
369
+ index_path = importlib.resources.files("instanseg").joinpath(
370
+ "bioimageio_models/model-index.json"
371
+ )
372
+ models = json.loads(index_path.read_text())
373
+ except (AttributeError, FileNotFoundError, ModuleNotFoundError, TypeError):
374
+ return None, None, None
375
+ matches = [model for model in models if model.get("name") == model_name]
376
+ if not matches:
377
+ return None, None, None
378
+ selected = matches[0]
379
+ version = str(selected["version"])
380
+ url = str(selected["url"])
381
+ base = os.environ.get("INSTANSEG_BIOIMAGEIO_PATH")
382
+ if base is None:
383
+ return version, url, None
384
+ weights = Path(base) / model_name / version / "instanseg.pt"
385
+ digest = _sha256_file(weights) if weights.is_file() else None
386
+ return version, url, digest