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,69 @@
|
|
|
1
|
+
import random
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
from typing import Any, List, Optional, Tuple
|
|
4
|
+
|
|
5
|
+
import orjson
|
|
6
|
+
import webdataset as wds
|
|
7
|
+
|
|
8
|
+
from wsi_patching.core.types.types import EncodedCollatedPatchBatch
|
|
9
|
+
from wsi_patching.writers.materialize_writers.materialize_writer_base import MaterializeWriterBase
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class WebDatasetWriter(MaterializeWriterBase):
|
|
13
|
+
"""Writer for WebDataset shards."""
|
|
14
|
+
|
|
15
|
+
def __init__(
|
|
16
|
+
self, outdir: Path = Path("./output/"), shard_size: int = 200, shuffle_buffer_size: Optional[int] = None
|
|
17
|
+
):
|
|
18
|
+
super().__init__()
|
|
19
|
+
self.outdir = outdir
|
|
20
|
+
self.shard_size = int(shard_size)
|
|
21
|
+
self.shuffle_buffer_size = int(shuffle_buffer_size) if shuffle_buffer_size is not None else int(shard_size * 3)
|
|
22
|
+
self.shard_pattern = str(self.outdir / "shard-%06d.tar")
|
|
23
|
+
self.write_count = 0
|
|
24
|
+
|
|
25
|
+
# runtime (allocated in open)
|
|
26
|
+
self._buffer: List[Tuple[str, Any, Any]] = []
|
|
27
|
+
self._sink: Optional[Any] = None
|
|
28
|
+
|
|
29
|
+
def open(self) -> None:
|
|
30
|
+
self.log.info("Opening...")
|
|
31
|
+
self.outdir.mkdir(parents=True, exist_ok=True)
|
|
32
|
+
# allocate sink in the writer process
|
|
33
|
+
self._sink = wds.ShardWriter(self.shard_pattern, maxcount=self.shard_size, verbose=0) # ty: ignore[unresolved-attribute]
|
|
34
|
+
|
|
35
|
+
def write(self, batch: EncodedCollatedPatchBatch) -> None:
|
|
36
|
+
self.log.info(f"Received batch from wsi: {batch.wsi_id} size: {len(batch.encoded_patches)}")
|
|
37
|
+
for sample_idx in range(batch.coords.shape[0]):
|
|
38
|
+
wsi_id, coord, _, meta = batch.get(sample_idx)
|
|
39
|
+
key = f"{wsi_id}_{coord[0]}_{coord[1]}"
|
|
40
|
+
encoded_patch = batch.encoded_patches[sample_idx]
|
|
41
|
+
self._buffer.append((key, encoded_patch, meta))
|
|
42
|
+
|
|
43
|
+
if len(self._buffer) >= self.shuffle_buffer_size:
|
|
44
|
+
self._flush_buffer()
|
|
45
|
+
|
|
46
|
+
def close(self) -> None:
|
|
47
|
+
if self._buffer:
|
|
48
|
+
self.log.info(f"Closing... Flushing remaining {len(self._buffer)} samples in buffer.")
|
|
49
|
+
self.log.info(f"Meta example: {self._buffer[0][2]}")
|
|
50
|
+
while self._buffer:
|
|
51
|
+
self._flush_buffer()
|
|
52
|
+
if self._sink is not None:
|
|
53
|
+
self.log.info(f"Processed {self.write_count} samples. Closing sink...")
|
|
54
|
+
self._sink.close()
|
|
55
|
+
self._sink = None
|
|
56
|
+
|
|
57
|
+
def _flush_buffer(self) -> None:
|
|
58
|
+
if not self._buffer or self._sink is None:
|
|
59
|
+
return
|
|
60
|
+
self.log.info(f"Flushing buffer of size: {len(self._buffer)}")
|
|
61
|
+
random.shuffle(self._buffer)
|
|
62
|
+
# Write up to shard_size at a time for better mixing; leftover stays buffered.
|
|
63
|
+
for _ in range(min(self.shard_size, len(self._buffer))):
|
|
64
|
+
s = self._buffer.pop()
|
|
65
|
+
self.write_count += 1
|
|
66
|
+
self._sink.write(
|
|
67
|
+
{"__key__": s[0], "png": s[1], "meta": orjson.dumps(s[2], option=orjson.OPT_SERIALIZE_NUMPY)}
|
|
68
|
+
)
|
|
69
|
+
self.log.info(f"Buffer size after flush: {len(self._buffer)}")
|
|
File without changes
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
from typing import Any, Iterator, Literal, Tuple
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
|
|
5
|
+
from wsi_patching.backends.cupy_numpy import ensure_numpy
|
|
6
|
+
from wsi_patching.core.types.types import CollatedPatchBatch
|
|
7
|
+
from wsi_patching.writers.stream_writers.stream_writer_base import StreamWriterBase
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class NumpyStreamWriter(StreamWriterBase):
|
|
11
|
+
"""
|
|
12
|
+
Returns the collated patches as numpy arrays in a streaming fashion.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
def __init__(self, layout: Literal["NCHW", "NHWC"] = "NCHW", dtype: Any = np.float32) -> None:
|
|
16
|
+
super().__init__()
|
|
17
|
+
self.layout = layout
|
|
18
|
+
self.dtype = dtype
|
|
19
|
+
|
|
20
|
+
def stream(self, batch: CollatedPatchBatch) -> Iterator[Tuple[str, np.ndarray, np.ndarray, Any]]:
|
|
21
|
+
self.log.info(f"Received batch from wsi: {batch.wsi_id} size: {len(batch.patches)}")
|
|
22
|
+
|
|
23
|
+
# coords -> np.int64
|
|
24
|
+
coords_np = np.asarray(batch.coords, dtype=np.int64)
|
|
25
|
+
|
|
26
|
+
# patches -> np.float (from numpy or cupy)
|
|
27
|
+
images_np = ensure_numpy(batch.patches)
|
|
28
|
+
images_np = np.asarray(images_np, dtype=self.dtype)
|
|
29
|
+
|
|
30
|
+
# store as requested layout (assume input is BHWC)
|
|
31
|
+
if self.layout == "NCHW":
|
|
32
|
+
# BHWC -> BCHW
|
|
33
|
+
images_np = np.transpose(images_np, (0, 3, 1, 2))
|
|
34
|
+
|
|
35
|
+
# yield
|
|
36
|
+
yield batch.wsi_id, images_np, coords_np, batch.metadata.get_all_row_wise()
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
from queue import Empty, Queue
|
|
3
|
+
from threading import Event
|
|
4
|
+
from typing import Any, Iterable, Iterator, 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 StreamWriterBase(ContextAware, metaclass=WriterMeta):
|
|
12
|
+
"""
|
|
13
|
+
Base class for generator sink stages (writers).
|
|
14
|
+
To be used for pipelines that are written to memory, instead of to disk.
|
|
15
|
+
By using a generator writer, you can process your patches in a streaming fashion.
|
|
16
|
+
This is useful for large datasets that do not fit into memory, or for real-time processing
|
|
17
|
+
|
|
18
|
+
Implementers override:
|
|
19
|
+
- write(self, batch: Any) -> None # write a batch of items
|
|
20
|
+
|
|
21
|
+
Single-process usage: writer(it) will consume the iterable and write everything.
|
|
22
|
+
Multi-process usage: writer.start_writer(queue) will block and consume messages from producers.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
def __init__(self) -> None:
|
|
26
|
+
self._is_open = False
|
|
27
|
+
|
|
28
|
+
def __init_subclass__(cls, **kwargs):
|
|
29
|
+
super().__init_subclass__(**kwargs)
|
|
30
|
+
cls.log = logging.getLogger(f"{cls.__name__}")
|
|
31
|
+
|
|
32
|
+
def stream(self, batch: Any) -> Iterator[Any]:
|
|
33
|
+
"""Stream a batch of items. Must be implemented by subclass."""
|
|
34
|
+
raise NotImplementedError
|
|
35
|
+
|
|
36
|
+
def start_writer(
|
|
37
|
+
self, queue: Queue, verbosity_level: LogLevel, stop_event: Optional[Event] = None, poll_s: float = 0.5
|
|
38
|
+
) -> Iterable[Any]:
|
|
39
|
+
"""
|
|
40
|
+
Start the writer. This will block and consume messages from the queue.
|
|
41
|
+
It will yield items as they are written.
|
|
42
|
+
"""
|
|
43
|
+
init_logging(verbosity_level)
|
|
44
|
+
|
|
45
|
+
self.log.info("Starting generator writer...")
|
|
46
|
+
try:
|
|
47
|
+
while True:
|
|
48
|
+
try:
|
|
49
|
+
msg = queue.get(timeout=poll_s)
|
|
50
|
+
except Empty:
|
|
51
|
+
if stop_event is not None and stop_event.is_set():
|
|
52
|
+
self.log.info("Stop event set; writer exiting.")
|
|
53
|
+
break
|
|
54
|
+
continue
|
|
55
|
+
|
|
56
|
+
if isinstance(msg, EndOfStream):
|
|
57
|
+
self.log.info("Received EndOfStream signal.")
|
|
58
|
+
continue
|
|
59
|
+
elif isinstance(msg, EndOfQueue):
|
|
60
|
+
self.log.info("Received EndOfQueue signal. Finishing writer.")
|
|
61
|
+
break
|
|
62
|
+
else:
|
|
63
|
+
self.log.debug(f"Received batch of size {len(msg)}")
|
|
64
|
+
for item in self.stream(msg):
|
|
65
|
+
yield item
|
|
66
|
+
|
|
67
|
+
except Exception as e:
|
|
68
|
+
self.log.exception(f"Exception in writer: {e}")
|
|
69
|
+
raise
|
|
70
|
+
finally:
|
|
71
|
+
self.log.info("Writer finished.")
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
from typing import TYPE_CHECKING, Any, Iterator, Literal, Optional, Tuple, Union
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
|
|
5
|
+
try:
|
|
6
|
+
import torch
|
|
7
|
+
except ImportError as e:
|
|
8
|
+
raise ImportError("TorchStreamWriter requires torch. Install it with: pip install wsi-patching[gpu]") from e
|
|
9
|
+
|
|
10
|
+
from wsi_patching.core.types.types import CollatedPatchBatch
|
|
11
|
+
from wsi_patching.writers.stream_writers.stream_writer_base import StreamWriterBase
|
|
12
|
+
|
|
13
|
+
if TYPE_CHECKING:
|
|
14
|
+
import cupy as cp
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class TorchStreamWriter(StreamWriterBase):
|
|
18
|
+
"""Returns the collated patches as numpy arrays in a streaming fashion."""
|
|
19
|
+
|
|
20
|
+
def __init__(
|
|
21
|
+
self,
|
|
22
|
+
layout: Literal["NCHW", "NHWC"] = "NCHW",
|
|
23
|
+
dtype: torch.dtype = torch.float32,
|
|
24
|
+
device: Optional[torch.device] = None,
|
|
25
|
+
) -> None:
|
|
26
|
+
super().__init__()
|
|
27
|
+
|
|
28
|
+
self.layout = layout
|
|
29
|
+
self.dtype = dtype
|
|
30
|
+
self.device = device
|
|
31
|
+
|
|
32
|
+
def validate(self) -> None:
|
|
33
|
+
self.ctx.require_key("use_gpu")
|
|
34
|
+
|
|
35
|
+
if self.device is None:
|
|
36
|
+
self.device = torch.device("cuda" if self._ctx["use_gpu"] else "cpu")
|
|
37
|
+
|
|
38
|
+
def stream(self, batch: CollatedPatchBatch) -> Iterator[Tuple[str, torch.Tensor, torch.Tensor, Any]]:
|
|
39
|
+
self.log.info(f"Received batch from wsi: {batch.wsi_id} size: {len(batch.patches)}")
|
|
40
|
+
|
|
41
|
+
assert self.device is not None
|
|
42
|
+
# coords -> torch.long on target device
|
|
43
|
+
coords_t = torch.as_tensor(batch.coords, dtype=torch.long, device=self.device)
|
|
44
|
+
|
|
45
|
+
# patches -> torch.float32 on target device
|
|
46
|
+
images_t = self._to_tensor(batch.patches, device=self.device, dtype=self.dtype)
|
|
47
|
+
|
|
48
|
+
# expect BHWC; permute if user requested NCHW (default)
|
|
49
|
+
if self.layout == "NCHW":
|
|
50
|
+
images_t = images_t.permute(0, 3, 1, 2).contiguous()
|
|
51
|
+
|
|
52
|
+
# basic length check
|
|
53
|
+
if images_t.shape[0] != coords_t.shape[0]:
|
|
54
|
+
raise ValueError(
|
|
55
|
+
f"Batch length mismatch: images N={images_t.shape[0]} vs coords N={coords_t.shape[0]} "
|
|
56
|
+
f"(wsi_id={batch.wsi_id})"
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
# accumulate
|
|
60
|
+
yield batch.wsi_id, images_t, coords_t, batch.metadata.get_all_row_wise()
|
|
61
|
+
|
|
62
|
+
def _to_tensor(
|
|
63
|
+
self, arr: Union[np.ndarray, "cp.ndarray"], device: torch.device, dtype: torch.dtype
|
|
64
|
+
) -> torch.Tensor:
|
|
65
|
+
"""Convert numpy/cupy BCHW array to torch.Tensor on desired device & dtype (eager)."""
|
|
66
|
+
# move/cast in one go
|
|
67
|
+
return torch.as_tensor(arr).to(device=device, dtype=dtype, non_blocking=(device.type in ("cuda", "mps")))
|
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: wsi-patching
|
|
3
|
+
Version: 0.5.0
|
|
4
|
+
Summary: A High Performance Patching Library for Digital Pathology AI dataset creation.
|
|
5
|
+
Project-URL: Homepage, https://github.com/amspath/wsi-patching-pipeline
|
|
6
|
+
Project-URL: Repository, https://github.com/amspath/wsi-patching-pipeline
|
|
7
|
+
Author-email: Robin van Hoorn <r.d.vanhoorn@amsterdamumc.nl>
|
|
8
|
+
License: MIT License
|
|
9
|
+
|
|
10
|
+
Copyright (c) 2024 Robin van Hoorn
|
|
11
|
+
|
|
12
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
13
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
14
|
+
in the Software without restriction, including without limitation the rights
|
|
15
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
16
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
17
|
+
furnished to do so, subject to the following conditions:
|
|
18
|
+
|
|
19
|
+
The above copyright notice and this permission notice shall be included in all
|
|
20
|
+
copies or substantial portions of the Software.
|
|
21
|
+
|
|
22
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
23
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
24
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
25
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
26
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
27
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
28
|
+
SOFTWARE.
|
|
29
|
+
License-File: LICENSE
|
|
30
|
+
Keywords: WSI,deep learning,digital pathology,medical imaging,patching,whole slide image
|
|
31
|
+
Classifier: Development Status :: 4 - Beta
|
|
32
|
+
Classifier: Intended Audience :: Science/Research
|
|
33
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
34
|
+
Classifier: Operating System :: OS Independent
|
|
35
|
+
Classifier: Programming Language :: Python :: 3
|
|
36
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
37
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
38
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
39
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
40
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
41
|
+
Classifier: Topic :: Scientific/Engineering :: Medical Science Apps.
|
|
42
|
+
Requires-Python: <3.14,>=3.10
|
|
43
|
+
Requires-Dist: fastslide==0.5.2
|
|
44
|
+
Requires-Dist: numpy>=1.24
|
|
45
|
+
Requires-Dist: opencv-python-headless>=4.8
|
|
46
|
+
Requires-Dist: orjson>=3.8
|
|
47
|
+
Requires-Dist: pillow>=9.0
|
|
48
|
+
Requires-Dist: rtree>=1.0
|
|
49
|
+
Requires-Dist: webdataset>=0.2.86
|
|
50
|
+
Provides-Extra: dev
|
|
51
|
+
Requires-Dist: mkdocs-material; extra == 'dev'
|
|
52
|
+
Requires-Dist: pytest; extra == 'dev'
|
|
53
|
+
Requires-Dist: pytest-benchmark; extra == 'dev'
|
|
54
|
+
Requires-Dist: ruff; extra == 'dev'
|
|
55
|
+
Requires-Dist: tifffile; extra == 'dev'
|
|
56
|
+
Requires-Dist: ty; extra == 'dev'
|
|
57
|
+
Provides-Extra: gpu
|
|
58
|
+
Requires-Dist: cupy-cuda12x; (platform_system != 'Darwin') and extra == 'gpu'
|
|
59
|
+
Requires-Dist: torch; extra == 'gpu'
|
|
60
|
+
Requires-Dist: torchvision; extra == 'gpu'
|
|
61
|
+
Description-Content-Type: text/markdown
|
|
62
|
+
|
|
63
|
+
[](https://github.com/amspath/wsi-patching-pipeline/actions/workflows/unit_tests.yaml)
|
|
64
|
+
[](https://github.com/amspath/wsi-patching-pipeline/actions/workflows/integration_tests.yaml)
|
|
65
|
+
|
|
66
|
+
# wsi-patching-pipeline
|
|
67
|
+
A pragmatic pipeline for streaming whole-slide image (WSI) patches with region prefetch, per-WSI multiprocessing producers, and an async writer. It's ideal for building pipelines that create datasets, or for patching in a streaming fashion during inference without overloading your memory. It’s designed as a runnable skeleton you can extend: swap in your own ROI logic, classifiers, encoders, or sinks by building components on the `custom_component` module facilities.
|
|
68
|
+
|
|
69
|
+
✨ What you get
|
|
70
|
+
- Streaming, regionized tiling of WSIs.
|
|
71
|
+
- Per-slide producers (theading) feeding a bounded queue.
|
|
72
|
+
- Single writer process for continuous writing in the sink (i.e. to a webdataset, or numpy arrays).
|
|
73
|
+
- Batched GPU steps.
|
|
74
|
+
- Built-in isolated stage profiling per slide + aggregated stats.
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
## 1) Library install
|
|
78
|
+
|
|
79
|
+
Python ≥3.10 <3.14 is recommended. 3.14 is yet unsupported.
|
|
80
|
+
```
|
|
81
|
+
# CPU install
|
|
82
|
+
pip install "wsi-patching @ git+https://github.com/amspath/wsi-patching-pipeline.git"
|
|
83
|
+
|
|
84
|
+
# GPU install
|
|
85
|
+
pip install "wsi-patching[gpu] @ git+https://github.com/amspath/wsi-patching-pipeline.git"
|
|
86
|
+
```
|
|
87
|
+
> For some stages, GPUs are required, and thus the GPU install is required.
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
## 2) Checkout the examples
|
|
91
|
+
`numpy_mem_writer_demo.py` shows you how to build a basic pipeline for patching up a wsi in memory, without the need of writing to disk (RAM heavy for larger datasets, obviously).
|
|
92
|
+
```python
|
|
93
|
+
p = (
|
|
94
|
+
WSIGrid(slides=slides, resolution=0, unit="level", use_gpu=True)
|
|
95
|
+
.then(PatchExtractor(tile_size=256, stride=256, max_batch_size=800, num_workers=4))
|
|
96
|
+
.then(LowContrastBackgroundFilter(range_threshold=0.2))
|
|
97
|
+
.then(ReinhardNormalizer())
|
|
98
|
+
.to(NumpyMemoryWriter(layout="NCHW"))
|
|
99
|
+
)
|
|
100
|
+
stream = p.stream(num_workers=4)
|
|
101
|
+
for wsi_id, final_images, final_coords, meta in stream:
|
|
102
|
+
...
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
> Useful to know: Stream writers do not order the patches per WSI. This improves speed. You can check the wsi_id returned from the stream to check which WSI each batch belongs to. If you per se want ordered batches, you can set the num_workers to 1.
|
|
106
|
+
|
|
107
|
+
`webdataset_materialize_writer_demo.py` shows you how to build a basic pipeline for creating a WebDataset (A materializing pipeline)
|
|
108
|
+
```python
|
|
109
|
+
p = (
|
|
110
|
+
WSIGrid(slides=slides, resolution=0, unit="level")
|
|
111
|
+
.then(AttachROIs(providers=[RectROIProvider(rois_dict)]))
|
|
112
|
+
.then(PatchExtractor(tile_size=224, stride=224))
|
|
113
|
+
.then(PNGEncoder())
|
|
114
|
+
.to(WebDatasetWriter(shard_size=300, shuffle_buffer_size=500))
|
|
115
|
+
)
|
|
116
|
+
p.materialize(num_workers=4)
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
## 3) Check out the currently available components:
|
|
120
|
+
#### Core components
|
|
121
|
+
- `WSIGrid`: Your starter block
|
|
122
|
+
- `AttachROIs`: Attach an ROI provider class to ensure that only your regions of interest are patched up. There are two basic ROI providers implemented, being a `RectROIProvider`, and a `RectROIfromXMLProvider`. More to come when needed.
|
|
123
|
+
- `PatchExtractor`: A necessary component in every pipeline. This will nicely read and batch up all your patches. The PatchExtractor is a composite stage, which contains three stages. If you want to adapt the PatchExtractor logic, you can individually add the substages to your pipeline and swap out stages for custom ones.
|
|
124
|
+
- A sink component to define what the output should be. There are two types of writers:
|
|
125
|
+
- `MaterializeWriterBase` writers: For writers that materialize data (i.e. write to disk). These types of writers are particularly useful for making large training datasets. Examples include:
|
|
126
|
+
- `WebdatasetWriter`: For writing to/creating a webdataset.
|
|
127
|
+
- `StreamWriterBase` writers: For writers that stream batches of data to memory. These types of writers are particularly useful for patching during inference or in any situation where you don't necessarily want to write to your disk. Examples include:
|
|
128
|
+
- `NumpyStreamWriter`: For obtaining numpy patches.
|
|
129
|
+
- `TorchStreamWriter`: For obtaining torch tensors.
|
|
130
|
+
|
|
131
|
+
#### Other components
|
|
132
|
+
- Filters: For filtering out your patches that you do not need
|
|
133
|
+
- `LowContrastBackgroundFilter`: A simple filter for filtering out background with very little difference between pixels.
|
|
134
|
+
- `OtsuFilter`: Applying otsu's method and filtering on a threshold.
|
|
135
|
+
- `PenArtifactFilter`: Applying histolabs blue, green and red pen filters, but using our own batched, gpu accelerated implementation.
|
|
136
|
+
- `CellVitTissueClassifierFilter`: Using CellVits original tissue classifier, it classifies patches as background using a mobilenetv3.
|
|
137
|
+
- Transforms: For transforming your patches
|
|
138
|
+
- `Macenko Normalizer`: Applies Macenko normalizer, fitting on the first batch it encounters (watch out for the first batch being a background batch).
|
|
139
|
+
- `Reinhard Normalizer`: Applies Reinhard normalizer with the reference LAB color mean and std statistics provided. Uses this configuration by default (computed for "golden" kidney AUMC scans):
|
|
140
|
+
```
|
|
141
|
+
lab_reference_mean = [68.94, 29.76, -18.97]
|
|
142
|
+
lab_reference_std = [11.52, 13.42, 8.59]
|
|
143
|
+
```
|
|
144
|
+
- Encoders: For encoding your patches into the right format
|
|
145
|
+
- `PNGEncoder` Transforming your patches into PNGs. Particularly useful for the WebDatasetWriter.
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
More to come! Request if you would like your stage to be in the library.
|
|
149
|
+
|
|
150
|
+
## 4) Build your own components
|
|
151
|
+
This library is setup such that you can easily build your own components to suit your own needs and pop it into the pipeline. Components can either extend the `Stage` (a processing stage) or `WriterBase` (a sink) components.
|
|
152
|
+
|
|
153
|
+
#### Creating a stage component:
|
|
154
|
+
```python
|
|
155
|
+
from wsi_patching.custom_component import Stage, PipelineContext, # <PreviousStageOutputType> and <NextStageInputType> can also be found here
|
|
156
|
+
|
|
157
|
+
class CustomStage(Stage):
|
|
158
|
+
def __init__(self, ...):
|
|
159
|
+
...
|
|
160
|
+
|
|
161
|
+
def export_context(self, ctx: "PipelineContext") -> None:
|
|
162
|
+
# Optional: Seed/override global grid parameters for other stages to read, i.e.
|
|
163
|
+
ctx["tile_size"] = self.tile_size
|
|
164
|
+
def validate(self) -> None:
|
|
165
|
+
# Optional: Validate your class before starting processing, i.e.
|
|
166
|
+
self.ctx.require_key("use_gpu")
|
|
167
|
+
if self.ctx['some_key'] < self.some_init_param:
|
|
168
|
+
...
|
|
169
|
+
|
|
170
|
+
def __call__(self, it: Iterable[<PreviousStageOutputType>]) -> Iterable[<NextStageInputType>]:
|
|
171
|
+
# The logic of your stage. You should specifiy the type of your call function.
|
|
172
|
+
# These should align with the preceeding and succeeding stages (checked at initialization).
|
|
173
|
+
...
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
#### Creating a custom sink component:
|
|
177
|
+
```python
|
|
178
|
+
from wsi_patching.custom_component import StreamWriterBase, MaterializeWriterBase, # <PreviousStageOutputType> can also be found here
|
|
179
|
+
|
|
180
|
+
class CustomWriter(MaterializeWriterBase):
|
|
181
|
+
def __init__(self, ...):
|
|
182
|
+
...
|
|
183
|
+
def open(self) -> None:
|
|
184
|
+
# Opening your writer
|
|
185
|
+
|
|
186
|
+
def write(self, sample: <PreviousStageOutputType>) -> None:
|
|
187
|
+
# What to do with a single sample
|
|
188
|
+
def close(self) -> None:
|
|
189
|
+
# Closing up the buffer
|
|
190
|
+
|
|
191
|
+
def get_output(self) -> Any:
|
|
192
|
+
# Optional: if you want to output something in memory.
|
|
193
|
+
|
|
194
|
+
# StreamWriterBase is slightly simpler
|
|
195
|
+
```
|
|
196
|
+
|
|
197
|
+
#### Profiling runtime of a custom component:
|
|
198
|
+
```python
|
|
199
|
+
import time
|
|
200
|
+
|
|
201
|
+
class CustomStage(Stage/WriterBase):
|
|
202
|
+
...
|
|
203
|
+
|
|
204
|
+
def __call__(self, it: ...):
|
|
205
|
+
prof = self.get_current_profiler()
|
|
206
|
+
for something in it:
|
|
207
|
+
# Start measuring the iteration
|
|
208
|
+
t0 = time.perf_counter()
|
|
209
|
+
|
|
210
|
+
# Do some heavy operation
|
|
211
|
+
output = ...
|
|
212
|
+
|
|
213
|
+
# Stop the clock
|
|
214
|
+
dt = time.perf_counter() - t0
|
|
215
|
+
if output:
|
|
216
|
+
prof.add_time("CustomStage", dt, yielded=True)
|
|
217
|
+
yield output
|
|
218
|
+
else:
|
|
219
|
+
prof.add_time("CustomStage", dt, yielded=False)
|
|
220
|
+
```
|
|
221
|
+
This will count per slide per iteration breakdown of how fast this stage is, in the form of:
|
|
222
|
+
```
|
|
223
|
+
=== Pipeline Profile (isolated timings only) ===
|
|
224
|
+
Stage Yields Wall (s) Avg (ms/yield)
|
|
225
|
+
PNGEncoder.isolated 640 1.440s 2.412ms
|
|
226
|
+
|
|
227
|
+
--- Per slide breakdown ---
|
|
228
|
+
[RBIO-GC072-HE-02]
|
|
229
|
+
PNGEncoder.isolated yields= 320 wall= 0.762s avg= 2.382ms
|
|
230
|
+
[RBIO-GC072-HE-01]
|
|
231
|
+
PNGEncoder.isolated yields= 320 wall= 0.778s avg= 2.432ms
|
|
232
|
+
```
|
|
233
|
+
|
|
234
|
+
## 5) Development install
|
|
235
|
+
|
|
236
|
+
Python ≥3.10 is recommended. UV is also recommended as the package manager
|
|
237
|
+
```
|
|
238
|
+
git clone https://github.com/amspath/wsi-patching-pipeline.git
|
|
239
|
+
cd wsi-patching-pipeline
|
|
240
|
+
uv sync --extra dev,gpu
|
|
241
|
+
```
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
## 6) More will come
|
|
245
|
+
- [ ] Retrained MobileNet classifier for tissue detection with proper documentation.
|
|
246
|
+
- [ ] Controlled batch sizes in each of the shipped writers
|
|
247
|
+
|
|
248
|
+
## 7) Contributing
|
|
249
|
+
Feel free to contribute by opening a pull request or adding an issue to the github. We develop this library based on our own usage of it. So if something is not implemented, we just haven´t had the need for it yet. However, we are very open to add new functionality.
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
wsi_patching/__init__.py,sha256=gr0caeNw65KvEnI1vJtQ3WjAZeMP8uGncGKvbTURGpU,1143
|
|
2
|
+
wsi_patching/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
3
|
+
wsi_patching/annotations/__init__.py,sha256=pOUTUE6dqbdhMxosFasWSBHqSjqcpx7RNIR-4zbu-T0,107
|
|
4
|
+
wsi_patching/annotations/add_cell_annotation_from_csv.py,sha256=WeIztAddLAnIqSatkaiFjwNV36si2G2rKVBh0NTtIXE,5856
|
|
5
|
+
wsi_patching/assets/models/cellvit_tissue_detector.pt,sha256=9UexgRatCxpDkKARdOZuOzRCiTsDYQnABYHYLtImzgs,6219914
|
|
6
|
+
wsi_patching/backends/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
7
|
+
wsi_patching/backends/cupy_numpy.py,sha256=Ea-BtbYIPSMVEWLkpOWvdAe6nefCZ__mrZ12IJAgP4g,2546
|
|
8
|
+
wsi_patching/backends/fastslide.py,sha256=kECoX25oTbH6kvdSfB9kJEub4G_iUbLmd09r3Ogwl20,9055
|
|
9
|
+
wsi_patching/backends/torch_device.py,sha256=im_6WqFj7dFMWYrb-AxMI-aFy5LyZvVOcU_QUqf7f6U,1461
|
|
10
|
+
wsi_patching/core/__init__.py,sha256=xpTNz_aNL5hzvFuara82FuVS8sXPzPcJ2orQ9DauCLU,231
|
|
11
|
+
wsi_patching/core/chunking_and_batching.py,sha256=9kwAVRZcYDQqSuCtK9Z7476WwRQnUmc6V38r6PmB7mY,23101
|
|
12
|
+
wsi_patching/core/pipeline.py,sha256=3qHcBv0SZu3xOCTSz7S0KsWg5hUVIdcydVW-ZLuwc0I,21547
|
|
13
|
+
wsi_patching/core/wsi_grid.py,sha256=uU1LlTvlMF8Bn7wHi_XLAydLTP_PbSuHoH-5SOt9hzM,5077
|
|
14
|
+
wsi_patching/core/types/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
15
|
+
wsi_patching/core/types/types.py,sha256=6bo6v3k7b5cvvYCgEi9372AuIOj5glzvvjzH5BkdYIU,4123
|
|
16
|
+
wsi_patching/core/types/util_types.py,sha256=K5R1nxsI8R06LN-9r1zDnnRuR9XwH0n2qVRxnUdW3FY,2887
|
|
17
|
+
wsi_patching/custom_component/__init__.py,sha256=T2liaNaAZttF0dtYqMr9EOHfU1wD0JinY2aGKoitC5k,548
|
|
18
|
+
wsi_patching/encoders/__init__.py,sha256=t92vyUdZnDjM_oyCHBblhqxZIlB3GbA_fSIs2FQLGZ4,61
|
|
19
|
+
wsi_patching/encoders/pngencoder.py,sha256=UJxOegwxxkNWJorTYJ8bnsXiRhaNbvV-3vndnOme0Vk,2960
|
|
20
|
+
wsi_patching/filtering/__init__.py,sha256=U2_YyO2yLapgQqkOCQSdFbMtqaZ_Vi9-4CZ246OytOA,404
|
|
21
|
+
wsi_patching/filtering/cellvit_tissue_classifier_filter.py,sha256=ki_IUWxdF2aA0Dc0kAaCwIkyd-cwr8fWppURca5ZVHs,4661
|
|
22
|
+
wsi_patching/filtering/low_contrast_background_filter.py,sha256=ouIfDAEDjhG_98SVurh7KXeIggl-uz0SzdChct89AaE,5081
|
|
23
|
+
wsi_patching/filtering/otsu_filter.py,sha256=w3aTGzQPxtXhvrZNgoTjk2NKmylDiFwnS9KXjZ7zt50,9228
|
|
24
|
+
wsi_patching/filtering/pen_artifact_filter.py,sha256=A7cMtVC-WQ_-EEi6DjRKNEsapXEzMF_-1wyDZQKZ0vc,8734
|
|
25
|
+
wsi_patching/regions_of_interest/__init__.py,sha256=obiKTO434izU_ju6RYMY8PSnzqkxBP5aNLbzTtMn1ho,216
|
|
26
|
+
wsi_patching/regions_of_interest/attach_rois.py,sha256=55u6dLpU-CuUHG1Ry3VJoXedzhqlqeKQamoZSVWT6I4,2675
|
|
27
|
+
wsi_patching/regions_of_interest/roi_providers.py,sha256=HlDwGo2neGpYj0JVBfMACt7_q0tQ3eodL-_2hij3NT0,3466
|
|
28
|
+
wsi_patching/regions_of_interest/rois.py,sha256=E7k-QtpZcHxEUid4tHuc6dyvDA603j7D_Z6H_8U7o04,2351
|
|
29
|
+
wsi_patching/transforms/__init__.py,sha256=QcwfLpjeJYpA-W9cQOfDRMmZgWm0ixCve7HUGn44vXc,157
|
|
30
|
+
wsi_patching/transforms/macenko_normalizer.py,sha256=sXa2ZBcuDCFH1B9KHfXAtjw_6oPI6cJNHrF_8Qbcvnw,6469
|
|
31
|
+
wsi_patching/transforms/reinhard_normalizer.py,sha256=gvYb3d4plfF-_lcFJasnWn2TjbD9yOKslApTt2h2UKE,10613
|
|
32
|
+
wsi_patching/utils/__init__.py,sha256=kfXp1eFA4bomjWxIDATT4EznPW3f57r5NHz5rSbT8Qc,110
|
|
33
|
+
wsi_patching/utils/logging_config.py,sha256=SWqYmzWdxjidrkyVIGX0o96oDkPFFSg0qXW40TRKLH4,411
|
|
34
|
+
wsi_patching/utils/meta_typing.py,sha256=orovTRMAPk6sVaD44UXDmwjW-4557Le7s9dsQYo3LYA,3096
|
|
35
|
+
wsi_patching/utils/profiling.py,sha256=ISuTbO31cdOyYG3oe9FVWkdCAkOW6fe77RuqmRO7DKc,4488
|
|
36
|
+
wsi_patching/utils/wsi_thumbnail_visualization.py,sha256=NRDpy5NFpvsjY0hgr8LxfgW4IDxDXi_IlUzK44optMo,7763
|
|
37
|
+
wsi_patching/writers/__init__.py,sha256=VTjrEoaxp_RvzhxUW_8gdxi6nB2z0px8rwMu-Gvf7bc,427
|
|
38
|
+
wsi_patching/writers/materialize_writers/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
39
|
+
wsi_patching/writers/materialize_writers/materialize_writer_base.py,sha256=ac1EkhzJd0bOfI98-WkvILAwNtnZxZyh1a9juE1GzHE,3470
|
|
40
|
+
wsi_patching/writers/materialize_writers/webdataset/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
41
|
+
wsi_patching/writers/materialize_writers/webdataset/webdataset_loader.py,sha256=odl07VTY8wu2nEWNYCtfVL0VprBxc_VS5Mx84eeWeww,6213
|
|
42
|
+
wsi_patching/writers/materialize_writers/webdataset/webdataset_writer.py,sha256=2vHmYHAFrHWqEonSb5L3eBRmTXsQgImw1MmI3s8AyKQ,2939
|
|
43
|
+
wsi_patching/writers/stream_writers/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
44
|
+
wsi_patching/writers/stream_writers/numpy_stream_writer.py,sha256=LOadvFK490CtKGID6uDbEAFpo9eyYYBbcCCeEmoD4Dw,1321
|
|
45
|
+
wsi_patching/writers/stream_writers/stream_writer_base.py,sha256=JY5twrLdkf1RR-YKJN5r3qzWCbMKrWbqfIVgtRbyD4E,2770
|
|
46
|
+
wsi_patching/writers/stream_writers/torch_stream_writer.py,sha256=a-Q0iSbOHjBfiqXRIEwe8633Kj9PfK8y4HPATV3jEcc,2495
|
|
47
|
+
wsi_patching-0.5.0.dist-info/METADATA,sha256=IBwm-uO2fu2QrxfO6GJTBLq4geZzcm668qLDPKuTPss,12385
|
|
48
|
+
wsi_patching-0.5.0.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
|
|
49
|
+
wsi_patching-0.5.0.dist-info/licenses/LICENSE,sha256=MeR4QXr60S_2dRxb22DS2Etj7oZ9Q1ppp4zZCnEjKQ8,1072
|
|
50
|
+
wsi_patching-0.5.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024 Robin van Hoorn
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|