radiuma-filter 0.0.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.
- radiuma_filter/__init__.py +84 -0
- radiuma_filter/api/__init__.py +6 -0
- radiuma_filter/api/errors.py +36 -0
- radiuma_filter/api/execution.py +324 -0
- radiuma_filter/api/extensions.py +175 -0
- radiuma_filter/api/identity.py +62 -0
- radiuma_filter/api/logs.py +218 -0
- radiuma_filter/filters/__init__.py +10 -0
- radiuma_filter/filters/core/__init__.py +4 -0
- radiuma_filter/filters/core/component.py +186 -0
- radiuma_filter/filters/native/__init__.py +8 -0
- radiuma_filter/filters/native/base.py +99 -0
- radiuma_filter/filters/native/canny.py +82 -0
- radiuma_filter/filters/native/gaussian.py +95 -0
- radiuma_filter/filters/native/median.py +52 -0
- radiuma_filter/filters/native/nlm.py +70 -0
- radiuma_filter/filters/native/sobel.py +75 -0
- radiuma_filter/filters/standardized/__init__.py +8 -0
- radiuma_filter/filters/standardized/base.py +54 -0
- radiuma_filter/filters/standardized/gabor.py +46 -0
- radiuma_filter/filters/standardized/laws.py +38 -0
- radiuma_filter/filters/standardized/legacy/__init__.py +4 -0
- radiuma_filter/filters/standardized/legacy/sera_filter.py +1561 -0
- radiuma_filter/filters/standardized/legacy/sera_readwrite.py +78 -0
- radiuma_filter/filters/standardized/log.py +38 -0
- radiuma_filter/filters/standardized/mean.py +30 -0
- radiuma_filter/filters/standardized/wavelet.py +46 -0
- radiuma_filter/runtime/__init__.py +1 -0
- radiuma_filter/runtime/execution/__init__.py +1 -0
- radiuma_filter/runtime/execution/engine.py +948 -0
- radiuma_filter/runtime/extensions/__init__.py +1 -0
- radiuma_filter/runtime/extensions/registry.py +149 -0
- radiuma_filter/runtime/io/__init__.py +1 -0
- radiuma_filter/runtime/io/inputs.py +363 -0
- radiuma_filter/runtime/observability/__init__.py +1 -0
- radiuma_filter/runtime/observability/dispatcher.py +534 -0
- radiuma_filter/runtime/observability/journal.py +306 -0
- radiuma_filter/runtime/observability/storage.py +629 -0
- radiuma_filter-0.0.0.dist-info/METADATA +695 -0
- radiuma_filter-0.0.0.dist-info/RECORD +43 -0
- radiuma_filter-0.0.0.dist-info/WHEEL +5 -0
- radiuma_filter-0.0.0.dist-info/licenses/LICENSE +21 -0
- radiuma_filter-0.0.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
"""Radiuma Filter public API.
|
|
2
|
+
|
|
3
|
+
The public Composite hierarchy is ``FilterComponent`` -> ``Filter`` leaves and
|
|
4
|
+
``FilterPipeline`` composites. Every component owns the same
|
|
5
|
+
``execute(inputs=...)`` operation; execution infrastructure remains private.
|
|
6
|
+
"""
|
|
7
|
+
from .api.errors import (
|
|
8
|
+
BackendUnavailableError,
|
|
9
|
+
DuplicateComponentError,
|
|
10
|
+
FilteringError,
|
|
11
|
+
InvalidExecutionError,
|
|
12
|
+
InvalidPipelineError,
|
|
13
|
+
ResultStateError,
|
|
14
|
+
UnsupportedFilterError,
|
|
15
|
+
UnsupportedInputError,
|
|
16
|
+
)
|
|
17
|
+
from .api.execution import (
|
|
18
|
+
DevicePreference,
|
|
19
|
+
ErrorPolicy,
|
|
20
|
+
EventType,
|
|
21
|
+
ExecutionEvent,
|
|
22
|
+
ExecutionObserver,
|
|
23
|
+
ExecutionOptions,
|
|
24
|
+
ExecutionResult,
|
|
25
|
+
)
|
|
26
|
+
from .filters import (
|
|
27
|
+
CannyFilter,
|
|
28
|
+
Filter,
|
|
29
|
+
FilterComponent,
|
|
30
|
+
FilterPipeline,
|
|
31
|
+
GaborFilter,
|
|
32
|
+
GaussianFilter,
|
|
33
|
+
LawsFilter,
|
|
34
|
+
LoGFilter,
|
|
35
|
+
MeanFilter,
|
|
36
|
+
MedianFilter,
|
|
37
|
+
NLMFilter,
|
|
38
|
+
SobelFilter,
|
|
39
|
+
WaveletFilter,
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
__all__ = [
|
|
43
|
+
"BackendUnavailableError",
|
|
44
|
+
"CannyFilter",
|
|
45
|
+
"DevicePreference",
|
|
46
|
+
"DuplicateComponentError",
|
|
47
|
+
"ErrorPolicy",
|
|
48
|
+
"EventType",
|
|
49
|
+
"ExecutionEvent",
|
|
50
|
+
"ExecutionObserver",
|
|
51
|
+
"ExecutionOptions",
|
|
52
|
+
"ExecutionResult",
|
|
53
|
+
"Filter",
|
|
54
|
+
"FilterComponent",
|
|
55
|
+
"FilterPipeline",
|
|
56
|
+
"FilteringError",
|
|
57
|
+
"GaborFilter",
|
|
58
|
+
"GaussianFilter",
|
|
59
|
+
"InvalidExecutionError",
|
|
60
|
+
"InvalidPipelineError",
|
|
61
|
+
"LawsFilter",
|
|
62
|
+
"LoGFilter",
|
|
63
|
+
"MeanFilter",
|
|
64
|
+
"MedianFilter",
|
|
65
|
+
"NLMFilter",
|
|
66
|
+
"ResultStateError",
|
|
67
|
+
"SobelFilter",
|
|
68
|
+
"UnsupportedFilterError",
|
|
69
|
+
"UnsupportedInputError",
|
|
70
|
+
"WaveletFilter",
|
|
71
|
+
]
|
|
72
|
+
|
|
73
|
+
# Stable advanced submodule imports without physical shell packages.
|
|
74
|
+
import sys as _sys
|
|
75
|
+
from .api import errors as errors, execution as execution, extensions as extensions, identity as identity, logs as logs
|
|
76
|
+
for _name, _module in {
|
|
77
|
+
"errors": errors,
|
|
78
|
+
"execution": execution,
|
|
79
|
+
"extensions": extensions,
|
|
80
|
+
"identity": identity,
|
|
81
|
+
"logs": logs,
|
|
82
|
+
}.items():
|
|
83
|
+
_sys.modules.setdefault(f"{__name__}.{_name}", _module)
|
|
84
|
+
del _name, _module, _sys
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
"""Public exception hierarchy for the filtering library."""
|
|
2
|
+
|
|
3
|
+
class FilteringError(Exception):
|
|
4
|
+
"""Base class for library-defined failures."""
|
|
5
|
+
|
|
6
|
+
class InvalidExecutionError(FilteringError):
|
|
7
|
+
pass
|
|
8
|
+
|
|
9
|
+
class DuplicateComponentError(InvalidExecutionError):
|
|
10
|
+
pass
|
|
11
|
+
|
|
12
|
+
class InvalidPipelineError(FilteringError):
|
|
13
|
+
pass
|
|
14
|
+
|
|
15
|
+
class ResultStateError(FilteringError):
|
|
16
|
+
pass
|
|
17
|
+
|
|
18
|
+
class UnsupportedInputError(FilteringError):
|
|
19
|
+
pass
|
|
20
|
+
|
|
21
|
+
class UnsupportedFilterError(FilteringError):
|
|
22
|
+
pass
|
|
23
|
+
|
|
24
|
+
class BackendUnavailableError(FilteringError):
|
|
25
|
+
pass
|
|
26
|
+
|
|
27
|
+
__all__ = [
|
|
28
|
+
"BackendUnavailableError",
|
|
29
|
+
"DuplicateComponentError",
|
|
30
|
+
"FilteringError",
|
|
31
|
+
"InvalidExecutionError",
|
|
32
|
+
"InvalidPipelineError",
|
|
33
|
+
"ResultStateError",
|
|
34
|
+
"UnsupportedFilterError",
|
|
35
|
+
"UnsupportedInputError",
|
|
36
|
+
]
|
|
@@ -0,0 +1,324 @@
|
|
|
1
|
+
"""Execution policies, events, errors, and result model."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import threading
|
|
5
|
+
from collections.abc import Callable, Iterator, Sequence
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from datetime import datetime
|
|
8
|
+
from enum import Enum
|
|
9
|
+
from typing import Any, Protocol, Self, runtime_checkable
|
|
10
|
+
|
|
11
|
+
from .errors import ResultStateError
|
|
12
|
+
from ..filters.core import Filter, FilterComponent
|
|
13
|
+
from .identity import ApplicationSessionId, CorrelationId, ExecutionId, JournalPosition
|
|
14
|
+
from .logs import ExecutionLogs
|
|
15
|
+
|
|
16
|
+
class ErrorPolicy(str, Enum):
|
|
17
|
+
RAISE = "raise"
|
|
18
|
+
COLLECT = "collect"
|
|
19
|
+
|
|
20
|
+
class DevicePreference(str, Enum):
|
|
21
|
+
AUTO = "auto"
|
|
22
|
+
CPU = "cpu"
|
|
23
|
+
GPU = "gpu"
|
|
24
|
+
|
|
25
|
+
@dataclass(frozen=True, slots=True)
|
|
26
|
+
class ExecutionOptions:
|
|
27
|
+
max_in_flight: int = 1
|
|
28
|
+
error_policy: ErrorPolicy = ErrorPolicy.RAISE
|
|
29
|
+
device: DevicePreference = DevicePreference.AUTO
|
|
30
|
+
progress: bool = True
|
|
31
|
+
|
|
32
|
+
def __post_init__(self) -> None:
|
|
33
|
+
maximum = int(self.max_in_flight)
|
|
34
|
+
if maximum < 1:
|
|
35
|
+
raise ValueError("max_in_flight must be at least 1")
|
|
36
|
+
object.__setattr__(self, "max_in_flight", maximum)
|
|
37
|
+
if not isinstance(self.error_policy, ErrorPolicy):
|
|
38
|
+
object.__setattr__(self, "error_policy", ErrorPolicy(self.error_policy))
|
|
39
|
+
if not isinstance(self.device, DevicePreference):
|
|
40
|
+
object.__setattr__(self, "device", DevicePreference(self.device))
|
|
41
|
+
object.__setattr__(self, "progress", bool(self.progress))
|
|
42
|
+
|
|
43
|
+
class EventType(str, Enum):
|
|
44
|
+
EXECUTION_STARTED = "execution_started"
|
|
45
|
+
EXECUTION_COMPLETED = "execution_completed"
|
|
46
|
+
EXECUTION_FAILED = "execution_failed"
|
|
47
|
+
FILTER_STARTED = "filter_started"
|
|
48
|
+
FILTER_COMPLETED = "filter_completed"
|
|
49
|
+
FILTER_FAILED = "filter_failed"
|
|
50
|
+
PROBLEM = "problem"
|
|
51
|
+
|
|
52
|
+
@dataclass(frozen=True, slots=True, kw_only=True)
|
|
53
|
+
class ExecutionEvent:
|
|
54
|
+
"""Immutable semantic notification, deliberately separate from logs."""
|
|
55
|
+
type: EventType
|
|
56
|
+
execution_id: ExecutionId
|
|
57
|
+
timestamp: datetime
|
|
58
|
+
sequence: int = 0
|
|
59
|
+
correlation_id: CorrelationId | None = None
|
|
60
|
+
root_component: FilterComponent | None = None
|
|
61
|
+
filter: Filter | None = None
|
|
62
|
+
input_index: int | None = None
|
|
63
|
+
error: BaseException | None = None
|
|
64
|
+
|
|
65
|
+
def __post_init__(self) -> None:
|
|
66
|
+
object.__setattr__(self, "type", self.type if isinstance(self.type, EventType) else EventType(self.type))
|
|
67
|
+
object.__setattr__(self, "execution_id", ExecutionId.parse(self.execution_id))
|
|
68
|
+
if not isinstance(self.timestamp, datetime) or self.timestamp.tzinfo is None:
|
|
69
|
+
raise ValueError("ExecutionEvent.timestamp must be timezone-aware")
|
|
70
|
+
sequence = int(self.sequence)
|
|
71
|
+
if sequence < 0:
|
|
72
|
+
raise ValueError("ExecutionEvent.sequence cannot be negative")
|
|
73
|
+
object.__setattr__(self, "sequence", sequence)
|
|
74
|
+
if self.correlation_id is not None:
|
|
75
|
+
object.__setattr__(self, "correlation_id", CorrelationId.parse(self.correlation_id))
|
|
76
|
+
if self.root_component is not None and not isinstance(self.root_component, FilterComponent):
|
|
77
|
+
raise TypeError("root_component must be FilterComponent")
|
|
78
|
+
if self.filter is not None and not isinstance(self.filter, Filter):
|
|
79
|
+
raise TypeError("filter must be Filter")
|
|
80
|
+
if self.input_index is not None:
|
|
81
|
+
index = int(self.input_index)
|
|
82
|
+
if index < 0:
|
|
83
|
+
raise ValueError("input_index cannot be negative")
|
|
84
|
+
object.__setattr__(self, "input_index", index)
|
|
85
|
+
|
|
86
|
+
@runtime_checkable
|
|
87
|
+
class ExecutionObserver(Protocol):
|
|
88
|
+
def on_event(self, event: ExecutionEvent) -> None: ...
|
|
89
|
+
|
|
90
|
+
class ErrorStage(str, Enum):
|
|
91
|
+
DISCOVER = "discover"
|
|
92
|
+
LOAD = "load"
|
|
93
|
+
FILTER = "filter"
|
|
94
|
+
|
|
95
|
+
@dataclass(frozen=True, slots=True, kw_only=True)
|
|
96
|
+
class ExecutionError:
|
|
97
|
+
stage: ErrorStage
|
|
98
|
+
exception: BaseException
|
|
99
|
+
input_index: int | None = None
|
|
100
|
+
input_key: str | None = None
|
|
101
|
+
root_component: FilterComponent | None = None
|
|
102
|
+
filter: Filter | None = None
|
|
103
|
+
|
|
104
|
+
def __post_init__(self) -> None:
|
|
105
|
+
if not isinstance(self.stage, ErrorStage):
|
|
106
|
+
object.__setattr__(self, "stage", ErrorStage(self.stage))
|
|
107
|
+
if not isinstance(self.exception, BaseException):
|
|
108
|
+
raise TypeError("exception must be BaseException")
|
|
109
|
+
if self.input_index is not None:
|
|
110
|
+
index = int(self.input_index)
|
|
111
|
+
if index < 0:
|
|
112
|
+
raise ValueError("input_index cannot be negative")
|
|
113
|
+
object.__setattr__(self, "input_index", index)
|
|
114
|
+
if self.input_key is not None:
|
|
115
|
+
object.__setattr__(self, "input_key", str(self.input_key))
|
|
116
|
+
if self.root_component is not None and not isinstance(self.root_component, FilterComponent):
|
|
117
|
+
raise TypeError("root_component must be FilterComponent")
|
|
118
|
+
if self.filter is not None and not isinstance(self.filter, Filter):
|
|
119
|
+
raise TypeError("filter must be Filter")
|
|
120
|
+
|
|
121
|
+
class _OutputRecord:
|
|
122
|
+
"""All independent root outcomes for one logical input.
|
|
123
|
+
|
|
124
|
+
This record is intentionally private to the result layer. Lookup is
|
|
125
|
+
identity-based: ``output[filter_definition]``.
|
|
126
|
+
"""
|
|
127
|
+
|
|
128
|
+
__slots__ = ("index", "key", "errors", "_values", "_roots")
|
|
129
|
+
|
|
130
|
+
def __init__(
|
|
131
|
+
self,
|
|
132
|
+
*,
|
|
133
|
+
index: int,
|
|
134
|
+
key: str,
|
|
135
|
+
roots: tuple[FilterComponent, ...],
|
|
136
|
+
values: tuple[tuple[FilterComponent, Any], ...],
|
|
137
|
+
errors: tuple[ExecutionError, ...] = (),
|
|
138
|
+
) -> None:
|
|
139
|
+
self.index = int(index)
|
|
140
|
+
self.key = str(key)
|
|
141
|
+
self.errors = tuple(errors)
|
|
142
|
+
self._roots = tuple(roots)
|
|
143
|
+
self._values = tuple(values)
|
|
144
|
+
|
|
145
|
+
def __getitem__(self, component: FilterComponent) -> Any:
|
|
146
|
+
if not isinstance(component, FilterComponent):
|
|
147
|
+
raise TypeError("component must be FilterComponent")
|
|
148
|
+
if not any(root is component for root in self._roots):
|
|
149
|
+
raise KeyError("component is not a root of this execution")
|
|
150
|
+
for root, value in self._values:
|
|
151
|
+
if root is component:
|
|
152
|
+
return value
|
|
153
|
+
for error in self.errors:
|
|
154
|
+
if error.root_component is component:
|
|
155
|
+
raise LookupError(
|
|
156
|
+
f"root component failed for logical input {self.index}: "
|
|
157
|
+
f"{error.exception}"
|
|
158
|
+
) from error.exception
|
|
159
|
+
raise LookupError(f"no output is available for logical input {self.index}")
|
|
160
|
+
|
|
161
|
+
def __repr__(self) -> str:
|
|
162
|
+
return (
|
|
163
|
+
f"OutputRecord(index={self.index}, key={self.key!r}, "
|
|
164
|
+
f"errors={len(self.errors)})"
|
|
165
|
+
)
|
|
166
|
+
|
|
167
|
+
class ExecutionResult:
|
|
168
|
+
"""Lazy single-stream execution handle.
|
|
169
|
+
|
|
170
|
+
``output()`` is the only public output-access operation. It always yields
|
|
171
|
+
lightweight per-input output records, independent of input and root-component cardinality.
|
|
172
|
+
"""
|
|
173
|
+
|
|
174
|
+
__slots__ = (
|
|
175
|
+
"_id",
|
|
176
|
+
"_roots",
|
|
177
|
+
"_logs",
|
|
178
|
+
"_stream_factory",
|
|
179
|
+
"_stream_close",
|
|
180
|
+
"_errors",
|
|
181
|
+
"_lock",
|
|
182
|
+
"_state",
|
|
183
|
+
"_cache",
|
|
184
|
+
"_active_iterator",
|
|
185
|
+
)
|
|
186
|
+
|
|
187
|
+
_READY = "ready"
|
|
188
|
+
_STREAMING = "streaming"
|
|
189
|
+
_CONSUMED = "consumed"
|
|
190
|
+
_MATERIALIZED = "materialized"
|
|
191
|
+
_CLOSED = "closed"
|
|
192
|
+
|
|
193
|
+
def __init__(
|
|
194
|
+
self,
|
|
195
|
+
*,
|
|
196
|
+
execution_id: ExecutionId,
|
|
197
|
+
roots: tuple[FilterComponent, ...],
|
|
198
|
+
logs: ExecutionLogs,
|
|
199
|
+
stream_factory: Callable[[], Iterator[_OutputRecord]],
|
|
200
|
+
stream_close: Callable[[], None],
|
|
201
|
+
errors: list[ExecutionError],
|
|
202
|
+
) -> None:
|
|
203
|
+
self._id = ExecutionId.parse(execution_id)
|
|
204
|
+
self._roots = tuple(roots)
|
|
205
|
+
self._logs = logs
|
|
206
|
+
self._stream_factory = stream_factory
|
|
207
|
+
self._stream_close = stream_close
|
|
208
|
+
self._errors = errors
|
|
209
|
+
self._lock = threading.RLock()
|
|
210
|
+
self._state = self._READY
|
|
211
|
+
self._cache: tuple[_OutputRecord, ...] | None = None
|
|
212
|
+
self._active_iterator: Iterator[_OutputRecord] | None = None
|
|
213
|
+
|
|
214
|
+
@property
|
|
215
|
+
def id(self) -> ExecutionId:
|
|
216
|
+
return self._id
|
|
217
|
+
|
|
218
|
+
@property
|
|
219
|
+
def roots(self) -> tuple[FilterComponent, ...]:
|
|
220
|
+
return self._roots
|
|
221
|
+
|
|
222
|
+
@property
|
|
223
|
+
def logs(self) -> ExecutionLogs:
|
|
224
|
+
return self._logs
|
|
225
|
+
|
|
226
|
+
@property
|
|
227
|
+
def errors(self) -> Sequence[ExecutionError]:
|
|
228
|
+
with self._lock:
|
|
229
|
+
return tuple(self._errors)
|
|
230
|
+
|
|
231
|
+
@property
|
|
232
|
+
def is_materialized(self) -> bool:
|
|
233
|
+
with self._lock:
|
|
234
|
+
return self._state == self._MATERIALIZED
|
|
235
|
+
|
|
236
|
+
@property
|
|
237
|
+
def is_closed(self) -> bool:
|
|
238
|
+
with self._lock:
|
|
239
|
+
return self._state == self._CLOSED
|
|
240
|
+
|
|
241
|
+
def output(self) -> Iterator[_OutputRecord]:
|
|
242
|
+
with self._lock:
|
|
243
|
+
if self._state == self._MATERIALIZED:
|
|
244
|
+
return iter(self._cache or ())
|
|
245
|
+
iterator = self._start_stream_locked()
|
|
246
|
+
|
|
247
|
+
def consume() -> Iterator[_OutputRecord]:
|
|
248
|
+
try:
|
|
249
|
+
yield from iterator
|
|
250
|
+
finally:
|
|
251
|
+
self._finish_stream(self._CONSUMED)
|
|
252
|
+
|
|
253
|
+
return consume()
|
|
254
|
+
|
|
255
|
+
def materialize(self) -> Self:
|
|
256
|
+
with self._lock:
|
|
257
|
+
if self._state == self._MATERIALIZED:
|
|
258
|
+
return self
|
|
259
|
+
iterator = self._start_stream_locked()
|
|
260
|
+
|
|
261
|
+
try:
|
|
262
|
+
cache = tuple(iterator)
|
|
263
|
+
except BaseException:
|
|
264
|
+
self._finish_stream(self._CONSUMED)
|
|
265
|
+
raise
|
|
266
|
+
self._finish_stream(self._MATERIALIZED, cache=cache)
|
|
267
|
+
return self
|
|
268
|
+
|
|
269
|
+
def close(self) -> None:
|
|
270
|
+
with self._lock:
|
|
271
|
+
if self._state == self._CLOSED:
|
|
272
|
+
return
|
|
273
|
+
self._state = self._CLOSED
|
|
274
|
+
iterator = self._active_iterator
|
|
275
|
+
self._active_iterator = None
|
|
276
|
+
try:
|
|
277
|
+
close = getattr(iterator, "close", None)
|
|
278
|
+
if callable(close):
|
|
279
|
+
close()
|
|
280
|
+
finally:
|
|
281
|
+
self._stream_close()
|
|
282
|
+
|
|
283
|
+
def __enter__(self) -> Self:
|
|
284
|
+
if self.is_closed:
|
|
285
|
+
raise ResultStateError("ExecutionResult is closed")
|
|
286
|
+
return self
|
|
287
|
+
|
|
288
|
+
def __exit__(self, exc_type, exc_value, traceback) -> bool | None:
|
|
289
|
+
self.close()
|
|
290
|
+
return None
|
|
291
|
+
|
|
292
|
+
def _start_stream_locked(self) -> Iterator[_OutputRecord]:
|
|
293
|
+
if self._state == self._CLOSED:
|
|
294
|
+
raise ResultStateError("ExecutionResult is closed")
|
|
295
|
+
if self._state != self._READY:
|
|
296
|
+
raise ResultStateError(
|
|
297
|
+
"ExecutionResult.output() is single-pass; call materialize() "
|
|
298
|
+
"before streaming when repeatable output is required"
|
|
299
|
+
)
|
|
300
|
+
self._state = self._STREAMING
|
|
301
|
+
iterator = self._stream_factory()
|
|
302
|
+
self._active_iterator = iterator
|
|
303
|
+
return iterator
|
|
304
|
+
|
|
305
|
+
def _finish_stream(
|
|
306
|
+
self,
|
|
307
|
+
state: str,
|
|
308
|
+
*,
|
|
309
|
+
cache: tuple[_OutputRecord, ...] | None = None,
|
|
310
|
+
) -> None:
|
|
311
|
+
try:
|
|
312
|
+
self._stream_close()
|
|
313
|
+
finally:
|
|
314
|
+
with self._lock:
|
|
315
|
+
self._active_iterator = None
|
|
316
|
+
if self._state != self._CLOSED:
|
|
317
|
+
self._cache = cache
|
|
318
|
+
self._state = state
|
|
319
|
+
|
|
320
|
+
__all__ = [
|
|
321
|
+
"ApplicationSessionId", "CorrelationId", "ExecutionId", "JournalPosition",
|
|
322
|
+
"DevicePreference", "ErrorPolicy", "ErrorStage", "EventType",
|
|
323
|
+
"ExecutionError", "ExecutionEvent", "ExecutionObserver", "ExecutionOptions", "ExecutionResult",
|
|
324
|
+
]
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
"""Stable extension contracts for custom input adapters and filter backends.
|
|
2
|
+
|
|
3
|
+
Normal end users do not need this module. It is the supported extension surface
|
|
4
|
+
for packages that add new input formats or alternative CPU/GPU filter backends.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import copy
|
|
9
|
+
from collections.abc import Iterator, Mapping
|
|
10
|
+
from dataclasses import dataclass, field, replace
|
|
11
|
+
from os import PathLike
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from types import MappingProxyType
|
|
14
|
+
from typing import Any, Protocol, runtime_checkable
|
|
15
|
+
|
|
16
|
+
import numpy as np
|
|
17
|
+
|
|
18
|
+
from .execution import DevicePreference
|
|
19
|
+
from ..filters.core import Filter
|
|
20
|
+
from .identity import CorrelationId, ExecutionId
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class InputSource:
|
|
24
|
+
"""Normalized source marker used between the resolver and input adapters."""
|
|
25
|
+
|
|
26
|
+
__slots__ = ()
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@staticmethod
|
|
30
|
+
def _normalize_path(value: str | PathLike[str]) -> Path:
|
|
31
|
+
return Path(value).expanduser()
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@dataclass(frozen=True, slots=True)
|
|
35
|
+
class MemorySource(InputSource):
|
|
36
|
+
image: Any
|
|
37
|
+
key: str
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@dataclass(frozen=True, slots=True)
|
|
41
|
+
class PathSource(InputSource):
|
|
42
|
+
path: Path
|
|
43
|
+
|
|
44
|
+
def __init__(self, path: str | PathLike[str]) -> None:
|
|
45
|
+
object.__setattr__(self, "path", self._normalize_path(path))
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
@dataclass(frozen=True, slots=True)
|
|
49
|
+
class DicomSeriesSource(InputSource):
|
|
50
|
+
directory: Path
|
|
51
|
+
series_id: str
|
|
52
|
+
|
|
53
|
+
def __init__(self, directory: str | PathLike[str], series_id: str) -> None:
|
|
54
|
+
object.__setattr__(self, "directory", self._normalize_path(directory))
|
|
55
|
+
object.__setattr__(self, "series_id", str(series_id))
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
@dataclass(frozen=True, slots=True)
|
|
59
|
+
class LogicalInput:
|
|
60
|
+
index: int
|
|
61
|
+
key: str
|
|
62
|
+
source: InputSource
|
|
63
|
+
|
|
64
|
+
def __post_init__(self) -> None:
|
|
65
|
+
index = int(self.index)
|
|
66
|
+
if index < 0:
|
|
67
|
+
raise ValueError("LogicalInput.index cannot be negative")
|
|
68
|
+
object.__setattr__(self, "index", index)
|
|
69
|
+
key = str(self.key).strip()
|
|
70
|
+
if not key:
|
|
71
|
+
raise ValueError("LogicalInput.key is required")
|
|
72
|
+
object.__setattr__(self, "key", key)
|
|
73
|
+
if not isinstance(self.source, InputSource):
|
|
74
|
+
raise TypeError("LogicalInput.source must be InputSource")
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
@dataclass(frozen=True, slots=True)
|
|
78
|
+
class LoadedImage:
|
|
79
|
+
"""Metadata-preserving image payload used by input adapters and backends."""
|
|
80
|
+
|
|
81
|
+
data: Any
|
|
82
|
+
spacing: tuple[float, ...] | None = None
|
|
83
|
+
origin: tuple[float, ...] | None = None
|
|
84
|
+
direction: tuple[float, ...] | None = None
|
|
85
|
+
metadata: Mapping[str, Any] = field(default_factory=dict)
|
|
86
|
+
source: str | None = None
|
|
87
|
+
native: Any = None
|
|
88
|
+
|
|
89
|
+
def __post_init__(self) -> None:
|
|
90
|
+
array = np.asarray(self.data)
|
|
91
|
+
if array.ndim < 2:
|
|
92
|
+
raise ValueError("loaded image data must be at least 2D")
|
|
93
|
+
object.__setattr__(self, "data", array)
|
|
94
|
+
|
|
95
|
+
spacing = self.spacing
|
|
96
|
+
if spacing is None:
|
|
97
|
+
spacing = (1.0,) * array.ndim
|
|
98
|
+
spacing = tuple(float(value) for value in spacing)
|
|
99
|
+
if len(spacing) != array.ndim:
|
|
100
|
+
raise ValueError("spacing dimensionality must match image data")
|
|
101
|
+
if any(value <= 0.0 or not np.isfinite(value) for value in spacing):
|
|
102
|
+
raise ValueError("spacing values must be finite and positive")
|
|
103
|
+
object.__setattr__(self, "spacing", spacing)
|
|
104
|
+
|
|
105
|
+
if self.origin is not None:
|
|
106
|
+
object.__setattr__(self, "origin", tuple(float(value) for value in self.origin))
|
|
107
|
+
if self.direction is not None:
|
|
108
|
+
object.__setattr__(self, "direction", tuple(float(value) for value in self.direction))
|
|
109
|
+
object.__setattr__(
|
|
110
|
+
self,
|
|
111
|
+
"metadata",
|
|
112
|
+
MappingProxyType(copy.deepcopy(dict(self.metadata))),
|
|
113
|
+
)
|
|
114
|
+
object.__setattr__(self, "source", None if self.source is None else str(self.source))
|
|
115
|
+
|
|
116
|
+
def with_data(self, data: Any) -> "LoadedImage":
|
|
117
|
+
array = np.asarray(data)
|
|
118
|
+
if array.ndim == len(self.spacing):
|
|
119
|
+
return replace(self, data=array)
|
|
120
|
+
return replace(
|
|
121
|
+
self,
|
|
122
|
+
data=array,
|
|
123
|
+
spacing=(1.0,) * array.ndim,
|
|
124
|
+
origin=None,
|
|
125
|
+
direction=None,
|
|
126
|
+
)
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
@dataclass(frozen=True, slots=True)
|
|
130
|
+
class FilterContext:
|
|
131
|
+
execution_id: ExecutionId
|
|
132
|
+
correlation_id: CorrelationId
|
|
133
|
+
root_index: int
|
|
134
|
+
input_index: int
|
|
135
|
+
step_index: int
|
|
136
|
+
device: DevicePreference
|
|
137
|
+
|
|
138
|
+
def __post_init__(self) -> None:
|
|
139
|
+
object.__setattr__(self, "execution_id", ExecutionId.parse(self.execution_id))
|
|
140
|
+
object.__setattr__(self, "correlation_id", CorrelationId.parse(self.correlation_id))
|
|
141
|
+
object.__setattr__(self, "root_index", int(self.root_index))
|
|
142
|
+
object.__setattr__(self, "input_index", int(self.input_index))
|
|
143
|
+
object.__setattr__(self, "step_index", int(self.step_index))
|
|
144
|
+
if not isinstance(self.device, DevicePreference):
|
|
145
|
+
object.__setattr__(self, "device", DevicePreference(self.device))
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
@runtime_checkable
|
|
149
|
+
class InputAdapter(Protocol):
|
|
150
|
+
"""Extension contract for discovering and loading normalized inputs."""
|
|
151
|
+
|
|
152
|
+
def supports(self, source: InputSource) -> bool: ...
|
|
153
|
+
def discover(self, source: InputSource) -> Iterator[tuple[str, InputSource]]: ...
|
|
154
|
+
def load(self, item: LogicalInput) -> Any: ...
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
@runtime_checkable
|
|
158
|
+
class FilterBackend(Protocol):
|
|
159
|
+
"""Extension contract for executing a filter definition on a device."""
|
|
160
|
+
|
|
161
|
+
def supports(self, filter: Filter, *, device: DevicePreference) -> bool: ...
|
|
162
|
+
def execute(self, filter: Filter, *, image: Any, context: FilterContext) -> Any: ...
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
__all__ = [
|
|
166
|
+
"DicomSeriesSource",
|
|
167
|
+
"FilterBackend",
|
|
168
|
+
"FilterContext",
|
|
169
|
+
"InputAdapter",
|
|
170
|
+
"InputSource",
|
|
171
|
+
"LoadedImage",
|
|
172
|
+
"LogicalInput",
|
|
173
|
+
"MemorySource",
|
|
174
|
+
"PathSource",
|
|
175
|
+
]
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
"""Typed opaque identifiers shared by execution and diagnostics."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import uuid
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from typing import Self
|
|
7
|
+
|
|
8
|
+
@dataclass(frozen=True, slots=True, order=True)
|
|
9
|
+
class _OpaqueId:
|
|
10
|
+
value: str
|
|
11
|
+
|
|
12
|
+
def __post_init__(self) -> None:
|
|
13
|
+
value = str(self.value or "").strip()
|
|
14
|
+
if not value:
|
|
15
|
+
raise ValueError(f"{type(self).__name__} is required")
|
|
16
|
+
object.__setattr__(self, "value", value)
|
|
17
|
+
|
|
18
|
+
@classmethod
|
|
19
|
+
def new(cls) -> Self:
|
|
20
|
+
return cls(uuid.uuid4().hex)
|
|
21
|
+
|
|
22
|
+
@classmethod
|
|
23
|
+
def parse(cls, value: object) -> Self:
|
|
24
|
+
if isinstance(value, cls):
|
|
25
|
+
return value
|
|
26
|
+
return cls(str(value))
|
|
27
|
+
|
|
28
|
+
def __str__(self) -> str:
|
|
29
|
+
return self.value
|
|
30
|
+
|
|
31
|
+
class ApplicationSessionId(_OpaqueId):
|
|
32
|
+
"""Identity of one private filtering runtime session."""
|
|
33
|
+
|
|
34
|
+
class ExecutionId(_OpaqueId):
|
|
35
|
+
"""Identity of one filtering execution attempt."""
|
|
36
|
+
|
|
37
|
+
class CorrelationId(_OpaqueId):
|
|
38
|
+
"""Causal correlation token used by events and diagnostics."""
|
|
39
|
+
|
|
40
|
+
@dataclass(frozen=True, slots=True, order=True)
|
|
41
|
+
class JournalPosition:
|
|
42
|
+
"""Monotonic position in the canonical diagnostic journal."""
|
|
43
|
+
value: int
|
|
44
|
+
|
|
45
|
+
def __post_init__(self) -> None:
|
|
46
|
+
value = int(self.value)
|
|
47
|
+
if value < 0:
|
|
48
|
+
raise ValueError("JournalPosition must be non-negative")
|
|
49
|
+
object.__setattr__(self, "value", value)
|
|
50
|
+
|
|
51
|
+
def __int__(self) -> int:
|
|
52
|
+
return self.value
|
|
53
|
+
|
|
54
|
+
def __str__(self) -> str:
|
|
55
|
+
return str(self.value)
|
|
56
|
+
|
|
57
|
+
__all__ = [
|
|
58
|
+
"ApplicationSessionId",
|
|
59
|
+
"CorrelationId",
|
|
60
|
+
"ExecutionId",
|
|
61
|
+
"JournalPosition",
|
|
62
|
+
]
|