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,566 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
import threading
|
|
3
|
+
from dataclasses import dataclass, field
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from queue import Empty, Full, Queue
|
|
6
|
+
from threading import Event, Thread
|
|
7
|
+
from typing import Any, Callable, Iterable, Iterator, List, Optional, Tuple, Union, get_args, get_origin
|
|
8
|
+
|
|
9
|
+
from wsi_patching.backends.fastslide import close_cached_slides
|
|
10
|
+
from wsi_patching.core.types.util_types import EndOfQueue, EndOfStream
|
|
11
|
+
from wsi_patching.utils.logging_config import LogLevel, init_logging
|
|
12
|
+
from wsi_patching.utils.meta_typing import ContextAware, PipelineContext, StageMeta
|
|
13
|
+
from wsi_patching.utils.profiling import PipelineProfileAggregator, Profiler, get_current_profiler, set_current_profiler
|
|
14
|
+
from wsi_patching.writers.materialize_writers.materialize_writer_base import MaterializeWriterBase
|
|
15
|
+
from wsi_patching.writers.stream_writers.stream_writer_base import StreamWriterBase
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _type_options(t: Any) -> Tuple[type, ...]:
|
|
19
|
+
"""Normalize to tuple of types; (object,) means 'anything'."""
|
|
20
|
+
if t is object or t is None:
|
|
21
|
+
return (object,)
|
|
22
|
+
if isinstance(t, tuple):
|
|
23
|
+
return t
|
|
24
|
+
origin = get_origin(t)
|
|
25
|
+
if origin in (Union,) or str(origin).endswith("types.UnionType"):
|
|
26
|
+
return tuple(a for a in get_args(t) if a is not type(None))
|
|
27
|
+
return (t,)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _is_compatible(prod_out: Any, cons_in: Any) -> bool:
|
|
31
|
+
outs, ins = _type_options(prod_out), _type_options(cons_in)
|
|
32
|
+
for o in outs:
|
|
33
|
+
for i in ins:
|
|
34
|
+
try:
|
|
35
|
+
if i is object or o is object or issubclass(o, i):
|
|
36
|
+
return True
|
|
37
|
+
except TypeError:
|
|
38
|
+
pass
|
|
39
|
+
return False
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _tname(t: Any) -> str:
|
|
43
|
+
try:
|
|
44
|
+
return t.__name__
|
|
45
|
+
except Exception:
|
|
46
|
+
return str(t)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class Stage(ContextAware, metaclass=StageMeta):
|
|
50
|
+
input_type: Any = object
|
|
51
|
+
output_type: Any = object
|
|
52
|
+
|
|
53
|
+
def __init_subclass__(cls, **kwargs):
|
|
54
|
+
super().__init_subclass__(**kwargs)
|
|
55
|
+
cls.log = logging.getLogger(f"{cls.__name__}")
|
|
56
|
+
|
|
57
|
+
def __call__(self, it: Iterable[Any]) -> Iterable[Any]:
|
|
58
|
+
raise NotImplementedError
|
|
59
|
+
|
|
60
|
+
def then(self, nxt: "Stage") -> "Pipeline":
|
|
61
|
+
"""Add a stage to the pipeline and return a new Pipeline instance.
|
|
62
|
+
|
|
63
|
+
Args:
|
|
64
|
+
nxt: The next stage to add to the pipeline.
|
|
65
|
+
"""
|
|
66
|
+
return Pipeline([self, nxt])
|
|
67
|
+
|
|
68
|
+
def for_slide(self, slide_path: str) -> "Stage":
|
|
69
|
+
return self
|
|
70
|
+
|
|
71
|
+
def get_current_profiler(self) -> Optional[Profiler]:
|
|
72
|
+
return get_current_profiler()
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
# -------- Pipeline --------
|
|
76
|
+
@dataclass
|
|
77
|
+
class Pipeline(Stage):
|
|
78
|
+
stages: List[Stage]
|
|
79
|
+
writer: Optional[Union[MaterializeWriterBase, StreamWriterBase]] = None
|
|
80
|
+
prof_agg: Optional["PipelineProfileAggregator"] = None
|
|
81
|
+
_context: PipelineContext = field(default_factory=PipelineContext)
|
|
82
|
+
_runtime_type_asserts: bool = True
|
|
83
|
+
failed_slides: List[str] = field(default_factory=list)
|
|
84
|
+
|
|
85
|
+
def __init__(
|
|
86
|
+
self,
|
|
87
|
+
stages: List[Stage],
|
|
88
|
+
writer: Optional[Union[MaterializeWriterBase, StreamWriterBase]] = None,
|
|
89
|
+
prof_agg: Optional["PipelineProfileAggregator"] = None,
|
|
90
|
+
context: Optional[PipelineContext] = None,
|
|
91
|
+
):
|
|
92
|
+
self.stages = stages
|
|
93
|
+
self.writer = writer
|
|
94
|
+
self.prof_agg = prof_agg
|
|
95
|
+
self._context = context or PipelineContext()
|
|
96
|
+
self.failed_slides = []
|
|
97
|
+
self._preflight_types()
|
|
98
|
+
|
|
99
|
+
@property
|
|
100
|
+
def context(self) -> PipelineContext:
|
|
101
|
+
return self._context
|
|
102
|
+
|
|
103
|
+
def __call__(self, it: Iterable[Any]) -> Iterable[Any]:
|
|
104
|
+
stream: Iterable[Any] = it
|
|
105
|
+
for s in self.stages:
|
|
106
|
+
stream = self._wrap_runtime_asserts(s, stream) if self._runtime_type_asserts else s(stream)
|
|
107
|
+
return stream
|
|
108
|
+
|
|
109
|
+
def then(self, nxt: Stage) -> "Pipeline":
|
|
110
|
+
"""Add a stage to the pipeline and return a new Pipeline instance.
|
|
111
|
+
|
|
112
|
+
Args:
|
|
113
|
+
nxt: The next stage to add to the pipeline.
|
|
114
|
+
"""
|
|
115
|
+
if self.writer is not None:
|
|
116
|
+
raise RuntimeError("Cannot add stages after a writer. A writer is the last stage.")
|
|
117
|
+
|
|
118
|
+
return Pipeline(self.stages + [nxt], prof_agg=self.prof_agg, context=self._context)
|
|
119
|
+
|
|
120
|
+
def to(self, writer: Union[MaterializeWriterBase, StreamWriterBase]) -> "Pipeline":
|
|
121
|
+
return Pipeline(stages=self.stages, writer=writer, prof_agg=self.prof_agg, context=self._context)
|
|
122
|
+
|
|
123
|
+
def _preflight_types(self) -> None:
|
|
124
|
+
errors: List[str] = []
|
|
125
|
+
for i in range(len(self.stages) - 1):
|
|
126
|
+
a, b = self.stages[i], self.stages[i + 1]
|
|
127
|
+
if not _is_compatible(getattr(a, "output_type", object), getattr(b, "input_type", object)):
|
|
128
|
+
errors.append(
|
|
129
|
+
f"Type mismatch: {type(a).__name__}.out={_tname(a.output_type)} "
|
|
130
|
+
f"-> {type(b).__name__}.in={_tname(b.input_type)}"
|
|
131
|
+
)
|
|
132
|
+
|
|
133
|
+
if self.writer is not None:
|
|
134
|
+
if not _is_compatible(
|
|
135
|
+
getattr(self.stages[-1], "output_type", object), getattr(self.writer, "input_type", object)
|
|
136
|
+
):
|
|
137
|
+
errors.append(
|
|
138
|
+
f"Type mismatch: {type(self.stages[-1]).__name__}.out={_tname(self.stages[-1].output_type)} "
|
|
139
|
+
f"-> {type(self.writer).__name__}.in={_tname(getattr(self.writer, 'input_type', object))}"
|
|
140
|
+
)
|
|
141
|
+
if errors:
|
|
142
|
+
raise TypeError("Pipeline type preflight failed:\n - " + "\n - ".join(errors))
|
|
143
|
+
|
|
144
|
+
def _wrap_runtime_asserts(self, stage: Stage, it: Iterable[Any]) -> Iterable[Any]:
|
|
145
|
+
out_types = _type_options(stage.output_type)
|
|
146
|
+
|
|
147
|
+
def gen() -> Iterator[Any]:
|
|
148
|
+
for item in stage(it):
|
|
149
|
+
if out_types != (object,) and not isinstance(item, out_types):
|
|
150
|
+
exp = " | ".join(_tname(t) for t in out_types)
|
|
151
|
+
raise TypeError(f"{type(stage).__name__} yielded {_tname(type(item))}, expected {exp}")
|
|
152
|
+
yield item
|
|
153
|
+
|
|
154
|
+
return gen()
|
|
155
|
+
|
|
156
|
+
def get_profile(self) -> dict:
|
|
157
|
+
if self.prof_agg is None:
|
|
158
|
+
return {"by_stage": {}, "by_slide": {}}
|
|
159
|
+
return self.prof_agg.get_profile()
|
|
160
|
+
|
|
161
|
+
def print_profile(self) -> None:
|
|
162
|
+
if self.prof_agg is None:
|
|
163
|
+
return
|
|
164
|
+
self.prof_agg.print_profile()
|
|
165
|
+
|
|
166
|
+
def _ensure_prof_agg(self) -> None:
|
|
167
|
+
if self.prof_agg is None:
|
|
168
|
+
self.prof_agg = PipelineProfileAggregator()
|
|
169
|
+
|
|
170
|
+
def _orchestrate(
|
|
171
|
+
self,
|
|
172
|
+
*,
|
|
173
|
+
num_workers: int,
|
|
174
|
+
writer_prefetch_factor: int,
|
|
175
|
+
profile: bool,
|
|
176
|
+
verbosity: LogLevel,
|
|
177
|
+
gracefully_handle_producer_errors: bool,
|
|
178
|
+
sink_runner: Callable[[Queue, Any, Any], Union[Iterable[Any], Any]],
|
|
179
|
+
streaming: bool,
|
|
180
|
+
):
|
|
181
|
+
"""
|
|
182
|
+
Shared core:
|
|
183
|
+
- prepares stages/contexts
|
|
184
|
+
- sets up mp + bounded queue
|
|
185
|
+
- spawns producers & supervisor
|
|
186
|
+
- runs the sink (writer) either as iterator (streaming) or in a thread (materialize)
|
|
187
|
+
"""
|
|
188
|
+
slides = self._prep_and_validate(verbosity=verbosity, profile=profile)
|
|
189
|
+
if not slides:
|
|
190
|
+
self.log.info("[WARN] No slides provided. Nothing to do.")
|
|
191
|
+
return
|
|
192
|
+
|
|
193
|
+
producer_queue, profiler_queue, stop_event = self._init_threading(
|
|
194
|
+
queue_maxsize=writer_prefetch_factor * num_workers, profile=profile
|
|
195
|
+
)
|
|
196
|
+
|
|
197
|
+
sup_thread, stop_all, fail_box, failed_slides = self._spawn_supervisor(
|
|
198
|
+
slides=slides,
|
|
199
|
+
num_workers=num_workers,
|
|
200
|
+
queue=producer_queue,
|
|
201
|
+
profiler_queue=profiler_queue,
|
|
202
|
+
profile=profile,
|
|
203
|
+
verbosity=verbosity,
|
|
204
|
+
gracefully_handle_producer_errors=gracefully_handle_producer_errors,
|
|
205
|
+
stop_event=stop_event,
|
|
206
|
+
)
|
|
207
|
+
|
|
208
|
+
sink_exc_box: List[BaseException] = []
|
|
209
|
+
|
|
210
|
+
if streaming:
|
|
211
|
+
|
|
212
|
+
def _stream():
|
|
213
|
+
try:
|
|
214
|
+
for item in sink_runner(producer_queue, verbosity, stop_event): # <-- pass stop_event
|
|
215
|
+
if fail_box:
|
|
216
|
+
raise RuntimeError(fail_box[0])
|
|
217
|
+
yield item
|
|
218
|
+
sup_thread.join(timeout=5.0)
|
|
219
|
+
if fail_box:
|
|
220
|
+
raise RuntimeError(fail_box[0])
|
|
221
|
+
self.failed_slides = list(failed_slides)
|
|
222
|
+
if failed_slides:
|
|
223
|
+
self.log.warning(
|
|
224
|
+
f"Streaming completed with errors on slides (skipped): {', '.join(failed_slides)}"
|
|
225
|
+
)
|
|
226
|
+
else:
|
|
227
|
+
self.log.info("Streaming completed.")
|
|
228
|
+
except GeneratorExit:
|
|
229
|
+
self.log.info("Consumer stopped early; terminating producers.")
|
|
230
|
+
stop_event.set()
|
|
231
|
+
try:
|
|
232
|
+
producer_queue.put(EndOfQueue(), block=True, timeout=0.5)
|
|
233
|
+
except Exception:
|
|
234
|
+
pass
|
|
235
|
+
stop_all()
|
|
236
|
+
raise
|
|
237
|
+
except Exception:
|
|
238
|
+
stop_event.set()
|
|
239
|
+
try:
|
|
240
|
+
producer_queue.put(EndOfQueue(), block=True, timeout=0.5)
|
|
241
|
+
except Exception:
|
|
242
|
+
pass
|
|
243
|
+
stop_all()
|
|
244
|
+
raise
|
|
245
|
+
finally:
|
|
246
|
+
sup_thread.join(timeout=5.0)
|
|
247
|
+
|
|
248
|
+
return _stream()
|
|
249
|
+
else:
|
|
250
|
+
|
|
251
|
+
def _run_sink():
|
|
252
|
+
try:
|
|
253
|
+
sink_runner(producer_queue, verbosity, stop_event)
|
|
254
|
+
except BaseException as e:
|
|
255
|
+
sink_exc_box.append(e)
|
|
256
|
+
|
|
257
|
+
t = Thread(target=_run_sink, name="writer", daemon=False)
|
|
258
|
+
t.start()
|
|
259
|
+
|
|
260
|
+
try:
|
|
261
|
+
t.join()
|
|
262
|
+
sup_thread.join(timeout=5.0)
|
|
263
|
+
if sink_exc_box:
|
|
264
|
+
raise sink_exc_box[0]
|
|
265
|
+
if fail_box:
|
|
266
|
+
raise RuntimeError(fail_box[0])
|
|
267
|
+
self.failed_slides = list(failed_slides)
|
|
268
|
+
if failed_slides:
|
|
269
|
+
self.log.warning(
|
|
270
|
+
"Materialization completed with errors on slides (skipped): %s.", ", ".join(failed_slides)
|
|
271
|
+
)
|
|
272
|
+
else:
|
|
273
|
+
self.log.info("Materialization completed.")
|
|
274
|
+
except Exception:
|
|
275
|
+
stop_event.set()
|
|
276
|
+
try:
|
|
277
|
+
producer_queue.put(EndOfQueue(), block=True, timeout=0.5)
|
|
278
|
+
except Exception:
|
|
279
|
+
pass
|
|
280
|
+
stop_all()
|
|
281
|
+
raise
|
|
282
|
+
finally:
|
|
283
|
+
sup_thread.join(timeout=5.0)
|
|
284
|
+
|
|
285
|
+
def _prep_and_validate(self, *, verbosity: LogLevel, profile: bool) -> List[str]:
|
|
286
|
+
"""
|
|
287
|
+
- init logging
|
|
288
|
+
- ensure writer present
|
|
289
|
+
- collect slides from first stage (grid)
|
|
290
|
+
- export/attach/validate all stages + writer
|
|
291
|
+
- reset profile aggregator if requested
|
|
292
|
+
"""
|
|
293
|
+
init_logging(verbosity)
|
|
294
|
+
if self.writer is None:
|
|
295
|
+
raise RuntimeError("Pipeline has no writer; add one via .to(writer)")
|
|
296
|
+
|
|
297
|
+
self.log.info("Preparing pipeline (profile=%s).", profile)
|
|
298
|
+
|
|
299
|
+
grid = self.stages[0]
|
|
300
|
+
slides = list(getattr(grid, "slides", []))
|
|
301
|
+
# Do not cast to list() again later; preserve this order
|
|
302
|
+
|
|
303
|
+
for s in self.stages + [self.writer]:
|
|
304
|
+
s.export_context(self._context)
|
|
305
|
+
for s in self.stages + [self.writer]:
|
|
306
|
+
s.attach_context(self._context)
|
|
307
|
+
s.validate()
|
|
308
|
+
|
|
309
|
+
if profile:
|
|
310
|
+
self._ensure_prof_agg()
|
|
311
|
+
if self.prof_agg is not None:
|
|
312
|
+
self.prof_agg.reset()
|
|
313
|
+
|
|
314
|
+
return slides
|
|
315
|
+
|
|
316
|
+
def _init_threading(self, *, queue_maxsize: int, profile: bool) -> Tuple[Queue, Optional[Queue], Event]:
|
|
317
|
+
producer_queue: Queue = Queue(maxsize=queue_maxsize)
|
|
318
|
+
profiler_queue: Optional[Queue] = Queue() if profile else None
|
|
319
|
+
stop_event: Event = Event()
|
|
320
|
+
return producer_queue, profiler_queue, stop_event
|
|
321
|
+
|
|
322
|
+
def _spawn_supervisor(
|
|
323
|
+
self,
|
|
324
|
+
*,
|
|
325
|
+
slides: List[str],
|
|
326
|
+
num_workers: int,
|
|
327
|
+
queue: Queue,
|
|
328
|
+
profiler_queue: Optional[Queue],
|
|
329
|
+
profile: bool,
|
|
330
|
+
verbosity: LogLevel,
|
|
331
|
+
gracefully_handle_producer_errors: bool,
|
|
332
|
+
stop_event: Event,
|
|
333
|
+
) -> Tuple[Thread, Callable[[], None], List[str], List[str]]:
|
|
334
|
+
"""
|
|
335
|
+
Spawns a supervisor thread that:
|
|
336
|
+
- launches up to `num_workers` producer threads
|
|
337
|
+
- respawns producers until slides are exhausted
|
|
338
|
+
- collects profiling messages (optional)
|
|
339
|
+
- on exit or error, ALWAYS sends EndOfQueue to the writer
|
|
340
|
+
Returns:
|
|
341
|
+
- supervisor thread
|
|
342
|
+
- stop_all() callable to abort producers + signal EndOfQueue
|
|
343
|
+
- fail_box (list with reason string if fatal error)
|
|
344
|
+
- failed_slides list (if skipping is enabled)
|
|
345
|
+
"""
|
|
346
|
+
pending = list(slides)
|
|
347
|
+
# active: list of (thread, per-worker fail_box)
|
|
348
|
+
active: List[Tuple[Thread, List[str]]] = []
|
|
349
|
+
failed_slides: List[str] = []
|
|
350
|
+
fail_box: List[str] = [] # single-element list carrying error reason
|
|
351
|
+
kill_lock = threading.Lock()
|
|
352
|
+
|
|
353
|
+
def spawn_for(path: str) -> Tuple[Thread, List[str]]:
|
|
354
|
+
worker_fail_box: List[str] = []
|
|
355
|
+
t = Thread(
|
|
356
|
+
target=_producer_worker,
|
|
357
|
+
args=(
|
|
358
|
+
path,
|
|
359
|
+
self.stages,
|
|
360
|
+
queue,
|
|
361
|
+
profile,
|
|
362
|
+
profiler_queue,
|
|
363
|
+
gracefully_handle_producer_errors,
|
|
364
|
+
verbosity,
|
|
365
|
+
stop_event,
|
|
366
|
+
worker_fail_box,
|
|
367
|
+
self._context,
|
|
368
|
+
),
|
|
369
|
+
name=f"producer-{Path(path).stem}",
|
|
370
|
+
daemon=True,
|
|
371
|
+
)
|
|
372
|
+
t.start()
|
|
373
|
+
return t, worker_fail_box
|
|
374
|
+
|
|
375
|
+
for _ in range(min(num_workers, len(pending))):
|
|
376
|
+
active.append(spawn_for(pending.pop(0)))
|
|
377
|
+
|
|
378
|
+
def stop_all():
|
|
379
|
+
with kill_lock:
|
|
380
|
+
stop_event.set()
|
|
381
|
+
try:
|
|
382
|
+
queue.put(EndOfQueue(), block=True, timeout=0.5)
|
|
383
|
+
except Exception:
|
|
384
|
+
pass
|
|
385
|
+
|
|
386
|
+
def supervisor():
|
|
387
|
+
try:
|
|
388
|
+
while active:
|
|
389
|
+
for t, worker_fail in list(active):
|
|
390
|
+
t.join(timeout=0.1)
|
|
391
|
+
if not t.is_alive():
|
|
392
|
+
active.remove((t, worker_fail))
|
|
393
|
+
if worker_fail:
|
|
394
|
+
slide_name = t.name.replace("producer-", "")
|
|
395
|
+
failed_slides.append(slide_name)
|
|
396
|
+
if not gracefully_handle_producer_errors:
|
|
397
|
+
stop_event.set()
|
|
398
|
+
fail_box.append(f"Producer failed on slide '{slide_name}': {worker_fail[0]}")
|
|
399
|
+
return
|
|
400
|
+
|
|
401
|
+
while pending and len(active) < num_workers:
|
|
402
|
+
active.append(spawn_for(pending.pop(0)))
|
|
403
|
+
self.log.info("Spawning new producer... %d slides left.", len(pending))
|
|
404
|
+
|
|
405
|
+
if profile and profiler_queue is not None and self.prof_agg is not None:
|
|
406
|
+
received, expected = 0, len(slides)
|
|
407
|
+
while received < expected:
|
|
408
|
+
try:
|
|
409
|
+
msg = profiler_queue.get(timeout=1.0)
|
|
410
|
+
except Empty:
|
|
411
|
+
break
|
|
412
|
+
if isinstance(msg, dict) and msg.get("_profile"):
|
|
413
|
+
self.prof_agg.ingest_msg(msg)
|
|
414
|
+
received += 1
|
|
415
|
+
finally:
|
|
416
|
+
# Always signal writer; avoid blocking forever
|
|
417
|
+
try:
|
|
418
|
+
queue.put(EndOfQueue(), block=True, timeout=0.5)
|
|
419
|
+
except Exception:
|
|
420
|
+
pass
|
|
421
|
+
|
|
422
|
+
sup = Thread(target=supervisor, name="supervisor", daemon=True)
|
|
423
|
+
sup.start()
|
|
424
|
+
return sup, stop_all, fail_box, failed_slides
|
|
425
|
+
|
|
426
|
+
def stream(
|
|
427
|
+
self,
|
|
428
|
+
num_workers: int = 4,
|
|
429
|
+
writer_prefetch_factor: int = 2,
|
|
430
|
+
profile: bool = False,
|
|
431
|
+
verbosity_level: LogLevel = "WARNING",
|
|
432
|
+
gracefully_handle_producer_errors: bool = False,
|
|
433
|
+
) -> Iterable[Any]:
|
|
434
|
+
"""Streaming mode: returns a generator that can be streamed to obtain your patches.
|
|
435
|
+
|
|
436
|
+
Args:
|
|
437
|
+
num_workers: Number of producer threads, one per slide concurrently (default=4).
|
|
438
|
+
writer_prefetch_factor: Number of batches to prefetch for the writer per producer thread (default=2).
|
|
439
|
+
profile: Enable per-stage profiling for producers (default=False).
|
|
440
|
+
verbosity_level: Logging verbosity level (default="WARNING").
|
|
441
|
+
gracefully_handle_producer_errors: Skip slides that cause errors instead of failing the entire pipeline
|
|
442
|
+
(default=False).
|
|
443
|
+
|
|
444
|
+
Returns:
|
|
445
|
+
An iterable generator yielding items from the writer.
|
|
446
|
+
"""
|
|
447
|
+
if isinstance(self.writer, MaterializeWriterBase):
|
|
448
|
+
raise RuntimeError(
|
|
449
|
+
f"The writer {self.writer.__class__} is a MaterializeWriterBase; use .materialize() instead."
|
|
450
|
+
)
|
|
451
|
+
|
|
452
|
+
assert self.writer is not None
|
|
453
|
+
_writer = self.writer
|
|
454
|
+
sink_runner: Callable[[Queue, Any, Any], Iterable[Any]] = lambda q, v, e: _writer.start_writer(
|
|
455
|
+
q, v, stop_event=e
|
|
456
|
+
)
|
|
457
|
+
|
|
458
|
+
yield from self._orchestrate(
|
|
459
|
+
num_workers=num_workers,
|
|
460
|
+
writer_prefetch_factor=writer_prefetch_factor,
|
|
461
|
+
profile=profile,
|
|
462
|
+
verbosity=verbosity_level,
|
|
463
|
+
gracefully_handle_producer_errors=gracefully_handle_producer_errors,
|
|
464
|
+
sink_runner=sink_runner,
|
|
465
|
+
streaming=True,
|
|
466
|
+
)
|
|
467
|
+
|
|
468
|
+
def materialize(
|
|
469
|
+
self,
|
|
470
|
+
num_workers: int = 4,
|
|
471
|
+
writer_prefetch_factor: int = 2,
|
|
472
|
+
profile: bool = False,
|
|
473
|
+
verbosity_level: LogLevel = "WARNING",
|
|
474
|
+
gracefully_handle_producer_errors: bool = False,
|
|
475
|
+
) -> None:
|
|
476
|
+
"""Materializes the pipeline.
|
|
477
|
+
|
|
478
|
+
Args:
|
|
479
|
+
num_workers: Number of producer threads, one per slide concurrently (default=4).
|
|
480
|
+
writer_prefetch_factor: Number of batches to prefetch for the writer per producer thread (default=2).
|
|
481
|
+
profile: Enable per-stage profiling for producers (default=False).
|
|
482
|
+
verbosity_level: Logging verbosity level (default="WARNING").
|
|
483
|
+
gracefully_handle_producer_errors: Skip slides that cause errors instead of failing the entire pipeline
|
|
484
|
+
(default=False).
|
|
485
|
+
|
|
486
|
+
Returns:
|
|
487
|
+
Nothing. Materialization is performed by the writer.
|
|
488
|
+
"""
|
|
489
|
+
if isinstance(self.writer, StreamWriterBase):
|
|
490
|
+
raise RuntimeError(f"The writer {self.writer.__class__} is a StreamWriterBase; use .stream() instead.")
|
|
491
|
+
|
|
492
|
+
assert self.writer is not None
|
|
493
|
+
_writer = self.writer
|
|
494
|
+
sink_runner: Callable[[Queue, Any, Any], Iterable[Any] | Any] = lambda q, v, e: _writer.start_writer(
|
|
495
|
+
q, v, stop_event=e
|
|
496
|
+
)
|
|
497
|
+
|
|
498
|
+
self._orchestrate(
|
|
499
|
+
num_workers=num_workers,
|
|
500
|
+
writer_prefetch_factor=writer_prefetch_factor,
|
|
501
|
+
profile=profile,
|
|
502
|
+
verbosity=verbosity_level,
|
|
503
|
+
gracefully_handle_producer_errors=gracefully_handle_producer_errors,
|
|
504
|
+
sink_runner=sink_runner,
|
|
505
|
+
streaming=False,
|
|
506
|
+
)
|
|
507
|
+
|
|
508
|
+
|
|
509
|
+
def _producer_worker(
|
|
510
|
+
slide_path: str,
|
|
511
|
+
stage_specs: List[Stage],
|
|
512
|
+
producer_queue: Queue,
|
|
513
|
+
profile: bool,
|
|
514
|
+
profiler_queue: Optional[Queue],
|
|
515
|
+
gracefully_handle_producer_errors: bool,
|
|
516
|
+
verbosity_level: LogLevel = "WARNING",
|
|
517
|
+
stop_event: Optional[Event] = None,
|
|
518
|
+
fail_box: Optional[List[str]] = None,
|
|
519
|
+
context: Optional[PipelineContext] = None,
|
|
520
|
+
):
|
|
521
|
+
init_logging(verbosity_level)
|
|
522
|
+
profiler: Optional[Profiler] = None
|
|
523
|
+
try:
|
|
524
|
+
slide_id = Path(slide_path).stem
|
|
525
|
+
profiler = Profiler(enabled=profile, slide_id=slide_id)
|
|
526
|
+
set_current_profiler(profiler)
|
|
527
|
+
|
|
528
|
+
local_stages = [st.for_slide(slide_path) for st in stage_specs]
|
|
529
|
+
if context is not None:
|
|
530
|
+
for s in local_stages:
|
|
531
|
+
s.attach_context(context)
|
|
532
|
+
pipe = Pipeline(local_stages, context=context)
|
|
533
|
+
|
|
534
|
+
# sources ignore input
|
|
535
|
+
for out in pipe(iter(())):
|
|
536
|
+
if stop_event is not None and stop_event.is_set():
|
|
537
|
+
break
|
|
538
|
+
# bounded put with stop-aware retry
|
|
539
|
+
while True:
|
|
540
|
+
try:
|
|
541
|
+
producer_queue.put(out, block=True, timeout=0.5)
|
|
542
|
+
break
|
|
543
|
+
except Full:
|
|
544
|
+
if stop_event is not None and stop_event.is_set():
|
|
545
|
+
break
|
|
546
|
+
continue
|
|
547
|
+
|
|
548
|
+
except Exception as e:
|
|
549
|
+
if not gracefully_handle_producer_errors:
|
|
550
|
+
logging.exception(f"Producer error: {e}", exc_info=True)
|
|
551
|
+
if fail_box is not None:
|
|
552
|
+
fail_box.append(str(e))
|
|
553
|
+
finally:
|
|
554
|
+
close_cached_slides()
|
|
555
|
+
if profile and profiler_queue is not None and profiler is not None:
|
|
556
|
+
try:
|
|
557
|
+
profiler_queue.put({"_profile": True, **profiler.serialize()})
|
|
558
|
+
except Exception:
|
|
559
|
+
logging.info("Failed to send profile message.")
|
|
560
|
+
set_current_profiler(None)
|
|
561
|
+
|
|
562
|
+
# best-effort stream boundary
|
|
563
|
+
try:
|
|
564
|
+
producer_queue.put(EndOfStream(), block=True, timeout=0.5)
|
|
565
|
+
except Exception:
|
|
566
|
+
pass
|
|
File without changes
|