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,94 @@
1
+ import collections.abc as cabc
2
+ from typing import Any, Iterable, Union, get_args, get_origin
3
+
4
+
5
+ class StageMeta(type):
6
+ def __new__(mcls, name, bases, ns, **kw):
7
+ cls = super().__new__(mcls, name, bases, ns)
8
+ in_t = getattr(cls, "input_type", object)
9
+ out_t = getattr(cls, "output_type", object)
10
+ in_t, out_t = _infer_types_from_annotations(
11
+ ns.get("__call__"), in_key="it", out_key="return", default_in=in_t, default_out=out_t
12
+ )
13
+ setattr(cls, "input_type", in_t)
14
+ setattr(cls, "output_type", out_t)
15
+ if getattr(cls, "input_type") is object or getattr(cls, "output_type") is object:
16
+ raise ValueError(f"{name}: __call__ must have type annotations for both 'it' and return")
17
+ return cls
18
+
19
+
20
+ class WriterMeta(type):
21
+ def __new__(mcls, name, bases, ns, **kw):
22
+ cls = super().__new__(mcls, name, bases, ns)
23
+ in_t = getattr(cls, "input_type", object)
24
+ in_t, _ = _infer_types_from_annotations(
25
+ ns.get("write") or ns.get("stream"), in_key="batch", default_in=in_t, default_out=None
26
+ )
27
+ setattr(cls, "input_type", in_t)
28
+ if getattr(cls, "input_type") is object:
29
+ raise ValueError(f"{name}: write() must annotate its 'batch' parameter type")
30
+ return cls
31
+
32
+
33
+ def _infer_types_from_annotations(func, in_key=None, out_key=None, default_in=object, default_out=object):
34
+ in_t, out_t = default_in, default_out
35
+ if func and hasattr(func, "__annotations__"):
36
+ ann = func.__annotations__
37
+ if in_key:
38
+ in_t = _iter_payload(ann.get(in_key)) or in_t
39
+ if out_key:
40
+ out_t = _iter_payload(ann.get(out_key)) or out_t
41
+ return in_t, out_t
42
+
43
+
44
+ class PipelineContext(dict):
45
+ def require_key(self, key: str):
46
+ if key not in self:
47
+ raise KeyError(f"Missing required context key: '{key}'")
48
+
49
+
50
+ class ContextAware:
51
+ """Mixin for pipeline components that want a PipelineContext."""
52
+
53
+ _ctx: PipelineContext
54
+
55
+ def attach_context(self, ctx: PipelineContext) -> None:
56
+ self._ctx = ctx
57
+
58
+ def export_context(self, ctx: PipelineContext) -> None:
59
+ pass
60
+
61
+ def validate(self) -> None:
62
+ pass
63
+
64
+ @property
65
+ def ctx(self) -> PipelineContext:
66
+ if not hasattr(self, "_ctx"):
67
+ return PipelineContext()
68
+ return self._ctx
69
+
70
+
71
+ # -------- Annotation utilities --------
72
+ def _iter_payload(t: Any) -> Any:
73
+ """Extract T from Iterable[T]; support Union[T1, T2] and | unions."""
74
+ if t is None:
75
+ return object
76
+ origin = get_origin(t)
77
+
78
+ # Iterable[T]
79
+ if origin in (list, tuple, set, frozenset, iter, Iterable, cabc.Iterable):
80
+ args = get_args(t)
81
+ if not args:
82
+ return object
83
+ payload = args[0]
84
+ return _unwrap_union(payload)
85
+
86
+ # Already a Union or plain class
87
+ return _unwrap_union(t)
88
+
89
+
90
+ def _unwrap_union(t: Any) -> Any:
91
+ origin = get_origin(t)
92
+ if origin is Union or str(origin).endswith("types.UnionType"):
93
+ return tuple(a for a in get_args(t) if a is not type(None))
94
+ return t
@@ -0,0 +1,115 @@
1
+ import logging
2
+ import threading
3
+ from typing import Any, Dict, Optional, Union
4
+
5
+ logger = logging.getLogger(__name__)
6
+
7
+
8
+ class Profiler:
9
+ """Per-process profiler, but only used for isolated timings (manual calls)."""
10
+
11
+ def __init__(self, enabled: bool, slide_id: str):
12
+ self.enabled = bool(enabled)
13
+ self.slide_id = slide_id
14
+ self._stats: Dict[str, Dict[str, Union[float, int]]] = {}
15
+
16
+ def _ensure(self, stage_name: str):
17
+ if stage_name not in self._stats:
18
+ self._stats[stage_name] = {"wall_time_sec": 0.0, "yields": 0}
19
+
20
+ def add_time(self, stage_name: str, dt: float, yielded: bool):
21
+ """Record time spent. If `yielded` is True, increment yield count.
22
+
23
+ Yield represents whether the computation eventually produced an output item for the stage generator.
24
+ """
25
+ if not self.enabled:
26
+ return
27
+ self._ensure(stage_name)
28
+ self._stats[stage_name]["wall_time_sec"] = float(self._stats[stage_name]["wall_time_sec"]) + float(dt)
29
+ if yielded:
30
+ self._stats[stage_name]["yields"] = int(self._stats[stage_name]["yields"]) + 1
31
+
32
+ def serialize(self) -> Dict[str, Any]:
33
+ return {"slide_id": self.slide_id, "stages": self._stats}
34
+
35
+
36
+ class PipelineProfileAggregator:
37
+ """
38
+ Collects per-process _Profiler summaries and exposes an aggregated view
39
+ with the same shape you had before:
40
+ - get_profile(): {"by_stage": {...}, "by_slide": {...}}
41
+ - print_profile(): pretty console output
42
+ """
43
+
44
+ def __init__(self) -> None:
45
+ self.reset()
46
+
47
+ def reset(self) -> None:
48
+ self._agg: Dict[str, Any] = {"by_stage": {}, "by_slide": {}}
49
+
50
+ def ingest_msg(self, msg: Dict[str, Any]) -> None:
51
+ """Ingest a single producer summary message."""
52
+ slide_id = msg.get("slide_id", "<unknown>")
53
+ stages: Dict[str, Dict[str, Union[float, int]]] = msg.get("stages", {})
54
+
55
+ self._agg["by_slide"][slide_id] = {}
56
+ for stage_name, stats in stages.items():
57
+ wall = float(stats.get("wall_time_sec", 0.0))
58
+ n = int(stats.get("yields", 0))
59
+ avg = (wall / n * 1000.0) if n > 0 else 0.0
60
+
61
+ # Per-slide
62
+ self._agg["by_slide"][slide_id][stage_name] = {"wall_time_sec": wall, "yields": n, "avg_ms_per_yield": avg}
63
+
64
+ # Aggregate by stage
65
+ agg = self._agg["by_stage"].setdefault(stage_name, {"wall_time_sec": 0.0, "yields": 0})
66
+ agg["wall_time_sec"] = float(agg["wall_time_sec"]) + wall
67
+ agg["yields"] = int(agg["yields"]) + n
68
+
69
+ def get_profile(self) -> Dict[str, Any]:
70
+ out = {"by_stage": {}, "by_slide": self._agg.get("by_slide", {})}
71
+ for stage_name, agg in self._agg.get("by_stage", {}).items():
72
+ wall = float(agg["wall_time_sec"])
73
+ n = int(agg["yields"])
74
+ out["by_stage"][stage_name] = {
75
+ "wall_time_sec": wall,
76
+ "yields": n,
77
+ "avg_ms_per_yield": (wall / n * 1000.0) if n > 0 else 0.0,
78
+ }
79
+ return out
80
+
81
+ def print_profile(self) -> None:
82
+ prof = self.get_profile()
83
+ if not prof["by_stage"]:
84
+ return
85
+
86
+ def fmt(stats: Dict[str, Union[float, int]]) -> str:
87
+ return (
88
+ f"{int(stats['yields']):10d} {float(stats['wall_time_sec']):12.3f} "
89
+ f"{float(stats['avg_ms_per_yield']):16.3f}"
90
+ )
91
+
92
+ logger.info("\n=== Pipeline Profile (isolated timings only) ===")
93
+ logger.info(f"{'Stage':30} {'Yields':>10} {'Wall (s)':>12} {'Avg (ms/yield)':>16}")
94
+ for name, stats in sorted(prof["by_stage"].items(), key=lambda kv: kv[1]["wall_time_sec"], reverse=True):
95
+ logger.info(f"{name:30} {fmt(stats)}")
96
+
97
+ logger.info("\n--- Per slide breakdown ---")
98
+ for slide_id, stages in prof["by_slide"].items():
99
+ logger.info(f"[{slide_id}]")
100
+ for name, stats in sorted(stages.items(), key=lambda kv: kv[1]["wall_time_sec"], reverse=True):
101
+ logger.info(
102
+ f" {name:28} yields={int(stats['yields']):6d} "
103
+ f"wall={float(stats['wall_time_sec']):8.3f}s avg={float(stats['avg_ms_per_yield']):8.3f}ms"
104
+ )
105
+
106
+
107
+ _profiler_local = threading.local()
108
+
109
+
110
+ def set_current_profiler(p: Optional["Profiler"]) -> None:
111
+ _profiler_local.profiler = p
112
+
113
+
114
+ def get_current_profiler() -> Optional["Profiler"]:
115
+ return getattr(_profiler_local, "profiler", None)
@@ -0,0 +1,208 @@
1
+ from pathlib import Path
2
+ from typing import Iterable, Mapping, Optional, Sequence, Tuple, Union
3
+ from typing import cast as _cast
4
+
5
+ import numpy as np
6
+ from PIL import Image, ImageDraw
7
+
8
+ from wsi_patching.backends.fastslide import get_dimensions_for_level, get_level_for_resolution, read_region
9
+
10
+ CoordLike = Union[Tuple[int, int], Sequence[int], np.ndarray]
11
+
12
+
13
+ def visualize_selected_patches(
14
+ wsi_path: str,
15
+ coords: Iterable[CoordLike],
16
+ patch_size: int,
17
+ *,
18
+ stride: Optional[int] = None,
19
+ patch_images: Optional[Union[np.ndarray, Mapping[CoordLike, np.ndarray]]] = None,
20
+ thumb_long_side: int = 2000,
21
+ selected_outline_rgba: Tuple[int, int, int, int] = (0, 220, 0, 100),
22
+ save_path: Union[str, Path, None] = None,
23
+ ) -> Image.Image:
24
+ """
25
+ Render a thumbnail of the WSI and optionally overlay the actual patch images.
26
+
27
+ - Background: WSI thumbnail.
28
+ - Optional: fill every *candidate* tile (stride grid) in bounding region as dark gray.
29
+ - Optional: overlay real patch images at their locations (alpha-blended or replaced).
30
+ - Selected patches are outlined in green.
31
+
32
+ Args:
33
+ wsi_path: path to the slide.
34
+ coords: iterable of (x, y) top-left anchors at base resolution.
35
+ patch_size: square patch size at base resolution.
36
+ stride: grid stride at base resolution (defaults to patch_size).
37
+ patch_images:
38
+ numpy array of patch images in order of `coords`
39
+ save_path: if provided, save the output PNG to this path.
40
+
41
+ Returns:
42
+ PIL Image object of the composite visualization.
43
+ """
44
+ if stride is None:
45
+ stride = patch_size
46
+ if stride <= 0 or patch_size <= 0:
47
+ raise ValueError("`stride` and `patch_size` must be positive integers.")
48
+
49
+ # Normalize coords
50
+ coords_arr: list[tuple[int, int]] = []
51
+ for c in coords:
52
+ x, y = int(c[0]), int(c[1])
53
+ coords_arr.append((x, y))
54
+ if not coords_arr:
55
+ raise ValueError("No coordinates provided.")
56
+
57
+ # Optionally snap to stride grid to avoid tiny round-off mismatches
58
+ coords_arr = [((x // stride) * stride, (y // stride) * stride) for x, y in coords_arr]
59
+
60
+ # Map coords -> patch image (if provided)
61
+ coord_to_patch: dict[tuple[int, int], np.ndarray] = {}
62
+ if patch_images is not None:
63
+ if isinstance(patch_images, Mapping):
64
+ # dict mapping top-left to image
65
+ for k, v in patch_images.items():
66
+ _k = _cast(Sequence[int], k)
67
+ coord_to_patch[(int(_k[0]), int(_k[1]))] = np.asarray(v)
68
+ else:
69
+ # assume same order as coords
70
+ if len(patch_images) != len(coords_arr):
71
+ raise ValueError("If `patch_images` is a sequence, it must match len(coords).")
72
+ for xy, img in zip(coords_arr, patch_images):
73
+ coord_to_patch[xy] = np.asarray(img)
74
+
75
+ # Open slide and make thumbnail
76
+ W0, H0 = get_dimensions_for_level(wsi_path, level=0)
77
+ scale = float(thumb_long_side) / max(W0, H0)
78
+ tw = max(1, int(round(W0 * scale)))
79
+ th = max(1, int(round(H0 * scale)))
80
+ base_thumb = get_thumbnail(wsi_path, (tw, th), (W0, H0)).convert("RGB")
81
+ tw, th = base_thumb.size
82
+
83
+ # Overlay layers
84
+ # - gray grid + green outlines are drawn on 'overlay' (RGBA)
85
+ # - patch bitmaps are pasted directly onto 'composite' (start from the base thumbnail)
86
+ composite = base_thumb.convert("RGBA")
87
+ overlay = Image.new("RGBA", (tw, th), (0, 0, 0, 0))
88
+ draw = ImageDraw.Draw(overlay)
89
+
90
+ # Bounding region aligned to stride, covering all selected patches fully
91
+ xs = [x for x, _ in coords_arr]
92
+ ys = [y for _, y in coords_arr]
93
+
94
+ min_x_raw, min_y_raw = min(xs), min(ys)
95
+ max_x_end_raw = max(xs) + patch_size
96
+ max_y_end_raw = max(ys) + patch_size
97
+
98
+ def ceil_to_stride(v: int, s: int) -> int:
99
+ return ((v + s - 1) // s) * s
100
+
101
+ min_x = (min_x_raw // stride) * stride
102
+ min_y = (min_y_raw // stride) * stride
103
+ max_x_end = ceil_to_stride(max_x_end_raw, stride)
104
+ max_y_end = ceil_to_stride(max_y_end_raw, stride)
105
+
106
+ # Clamp to slide bounds
107
+ min_x = max(0, min_x)
108
+ min_y = max(0, min_y)
109
+ max_x_end = min(W0, max_x_end)
110
+ max_y_end = min(H0, max_y_end)
111
+
112
+ # scale factors
113
+ sx = tw / float(W0)
114
+ sy = th / float(H0)
115
+
116
+ # line width for outlines
117
+ line_w = max(1, int(round(max(tw, th) / 1000)))
118
+
119
+ # 2) paste/blend actual patch images (if provided)
120
+ if coord_to_patch:
121
+ for (x, y), np_patch in coord_to_patch.items():
122
+ if x + patch_size > W0 or y + patch_size > H0:
123
+ continue # skip out-of-bounds just in case
124
+
125
+ if np_patch.ndim == 3 and np_patch.shape[0] in (3, 4):
126
+ np_patch = np.transpose(np_patch, (1, 2, 0))
127
+ patch_img = _to_pil_rgb(np_patch)
128
+
129
+ # resize patch to thumbnail scale
130
+ dst_w = max(1, int(round(patch_size * sx)))
131
+ dst_h = max(1, int(round(patch_size * sy)))
132
+ if patch_img.size != (dst_w, dst_h):
133
+ patch_img = patch_img.resize((dst_w, dst_h), resample=Image.Resampling.BILINEAR)
134
+
135
+ # destination location on the thumbnail
136
+ x0_t, y0_t = int(round(x * sx)), int(round(y * sy))
137
+
138
+ composite.paste(patch_img, (x0_t, y0_t))
139
+
140
+ # 3) draw green outlines for selected patches on top
141
+ for x, y in coords_arr:
142
+ if x + patch_size > W0 or y + patch_size > H0:
143
+ continue
144
+ x0_t, y0_t = int(round(x * sx)), int(round(y * sy))
145
+ x1_t, y1_t = int(round((x + patch_size) * sx)), int(round((y + patch_size) * sy))
146
+ draw.rectangle([x0_t, y0_t, x1_t, y1_t], outline=selected_outline_rgba, width=line_w)
147
+
148
+ # composite: base + patch bitmaps + overlay (gray + outlines)
149
+ composite = Image.alpha_composite(composite, overlay)
150
+
151
+ if save_path is None:
152
+ return composite.convert("RGB") # or return RGBA if you want transparency
153
+
154
+ save_path = Path(save_path)
155
+ composite.convert("RGB").save(save_path, format="PNG")
156
+ return composite.convert("RGB")
157
+
158
+
159
+ def get_thumbnail(path, max_thumbnail_size: tuple[int, int], slide_dimensions: tuple[int, int]) -> Image.Image:
160
+ downsample = max(dim / thumb for dim, thumb in zip(slide_dimensions, max_thumbnail_size))
161
+ level = get_level_for_resolution(path, resolution=downsample, unit="downsample", fallback_mode="nearest")
162
+
163
+ tile: np.ndarray = read_region(path, 0, 0, *get_dimensions_for_level(path, level), level)
164
+
165
+ im = Image.fromarray(tile)
166
+
167
+ # If RGBA, composite onto white so thumbnail is RGB
168
+ if im.mode == "RGBA":
169
+ bg = Image.new("RGBA", im.size, (255, 255, 255, 255))
170
+ im = Image.alpha_composite(bg, im).convert("RGB")
171
+ else:
172
+ im = im.convert("RGB")
173
+
174
+ im.thumbnail(max_thumbnail_size, Image.Resampling.LANCZOS)
175
+ return im
176
+
177
+
178
+ def _to_pil_rgb(img: np.ndarray) -> Image.Image:
179
+ a = np.asarray(img)
180
+
181
+ # Handle CHW -> HWC
182
+ if a.ndim == 3 and a.shape[0] in (1, 3, 4) and a.shape[1] > 4 and a.shape[2] > 4:
183
+ a = np.transpose(a, (1, 2, 0))
184
+
185
+ # Squeeze singleton channel-last (H,W,1)
186
+ if a.ndim == 3 and a.shape[2] == 1:
187
+ a = a[..., 0]
188
+
189
+ # Grayscale -> RGB
190
+ if a.ndim == 2:
191
+ a = np.stack([a, a, a], axis=-1)
192
+
193
+ if a.ndim != 3 or a.shape[2] not in (3, 4):
194
+ raise ValueError(f"Unsupported patch array shape after processing: {a.shape}")
195
+
196
+ # Convert dtype/range to uint8 before PIL
197
+ if a.dtype != np.uint8:
198
+ a = a.astype(np.float32)
199
+ # common case: floats in [0,1]
200
+ if a.max() <= 1.0:
201
+ a *= 255.0
202
+ a = np.clip(a, 0, 255).astype(np.uint8)
203
+
204
+ # If RGBA, drop alpha (or composite). Dropping is simplest:
205
+ if a.shape[2] == 4:
206
+ a = a[..., :3]
207
+
208
+ return Image.fromarray(a, mode="RGB")
@@ -0,0 +1,10 @@
1
+ from .materialize_writers.webdataset.webdataset_writer import WebDatasetWriter
2
+ from .stream_writers.numpy_stream_writer import NumpyStreamWriter
3
+
4
+ try:
5
+ from .materialize_writers.webdataset.webdataset_loader import WebDatasetLoader
6
+ from .stream_writers.torch_stream_writer import TorchStreamWriter
7
+ except ImportError:
8
+ pass
9
+
10
+ __all__ = ["NumpyStreamWriter", "TorchStreamWriter", "WebDatasetWriter", "WebDatasetLoader"]
File without changes
@@ -0,0 +1,92 @@
1
+ import logging
2
+ from queue import Empty, Queue
3
+ from threading import Event
4
+ from typing import Any, Optional
5
+
6
+ from wsi_patching.core.types.util_types import EndOfQueue, EndOfStream
7
+ from wsi_patching.utils.logging_config import LogLevel, init_logging
8
+ from wsi_patching.utils.meta_typing import ContextAware, WriterMeta
9
+
10
+
11
+ class MaterializeWriterBase(ContextAware, metaclass=WriterMeta):
12
+ """
13
+ Base class for sink stages (writers). It hides multiprocessing queue handling and
14
+ special control messages (EndOfStream / EndOfQueue).
15
+
16
+ Implementers override:
17
+ - open(self) -> None # allocate resources; runs in writer process
18
+ - write(self, batch: Any) -> None # write a batch of items
19
+ - on_end_of_stream(self) -> None # optional per-slide finalization
20
+ - close(self) -> None # flush/close resources
21
+
22
+ Single-process usage: writer(it) will consume the iterable and write everything.
23
+ Multi-process usage: writer.start_writer(queue) will block and consume messages from producers.
24
+ """
25
+
26
+ def __init__(self) -> None:
27
+ self._is_open = False
28
+
29
+ def __init_subclass__(cls, **kwargs):
30
+ super().__init_subclass__(**kwargs)
31
+ cls.log = logging.getLogger(f"{cls.__name__}")
32
+
33
+ # ----- lifecycle hooks for subclasses -----
34
+ def open(self) -> None:
35
+ """Allocate resources. Called in the writer process (or current process for single-process)."""
36
+ pass
37
+
38
+ def write(self, batch: Any) -> None:
39
+ """Write a batch of items. Must be implemented by subclass."""
40
+ raise NotImplementedError
41
+
42
+ def on_end_of_stream(self) -> None:
43
+ """Called when a producer finishes a slide. Default: no-op."""
44
+ pass
45
+
46
+ def close(self) -> None:
47
+ """Flush and close resources."""
48
+ pass
49
+
50
+ # ----- helpers -----
51
+ def _ensure_open(self) -> None:
52
+ if not self._is_open:
53
+ self.open()
54
+ self._is_open = True
55
+
56
+ # ----- Threaded consumer entrypoint -----
57
+ def start_writer(
58
+ self, queue: Queue, verbosity_level: LogLevel, stop_event: Optional[Event] = None, poll_s: float = 0.5
59
+ ) -> None:
60
+ """
61
+ Multi-process: consume from a queue. Handles EndOfStream/EndOfQueue for you.
62
+ Subclasses SHOULD NOT override this; implement open/write/on_end_of_stream/close instead.
63
+ """
64
+ init_logging(verbosity_level)
65
+ self.log.info("Writer process started.")
66
+ self._ensure_open()
67
+ try:
68
+ while True:
69
+ try:
70
+ msg = queue.get(timeout=poll_s)
71
+ except Empty:
72
+ if stop_event is not None and stop_event.is_set():
73
+ self.log.info("Stop event set; writer exiting.")
74
+ break
75
+ continue
76
+
77
+ if isinstance(msg, EndOfQueue):
78
+ self.log.info("Writer received EndOfQueue (shutdown).")
79
+ break
80
+ if isinstance(msg, EndOfStream):
81
+ self.on_end_of_stream()
82
+ continue
83
+ self.write(msg)
84
+ except KeyboardInterrupt:
85
+ pass
86
+ except Exception:
87
+ self.log.exception("Unhandled exception in writer process:", exc_info=True)
88
+ finally:
89
+ try:
90
+ self.close()
91
+ except Exception:
92
+ self.log.exception("Writer.close() raised during shutdown.", exc_info=True)
@@ -0,0 +1,165 @@
1
+ from glob import glob
2
+ from pathlib import Path
3
+ from typing import Any, Dict, List, Optional, Tuple, cast
4
+
5
+ import numpy as np
6
+ import orjson
7
+ import webdataset as wds
8
+
9
+ try:
10
+ import torch
11
+ from torch.utils.data import DataLoader
12
+ from torch.utils.data import IterableDataset as TorchIterableDataset
13
+ except ImportError as e:
14
+ raise ImportError("WebDatasetLoader requires torch. Install it with: pip install wsi-patching[gpu]") from e
15
+
16
+
17
+ class WebDatasetLoader:
18
+ def __init__(
19
+ self,
20
+ tar_dir: Path = Path("./output/"),
21
+ sampled_wsi_names: Optional[List[str]] = None,
22
+ shuffle_size: int = 20_000,
23
+ batch_size: int = 32,
24
+ ):
25
+ """
26
+ Configurable dataset loader for PNG WebDataset shards that returns
27
+ image, key, and meta (json).
28
+
29
+ Args:
30
+ num_workers (int): DataLoader workers. Higher means more randomness in batches.
31
+ It is highly advised to use > 0 workers.
32
+ tar_dir (Path): Directory containing *.tar shards.
33
+ sampled_wsi_names (Sequence[str] | None): Keep a sample only if its __key__
34
+ starts with any of these prefixes (WSI names). If None, keep all.
35
+ shuffle_size (int): Per-worker shuffle buffer size (larger = more random).
36
+ batch_size (int): DataLoader batch size.
37
+ """
38
+ self.tar_dir = tar_dir
39
+ self.sampled_wsi_names = sampled_wsi_names
40
+ self.shuffle_size = shuffle_size
41
+ self.batch_size = batch_size
42
+
43
+ self.shards: List[str] = []
44
+
45
+ # ---- filtering helper ----------------------------------------------------
46
+ def key_in_train(self, sample: Dict[str, Any]) -> bool:
47
+ if not self.sampled_wsi_names:
48
+ return True
49
+ key = sample.get("__key__", "")
50
+ # Fast prefix check against provided WSI names
51
+ return any(key.startswith(prefix) for prefix in self.sampled_wsi_names)
52
+
53
+ # ---- dataset & dataloader -----------------------------------------------
54
+ def get_dataset(self) -> "TorchIterableDataset[Dict[str, Any]]":
55
+ self.shards = sorted(glob(str(self.tar_dir / "*.tar")))
56
+ if not self.shards:
57
+ raise FileNotFoundError(f"No shards found in {self.tar_dir}")
58
+
59
+ # Build core pipeline
60
+ ds = wds.WebDataset(self.shards, shardshuffle=50) # ty: ignore[unresolved-attribute]
61
+
62
+ # Optional prefix-filter on __key__
63
+ if self.sampled_wsi_names:
64
+ ds = ds.select(self.key_in_train)
65
+
66
+ # Shuffle within shards
67
+ if self.shuffle_size and self.shuffle_size > 0:
68
+ ds = ds.shuffle(self.shuffle_size)
69
+
70
+ # Decode PNG to RGB8 (numpy HWC uint8) and meta to dict
71
+ ds = ds.decode("torch").to_tuple("__key__", "png", "meta")
72
+
73
+ ds = ds.map(WebDatasetLoader._map_to_dict)
74
+
75
+ return cast("TorchIterableDataset[Dict[str, Any]]", ds)
76
+
77
+ @staticmethod
78
+ def _map_to_dict(sample):
79
+ key, img, meta = sample
80
+ if isinstance(meta, (bytes, bytearray)):
81
+ meta = orjson.loads(meta.decode("utf-8"))
82
+ return {"key": key, "patch": img, "meta": meta}
83
+
84
+ def get_dataloader(
85
+ self,
86
+ num_workers: int = 4,
87
+ drop_last: bool = True,
88
+ pin_memory: bool = True,
89
+ safe_collate: bool = True,
90
+ persistent_workers: bool = True,
91
+ prefetch_factor: Optional[int] = 4,
92
+ ) -> DataLoader:
93
+ dataset = self.get_dataset()
94
+ collate_fn = self.safe_collate if safe_collate else None
95
+
96
+ extra = {}
97
+ if persistent_workers is not None:
98
+ extra["persistent_workers"] = persistent_workers
99
+ if prefetch_factor is not None:
100
+ extra["prefetch_factor"] = prefetch_factor
101
+
102
+ return DataLoader(
103
+ dataset,
104
+ batch_size=self.batch_size,
105
+ num_workers=num_workers,
106
+ drop_last=drop_last,
107
+ pin_memory=pin_memory,
108
+ collate_fn=collate_fn,
109
+ **extra,
110
+ )
111
+
112
+ # ---- collate that “just works” ------------------------------------------
113
+ def safe_collate(self, batch: List[Dict[str, Any]]) -> Tuple[Any, List[str], List[Any]]:
114
+ """
115
+ - Converts HWC uint8 numpy images to float32 tensors in [0,1] and stacks to [B, C, H, W].
116
+ - Keeps keys as a list[str].
117
+ - Keeps metas as a list[dict].
118
+ """
119
+ if not batch:
120
+ return torch.empty(0), [], []
121
+
122
+ # Images: convert each HWC uint8 numpy -> CHW float32 tensor in [0,1]
123
+ imgs: List[torch.Tensor] = []
124
+ for sample in batch:
125
+ img = sample["patch"]
126
+ if isinstance(img, np.ndarray):
127
+ # numpy HWC -> torch CHW
128
+ t = torch.from_numpy(img) # [H, W, C], uint8
129
+ if t.ndim != 3 or t.shape[-1] not in (1, 3, 4):
130
+ raise ValueError(f"Unexpected patch shape: {t.shape}")
131
+ t = t.permute(2, 0, 1).contiguous() # CHW
132
+ # If RGBA, drop alpha
133
+ if t.shape[0] == 4:
134
+ t = t[:3, ...]
135
+ t = t.float().div_(255.0)
136
+ elif isinstance(img, torch.Tensor):
137
+ # Assume already CHW float or uint8; normalize to float [0,1]
138
+ t = img
139
+ if t.ndim == 3 and t.shape[0] in (1, 3, 4):
140
+ if t.dtype == torch.uint8:
141
+ t = t.float().div_(255.0)
142
+ if t.shape[0] == 4:
143
+ t = t[:3, ...]
144
+ else:
145
+ raise ValueError(f"Unexpected tensor patch shape: {t.shape}")
146
+ else:
147
+ raise TypeError(f"Unsupported patch type: {type(img)}")
148
+ imgs.append(t)
149
+
150
+ try:
151
+ patches = torch.stack(imgs, dim=0) # [B, C, H, W]
152
+ except Exception as e:
153
+ raise RuntimeError(f"Failed to stack patches: {e}")
154
+
155
+ keys = [s["key"] for s in batch]
156
+ metas = [s["meta"] for s in batch]
157
+
158
+ return patches, keys, metas
159
+
160
+ # ---- Helpers ------------------------------------------
161
+ def ensure_torch(self, x):
162
+ if isinstance(x, np.ndarray):
163
+ return torch.from_numpy(x)
164
+
165
+ raise TypeError(f"Unsupported type: {type(x)}")