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.
- wsi_patching/__init__.py +38 -0
- wsi_patching/annotations/__init__.py +3 -0
- wsi_patching/annotations/add_cell_annotation_from_csv.py +152 -0
- wsi_patching/assets/models/cellvit_tissue_detector.pt +0 -0
- wsi_patching/backends/__init__.py +0 -0
- wsi_patching/backends/cupy_numpy.py +80 -0
- wsi_patching/backends/fastslide.py +243 -0
- wsi_patching/backends/torch_device.py +45 -0
- wsi_patching/core/__init__.py +4 -0
- wsi_patching/core/chunking_and_batching.py +519 -0
- wsi_patching/core/pipeline.py +566 -0
- wsi_patching/core/types/__init__.py +0 -0
- wsi_patching/core/types/types.py +145 -0
- wsi_patching/core/types/util_types.py +93 -0
- wsi_patching/core/wsi_grid.py +119 -0
- wsi_patching/custom_component/__init__.py +18 -0
- wsi_patching/encoders/__init__.py +3 -0
- wsi_patching/encoders/pngencoder.py +72 -0
- wsi_patching/filtering/__init__.py +15 -0
- wsi_patching/filtering/cellvit_tissue_classifier_filter.py +124 -0
- wsi_patching/filtering/low_contrast_background_filter.py +125 -0
- wsi_patching/filtering/otsu_filter.py +217 -0
- wsi_patching/filtering/pen_artifact_filter.py +216 -0
- wsi_patching/py.typed +0 -0
- wsi_patching/regions_of_interest/__init__.py +4 -0
- wsi_patching/regions_of_interest/attach_rois.py +59 -0
- wsi_patching/regions_of_interest/roi_providers.py +94 -0
- wsi_patching/regions_of_interest/rois.py +78 -0
- wsi_patching/transforms/__init__.py +4 -0
- wsi_patching/transforms/macenko_normalizer.py +175 -0
- wsi_patching/transforms/reinhard_normalizer.py +271 -0
- wsi_patching/utils/__init__.py +3 -0
- wsi_patching/utils/logging_config.py +13 -0
- wsi_patching/utils/meta_typing.py +94 -0
- wsi_patching/utils/profiling.py +115 -0
- wsi_patching/utils/wsi_thumbnail_visualization.py +208 -0
- wsi_patching/writers/__init__.py +10 -0
- wsi_patching/writers/materialize_writers/__init__.py +0 -0
- wsi_patching/writers/materialize_writers/materialize_writer_base.py +92 -0
- wsi_patching/writers/materialize_writers/webdataset/__init__.py +0 -0
- wsi_patching/writers/materialize_writers/webdataset/webdataset_loader.py +165 -0
- wsi_patching/writers/materialize_writers/webdataset/webdataset_writer.py +69 -0
- wsi_patching/writers/stream_writers/__init__.py +0 -0
- wsi_patching/writers/stream_writers/numpy_stream_writer.py +36 -0
- wsi_patching/writers/stream_writers/stream_writer_base.py +71 -0
- wsi_patching/writers/stream_writers/torch_stream_writer.py +67 -0
- wsi_patching-0.5.0.dist-info/METADATA +249 -0
- wsi_patching-0.5.0.dist-info/RECORD +50 -0
- wsi_patching-0.5.0.dist-info/WHEEL +4 -0
- wsi_patching-0.5.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
from dataclasses import dataclass, field
|
|
2
|
+
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union
|
|
3
|
+
|
|
4
|
+
from wsi_patching.backends.cupy_numpy import ensure_array_matches_use_gpu, is_cupy
|
|
5
|
+
from wsi_patching.core.types.util_types import MetaColStorage
|
|
6
|
+
|
|
7
|
+
if TYPE_CHECKING:
|
|
8
|
+
import cupy as cp
|
|
9
|
+
import numpy as np
|
|
10
|
+
|
|
11
|
+
# Bounding box: (x, y, w, h)
|
|
12
|
+
Box = Tuple[int, int, int, int]
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass(frozen=True)
|
|
16
|
+
class SlideBase:
|
|
17
|
+
wsi_id: str
|
|
18
|
+
wsi_path: str
|
|
19
|
+
dims: Tuple[int, int]
|
|
20
|
+
level: int
|
|
21
|
+
downsample: float = 1.0
|
|
22
|
+
resample_factor: float = 1.0
|
|
23
|
+
meta: Dict[str, Any] = field(default_factory=dict)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@dataclass(frozen=True)
|
|
27
|
+
class Slide(SlideBase):
|
|
28
|
+
pass
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@dataclass(frozen=True)
|
|
32
|
+
class SlideWithROIs(SlideBase):
|
|
33
|
+
rois: List[Any] = field(default_factory=list) # ROI instances
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@dataclass(frozen=True)
|
|
37
|
+
class TilePlan:
|
|
38
|
+
wsi_id: str
|
|
39
|
+
wsi_path: str
|
|
40
|
+
dims: Tuple[int, int]
|
|
41
|
+
level: int
|
|
42
|
+
roi_index: int
|
|
43
|
+
roi_bounds: Box
|
|
44
|
+
tiles: List[Tuple[int, int]]
|
|
45
|
+
downsample: float = 1.0
|
|
46
|
+
resample_factor: float = 1.0
|
|
47
|
+
meta: Dict[str, Any] = field(default_factory=dict)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
@dataclass(frozen=True)
|
|
51
|
+
class RegionTask:
|
|
52
|
+
wsi_id: str
|
|
53
|
+
wsi_path: str
|
|
54
|
+
wsi_dims: Tuple[int, int]
|
|
55
|
+
level: int
|
|
56
|
+
region: Box
|
|
57
|
+
tiles: List[Tuple[int, int]]
|
|
58
|
+
downsample: float = 1.0
|
|
59
|
+
resample_factor: float = 1.0
|
|
60
|
+
meta: Dict[str, Any] = field(default_factory=dict)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class CollatedPatchBatch:
|
|
64
|
+
wsi_id: str
|
|
65
|
+
coords: np.ndarray # (N, 2)
|
|
66
|
+
patches: Union[np.ndarray, "cp.ndarray"] # (N, ...)
|
|
67
|
+
metadata: MetaColStorage
|
|
68
|
+
|
|
69
|
+
def __init__(
|
|
70
|
+
self,
|
|
71
|
+
wsi_id: str,
|
|
72
|
+
coords: np.ndarray,
|
|
73
|
+
patches: Union[np.ndarray, "cp.ndarray"],
|
|
74
|
+
use_gpu: bool,
|
|
75
|
+
metadata: Optional[MetaColStorage] = None,
|
|
76
|
+
):
|
|
77
|
+
self.wsi_id = wsi_id
|
|
78
|
+
self.coords = coords
|
|
79
|
+
self.patches = patches
|
|
80
|
+
|
|
81
|
+
if metadata is not None:
|
|
82
|
+
self.metadata = metadata
|
|
83
|
+
else:
|
|
84
|
+
self.metadata = MetaColStorage(length=coords.shape[0])
|
|
85
|
+
|
|
86
|
+
if use_gpu and not is_cupy(self.patches):
|
|
87
|
+
raise TypeError("patches must be a cupy.ndarray when use_gpu is True")
|
|
88
|
+
|
|
89
|
+
if self.patches.shape[0] != coords.shape[0]:
|
|
90
|
+
raise ValueError("coords and patches must have same first dimension")
|
|
91
|
+
|
|
92
|
+
def __len__(self) -> int:
|
|
93
|
+
return self.coords.shape[0]
|
|
94
|
+
|
|
95
|
+
def add_meta_column(self, name: str, values: Any) -> None:
|
|
96
|
+
self.metadata.add_column(name, values)
|
|
97
|
+
|
|
98
|
+
def drop_meta_column(self, name: str) -> None:
|
|
99
|
+
self.metadata.drop_column(name)
|
|
100
|
+
|
|
101
|
+
def filter_on_mask(self, bool_mask: np.ndarray) -> None:
|
|
102
|
+
"""In-place selection of rows using boolean mask.
|
|
103
|
+
|
|
104
|
+
Drops data from all fields where mask is False.
|
|
105
|
+
"""
|
|
106
|
+
n = self.coords.shape[0]
|
|
107
|
+
if bool_mask.dtype != np.bool_:
|
|
108
|
+
raise TypeError("Boolean mask must be of type np.bool_")
|
|
109
|
+
if bool_mask.shape[0] != n:
|
|
110
|
+
raise ValueError("Boolean mask length mismatch")
|
|
111
|
+
|
|
112
|
+
self.coords = self.coords[bool_mask]
|
|
113
|
+
self.patches = self.patches[ensure_array_matches_use_gpu(bool_mask, is_cupy(self.patches))]
|
|
114
|
+
self.metadata = self.metadata.take(bool_mask)
|
|
115
|
+
|
|
116
|
+
def get(self, idx: int):
|
|
117
|
+
"""
|
|
118
|
+
Return a single sample:
|
|
119
|
+
wsi_id: str
|
|
120
|
+
coords: shape (2,)
|
|
121
|
+
patch: shape (...)
|
|
122
|
+
meta: dict[str, Any] with per-column row values
|
|
123
|
+
"""
|
|
124
|
+
if not (0 <= idx < self.coords.shape[0]):
|
|
125
|
+
raise IndexError("Index out of range")
|
|
126
|
+
|
|
127
|
+
return self.wsi_id, self.coords[idx], self.patches[idx], self.metadata.get_sample(idx)
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
class EncodedCollatedPatchBatch(CollatedPatchBatch):
|
|
131
|
+
encoding: str
|
|
132
|
+
encoded_patches: Any
|
|
133
|
+
|
|
134
|
+
@classmethod
|
|
135
|
+
def from_collated_patch_batch(cls, batch: CollatedPatchBatch, encoding: str, encoded_patches: Any):
|
|
136
|
+
obj = cls(
|
|
137
|
+
wsi_id=batch.wsi_id,
|
|
138
|
+
coords=batch.coords,
|
|
139
|
+
patches=batch.patches,
|
|
140
|
+
use_gpu=is_cupy(batch.patches),
|
|
141
|
+
metadata=batch.metadata,
|
|
142
|
+
)
|
|
143
|
+
obj.encoding = encoding
|
|
144
|
+
obj.encoded_patches = encoded_patches
|
|
145
|
+
return obj
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
from dataclasses import dataclass
|
|
2
|
+
from typing import Any, Dict, List, Union
|
|
3
|
+
|
|
4
|
+
import numpy as np
|
|
5
|
+
|
|
6
|
+
from wsi_patching.backends.cupy_numpy import is_cupy
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class MetaColStorage:
|
|
10
|
+
__slots__ = ("_data", "_n")
|
|
11
|
+
|
|
12
|
+
def __init__(self, length: int) -> None:
|
|
13
|
+
self._n = length
|
|
14
|
+
self._data: Dict[str, Any] = {}
|
|
15
|
+
|
|
16
|
+
def __len__(self) -> int:
|
|
17
|
+
return self._n
|
|
18
|
+
|
|
19
|
+
def __contains__(self, key: str) -> bool:
|
|
20
|
+
return key in self._data
|
|
21
|
+
|
|
22
|
+
def __getitem__(self, key: str) -> Any:
|
|
23
|
+
return self._data[key]
|
|
24
|
+
|
|
25
|
+
def get(self, key: str, default: Any = None) -> Any:
|
|
26
|
+
return self._data.get(key, default)
|
|
27
|
+
|
|
28
|
+
def get_sample(self, i: int) -> Dict[str, Any]:
|
|
29
|
+
"""Return a single sample as a dict of column name to value."""
|
|
30
|
+
n = self._n
|
|
31
|
+
if not (0 <= i < n):
|
|
32
|
+
raise IndexError("Index out of range")
|
|
33
|
+
|
|
34
|
+
return {k: self._data[k][i] for k in self.columns()}
|
|
35
|
+
|
|
36
|
+
def get_all_row_wise(self) -> List[Dict[str, Any]]:
|
|
37
|
+
"""Return all metadata as a list of dictionaries, one per row."""
|
|
38
|
+
return [self.get_sample(i) for i in range(self._n)]
|
|
39
|
+
|
|
40
|
+
def columns(self) -> List[str]:
|
|
41
|
+
return list(self._data.keys())
|
|
42
|
+
|
|
43
|
+
def add_column(self, name: str, values: Union[list, np.ndarray]) -> None:
|
|
44
|
+
if type(values) not in (list, np.ndarray):
|
|
45
|
+
raise TypeError("Column values must be a list or numpy array")
|
|
46
|
+
|
|
47
|
+
self._ensure_serializable(values, self._n)
|
|
48
|
+
|
|
49
|
+
self._data[name] = values
|
|
50
|
+
|
|
51
|
+
def drop_column(self, name: str) -> None:
|
|
52
|
+
if name in self._data:
|
|
53
|
+
del self._data[name]
|
|
54
|
+
else:
|
|
55
|
+
raise KeyError(f"Column '{name}' does not exist")
|
|
56
|
+
|
|
57
|
+
def take(self, idx: np.ndarray) -> "MetaColStorage":
|
|
58
|
+
"""Return a new MetaColStorage with selected rows."""
|
|
59
|
+
new_mcs = MetaColStorage(length=idx.sum())
|
|
60
|
+
for k, v in self._data.items():
|
|
61
|
+
new_mcs.add_column(k, self._take(v, idx))
|
|
62
|
+
return new_mcs
|
|
63
|
+
|
|
64
|
+
def _ensure_serializable(self, values: Any, n: int):
|
|
65
|
+
"""Ensure length n and leave types JSON-convertible or convertible."""
|
|
66
|
+
# Allow numpy/cupy arrays or Python sequences
|
|
67
|
+
if hasattr(values, "shape"):
|
|
68
|
+
if values.shape[0] != n:
|
|
69
|
+
raise ValueError("Column length mismatch")
|
|
70
|
+
return values
|
|
71
|
+
# Python sequence
|
|
72
|
+
if len(values) != n:
|
|
73
|
+
raise ValueError("Column length mismatch")
|
|
74
|
+
return values
|
|
75
|
+
|
|
76
|
+
def _take(self, x: Any, idx):
|
|
77
|
+
"""Take rows from array/list/column using idx or boolean mask."""
|
|
78
|
+
if hasattr(x, "__array_interface__") or (is_cupy(x)):
|
|
79
|
+
# numpy/cupy array
|
|
80
|
+
return x[idx]
|
|
81
|
+
|
|
82
|
+
# integer array over list
|
|
83
|
+
return [x[idx] for idx, bool in enumerate(np.asarray(idx).tolist()) if bool]
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
@dataclass(frozen=True)
|
|
87
|
+
class EndOfStream:
|
|
88
|
+
pass
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
@dataclass(frozen=True)
|
|
92
|
+
class EndOfQueue:
|
|
93
|
+
pass
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
from pathlib import Path
|
|
2
|
+
from typing import Any, Iterable, List, Literal, cast
|
|
3
|
+
|
|
4
|
+
from wsi_patching.backends.cupy_numpy import validate_xp_backend
|
|
5
|
+
from wsi_patching.backends.fastslide import (
|
|
6
|
+
get_dimensions_for_level,
|
|
7
|
+
get_level_downsamples,
|
|
8
|
+
get_level_for_resolution,
|
|
9
|
+
get_resample_factor,
|
|
10
|
+
)
|
|
11
|
+
from wsi_patching.core.pipeline import PipelineContext, Stage
|
|
12
|
+
from wsi_patching.core.types.types import Slide
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class WSIGrid(Stage):
|
|
16
|
+
"""
|
|
17
|
+
Minimal source that yields one 'slide' sample per input slide.
|
|
18
|
+
(MVP simplified: we do not enumerate *all tiles* here; Regionize will do per-ROI tiling.)
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
def __init__(
|
|
22
|
+
self,
|
|
23
|
+
slides: List[str],
|
|
24
|
+
resolution: float,
|
|
25
|
+
unit: Literal["level", "mpp", "downsample"],
|
|
26
|
+
use_gpu: bool = False,
|
|
27
|
+
fallback_mode: Literal["nearest", "floor", "ceil", "error", "resample"] = "error",
|
|
28
|
+
resample_interpolation: Literal["nearest", "linear", "cubic", "area", "lanczos"] = "lanczos",
|
|
29
|
+
):
|
|
30
|
+
"""
|
|
31
|
+
Initializes the WSIGrid stage, the starting point of a WSI patching pipeline.
|
|
32
|
+
|
|
33
|
+
Args:
|
|
34
|
+
slides: List of file paths to whole slide images (WSIs).
|
|
35
|
+
use_gpu: Whether to use GPU-accelerated backends when possible (e.g., cuCIM, CuPy).
|
|
36
|
+
resolution: Desired resolution for patch extraction.
|
|
37
|
+
unit: Unit of the resolution ("level", "mpp", or "downsample").
|
|
38
|
+
fallback_mode: Strategy for selecting resolution if exact match is unavailable (default is "error").
|
|
39
|
+
Options are ("nearest", "floor", "ceil", "error", "resample").
|
|
40
|
+
- "resample": selects the finest level with resolution <= requested, reads extra pixels,
|
|
41
|
+
then downsamples to the exact target resolution using cv2.resize. Not valid for unit="level".
|
|
42
|
+
resample_interpolation: Interpolation method used when fallback_mode="resample".
|
|
43
|
+
Options are ("nearest", "linear", "cubic", "area", "lanczos"). Default is "lanczos".
|
|
44
|
+
"""
|
|
45
|
+
self.slides = list(slides)
|
|
46
|
+
self.use_gpu = use_gpu
|
|
47
|
+
self.resolution = resolution
|
|
48
|
+
self.unit = unit
|
|
49
|
+
self.fallback_mode = fallback_mode
|
|
50
|
+
self.resample_interpolation = resample_interpolation
|
|
51
|
+
|
|
52
|
+
def export_context(self, ctx: "PipelineContext") -> None:
|
|
53
|
+
# Seed/override global grid parameters for other stages to read.
|
|
54
|
+
ctx["resolution"] = self.resolution
|
|
55
|
+
ctx["unit"] = self.unit
|
|
56
|
+
ctx["fallback_mode"] = self.fallback_mode
|
|
57
|
+
ctx["use_gpu"] = self.use_gpu
|
|
58
|
+
ctx["resample_interpolation"] = self.resample_interpolation
|
|
59
|
+
|
|
60
|
+
def validate(self) -> None:
|
|
61
|
+
validate_xp_backend(self.use_gpu)
|
|
62
|
+
|
|
63
|
+
def for_slide(self, slide_path: str) -> "Stage":
|
|
64
|
+
return WSIGrid(
|
|
65
|
+
slides=[slide_path],
|
|
66
|
+
use_gpu=self.use_gpu,
|
|
67
|
+
resolution=self.resolution,
|
|
68
|
+
unit=self.unit,
|
|
69
|
+
fallback_mode=self.fallback_mode,
|
|
70
|
+
resample_interpolation=self.resample_interpolation,
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
def __call__(self, it: Iterable[Any]) -> Iterable[Slide]:
|
|
74
|
+
for path in self.slides:
|
|
75
|
+
if not self.check_slide_exists(path):
|
|
76
|
+
self.log.error(f"Slide path does not exist: {path}, skipping...")
|
|
77
|
+
raise FileNotFoundError(f"Slide path does not exist: {path}")
|
|
78
|
+
|
|
79
|
+
wsi_id = Path(path).stem
|
|
80
|
+
selected_level = get_level_for_resolution(path, self.resolution, self.unit, self.fallback_mode)
|
|
81
|
+
W, H = get_dimensions_for_level(path, selected_level)
|
|
82
|
+
level_downsamples = get_level_downsamples(path)
|
|
83
|
+
downsample = level_downsamples[selected_level]
|
|
84
|
+
|
|
85
|
+
if self.fallback_mode == "resample":
|
|
86
|
+
rf = get_resample_factor(
|
|
87
|
+
path, self.resolution, cast(Literal["mpp", "downsample"], self.unit), selected_level
|
|
88
|
+
)
|
|
89
|
+
W_virtual = round(W / rf)
|
|
90
|
+
H_virtual = round(H / rf)
|
|
91
|
+
virtual_ds = downsample * rf
|
|
92
|
+
slide_dims = (W_virtual, H_virtual)
|
|
93
|
+
slide_downsample = virtual_ds
|
|
94
|
+
resample_factor = rf
|
|
95
|
+
else:
|
|
96
|
+
slide_dims = (W, H)
|
|
97
|
+
slide_downsample = downsample
|
|
98
|
+
resample_factor = 1.0
|
|
99
|
+
|
|
100
|
+
self.log.info(f"Starting on Slide {wsi_id}")
|
|
101
|
+
yield Slide(
|
|
102
|
+
wsi_id=wsi_id,
|
|
103
|
+
wsi_path=path,
|
|
104
|
+
dims=slide_dims,
|
|
105
|
+
level=selected_level,
|
|
106
|
+
downsample=slide_downsample,
|
|
107
|
+
resample_factor=resample_factor,
|
|
108
|
+
meta={
|
|
109
|
+
"slide.wsi_id": wsi_id,
|
|
110
|
+
"slide.requested_resolution": self.resolution,
|
|
111
|
+
"slide.requested_unit": self.unit,
|
|
112
|
+
"slide.requested_fallback_mode": self.fallback_mode,
|
|
113
|
+
"slide.selected_level": selected_level,
|
|
114
|
+
"slide.path": path,
|
|
115
|
+
},
|
|
116
|
+
)
|
|
117
|
+
|
|
118
|
+
def check_slide_exists(self, path: str) -> bool:
|
|
119
|
+
return Path(path).exists()
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
from ..core.pipeline import PipelineContext, Stage
|
|
2
|
+
from ..core.types.types import Box, CollatedPatchBatch, RegionTask, Slide, SlideBase, SlideWithROIs, TilePlan
|
|
3
|
+
from ..writers.materialize_writers.materialize_writer_base import MaterializeWriterBase
|
|
4
|
+
from ..writers.stream_writers.stream_writer_base import StreamWriterBase
|
|
5
|
+
|
|
6
|
+
__all__ = [
|
|
7
|
+
"Stage",
|
|
8
|
+
"PipelineContext",
|
|
9
|
+
"MaterializeWriterBase",
|
|
10
|
+
"StreamWriterBase",
|
|
11
|
+
"Box",
|
|
12
|
+
"CollatedPatchBatch",
|
|
13
|
+
"RegionTask",
|
|
14
|
+
"Slide",
|
|
15
|
+
"SlideBase",
|
|
16
|
+
"SlideWithROIs",
|
|
17
|
+
"TilePlan",
|
|
18
|
+
]
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import io
|
|
2
|
+
import os
|
|
3
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
4
|
+
from typing import Iterable, List, Optional
|
|
5
|
+
|
|
6
|
+
import numpy as np
|
|
7
|
+
from PIL import Image
|
|
8
|
+
|
|
9
|
+
from wsi_patching.backends.cupy_numpy import ensure_numpy
|
|
10
|
+
from wsi_patching.core.pipeline import Stage
|
|
11
|
+
from wsi_patching.core.types.types import CollatedPatchBatch, EncodedCollatedPatchBatch
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class PNGEncoder(Stage):
|
|
15
|
+
"""
|
|
16
|
+
Encodes patches to PNG bytes and flattens batches into single-sample items ready for the writer.
|
|
17
|
+
Output items contain: "__key__", "sample_bytes", "json_bytes"
|
|
18
|
+
|
|
19
|
+
Speedups vs. baseline:
|
|
20
|
+
- Threaded encoding across patches (libpng releases GIL).
|
|
21
|
+
- Lower compress_level (1) for big throughput gains.
|
|
22
|
+
- Use frombuffer for 'L'/'RGB'/'RGBA' to avoid an extra copy.
|
|
23
|
+
- Ensure contiguous uint8 to keep the fast path.
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
def __init__(self, compress_level: int = 1, threads: Optional[int] = None):
|
|
27
|
+
# compress_level: 0 (no compression) .. 9 (max). 1–3 is a good speed/size tradeoff.
|
|
28
|
+
self.compress_level = int(compress_level)
|
|
29
|
+
self.threads = threads or os.cpu_count() or 8
|
|
30
|
+
|
|
31
|
+
@staticmethod
|
|
32
|
+
def _to_uint8_numpy(patch) -> np.ndarray:
|
|
33
|
+
# Move from CuPy to NumPy if needed, then ensure contiguous uint8.
|
|
34
|
+
arr = ensure_numpy(patch)
|
|
35
|
+
if arr.dtype != np.uint8:
|
|
36
|
+
# clip + astype in C (fast)
|
|
37
|
+
arr = np.clip(arr, 0, 255).astype(np.uint8, copy=False)
|
|
38
|
+
# some GPU→CPU transfers yield non-contiguous; enforce C-order
|
|
39
|
+
if not arr.flags.c_contiguous:
|
|
40
|
+
arr = np.ascontiguousarray(arr)
|
|
41
|
+
return arr
|
|
42
|
+
|
|
43
|
+
def _encode_one(self, patch) -> bytes:
|
|
44
|
+
arr = self._to_uint8_numpy(patch)
|
|
45
|
+
h, w = arr.shape[:2]
|
|
46
|
+
|
|
47
|
+
# Try zero-copy Image.frombuffer for common modes
|
|
48
|
+
im = None
|
|
49
|
+
if arr.ndim == 2:
|
|
50
|
+
# Grayscale
|
|
51
|
+
im = Image.frombuffer("L", (w, h), arr, "raw", "L", 0, 1)
|
|
52
|
+
elif arr.ndim == 3 and arr.shape[2] in (3, 4):
|
|
53
|
+
mode = "RGB" if arr.shape[2] == 3 else "RGBA"
|
|
54
|
+
im = Image.frombuffer(mode, (w, h), arr, "raw", mode, 0, 1)
|
|
55
|
+
else:
|
|
56
|
+
# Fallback if unusual shape
|
|
57
|
+
im = Image.fromarray(arr)
|
|
58
|
+
|
|
59
|
+
bio = io.BytesIO()
|
|
60
|
+
# Avoid optimize=True (slower), set only compress_level
|
|
61
|
+
im.save(bio, format="PNG", compress_level=self.compress_level)
|
|
62
|
+
return bio.getvalue()
|
|
63
|
+
|
|
64
|
+
def __call__(self, it: Iterable[CollatedPatchBatch]) -> Iterable[EncodedCollatedPatchBatch]:
|
|
65
|
+
# Single thread pool reused across all batches in this call
|
|
66
|
+
with ThreadPoolExecutor(max_workers=self.threads) as ex:
|
|
67
|
+
for batch in it:
|
|
68
|
+
# ex.map preserves order → aligns with batch.coords/indexing
|
|
69
|
+
encoded: List[bytes] = list(ex.map(self._encode_one, batch.patches))
|
|
70
|
+
yield EncodedCollatedPatchBatch.from_collated_patch_batch(
|
|
71
|
+
batch, encoding="PNG", encoded_patches=encoded
|
|
72
|
+
)
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
from .low_contrast_background_filter import LowContrastBackgroundFilter
|
|
2
|
+
from .otsu_filter import OtsuFilter
|
|
3
|
+
from .pen_artifact_filter import PenArtifactFilter
|
|
4
|
+
|
|
5
|
+
try:
|
|
6
|
+
from .cellvit_tissue_classifier_filter import CellVitTissueClassifierFilter
|
|
7
|
+
except ImportError:
|
|
8
|
+
pass
|
|
9
|
+
|
|
10
|
+
__all__ = [
|
|
11
|
+
"CellVitTissueClassifierFilter",
|
|
12
|
+
"LowContrastBackgroundFilter",
|
|
13
|
+
"OtsuFilter",
|
|
14
|
+
"PenArtifactFilter",
|
|
15
|
+
]
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
from pathlib import Path
|
|
2
|
+
from typing import Iterable, List, Union
|
|
3
|
+
|
|
4
|
+
import numpy as np
|
|
5
|
+
|
|
6
|
+
try:
|
|
7
|
+
import torch
|
|
8
|
+
import torch.nn as nn
|
|
9
|
+
from torchvision.models import mobilenet_v3_small
|
|
10
|
+
except ImportError as e:
|
|
11
|
+
raise ImportError(
|
|
12
|
+
"CellVitTissueClassifierFilter requires torch and torchvision. Install them with: pip install wsi-patching[gpu]"
|
|
13
|
+
) from e
|
|
14
|
+
|
|
15
|
+
from importlib.resources import as_file, files
|
|
16
|
+
|
|
17
|
+
from wsi_patching.backends.torch_device import get_torch_device
|
|
18
|
+
from wsi_patching.core.pipeline import Stage
|
|
19
|
+
from wsi_patching.core.types.types import CollatedPatchBatch
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class CellVitTissueClassifierFilter(Stage):
|
|
23
|
+
"""
|
|
24
|
+
Tissue classifier Stage using a MobileNetV3-small checkpoint:
|
|
25
|
+
- Expects checkpoint with key "model_state_dict"
|
|
26
|
+
- Class 0 is considered 'tissue' (kept); others are filtered out
|
|
27
|
+
- Adds per-patch predictions & probabilities to batch.meta
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
def __init__(self, model_file_path: Union[str, Path]):
|
|
31
|
+
self.model_train_size = 224
|
|
32
|
+
|
|
33
|
+
self.model: Union[nn.Module, None] = None
|
|
34
|
+
|
|
35
|
+
# ImageNet normalization (shape [1,3,1,1] to broadcast)
|
|
36
|
+
self.mean = torch.tensor([0.485, 0.456, 0.406]).view(1, 3, 1, 1)
|
|
37
|
+
self.std = torch.tensor([0.229, 0.224, 0.225]).view(1, 3, 1, 1)
|
|
38
|
+
|
|
39
|
+
self._ckpt_resource = files("wsi_patching").joinpath(str(model_file_path))
|
|
40
|
+
|
|
41
|
+
def validate(self):
|
|
42
|
+
# Use ctx['use_gpu'] if provided by the pipeline, else prefer_gpu
|
|
43
|
+
self.ctx.require_key("use_gpu")
|
|
44
|
+
self.ctx.require_key("tile_size")
|
|
45
|
+
|
|
46
|
+
self._device = get_torch_device(self.ctx["use_gpu"])
|
|
47
|
+
|
|
48
|
+
if self.ctx["tile_size"] < 32:
|
|
49
|
+
self.log.warning(
|
|
50
|
+
"The tissue classifier was not trained on very small patches (<32px). Results may be poor."
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
def __call__(self, it: Iterable[CollatedPatchBatch]) -> Iterable[CollatedPatchBatch]:
|
|
54
|
+
self._lazy_load()
|
|
55
|
+
|
|
56
|
+
for collated_patch_batch in it:
|
|
57
|
+
patches = collated_patch_batch.patches # (N,H,W,C) uint8, np or cp
|
|
58
|
+
|
|
59
|
+
# Forward pass in chunks
|
|
60
|
+
preds_list: List[torch.Tensor] = []
|
|
61
|
+
probs_list: List[torch.Tensor] = []
|
|
62
|
+
|
|
63
|
+
with torch.inference_mode():
|
|
64
|
+
t = self._preprocess_batch(patches) # (B,3,S,S) on device
|
|
65
|
+
assert self.model is not None
|
|
66
|
+
logits = self.model(t) # (B,4)
|
|
67
|
+
probs = torch.softmax(logits, dim=1) # (B,4)
|
|
68
|
+
preds = torch.argmax(probs, dim=1) # (B,)
|
|
69
|
+
preds_list.append(preds)
|
|
70
|
+
probs_list.append(probs)
|
|
71
|
+
|
|
72
|
+
preds_all = torch.cat(preds_list, dim=0).detach().cpu().numpy() # (N,)
|
|
73
|
+
|
|
74
|
+
# Class 0 == tissue -> keep
|
|
75
|
+
keep_mask_np = preds_all == 0
|
|
76
|
+
|
|
77
|
+
probs_all = torch.cat(probs_list, dim=0).detach().cpu().numpy() # (N,4)
|
|
78
|
+
collated_patch_batch.add_meta_column("cellvit_tissue_classifier_probs", np.round(probs_all, 2))
|
|
79
|
+
|
|
80
|
+
collated_patch_batch.filter_on_mask(keep_mask_np)
|
|
81
|
+
|
|
82
|
+
self.log.info(
|
|
83
|
+
f"Yielding: wsi={collated_patch_batch.wsi_id} in={len(patches)} "
|
|
84
|
+
f"kept={len(collated_patch_batch.patches)}"
|
|
85
|
+
)
|
|
86
|
+
yield collated_patch_batch
|
|
87
|
+
|
|
88
|
+
def _preprocess_batch(self, batch_imgs: np.ndarray) -> torch.Tensor:
|
|
89
|
+
"""
|
|
90
|
+
batch_imgs: uint8 (B,H,W,C) NumPy
|
|
91
|
+
returns: float32 (B,3,S,S) Torch tensor on self._device
|
|
92
|
+
"""
|
|
93
|
+
t = torch.as_tensor(batch_imgs).permute(0, 3, 1, 2).float() / 255.0 # (B,3,H,W) on CPU
|
|
94
|
+
t = t.to(self._device, non_blocking=True)
|
|
95
|
+
t = (t - self.mean) / self.std
|
|
96
|
+
return t
|
|
97
|
+
|
|
98
|
+
def _lazy_load(self):
|
|
99
|
+
if self.model is not None:
|
|
100
|
+
return
|
|
101
|
+
|
|
102
|
+
model = mobilenet_v3_small(weights=None)
|
|
103
|
+
|
|
104
|
+
# Replace classifier head to 4 classes
|
|
105
|
+
if isinstance(model.classifier[-1], nn.Linear):
|
|
106
|
+
in_features = model.classifier[-1].in_features
|
|
107
|
+
else:
|
|
108
|
+
# MobileNetV3 small's last layer is Linear(1024, 1000) by default
|
|
109
|
+
in_features = 1024
|
|
110
|
+
model.classifier[-1] = nn.Linear(in_features, 4)
|
|
111
|
+
|
|
112
|
+
# Get a real filesystem path (works even if package is in a zip)
|
|
113
|
+
with as_file(self._ckpt_resource) as ckpt_path:
|
|
114
|
+
checkpoint = torch.load(ckpt_path, map_location=self._device)
|
|
115
|
+
|
|
116
|
+
state = checkpoint.get("model_state_dict", checkpoint)
|
|
117
|
+
model.load_state_dict(state, strict=True)
|
|
118
|
+
self.model = model.to(self._device).eval()
|
|
119
|
+
|
|
120
|
+
# Move normalization buffers
|
|
121
|
+
self.mean = self.mean.to(self._device)
|
|
122
|
+
self.std = self.std.to(self._device)
|
|
123
|
+
|
|
124
|
+
self.log.info(f"Loaded checkpoint to {self._device}")
|