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