wsi-patching 0.5.5__tar.gz → 0.5.6__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (115) hide show
  1. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/PKG-INFO +1 -1
  2. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/docs/concepts.md +1 -1
  3. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/docs/extending.md +4 -0
  4. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/src/wsi_patching/core/chunking_and_batching.py +6 -1
  5. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/src/wsi_patching/core/pipeline.py +17 -15
  6. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/src/wsi_patching/core/types/types.py +4 -0
  7. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/src/wsi_patching/core/types/util_types.py +11 -2
  8. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/src/wsi_patching/filtering/cellvit_tissue_classifier_filter.py +2 -0
  9. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/src/wsi_patching/filtering/low_contrast_background_filter.py +5 -2
  10. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/src/wsi_patching/filtering/otsu_filter.py +12 -6
  11. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/src/wsi_patching/filtering/pen_artifact_filter.py +10 -3
  12. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/src/wsi_patching/filtering/remove_edge_tiles.py +3 -0
  13. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/src/wsi_patching/transforms/macenko_normalizer.py +3 -0
  14. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/src/wsi_patching/transforms/reinhard_normalizer.py +5 -1
  15. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/src/wsi_patching/writers/stream_writers/stream_writer_base.py +21 -2
  16. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/tests/integration/conftest.py +13 -0
  17. wsi_patching-0.5.6/tests/integration/test_empty_slide.py +58 -0
  18. wsi_patching-0.5.6/tests/integration/test_level0_scale.py +38 -0
  19. wsi_patching-0.5.6/tests/integration/test_slide_end_hook.py +38 -0
  20. wsi_patching-0.5.6/tests/integration/test_slide_failed.py +49 -0
  21. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/tests/unit/src/wsi_patching/core/test_chunking_and_batching.py +22 -1
  22. wsi_patching-0.5.6/tests/unit/src/wsi_patching/test_empty_batches.py +89 -0
  23. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/tests/unit/src/wsi_patching/writers/stream_writers/test_stream_writer_base.py +47 -1
  24. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/.github/workflows/docs.yml +0 -0
  25. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/.github/workflows/integration_tests.yaml +0 -0
  26. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/.github/workflows/publish.yaml +0 -0
  27. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/.github/workflows/unit_tests.yaml +0 -0
  28. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/.gitignore +0 -0
  29. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/LICENSE +0 -0
  30. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/README.md +0 -0
  31. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/docs/auditing.md +0 -0
  32. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/docs/index.md +0 -0
  33. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/docs/installation.md +0 -0
  34. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/docs/quickstart.md +0 -0
  35. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/docs/reference.md +0 -0
  36. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/examples/audit_and_visualize_demo.ipynb +0 -0
  37. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/examples/numpy_stream_writer_demo.py +0 -0
  38. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/examples/torch_stream_writer_demo.py +0 -0
  39. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/examples/webdataset_materialize_writer_demo.py +0 -0
  40. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/mkdocs.yml +0 -0
  41. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/pyproject.toml +0 -0
  42. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/src/wsi_patching/__init__.py +0 -0
  43. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/src/wsi_patching/annotations/__init__.py +0 -0
  44. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/src/wsi_patching/annotations/add_annotation_from_geojson.py +0 -0
  45. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/src/wsi_patching/annotations/add_cell_annotation_from_csv.py +0 -0
  46. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/src/wsi_patching/assets/models/cellvit_tissue_detector.pt +0 -0
  47. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/src/wsi_patching/backends/__init__.py +0 -0
  48. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/src/wsi_patching/backends/cupy_numpy.py +0 -0
  49. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/src/wsi_patching/backends/fastslide.py +0 -0
  50. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/src/wsi_patching/backends/torch_device.py +0 -0
  51. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/src/wsi_patching/core/__init__.py +0 -0
  52. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/src/wsi_patching/core/types/__init__.py +0 -0
  53. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/src/wsi_patching/core/wsi_grid.py +0 -0
  54. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/src/wsi_patching/custom_component/__init__.py +0 -0
  55. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/src/wsi_patching/encoders/__init__.py +0 -0
  56. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/src/wsi_patching/encoders/pngencoder.py +0 -0
  57. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/src/wsi_patching/filtering/__init__.py +0 -0
  58. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/src/wsi_patching/py.typed +0 -0
  59. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/src/wsi_patching/regions_of_interest/__init__.py +0 -0
  60. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/src/wsi_patching/regions_of_interest/attach_rois.py +0 -0
  61. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/src/wsi_patching/regions_of_interest/roi_providers.py +0 -0
  62. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/src/wsi_patching/regions_of_interest/rois.py +0 -0
  63. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/src/wsi_patching/transforms/__init__.py +0 -0
  64. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/src/wsi_patching/utils/__init__.py +0 -0
  65. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/src/wsi_patching/utils/audit.py +0 -0
  66. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/src/wsi_patching/utils/logging_config.py +0 -0
  67. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/src/wsi_patching/utils/meta_typing.py +0 -0
  68. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/src/wsi_patching/utils/profiling.py +0 -0
  69. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/src/wsi_patching/utils/wsi_thumbnail_visualization.py +0 -0
  70. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/src/wsi_patching/writers/__init__.py +0 -0
  71. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/src/wsi_patching/writers/materialize_writers/__init__.py +0 -0
  72. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/src/wsi_patching/writers/materialize_writers/materialize_writer_base.py +0 -0
  73. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/src/wsi_patching/writers/materialize_writers/webdataset/__init__.py +0 -0
  74. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/src/wsi_patching/writers/materialize_writers/webdataset/webdataset_loader.py +0 -0
  75. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/src/wsi_patching/writers/materialize_writers/webdataset/webdataset_writer.py +0 -0
  76. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/src/wsi_patching/writers/stream_writers/__init__.py +0 -0
  77. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/src/wsi_patching/writers/stream_writers/numpy_stream_writer.py +0 -0
  78. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/src/wsi_patching/writers/stream_writers/torch_stream_writer.py +0 -0
  79. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/tests/benchmarks/conftest.py +0 -0
  80. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/tests/benchmarks/test_benchmark_pipeline.py +0 -0
  81. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/tests/benchmarks/test_benchmark_png_encoding.py +0 -0
  82. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/tests/benchmarks/test_benchmark_tile_planning.py +0 -0
  83. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/tests/integration/test_audit_pipeline.py +0 -0
  84. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/tests/integration/test_materialize_pipeline.py +0 -0
  85. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/tests/integration/test_resample_pipeline.py +0 -0
  86. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/tests/integration/test_roi_pipeline.py +0 -0
  87. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/tests/integration/test_streaming_pipeline.py +0 -0
  88. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/tests/unit/src/wsi_patching/.gitkeep +0 -0
  89. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/tests/unit/src/wsi_patching/annotations/test_add_annotation_from_geojson.py +0 -0
  90. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/tests/unit/src/wsi_patching/annotations/test_add_cell_annotation_from_csv.py +0 -0
  91. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/tests/unit/src/wsi_patching/backends/test_cupy_numpy.py +0 -0
  92. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/tests/unit/src/wsi_patching/backends/test_fastslide.py +0 -0
  93. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/tests/unit/src/wsi_patching/backends/test_torch_device.py +0 -0
  94. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/tests/unit/src/wsi_patching/core/test_pipeline.py +0 -0
  95. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/tests/unit/src/wsi_patching/core/test_wsi_grid.py +0 -0
  96. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/tests/unit/src/wsi_patching/filtering/test_cellvit_tissue_classifier_filter.py +0 -0
  97. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/tests/unit/src/wsi_patching/filtering/test_low_contrast_background_filter.py +0 -0
  98. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/tests/unit/src/wsi_patching/filtering/test_otsu_filter.py +0 -0
  99. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/tests/unit/src/wsi_patching/filtering/test_pen_artifact_filter.py +0 -0
  100. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/tests/unit/src/wsi_patching/filtering/test_remove_edge_tiles.py +0 -0
  101. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/tests/unit/src/wsi_patching/regions_of_interest/test_attach_rois.py +0 -0
  102. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/tests/unit/src/wsi_patching/regions_of_interest/test_roi_providers.py +0 -0
  103. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/tests/unit/src/wsi_patching/regions_of_interest/test_rois.py +0 -0
  104. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/tests/unit/src/wsi_patching/transforms/test_macenko_normalizer.py +0 -0
  105. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/tests/unit/src/wsi_patching/transforms/test_reinhard_normalizer.py +0 -0
  106. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/tests/unit/src/wsi_patching/utils/test_audit.py +0 -0
  107. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/tests/unit/src/wsi_patching/utils/test_logging_config.py +0 -0
  108. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/tests/unit/src/wsi_patching/utils/test_meta_typing.py +0 -0
  109. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/tests/unit/src/wsi_patching/utils/test_profiling.py +0 -0
  110. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/tests/unit/src/wsi_patching/writers/materialize_writers/test_materialize_writer_base.py +0 -0
  111. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/tests/unit/src/wsi_patching/writers/materialize_writers/webdataset/test_webdataset_loader.py +0 -0
  112. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/tests/unit/src/wsi_patching/writers/materialize_writers/webdataset/test_webdataset_writer.py +0 -0
  113. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/tests/unit/src/wsi_patching/writers/stream_writers/test_numpy_stream_writer.py +0 -0
  114. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/tests/unit/src/wsi_patching/writers/stream_writers/test_torch_stream_writer.py +0 -0
  115. {wsi_patching-0.5.5 → wsi_patching-0.5.6}/uv.lock +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: wsi-patching
3
- Version: 0.5.5
3
+ Version: 0.5.6
4
4
  Summary: A High Performance Patching Library for Digital Pathology AI dataset creation.
5
5
  Project-URL: Homepage, https://github.com/amspath/wsi-patching-pipeline
6
6
  Project-URL: Repository, https://github.com/amspath/wsi-patching-pipeline
@@ -46,7 +46,7 @@ Running a pipeline spawns three categories of threads:
46
46
  └─────────────────────┘
47
47
  ```
48
48
 
49
- - **Producer threads** each run an independent copy of the full stage chain for one slide. When a producer finishes a slide it puts an `EndOfStream` sentinel on the queue to signal the slide boundary. The supervisor then spawns a new producer for the next pending slide.
49
+ - **Producer threads** each run an independent copy of the full stage chain for one slide. When a producer finishes a slide it puts an `EndOfStream(wsi_id)` sentinel on the queue to signal the slide boundary. Stream writers receive it through `on_slide_end(wsi_id)`. If the producer fails, it puts a `SlideFailed(wsi_id, error)` instead, which stream writers receive through `on_slide_failed(wsi_id, error)`. The supervisor then spawns a new producer for the next pending slide.
50
50
  - **The queue** is bounded (`maxsize = writer_prefetch_factor × num_workers`, default 8). This provides natural backpressure: producers block when the writer is slow rather than accumulating unbounded memory.
51
51
  - **`EndOfQueue`** is put onto the queue once all slides are done, signalling the writer to stop.
52
52
  - In **`.stream()` mode** the writer runs as a generator in the caller's thread — each iteration of `for wsi_id, images, ... in p.stream()` drives the writer forward.
@@ -78,6 +78,10 @@ class MyStreamWriter(StreamWriterBase):
78
78
 
79
79
  `stream()` is called once per queue item. The pipeline handles threading and queue management; you only need to focus on the transformation.
80
80
 
81
+ Override `on_slide_end(wsi_id)` to act when a slide is done. It is called once per slide, after that slide's last batch, and anything it yields is streamed like `stream()` output. The default does nothing.
82
+
83
+ Override `on_slide_failed(wsi_id, error)` to act when a producer fails on a slide. It is called instead of `on_slide_end` for that slide. Batches of that slide that were already streamed stay streamed. With `gracefully_handle_producer_errors=True` the other slides keep going. The default does nothing.
84
+
81
85
  ---
82
86
 
83
87
  ## Custom MaterializeWriter
@@ -415,7 +415,12 @@ class RegionReadAndBatch(Stage):
415
415
  coords_out = coords_slice.copy()
416
416
  patches_xp = xp.asarray(batch_slice.copy(), dtype=self.dtype)
417
417
  cpb = CollatedPatchBatch(
418
- task.wsi_id, coords_out, patches_xp, use_gpu=self.ctx["use_gpu"], wsi_dims=task.wsi_dims
418
+ task.wsi_id,
419
+ coords_out,
420
+ patches_xp,
421
+ use_gpu=self.ctx["use_gpu"],
422
+ wsi_dims=task.wsi_dims,
423
+ level0_scale=task.downsample,
419
424
  )
420
425
  for k, v in task.meta.items():
421
426
  cpb.add_meta_column(k, np.array([v] * len(coords_out)))
@@ -11,7 +11,7 @@ import numpy as np
11
11
 
12
12
  from wsi_patching.backends.fastslide import close_cached_slides
13
13
  from wsi_patching.core.types.types import EncodedCollatedPatchBatch
14
- from wsi_patching.core.types.util_types import EndOfQueue, EndOfStream
14
+ from wsi_patching.core.types.util_types import EndOfQueue, EndOfStream, SlideFailed
15
15
  from wsi_patching.utils.audit import AuditRecorder, PipelineAuditAggregator, get_current_audit, set_current_audit
16
16
  from wsi_patching.utils.logging_config import LogLevel, init_logging
17
17
  from wsi_patching.utils.meta_typing import ContextAware, PipelineContext, StageMeta
@@ -724,8 +724,9 @@ def _producer_worker(
724
724
  init_logging(verbosity_level)
725
725
  profiler: Optional[Profiler] = None
726
726
  recorder: Optional[AuditRecorder] = None
727
+ error: Optional[str] = None
728
+ slide_id = Path(slide_path).stem
727
729
  try:
728
- slide_id = Path(slide_path).stem
729
730
  profiler = Profiler(enabled=profile, slide_id=slide_id)
730
731
  set_current_profiler(profiler)
731
732
  recorder = AuditRecorder(enabled=audit, slide_id=slide_id)
@@ -742,17 +743,10 @@ def _producer_worker(
742
743
  for out in pipe(iter(())):
743
744
  if stop_event is not None and stop_event.is_set():
744
745
  break
745
- # bounded put with stop-aware retry
746
- while True:
747
- try:
748
- producer_queue.put(out, block=True, timeout=0.5)
749
- break
750
- except Full:
751
- if stop_event is not None and stop_event.is_set():
752
- break
753
- continue
746
+ _put_until_stopped(producer_queue, out, stop_event)
754
747
 
755
748
  except Exception as e:
749
+ error = f"{type(e).__name__}: {e}"
756
750
  if not gracefully_handle_producer_errors:
757
751
  logging.exception(f"Producer error: {e}", exc_info=True)
758
752
  if fail_box is not None:
@@ -772,8 +766,16 @@ def _producer_worker(
772
766
  set_current_profiler(None)
773
767
  set_current_audit(None)
774
768
 
775
- # best-effort stream boundary
769
+ end = EndOfStream(wsi_id=slide_id) if error is None else SlideFailed(wsi_id=slide_id, error=error)
770
+ _put_until_stopped(producer_queue, end, stop_event)
771
+
772
+
773
+ def _put_until_stopped(queue: Queue, item: Any, stop_event: Optional[Event]) -> None:
774
+ """Block until `item` is on `queue`, giving up only once `stop_event` is set."""
775
+ while True:
776
776
  try:
777
- producer_queue.put(EndOfStream(), block=True, timeout=0.5)
778
- except Exception:
779
- pass
777
+ queue.put(item, block=True, timeout=0.5)
778
+ return
779
+ except Full:
780
+ if stop_event is not None and stop_event.is_set():
781
+ return
@@ -67,6 +67,7 @@ class CollatedPatchBatch:
67
67
  patches: Union[np.ndarray, "cp.ndarray"] # (N, ...)
68
68
  metadata: MetaColStorage
69
69
  wsi_dims: Tuple[int, int] # (W, H) of the whole slide at patched resolution
70
+ level0_scale: float # coords * level0_scale = level-0 pixels (read downsample * resample factor)
70
71
 
71
72
  def __init__(
72
73
  self,
@@ -76,11 +77,13 @@ class CollatedPatchBatch:
76
77
  use_gpu: bool,
77
78
  wsi_dims: Tuple[int, int],
78
79
  metadata: Optional[MetaColStorage] = None,
80
+ level0_scale: float = 1.0,
79
81
  ):
80
82
  self.wsi_id = wsi_id
81
83
  self.coords = coords
82
84
  self.patches = patches
83
85
  self.wsi_dims = wsi_dims
86
+ self.level0_scale = level0_scale
84
87
 
85
88
  if metadata is not None:
86
89
  self.metadata = metadata
@@ -151,6 +154,7 @@ class EncodedCollatedPatchBatch(CollatedPatchBatch):
151
154
  use_gpu=is_cupy(batch.patches),
152
155
  wsi_dims=batch.wsi_dims,
153
156
  metadata=batch.metadata,
157
+ level0_scale=batch.level0_scale,
154
158
  )
155
159
  obj.encoding = encoding
156
160
  obj.encoded_patches = encoded_patches
@@ -1,5 +1,5 @@
1
1
  from dataclasses import dataclass
2
- from typing import Any, Dict, List, Union
2
+ from typing import Any, Dict, List, Optional, Union
3
3
 
4
4
  import numpy as np
5
5
 
@@ -85,7 +85,16 @@ class MetaColStorage:
85
85
 
86
86
  @dataclass(frozen=True)
87
87
  class EndOfStream:
88
- pass
88
+ """A producer finished a slide. `wsi_id` names the slide, or is None for a bare stream boundary."""
89
+
90
+ wsi_id: Optional[str] = None
91
+
92
+
93
+ @dataclass(frozen=True)
94
+ class SlideFailed(EndOfStream):
95
+ """A producer failed on slide `wsi_id` and ends its stream early. `error` describes the failure."""
96
+
97
+ error: str = ""
89
98
 
90
99
 
91
100
  @dataclass(frozen=True)
@@ -55,6 +55,8 @@ class CellVitTissueClassifierFilter(Stage):
55
55
 
56
56
  for collated_patch_batch in it:
57
57
  patches = collated_patch_batch.patches # (N,H,W,C) uint8, np or cp
58
+ if len(patches) == 0:
59
+ continue
58
60
 
59
61
  # Forward pass in chunks
60
62
  preds_list: List[torch.Tensor] = []
@@ -66,14 +66,17 @@ class LowContrastBackgroundFilter(Stage):
66
66
  thr = xp.asarray(self.range_threshold, dtype=xp.float32 if self.float_precision == "float32" else xp.float64)
67
67
 
68
68
  for collated_patch_batch in it:
69
+ if len(collated_patch_batch.patches) == 0:
70
+ continue
71
+
69
72
  patches = ensure_array_matches_use_gpu(collated_patch_batch.patches, use_gpu)
70
73
 
71
74
  # 1) RGB/RGBA -> grayscale in [0,1]
72
75
  gray = self._rgb_to_gray_xp(patches, xp)
73
76
 
74
77
  # 2) Per-patch min/max and dynamic range
75
- B = gray.shape[0]
76
- gray_flat = gray.reshape(B, -1)
78
+ B, H, W = gray.shape
79
+ gray_flat = gray.reshape(B, H * W)
77
80
  g_min = gray_flat.min(axis=1) # (B,)
78
81
  g_max = gray_flat.max(axis=1) # (B,)
79
82
  g_range = (g_max - g_min).astype(gray.dtype) # (B,)
@@ -84,6 +84,8 @@ class OtsuFilter(Stage):
84
84
 
85
85
  for collated_patch_batch in it:
86
86
  in_sz = len(collated_patch_batch.patches)
87
+ if in_sz == 0:
88
+ continue
87
89
 
88
90
  patches = ensure_array_matches_use_gpu(collated_patch_batch.patches, use_gpu)
89
91
 
@@ -100,9 +102,9 @@ class OtsuFilter(Stage):
100
102
  tissue_mask = gray >= thresholds[:, None, None]
101
103
 
102
104
  # 4) Coverage stats per patch
103
- B = tissue_mask.shape[0]
104
- tissue_pixel_count = tissue_mask.reshape(B, -1).sum(axis=1)
105
- total_pixels = tissue_mask.shape[1] * tissue_mask.shape[2]
105
+ B, H, W = tissue_mask.shape
106
+ total_pixels = H * W
107
+ tissue_pixel_count = tissue_mask.reshape(B, total_pixels).sum(axis=1)
106
108
  tissue_fraction = tissue_pixel_count.astype(xp.float32) / float(total_pixels)
107
109
 
108
110
  # Optional filtering
@@ -123,6 +125,10 @@ class OtsuFilter(Stage):
123
125
  f"(tissue_is_darker={self.tissue_is_darker}, num_bins={self.num_bins}, "
124
126
  f"float_precision={self.float_precision}, min_tissue_fraction={self.min_tissue_fraction})"
125
127
  )
128
+
129
+ if len(collated_patch_batch.patches) == 0:
130
+ continue
131
+
126
132
  yield collated_patch_batch
127
133
 
128
134
  # ---- helpers (xp-native) ----
@@ -168,8 +174,8 @@ class OtsuFilter(Stage):
168
174
  -------
169
175
  thresholds : (B,) same dtype as `gray`, each in [0,1] (gray domain)
170
176
  """
171
- B, _, _ = gray.shape
172
- gray_flat = gray.reshape(B, -1)
177
+ B, H, W = gray.shape
178
+ gray_flat = gray.reshape(B, H * W)
173
179
 
174
180
  # Per-image normalization to [0,1] (robust to constants)
175
181
  g_min = gray_flat.min(axis=1)
@@ -187,7 +193,7 @@ class OtsuFilter(Stage):
187
193
  xp.clip(bin_idx, 0, num_bins - 1, out=bin_idx)
188
194
 
189
195
  # Batched histograms via offset bincount
190
- bin_idx_flat = bin_idx.reshape(B, -1).astype(xp.int64, copy=False)
196
+ bin_idx_flat = bin_idx.reshape(B, H * W).astype(xp.int64, copy=False)
191
197
  offsets = (num_bins * xp.arange(B, dtype=xp.int64))[:, None]
192
198
  keys = (bin_idx_flat + offsets).ravel()
193
199
  counts_flat = xp.bincount(keys, minlength=B * num_bins)
@@ -97,6 +97,7 @@ class PenArtifactFilter(Stage):
97
97
  def __call__(self, it: Iterable[CollatedPatchBatch]) -> Iterable[CollatedPatchBatch]:
98
98
  """
99
99
  For each batch:
100
+ - Skip batches with no patches (e.g. an earlier filter dropped them all).
100
101
  - Ensure dtype uint8 (accept float32 in [0,255] and cast).
101
102
  - Compute per-pixel keep mask from LUTs + darkness guard.
102
103
  - Derive per-patch pen_fraction; drop patches exceeding `max_pen_fraction`.
@@ -108,6 +109,8 @@ class PenArtifactFilter(Stage):
108
109
 
109
110
  for collated_patch_batch in it:
110
111
  in_sz = len(collated_patch_batch.patches)
112
+ if in_sz == 0:
113
+ continue
111
114
 
112
115
  # Normalize dtype: prefer uint8 for LUT indexing
113
116
  if collated_patch_batch.patches.dtype != xp.uint8:
@@ -133,9 +136,9 @@ class PenArtifactFilter(Stage):
133
136
  pen = xp.logical_not(keep_final) # [B,H,W] bool
134
137
 
135
138
  # Per-patch stats
136
- Bsz = pen.shape[0]
137
- pen_pixel_count = pen.reshape(Bsz, -1).sum(axis=1) # xp integer (per patch)
138
- total_pixels = pen.shape[1] * pen.shape[2]
139
+ Bsz, H, W = pen.shape
140
+ total_pixels = H * W
141
+ pen_pixel_count = pen.reshape(Bsz, total_pixels).sum(axis=1) # xp integer (per patch)
139
142
  pen_fraction = pen_pixel_count.astype(xp.float32) / float(total_pixels)
140
143
 
141
144
  # Drop patches with too much pen content
@@ -150,6 +153,10 @@ class PenArtifactFilter(Stage):
150
153
  f"batch_in={in_sz} batch_out={len(collated_patch_batch.patches)} "
151
154
  f"(max_pen_fraction={self.max_pen_fraction})"
152
155
  )
156
+
157
+ if len(collated_patch_batch.patches) == 0:
158
+ continue
159
+
153
160
  yield collated_patch_batch
154
161
 
155
162
  # -------- helpers (xp-native) --------
@@ -62,6 +62,9 @@ class RemoveEdgeTiles(Stage):
62
62
  tile_size = int(self.ctx["tile_size"])
63
63
 
64
64
  for batch in it:
65
+ if len(batch.patches) == 0:
66
+ continue
67
+
65
68
  # Attach the metric for every row (the audit needs it even at depth=0).
66
69
  edge_distance = _edge_distance(batch.coords, batch.wsi_dims, tile_size)
67
70
  batch.add_meta_column("edge_distance", edge_distance)
@@ -42,6 +42,9 @@ class MacenkoNormalizer(Stage):
42
42
 
43
43
  def __call__(self, it: Iterable[CollatedPatchBatch]) -> Iterable[CollatedPatchBatch]:
44
44
  for batch in it:
45
+ if len(batch.patches) == 0:
46
+ continue
47
+
45
48
  if not self._fitted:
46
49
  self.fit(batch)
47
50
 
@@ -199,6 +199,9 @@ class ReinhardNormalizer(Stage):
199
199
  Same batches with ``batch.patches`` replaced by the normalized NHWC uint8 array.
200
200
  """
201
201
  for batch in it:
202
+ if len(batch.patches) == 0:
203
+ continue
204
+
202
205
  if self._xp is None:
203
206
  self._xp = get_xp_backend(self.ctx["use_gpu"])
204
207
  self._ref_mean = self._xp.asarray(self.lab_reference_mean, dtype=self._xp.float32)
@@ -225,7 +228,8 @@ class ReinhardNormalizer(Stage):
225
228
  lab = _rgb_to_lab(rgb_float, self._xp, rgb2xyz=self._rgb2xyz, white=self._white) # (N, H, W, 3)
226
229
 
227
230
  # Compute per‑patch mean and std over spatial axes (H,W)
228
- lab_flat = lab.reshape(len(lab), -1, 3)
231
+ N, H, W, _ = lab.shape
232
+ lab_flat = lab.reshape(N, H * W, 3)
229
233
  mean_lab = lab_flat.mean(axis=1) # (N,3)
230
234
  std_lab = lab_flat.std(axis=1, ddof=1) # (N,3)
231
235
 
@@ -3,7 +3,7 @@ from queue import Empty, Queue
3
3
  from threading import Event
4
4
  from typing import Any, Iterable, Iterator, Optional
5
5
 
6
- from wsi_patching.core.types.util_types import EndOfQueue, EndOfStream
6
+ from wsi_patching.core.types.util_types import EndOfQueue, EndOfStream, SlideFailed
7
7
  from wsi_patching.utils.logging_config import LogLevel, init_logging
8
8
  from wsi_patching.utils.meta_typing import ContextAware, WriterMeta
9
9
 
@@ -16,7 +16,9 @@ class StreamWriterBase(ContextAware, metaclass=WriterMeta):
16
16
  This is useful for large datasets that do not fit into memory, or for real-time processing
17
17
 
18
18
  Implementers override:
19
- - write(self, batch: Any) -> None # write a batch of items
19
+ - stream(self, batch: Any) -> Iterator[Any] # yield items for a batch
20
+ - on_slide_end(self, wsi_id: str) -> Iterable[Any] # optional; yield items after a slide's last batch
21
+ - on_slide_failed(self, wsi_id: str, error: str) -> Iterable[Any] # optional; yield items when a slide fails
20
22
 
21
23
  Single-process usage: writer(it) will consume the iterable and write everything.
22
24
  Multi-process usage: writer.start_writer(queue) will block and consume messages from producers.
@@ -33,6 +35,17 @@ class StreamWriterBase(ContextAware, metaclass=WriterMeta):
33
35
  """Stream a batch of items. Must be implemented by subclass."""
34
36
  raise NotImplementedError
35
37
 
38
+ def on_slide_end(self, wsi_id: str) -> Iterable[Any]:
39
+ """Called once per slide, after its last batch. Yielded items are streamed. Default: no-op."""
40
+ return ()
41
+
42
+ def on_slide_failed(self, wsi_id: str, error: str) -> Iterable[Any]:
43
+ """Called instead of `on_slide_end` when a producer fails on a slide. Yielded items are streamed.
44
+
45
+ Batches of that slide streamed before the failure are not retracted. Default: no-op.
46
+ """
47
+ return ()
48
+
36
49
  def start_writer(
37
50
  self, queue: Queue, verbosity_level: LogLevel, stop_event: Optional[Event] = None, poll_s: float = 0.5
38
51
  ) -> Iterable[Any]:
@@ -53,8 +66,14 @@ class StreamWriterBase(ContextAware, metaclass=WriterMeta):
53
66
  break
54
67
  continue
55
68
 
69
+ if isinstance(msg, SlideFailed):
70
+ self.log.info(f"Received SlideFailed for {msg.wsi_id}: {msg.error}")
71
+ yield from self.on_slide_failed(msg.wsi_id, msg.error)
72
+ continue
56
73
  if isinstance(msg, EndOfStream):
57
74
  self.log.info("Received EndOfStream signal.")
75
+ if msg.wsi_id is not None:
76
+ yield from self.on_slide_end(msg.wsi_id)
58
77
  continue
59
78
  elif isinstance(msg, EndOfQueue):
60
79
  self.log.info("Received EndOfQueue signal. Finishing writer.")
@@ -1,6 +1,8 @@
1
1
  from __future__ import annotations
2
2
 
3
+ import shutil
3
4
  import textwrap
5
+ from pathlib import Path
4
6
 
5
7
  import numpy as np
6
8
  import pytest
@@ -67,3 +69,14 @@ def pyramid_slide(tmp_path_factory):
67
69
  tif.write(img_l1, tile=(256, 256), subfiletype=1, **opts)
68
70
 
69
71
  return str(path)
72
+
73
+
74
+ @pytest.fixture(scope="module")
75
+ def three_slides(tmp_path_factory, synthetic_slide):
76
+ """Three copies of the synthetic slide with distinct wsi ids."""
77
+ tmp = tmp_path_factory.mktemp("three_slides")
78
+ src = Path(synthetic_slide[0])
79
+ paths = [tmp / f"slide_{i}.tif" for i in range(3)]
80
+ for p in paths:
81
+ shutil.copy(src, p)
82
+ return [str(p) for p in paths]
@@ -0,0 +1,58 @@
1
+ """A slide whose patches are all filtered out must stream 0 patches without error."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import numpy as np
6
+ import pytest
7
+ import tifffile
8
+
9
+ from wsi_patching import (
10
+ LowContrastBackgroundFilter,
11
+ NumpyStreamWriter,
12
+ OtsuFilter,
13
+ PatchExtractor,
14
+ PenArtifactFilter,
15
+ RemoveEdgeTiles,
16
+ WSIGrid,
17
+ )
18
+ from wsi_patching.transforms.macenko_normalizer import MacenkoNormalizer
19
+ from wsi_patching.transforms.reinhard_normalizer import ReinhardNormalizer
20
+
21
+
22
+ @pytest.fixture(scope="module")
23
+ def blank_slide(tmp_path_factory):
24
+ path = tmp_path_factory.mktemp("blank") / "blank.tif"
25
+ img = np.full((1024, 1024, 3), 255, np.uint8)
26
+ tifffile.imwrite(
27
+ str(path),
28
+ img,
29
+ photometric="rgb",
30
+ tile=(256, 256),
31
+ compression="deflate",
32
+ resolution=(2e4, 2e4),
33
+ resolutionunit="CENTIMETER",
34
+ )
35
+ return str(path)
36
+
37
+
38
+ @pytest.mark.parametrize(
39
+ "downstream",
40
+ [
41
+ PenArtifactFilter,
42
+ lambda: OtsuFilter(min_tissue_fraction=0.05),
43
+ LowContrastBackgroundFilter,
44
+ lambda: RemoveEdgeTiles(depth=1),
45
+ ReinhardNormalizer,
46
+ MacenkoNormalizer,
47
+ ],
48
+ ids=["pen", "otsu", "low_contrast", "edge", "reinhard", "macenko"],
49
+ )
50
+ def test_blank_slide_streams_no_patches(blank_slide, downstream):
51
+ p = (
52
+ WSIGrid([blank_slide], resolution=0.5, unit="mpp", use_gpu=False)
53
+ .then(PatchExtractor(tile_size=256, stride=256))
54
+ .then(OtsuFilter(min_tissue_fraction=0.05))
55
+ .then(downstream())
56
+ .to(NumpyStreamWriter(layout="NHWC"))
57
+ )
58
+ assert list(p.stream()) == []
@@ -0,0 +1,38 @@
1
+ import numpy as np
2
+ import pytest
3
+
4
+ from wsi_patching.core import PatchExtractor, WSIGrid
5
+ from wsi_patching.core.types.types import CollatedPatchBatch
6
+ from wsi_patching.writers.stream_writers.stream_writer_base import StreamWriterBase
7
+
8
+ TILE = 64
9
+ QUADRANT_COLORS = np.array([[[200, 50, 50], [50, 200, 50]], [[50, 50, 200], [200, 200, 50]]])
10
+
11
+
12
+ class _BatchWriter(StreamWriterBase):
13
+ def stream(self, batch: CollatedPatchBatch):
14
+ yield batch
15
+
16
+
17
+ def _level0_color(x0: float, y0: float) -> np.ndarray:
18
+ return QUADRANT_COLORS[int(y0 >= 256), int(x0 >= 256)]
19
+
20
+
21
+ @pytest.mark.parametrize(
22
+ "grid_kwargs, expected_scale",
23
+ [(dict(resolution=1, unit="level"), 2.0), (dict(resolution=4.0, unit="downsample", fallback_mode="resample"), 4.0)],
24
+ )
25
+ def test_scaled_coords_hit_level0_quadrant(pyramid_slide, grid_kwargs, expected_scale):
26
+ p = (
27
+ WSIGrid(slides=[pyramid_slide], use_gpu=False, **grid_kwargs)
28
+ .then(PatchExtractor(tile_size=TILE, stride=TILE, max_batch_size=100))
29
+ .to(_BatchWriter())
30
+ )
31
+ batches = list(p.stream())
32
+ assert batches
33
+
34
+ for batch in batches:
35
+ assert batch.level0_scale == pytest.approx(expected_scale)
36
+ centers_l0 = (batch.coords + TILE / 2) * batch.level0_scale
37
+ for (cx, cy), patch in zip(centers_l0, batch.patches):
38
+ np.testing.assert_allclose(patch.reshape(-1, 3).mean(axis=0), _level0_color(cx, cy), atol=10)
@@ -0,0 +1,38 @@
1
+ from wsi_patching.core import PatchExtractor, WSIGrid
2
+ from wsi_patching.core.types.types import CollatedPatchBatch
3
+ from wsi_patching.writers import NumpyStreamWriter
4
+ from wsi_patching.writers.stream_writers.stream_writer_base import StreamWriterBase
5
+
6
+
7
+ class _RecordingWriter(StreamWriterBase):
8
+ def stream(self, batch: CollatedPatchBatch):
9
+ yield "batch", batch.wsi_id
10
+
11
+ def on_slide_end(self, wsi_id: str):
12
+ yield "end", wsi_id
13
+
14
+
15
+ def _pipeline(slides, writer):
16
+ return (
17
+ WSIGrid(slides=slides, resolution=0, unit="level", use_gpu=False)
18
+ .then(PatchExtractor(tile_size=64, stride=64, max_batch_size=8))
19
+ .to(writer)
20
+ )
21
+
22
+
23
+ def test_one_slide_end_per_slide_after_its_last_batch(three_slides):
24
+ events = list(_pipeline(three_slides, _RecordingWriter()).stream(num_workers=2, writer_prefetch_factor=1))
25
+
26
+ ids = {f"slide_{i}" for i in range(3)}
27
+ ends = [wid for kind, wid in events if kind == "end"]
28
+ assert sorted(ends) == sorted(ids)
29
+ for wid in ids:
30
+ last_batch = max(i for i, e in enumerate(events) if e == ("batch", wid))
31
+ assert events.index(("end", wid)) > last_batch
32
+ assert sum(kind == "batch" for kind, _ in events) == 3 * 8
33
+
34
+
35
+ def test_writer_without_hook_is_unchanged(three_slides):
36
+ out = list(_pipeline(three_slides, NumpyStreamWriter(layout="NHWC")).stream(num_workers=2))
37
+ assert all(len(item) == 4 for item in out)
38
+ assert sum(imgs.shape[0] for _, imgs, _, _ in out) == 3 * 64
@@ -0,0 +1,49 @@
1
+ import shutil
2
+ from threading import Thread
3
+
4
+ import pytest
5
+
6
+ from wsi_patching.core import PatchExtractor, WSIGrid
7
+ from wsi_patching.core.types.types import CollatedPatchBatch
8
+ from wsi_patching.writers.stream_writers.stream_writer_base import StreamWriterBase
9
+
10
+
11
+ class _RecordingWriter(StreamWriterBase):
12
+ def stream(self, batch: CollatedPatchBatch):
13
+ yield "batch", batch.wsi_id
14
+
15
+ def on_slide_end(self, wsi_id: str):
16
+ yield "end", wsi_id
17
+
18
+ def on_slide_failed(self, wsi_id: str, error: str):
19
+ yield "failed", wsi_id, error
20
+
21
+
22
+ @pytest.fixture
23
+ def good_corrupt_good(tmp_path, synthetic_slide):
24
+ paths = [tmp_path / name for name in ("good_a.tif", "corrupt.tif", "good_b.tif")]
25
+ shutil.copy(synthetic_slide[0], paths[0])
26
+ paths[1].write_bytes(b"not a tiff" * 100)
27
+ shutil.copy(synthetic_slide[0], paths[2])
28
+ return [str(p) for p in paths]
29
+
30
+
31
+ def test_corrupt_slide_emits_slide_failed_and_others_complete(good_corrupt_good):
32
+ p = (
33
+ WSIGrid(slides=good_corrupt_good, resolution=0, unit="level", use_gpu=False)
34
+ .then(PatchExtractor(tile_size=128, stride=128, max_batch_size=100))
35
+ .to(_RecordingWriter())
36
+ )
37
+ events: list = []
38
+ t = Thread(target=lambda: events.extend(p.stream(num_workers=2, gracefully_handle_producer_errors=True)))
39
+ t.start()
40
+ t.join(timeout=60)
41
+ assert not t.is_alive(), "stream hung"
42
+
43
+ assert sorted(e[1] for e in events if e[0] == "end") == ["good_a", "good_b"]
44
+ failed = [e for e in events if e[0] == "failed"]
45
+ assert len(failed) == 1
46
+ _, wsi_id, error = failed[0]
47
+ assert wsi_id == "corrupt"
48
+ assert error
49
+ assert p.failed_slides == ["corrupt"]
@@ -4,7 +4,7 @@ import numpy as np
4
4
  import pytest
5
5
 
6
6
  from wsi_patching.core.chunking_and_batching import PatchExtractor, ReadWindowChunker, RegionReadAndBatch, TilePlanner
7
- from wsi_patching.core.types.types import RegionTask, Slide, SlideWithROIs, TilePlan
7
+ from wsi_patching.core.types.types import EncodedCollatedPatchBatch, RegionTask, Slide, SlideWithROIs, TilePlan
8
8
  from wsi_patching.regions_of_interest.rois import BoxROI
9
9
  from wsi_patching.utils.meta_typing import PipelineContext
10
10
 
@@ -510,6 +510,27 @@ def test_region_read_and_batch_scales_coords_to_level0():
510
510
  assert recorded["xy"] == (50, 75), f"Expected unchanged coords (50, 75) for level-0 but got {recorded['xy']}."
511
511
 
512
512
 
513
+ @patch("wsi_patching.core.chunking_and_batching.read_region", new=fake_read_region)
514
+ def test_region_read_and_batch_sets_level0_scale_from_task_downsample():
515
+ task = RegionTask(
516
+ wsi_id="S",
517
+ wsi_path="/s",
518
+ wsi_dims=(64, 64),
519
+ level=1,
520
+ region=(0, 0, 32, 32),
521
+ tiles=[(0, 0), (16, 16)],
522
+ downsample=6.0,
523
+ resample_factor=1.5,
524
+ )
525
+ r = RegionReadAndBatch(batch_size=10, dtype=np.uint8)
526
+ r.attach_context(PipelineContext({"tile_size": 16, "level": 1, "use_gpu": False}))
527
+ r.validate()
528
+
529
+ (batch,) = list(r(iter([task])))
530
+ assert batch.level0_scale == 6.0
531
+ assert EncodedCollatedPatchBatch.from_collated_patch_batch(batch, "png", None).level0_scale == 6.0
532
+
533
+
513
534
  # ------------------- PatchExtractor (composite stage) -------------------
514
535
  @patch("wsi_patching.core.chunking_and_batching.get_xp_backend", new=lambda use_gpu: np)
515
536
  @patch("wsi_patching.core.chunking_and_batching.read_region", new=fake_read_region)
@@ -0,0 +1,89 @@
1
+ """Every built-in stage must accept a batch with zero patches.
2
+
3
+ An earlier filter can drop every patch in a batch (e.g. ``OtsuFilter`` on a
4
+ background-only slide). Stages downstream of it must not crash on that, and
5
+ should not pass the empty batch on.
6
+ """
7
+
8
+ from typing import Any, Callable, Dict, cast
9
+ from unittest.mock import patch
10
+
11
+ import numpy as np
12
+ import pytest
13
+
14
+ from wsi_patching.core.types.types import CollatedPatchBatch
15
+ from wsi_patching.filtering import LowContrastBackgroundFilter, OtsuFilter, PenArtifactFilter, RemoveEdgeTiles
16
+ from wsi_patching.transforms.macenko_normalizer import MacenkoNormalizer
17
+ from wsi_patching.transforms.reinhard_normalizer import ReinhardNormalizer
18
+ from wsi_patching.utils.meta_typing import PipelineContext
19
+
20
+ CTX: Dict[str, Any] = {"use_gpu": False, "tile_size": 16}
21
+
22
+ STAGES: Dict[str, Callable[[], Any]] = {
23
+ "OtsuFilter": lambda: OtsuFilter(min_tissue_fraction=0.05),
24
+ "PenArtifactFilter": lambda: PenArtifactFilter(),
25
+ "LowContrastBackgroundFilter": lambda: LowContrastBackgroundFilter(),
26
+ "RemoveEdgeTiles": lambda: RemoveEdgeTiles(depth=0),
27
+ "ReinhardNormalizer": lambda: ReinhardNormalizer(),
28
+ "MacenkoNormalizer": lambda: MacenkoNormalizer(),
29
+ }
30
+
31
+
32
+ def _batch(n: int, value: int = 255, size: int = 16) -> CollatedPatchBatch:
33
+ return CollatedPatchBatch(
34
+ wsi_id="wsi",
35
+ patches=np.full((n, size, size, 3), value, dtype=np.uint8),
36
+ coords=np.zeros((n, 2), dtype=np.int64),
37
+ use_gpu=False,
38
+ wsi_dims=(1024, 1024),
39
+ )
40
+
41
+
42
+ def _ready(stage):
43
+ stage.attach_context(PipelineContext(dict(CTX)))
44
+ stage.validate()
45
+ return stage
46
+
47
+
48
+ @pytest.mark.parametrize("name", list(STAGES))
49
+ def test_stage_skips_empty_batch(name):
50
+ stage = _ready(STAGES[name]())
51
+ assert list(stage(iter([_batch(0)]))) == []
52
+
53
+
54
+ @pytest.mark.parametrize("name", list(STAGES))
55
+ def test_stage_after_filter_that_drops_everything(name):
56
+ """The scenario from the bug report: OtsuFilter empties a blank batch first."""
57
+ upstream = _ready(OtsuFilter(min_tissue_fraction=0.05))
58
+ stage = _ready(STAGES[name]())
59
+ assert list(stage(upstream(iter([_batch(4)])))) == []
60
+
61
+
62
+ def test_macenko_does_not_fit_on_empty_batch():
63
+ stage = _ready(MacenkoNormalizer())
64
+ list(stage(iter([_batch(0)])))
65
+ assert stage._fitted is False
66
+
67
+
68
+ @pytest.mark.parametrize("name", ["PenArtifactFilter", "OtsuFilter"])
69
+ def test_empty_batch_does_not_stop_later_batches(name):
70
+ stage = _ready(STAGES[name]())
71
+ content = _batch(1, value=200)
72
+ content.patches[:, :8] = 40
73
+ out = list(stage(iter([_batch(0), content])))
74
+ assert len(out) == 1 and len(out[0].patches) == 1
75
+
76
+
77
+ def test_cellvit_skips_empty_batch():
78
+ torch = pytest.importorskip("torch")
79
+ from wsi_patching.filtering.cellvit_tissue_classifier_filter import CellVitTissueClassifierFilter
80
+
81
+ with patch(
82
+ "wsi_patching.filtering.cellvit_tissue_classifier_filter.get_torch_device",
83
+ new=lambda use_gpu: torch.device("cpu"),
84
+ ):
85
+ stage = CellVitTissueClassifierFilter("dummy_path.pt")
86
+ stage.attach_context(PipelineContext(dict(CTX)))
87
+ stage.validate()
88
+ cast(Any, stage)._lazy_load = lambda: None
89
+ assert list(stage(iter([_batch(0)]))) == []
@@ -4,7 +4,7 @@ from typing import Any, Iterable
4
4
 
5
5
  import pytest
6
6
 
7
- from wsi_patching.core.types.util_types import EndOfQueue, EndOfStream
7
+ from wsi_patching.core.types.util_types import EndOfQueue, EndOfStream, SlideFailed
8
8
  from wsi_patching.writers.stream_writers.stream_writer_base import StreamWriterBase
9
9
 
10
10
 
@@ -102,3 +102,49 @@ def test_exception_in_stream_is_propagated(caplog):
102
102
 
103
103
  # optional: ensure error was logged
104
104
  assert any("Exception in writer:" in rec.message for rec in caplog.records)
105
+
106
+
107
+ class _SlideEndWriter(_PassThroughWriter):
108
+ def on_slide_end(self, wsi_id: str):
109
+ yield f"END:{wsi_id}"
110
+
111
+
112
+ def test_on_slide_end_yields_after_end_of_stream_with_id():
113
+ q = Queue()
114
+ for msg in (["a"], EndOfStream(wsi_id="s1"), EndOfStream(), ["b"], EndOfQueue()):
115
+ q.put(msg)
116
+
117
+ out = _drain(_SlideEndWriter().start_writer(q, verbosity_level="INFO", poll_s=0.05))
118
+ assert out == ["Y:a", "END:s1", "Y:b"]
119
+
120
+
121
+ def test_default_on_slide_end_is_noop():
122
+ q = Queue()
123
+ for msg in (["a"], EndOfStream(wsi_id="s1"), EndOfQueue()):
124
+ q.put(msg)
125
+
126
+ out = _drain(_PassThroughWriter().start_writer(q, verbosity_level="INFO", poll_s=0.05))
127
+ assert out == ["Y:a"]
128
+
129
+
130
+ class _SlideFailedWriter(_SlideEndWriter):
131
+ def on_slide_failed(self, wsi_id: str, error: str):
132
+ yield f"FAIL:{wsi_id}:{error}"
133
+
134
+
135
+ def test_slide_failed_calls_on_slide_failed_not_on_slide_end():
136
+ q = Queue()
137
+ for msg in (["a"], SlideFailed(wsi_id="s1", error="boom"), EndOfStream(wsi_id="s2"), EndOfQueue()):
138
+ q.put(msg)
139
+
140
+ out = _drain(_SlideFailedWriter().start_writer(q, verbosity_level="INFO", poll_s=0.05))
141
+ assert out == ["Y:a", "FAIL:s1:boom", "END:s2"]
142
+
143
+
144
+ def test_default_on_slide_failed_is_noop():
145
+ q = Queue()
146
+ for msg in (SlideFailed(wsi_id="s1", error="boom"), ["a"], EndOfQueue()):
147
+ q.put(msg)
148
+
149
+ out = _drain(_PassThroughWriter().start_writer(q, verbosity_level="INFO", poll_s=0.05))
150
+ assert out == ["Y:a"]
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes