wsi-patching 0.5.0__py3-none-any.whl

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 (50) hide show
  1. wsi_patching/__init__.py +38 -0
  2. wsi_patching/annotations/__init__.py +3 -0
  3. wsi_patching/annotations/add_cell_annotation_from_csv.py +152 -0
  4. wsi_patching/assets/models/cellvit_tissue_detector.pt +0 -0
  5. wsi_patching/backends/__init__.py +0 -0
  6. wsi_patching/backends/cupy_numpy.py +80 -0
  7. wsi_patching/backends/fastslide.py +243 -0
  8. wsi_patching/backends/torch_device.py +45 -0
  9. wsi_patching/core/__init__.py +4 -0
  10. wsi_patching/core/chunking_and_batching.py +519 -0
  11. wsi_patching/core/pipeline.py +566 -0
  12. wsi_patching/core/types/__init__.py +0 -0
  13. wsi_patching/core/types/types.py +145 -0
  14. wsi_patching/core/types/util_types.py +93 -0
  15. wsi_patching/core/wsi_grid.py +119 -0
  16. wsi_patching/custom_component/__init__.py +18 -0
  17. wsi_patching/encoders/__init__.py +3 -0
  18. wsi_patching/encoders/pngencoder.py +72 -0
  19. wsi_patching/filtering/__init__.py +15 -0
  20. wsi_patching/filtering/cellvit_tissue_classifier_filter.py +124 -0
  21. wsi_patching/filtering/low_contrast_background_filter.py +125 -0
  22. wsi_patching/filtering/otsu_filter.py +217 -0
  23. wsi_patching/filtering/pen_artifact_filter.py +216 -0
  24. wsi_patching/py.typed +0 -0
  25. wsi_patching/regions_of_interest/__init__.py +4 -0
  26. wsi_patching/regions_of_interest/attach_rois.py +59 -0
  27. wsi_patching/regions_of_interest/roi_providers.py +94 -0
  28. wsi_patching/regions_of_interest/rois.py +78 -0
  29. wsi_patching/transforms/__init__.py +4 -0
  30. wsi_patching/transforms/macenko_normalizer.py +175 -0
  31. wsi_patching/transforms/reinhard_normalizer.py +271 -0
  32. wsi_patching/utils/__init__.py +3 -0
  33. wsi_patching/utils/logging_config.py +13 -0
  34. wsi_patching/utils/meta_typing.py +94 -0
  35. wsi_patching/utils/profiling.py +115 -0
  36. wsi_patching/utils/wsi_thumbnail_visualization.py +208 -0
  37. wsi_patching/writers/__init__.py +10 -0
  38. wsi_patching/writers/materialize_writers/__init__.py +0 -0
  39. wsi_patching/writers/materialize_writers/materialize_writer_base.py +92 -0
  40. wsi_patching/writers/materialize_writers/webdataset/__init__.py +0 -0
  41. wsi_patching/writers/materialize_writers/webdataset/webdataset_loader.py +165 -0
  42. wsi_patching/writers/materialize_writers/webdataset/webdataset_writer.py +69 -0
  43. wsi_patching/writers/stream_writers/__init__.py +0 -0
  44. wsi_patching/writers/stream_writers/numpy_stream_writer.py +36 -0
  45. wsi_patching/writers/stream_writers/stream_writer_base.py +71 -0
  46. wsi_patching/writers/stream_writers/torch_stream_writer.py +67 -0
  47. wsi_patching-0.5.0.dist-info/METADATA +249 -0
  48. wsi_patching-0.5.0.dist-info/RECORD +50 -0
  49. wsi_patching-0.5.0.dist-info/WHEEL +4 -0
  50. wsi_patching-0.5.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,519 @@
1
+ import math
2
+ from typing import Any, Iterable, List, Literal, Optional, Tuple, Union, cast
3
+
4
+ import cv2
5
+ import numpy as np
6
+
7
+ from wsi_patching.backends.cupy_numpy import get_xp_backend
8
+ from wsi_patching.backends.fastslide import read_region
9
+ from wsi_patching.core.pipeline import Stage
10
+ from wsi_patching.core.types.types import CollatedPatchBatch, RegionTask, Slide, SlideWithROIs, TilePlan
11
+ from wsi_patching.regions_of_interest.roi_providers import WholeSlideProvider
12
+ from wsi_patching.regions_of_interest.rois import ROI, BoxROI
13
+
14
+ _CV2_INTERPOLATION = {
15
+ "nearest": cv2.INTER_NEAREST,
16
+ "linear": cv2.INTER_LINEAR,
17
+ "cubic": cv2.INTER_CUBIC,
18
+ "area": cv2.INTER_AREA,
19
+ "lanczos": cv2.INTER_LANCZOS4,
20
+ }
21
+
22
+
23
+ class TilePlanner(Stage):
24
+ """
25
+ Divide slides (with or without ROIs) into patches on a regular grid.
26
+
27
+ The TilePlanner emits a TilePlan. Each TilePlan corresponds to a single slide,
28
+ and has a list of coordinates corresponding to patches to be extracted.
29
+ If ROIs are attached to the slide, all generated coordinates will lie within the ROIs.
30
+ If no ROIs are attached, the WholeSlideProvider is used to generate a single ROI
31
+ covering the entire slide.
32
+
33
+ tile_selection_mode:
34
+ - "any_overlap" (default): accept tile if any pixel overlaps ROI.
35
+ - "full_inside_bounds": accept tile only if fully inside ROI bounds rectangle (exact for BoxROI).
36
+ - "center_in_roi": accept tile if its center is inside ROI.
37
+ """
38
+
39
+ def __init__(
40
+ self,
41
+ tile_size: int,
42
+ stride: int,
43
+ tile_selection_mode: Literal["any_overlap", "full_inside_bounds", "center_in_roi"] = "any_overlap",
44
+ ):
45
+ """
46
+ Args:
47
+ tile_size: size of square patches to extract
48
+ stride: spacing between patch top-left corners of each of the patches
49
+ tile_selection_mode: how to select tiles with respect to ROIs.
50
+ - "any_overlap": accept tile if any pixel overlaps ROI.
51
+ - "full_inside_bounds": accept tile only if fully inside ROI bounds rectangle (exact for BoxROI).
52
+ - "center_in_roi": accept tile if its center is inside ROI.
53
+ """
54
+ self.tile_size = tile_size
55
+ self.stride = stride
56
+ self.tile_selection_mode = tile_selection_mode
57
+
58
+ def export_context(self, ctx) -> None:
59
+ ctx["tile_size"] = self.tile_size
60
+ ctx["stride"] = self.stride
61
+
62
+ def validate(self) -> None:
63
+ self.ctx.require_key("tile_size")
64
+ self.ctx.require_key("stride")
65
+
66
+ if self.ctx["tile_size"] <= 0:
67
+ raise ValueError("Tile size must be positive")
68
+ if self.ctx["stride"] <= 0:
69
+ raise ValueError("Stride must be positive")
70
+ if self.ctx["stride"] > self.ctx["tile_size"]:
71
+ self.log.warning("Stride is larger than tile size, resulting in gaps between tiles.")
72
+
73
+ def __call__(self, it: Iterable[Union[Slide, SlideWithROIs]]) -> Iterable[TilePlan]:
74
+ tile_size = int(self.ctx["tile_size"])
75
+ stride = int(self.ctx["stride"])
76
+
77
+ for s in it:
78
+ rois = getattr(s, "rois", None) or WholeSlideProvider().for_slide(s)
79
+ W, H = s.dims
80
+ for idx, roi in enumerate(rois):
81
+ bx, by, bw, bh = roi.bounds()
82
+ x1 = min(bx + bw, W)
83
+ y1 = min(by + bh, H)
84
+
85
+ tiles = self._generate_tiles_vectorized(roi, bx, by, bw, bh, x1, y1, tile_size, stride)
86
+
87
+ if tiles:
88
+ yield TilePlan(
89
+ wsi_id=s.wsi_id,
90
+ wsi_path=s.wsi_path,
91
+ dims=s.dims,
92
+ level=s.level,
93
+ roi_index=idx,
94
+ roi_bounds=(bx, by, bw, bh),
95
+ tiles=tiles,
96
+ downsample=s.downsample,
97
+ resample_factor=s.resample_factor,
98
+ meta={
99
+ **s.meta,
100
+ "roi_bounds": (bx, by, bw, bh),
101
+ "slide.stride": stride,
102
+ "slide.tile_size": tile_size,
103
+ },
104
+ )
105
+ else:
106
+ self.log.warning(f"No tiles found for slide {s.wsi_id} ROI {idx} bounds {bx, by, bw, bh}")
107
+
108
+ def _axis_positions(self, start: int, end: int, tile_size: int, stride: int) -> List[int]:
109
+ """
110
+ Generate tile start positions along a single axis.
111
+
112
+ Assumes stride < tile_size if you want overlap & full coverage.
113
+ """
114
+ roi_len = end - start
115
+
116
+ # 1) ROI smaller than a tile: just one tile anchored at start.
117
+ if roi_len <= tile_size:
118
+ return [start]
119
+
120
+ # 2) Normal case: stride < tile_size, ROI larger than tile.
121
+ positions: List[int] = []
122
+ pos = start
123
+
124
+ # keep stepping as long as "previous start + tile_size" still needs to reach 'end'
125
+ last_tile_correction = -stride + tile_size if stride < tile_size else 0
126
+ while pos + last_tile_correction < end:
127
+ positions.append(pos)
128
+ pos += stride
129
+
130
+ return positions
131
+
132
+ def _generate_tiles_vectorized(
133
+ self, roi: ROI, bx: int, by: int, bw: int, bh: int, x1: int, y1: int, tile_size: int, stride: int
134
+ ) -> List[Tuple[int, int]]:
135
+ """Generate accepted tile positions using numpy operations where possible.
136
+
137
+ For BoxROI, acceptance checks are fully vectorized. For other ROI types,
138
+ grid generation is vectorized but per-tile filtering falls back to scalar.
139
+ """
140
+ last_tile_correction = max(0, tile_size - stride)
141
+
142
+ # Generate x positions
143
+ roi_w = x1 - bx
144
+ if roi_w <= tile_size:
145
+ xs = np.array([bx], dtype=np.int64)
146
+ else:
147
+ xs = np.arange(bx, x1 - last_tile_correction, stride, dtype=np.int64)
148
+
149
+ # Generate y positions
150
+ roi_h = y1 - by
151
+ if roi_h <= tile_size:
152
+ ys = np.array([by], dtype=np.int64)
153
+ else:
154
+ ys = np.arange(by, y1 - last_tile_correction, stride, dtype=np.int64)
155
+
156
+ # Build full grid of (tx, ty) pairs
157
+ gx, gy = np.meshgrid(xs, ys)
158
+ tx = gx.ravel()
159
+ ty = gy.ravel()
160
+
161
+ if isinstance(roi, BoxROI):
162
+ mode = self.tile_selection_mode
163
+ if mode == "any_overlap":
164
+ # All positions are within ROI bounding box by construction; top-left
165
+ # corner is always inside, so intersects_patch is always True.
166
+ pass # tx/ty already the full set
167
+ elif mode == "full_inside_bounds":
168
+ mask = (tx + tile_size <= bx + bw) & (ty + tile_size <= by + bh)
169
+ tx, ty = tx[mask], ty[mask]
170
+ elif mode == "center_in_roi":
171
+ cx = tx + tile_size / 2.0
172
+ cy = ty + tile_size / 2.0
173
+ mask = (cx < bx + bw) & (cy < by + bh)
174
+ tx, ty = tx[mask], ty[mask]
175
+ return list(zip(tx.tolist(), ty.tolist()))
176
+
177
+ # Non-BoxROI: scalar fallback for per-tile acceptance
178
+ result: List[Tuple[int, int]] = []
179
+ for txx, tyy in zip(tx.tolist(), ty.tolist()):
180
+ if self._accept_tile(roi, txx, tyy, tile_size):
181
+ result.append((txx, tyy))
182
+ return result
183
+
184
+ def _accept_tile(self, roi: ROI, tx: int, ty: int, tile_size: int) -> bool:
185
+ mode = self.tile_selection_mode
186
+
187
+ if mode == "any_overlap":
188
+ return roi.intersects_patch(tx, ty, tile_size, tile_size)
189
+ elif mode == "full_inside_bounds":
190
+ return roi.contains_patch(tx, ty, tile_size, tile_size)
191
+ elif mode == "center_in_roi":
192
+ cx = tx + tile_size / 2.0
193
+ cy = ty + tile_size / 2.0
194
+ return roi.contains_point(cx, cy)
195
+ else:
196
+ raise ValueError(f"TilePlanner: unknown tile_selection_mode '{mode}'")
197
+
198
+
199
+ class ReadWindowChunker(Stage):
200
+ """
201
+ Packs tiles into rectangular read windows of max_window_size.
202
+
203
+ The goal here is to batch together coordinates that lie closely together.
204
+ These can be read as a single large region read from the WSI, and then sliced into individual patches.
205
+ Since the region read is square, we group together patches that fit in a square.
206
+ Each slide object is split into one or more region tasks dependend on the max_window_size.
207
+ Controlling the max_window_size is a tradeoff between memory use and read efficiency.
208
+ A larger window size means fewer, larger reads, but more memory use.
209
+ A smaller window size means more, smaller reads, and less memory use.
210
+ As the library multiprocesses over slides, reading in complete slides for each cpu might be too much memory.
211
+ """
212
+
213
+ def __init__(self, max_window_size: Optional[int] = None):
214
+ self.max_window_size = max_window_size
215
+
216
+ def validate(self) -> None:
217
+ self.ctx.require_key("stride")
218
+
219
+ if self.max_window_size is None:
220
+ self.max_window_size = (5000 // self.ctx["stride"]) * self.ctx["stride"]
221
+ self.log.info(f"Defaulting max_window_size to (5000//stride)*stride={self.max_window_size}")
222
+
223
+ if self.max_window_size % self.ctx["stride"] != 0:
224
+ raise ValueError(
225
+ "ReadWindowChunker: max_window_size must be a multiple of stride to avoid unnecessary padding"
226
+ )
227
+
228
+ if self.max_window_size > 10000:
229
+ self.log.warning(
230
+ f"max_window_size {self.max_window_size} is quite large, "
231
+ "this may lead to high memory usage and OOM errors. Consider reducing it."
232
+ )
233
+
234
+ def __call__(self, it: Iterable[TilePlan]) -> Iterable[RegionTask]:
235
+ tile_size = int(self.ctx["tile_size"])
236
+ stride = int(self.ctx["stride"])
237
+ overlap = max(0, tile_size - stride) # e.g. 64 when tile_size=1022, stride=958
238
+ mws = self.max_window_size
239
+ assert mws is not None
240
+
241
+ for plan in it:
242
+ bx, by, bw, bh = plan.roi_bounds
243
+ W, H = plan.dims
244
+ if not plan.tiles:
245
+ self.log.warning(f"No tiles in plan for slide {plan.wsi_id} ROI {plan.roi_index}")
246
+ continue
247
+
248
+ x_roi_end, y_roi_end = min(bx + bw, W), min(by + bh, H)
249
+
250
+ # Number of base windows along each axis
251
+ n_x_win = max(1, math.ceil((x_roi_end - bx) / mws))
252
+ n_y_win = max(1, math.ceil((y_roi_end - by) / mws))
253
+
254
+ # Assign each tile to a window index using numpy vectorised division
255
+ tiles_arr = np.array(plan.tiles, dtype=np.int64) # (N, 2)
256
+ win_x = np.clip((tiles_arr[:, 0] - bx) // mws, 0, n_x_win - 1)
257
+ win_y = np.clip((tiles_arr[:, 1] - by) // mws, 0, n_y_win - 1)
258
+
259
+ # Stable sort by combined window key so groups come out in scan order
260
+ win_key = win_y * n_x_win + win_x
261
+ order = np.argsort(win_key, kind="stable")
262
+ sorted_keys = win_key[order]
263
+
264
+ boundaries = np.where(np.diff(sorted_keys) != 0)[0] + 1
265
+ groups = np.split(order, boundaries)
266
+ unique_keys = sorted_keys[np.concatenate([[0], boundaries])]
267
+
268
+ for group_indices, ukey in zip(groups, unique_keys.tolist()):
269
+ wx = int(ukey % n_x_win)
270
+ wy = int(ukey // n_x_win)
271
+
272
+ x_region_start = bx + wx * mws
273
+ y_region_start = by + wy * mws
274
+
275
+ # Base window size (defines ownership; READ window is expanded by overlap)
276
+ base_w = min(mws, x_roi_end - x_region_start)
277
+ base_h = min(mws, y_roi_end - y_region_start)
278
+ read_w = min(base_w + overlap, x_roi_end - x_region_start)
279
+ read_h = min(base_h + overlap, y_roi_end - y_region_start)
280
+
281
+ in_window: List[Tuple[int, int]] = [tuple(t) for t in tiles_arr[group_indices].tolist()]
282
+
283
+ if in_window:
284
+ yield RegionTask(
285
+ wsi_id=plan.wsi_id,
286
+ wsi_path=plan.wsi_path,
287
+ wsi_dims=plan.dims,
288
+ level=plan.level,
289
+ region=(x_region_start, y_region_start, read_w, read_h),
290
+ tiles=in_window,
291
+ downsample=plan.downsample,
292
+ resample_factor=plan.resample_factor,
293
+ meta=plan.meta,
294
+ )
295
+
296
+
297
+ class RegionReadAndBatch(Stage):
298
+ """
299
+ For each RegionTask:
300
+ - open slide (per-process, no sharing)
301
+ - read the entire region once
302
+ - slice region into tile patches
303
+ - Pad or drop patches at the wsi edge according to edge_policy
304
+ - accumulate into batches of 'batch_size', yield {"batch": [samples,...]}
305
+ - Output patch batches are of shape [B, H, W, C]
306
+ - Output patches are of type dtype (default np.uint8) and are within range [0, 255]
307
+ - Changing dtype to e.g. np.float32 is allowed, but no normalization is applied
308
+ """
309
+
310
+ def __init__(
311
+ self,
312
+ batch_size: int = 200,
313
+ wsi_edge_policy: Literal["drop", "pad_with_zeros", "pad_with_edge"] = "pad_with_zeros",
314
+ roi_edge_policy: Literal["read_from_image", "use_wsi_edge_policy"] = "use_wsi_edge_policy",
315
+ dtype: Any = np.uint8,
316
+ ):
317
+ """
318
+ Args:
319
+ batch_size: Maximum number of patches per output batch
320
+ wsi_edge_policy: how to handle tiles that extend beyond the WSI edge.
321
+ - "drop": drop incomplete tiles
322
+ - "pad_with_zeros": right/bottom pad incomplete tiles with zeros
323
+ - "pad_with_edge": right/bottom pad incomplete tiles with edge pixel values
324
+ roi_edge_policy: how to handle tiles that extend beyond the ROI bounds.
325
+ - "read_from_image": expand region bounds to next full tile_size multiple, read from image,
326
+ and apply wsi_edge_policy to any incomplete tiles at the WSI edge.
327
+ - "use_wsi_edge_policy": do not expand ROI bounds, read as-is from image,
328
+ and apply wsi_edge_policy to any incomplete tiles at the region or WSI edge.
329
+ dtype: output patch dtype, e.g. np.uint8 or np.float32
330
+ """
331
+ self.batch_size = int(batch_size)
332
+ self.dtype = dtype
333
+ self.roi_edge_policy = roi_edge_policy
334
+ self.wsi_edge_policy = wsi_edge_policy
335
+
336
+ def validate(self) -> None:
337
+ self.ctx.require_key("tile_size")
338
+ self.ctx.require_key("use_gpu")
339
+
340
+ if self.wsi_edge_policy not in {"drop", "pad_with_zeros", "pad_with_edge"}:
341
+ raise ValueError(f"Unknown edge_policy '{self.wsi_edge_policy}'")
342
+
343
+ def __call__(self, it: Iterable[RegionTask]) -> Iterable[CollatedPatchBatch]:
344
+ xp = get_xp_backend(self.ctx["use_gpu"])
345
+ tile_size = int(self.ctx["tile_size"])
346
+
347
+ for task in it:
348
+ x0, y0, w, h = task.region
349
+
350
+ if self.roi_edge_policy == "read_from_image":
351
+ # Compute the minimum region size needed so that every tile can be fully
352
+ # sliced without running off the end of the read buffer. Using
353
+ # `w % tile_size` is fragile: when w happens to be a multiple of
354
+ # tile_size the check is silently skipped even though the rightmost /
355
+ # bottom-most tiles may still extend well beyond w (e.g. tile_size=256,
356
+ # stride=192, ROI width=512 → last tile at x=384 needs 640 px but the
357
+ # read window is only 512 wide).
358
+ required_w = max(tx - x0 + tile_size for tx, ty in task.tiles)
359
+ required_h = max(ty - y0 + tile_size for tx, ty in task.tiles)
360
+ if w < required_w:
361
+ w = min(required_w, task.wsi_dims[0] - x0)
362
+ if h < required_h:
363
+ h = min(required_h, task.wsi_dims[1] - y0)
364
+
365
+ # Convert level-N coordinates to level-0 for the read_region() call, which
366
+ # backend expects in level-0 space.
367
+ # round() gives the nearest integer, which is correct for both integer and
368
+ # non-integer downsample factors.
369
+ ds = task.downsample
370
+ x0_l0 = round(x0 * ds)
371
+ y0_l0 = round(y0 * ds)
372
+
373
+ rf = task.resample_factor
374
+ if rf != 1.0:
375
+ read_w = round(w * rf)
376
+ read_h = round(h * rf)
377
+ else:
378
+ read_w, read_h = w, h
379
+
380
+ region_img = read_region(task.wsi_path, x0_l0, y0_l0, read_w, read_h, task.level)
381
+
382
+ if rf != 1.0:
383
+ interp = _CV2_INTERPOLATION[self.ctx.get("resample_interpolation", "lanczos")]
384
+ region_img = cv2.resize(region_img, (w, h), interpolation=interp)
385
+
386
+ n_tiles = len(task.tiles)
387
+ buf_size = min(n_tiles, self.batch_size)
388
+ batch_buf = np.empty((buf_size, tile_size, tile_size, 3), dtype=np.uint8)
389
+ coords_buf = np.empty((buf_size, 2), dtype=np.int64)
390
+ fill_idx = 0
391
+
392
+ for tx, ty in task.tiles:
393
+ rx, ry = tx - x0, ty - y0
394
+ patch = region_img[ry : ry + tile_size, rx : rx + tile_size, :]
395
+ if patch.shape[:2] != (tile_size, tile_size):
396
+ if self.wsi_edge_policy == "drop":
397
+ continue
398
+ patch = self._pad_to_tile_size(patch, tile_size, xp)
399
+
400
+ batch_buf[fill_idx] = patch
401
+ coords_buf[fill_idx, 0] = tx
402
+ coords_buf[fill_idx, 1] = ty
403
+ fill_idx += 1
404
+
405
+ if fill_idx >= self.batch_size:
406
+ yield self._make_batch_from_buf(task, coords_buf[:fill_idx], batch_buf[:fill_idx], xp)
407
+ fill_idx = 0
408
+
409
+ if fill_idx > 0:
410
+ yield self._make_batch_from_buf(task, coords_buf[:fill_idx], batch_buf[:fill_idx], xp)
411
+
412
+ def _make_batch_from_buf(self, task, coords_slice: np.ndarray, batch_slice: np.ndarray, xp):
413
+ # Both .copy() calls are mandatory: xp.asarray on CPU with matching dtype
414
+ # returns a view of the buffer, which is reused on the next batch iteration.
415
+ coords_out = coords_slice.copy()
416
+ patches_xp = xp.asarray(batch_slice.copy(), dtype=self.dtype)
417
+ cpb = CollatedPatchBatch(task.wsi_id, coords_out, patches_xp, use_gpu=self.ctx["use_gpu"])
418
+ for k, v in task.meta.items():
419
+ cpb.add_meta_column(k, np.array([v] * len(coords_out)))
420
+ return cpb
421
+
422
+ def _pad_to_tile_size(self, patch, tile_size: int, xp_module):
423
+ """Right/bottom pad to (tile_size, tile_size). Works for numpy or cupy arrays."""
424
+ h, w = int(patch.shape[0]), int(patch.shape[1])
425
+ pad_h = max(0, tile_size - h)
426
+ pad_w = max(0, tile_size - w)
427
+ if pad_h == 0 and pad_w == 0:
428
+ return patch
429
+
430
+ pad_spec = ((0, pad_h), (0, pad_w), (0, 0))
431
+
432
+ if self.wsi_edge_policy == "pad_with_zeros":
433
+ return np.pad(patch, pad_spec, mode="constant", constant_values=0)
434
+ elif self.wsi_edge_policy == "pad_with_edge":
435
+ return np.pad(patch, pad_spec, mode="edge")
436
+ else:
437
+ raise ValueError(f"Unknown edge_policy '{self.wsi_edge_policy}'")
438
+
439
+
440
+ class PatchExtractor(Stage):
441
+ """
442
+ PatchExtractor is a composite stage that combines TilePlanner, ReadWindowChunker, and RegionReadAndBatch.
443
+
444
+ It takes slides (with or without ROIs) as input, and outputs batches of image patches.
445
+ It handles tile planning, region chunking, reading, and batching internally.
446
+ This is a convenience stage for common use cases where you want to extract patches from slides.
447
+ """
448
+
449
+ def __init__(
450
+ self,
451
+ *,
452
+ tile_size: int,
453
+ stride: int,
454
+ tile_selection_mode: Literal["any_overlap", "full_inside_bounds", "center_in_roi"] = "any_overlap",
455
+ max_batch_size: int = 200,
456
+ wsi_edge_policy: Literal["drop", "pad_with_zeros", "pad_with_edge"] = "pad_with_zeros",
457
+ roi_edge_policy: Literal["read_from_image", "use_wsi_edge_policy"] = "use_wsi_edge_policy",
458
+ dtype: Any = np.uint8,
459
+ max_window_size: Optional[int] = None,
460
+ ):
461
+ """
462
+ Args:
463
+ tile_size: size of square patches to extract
464
+ stride: spacing between patch top-left corners of each of the patches
465
+ tile_selection_mode: how to select tiles with respect to ROIs.
466
+ max_batch_size: Maximum number of patches per output batch
467
+ wsi_edge_policy: how to handle tiles that extend beyond the WSI edge.
468
+ - "drop": drop incomplete tiles
469
+ - "pad_with_zeros": right/bottom pad incomplete tiles with zeros
470
+ - "pad_with_edge": right/bottom pad incomplete tiles with edge pixel values
471
+ roi_edge_policy: how to handle tiles that extend beyond the ROI bounds.
472
+ - "read_from_image": expand region bounds to next full tile_size multiple, read from image,
473
+ and apply wsi_edge_policy to any incomplete tiles at the WSI edge.
474
+ - "use_wsi_edge_policy": do not expand ROI bounds, read as-is from image,
475
+ and apply wsi_edge_policy to any incomplete tiles at the region or WSI edge.
476
+ dtype: output patch dtype, e.g. np.uint8 or np.float32
477
+ max_window_size: maximum size of square read windows. If None, defaults to 20*tile_size.
478
+ """
479
+ self.params = dict(
480
+ tile_size=tile_size,
481
+ stride=stride,
482
+ tile_selection_mode=tile_selection_mode,
483
+ max_window_size=max_window_size,
484
+ batch_size=max_batch_size,
485
+ dtype=dtype,
486
+ wsi_edge_policy=wsi_edge_policy,
487
+ roi_edge_policy=roi_edge_policy,
488
+ )
489
+
490
+ # Internal stages (created now; context attached later)
491
+ self._tp = TilePlanner(tile_size=tile_size, stride=stride, tile_selection_mode=tile_selection_mode)
492
+ self._rwc = ReadWindowChunker(max_window_size=max_window_size)
493
+ self._rbb = RegionReadAndBatch(
494
+ batch_size=max_batch_size, dtype=dtype, wsi_edge_policy=wsi_edge_policy, roi_edge_policy=roi_edge_policy
495
+ )
496
+ self._substages: List[Stage] = [self._tp, self._rwc, self._rbb]
497
+
498
+ def export_context(self, ctx) -> None:
499
+ for s in self._substages:
500
+ s.export_context(ctx)
501
+
502
+ def attach_context(self, ctx) -> None:
503
+ super().attach_context(ctx) # gives self.ctx, self.log
504
+ # Propagate context to inner stages
505
+ for s in self._substages:
506
+ s.attach_context(ctx)
507
+
508
+ def validate(self) -> None:
509
+ # Export context to inner stages, then validate each
510
+ for s in self._substages:
511
+ s.export_context(self.ctx)
512
+ for s in self._substages:
513
+ s.validate()
514
+
515
+ def __call__(self, it: Iterable[Union[Slide, SlideWithROIs]]) -> Iterable[CollatedPatchBatch]:
516
+ stream = it
517
+ for s in self._substages:
518
+ stream = s(stream)
519
+ return cast(Iterable[CollatedPatchBatch], stream)