ezmsg-qt 0.2.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.
ezmsg/qt/__init__.py ADDED
@@ -0,0 +1,59 @@
1
+ """
2
+ ezmsg.qt - Qt integration for ezmsg with direct topic-based pub/sub.
3
+
4
+ This package provides Qt widgets that can subscribe to and publish messages
5
+ on ezmsg topics using a familiar Qt signal/slot pattern.
6
+
7
+ Example:
8
+ from ezmsg.qt import EzSubscriber, EzPublisher, EzSession, ProcessorChain
9
+
10
+ class MyWidget(QtWidgets.QWidget):
11
+ def __init__(self, session):
12
+ super().__init__()
13
+ # Simple subscription (no processing)
14
+ self.data_sub = EzSubscriber(MyTopic.OUTPUT, parent=self, session=session)
15
+ self.data_sub.connect(self.on_data)
16
+
17
+ # Processing pipeline with isolated and shared sidecar stages
18
+ self.chain = (
19
+ ProcessorChain(MyTopic.RAW, parent=self)
20
+ .parallel(LowPassFilter, ScaleProcessor)
21
+ .local(ThresholdDetector)
22
+ .connect(self.on_processed)
23
+ .attach(session)
24
+ )
25
+
26
+ def on_data(self, msg):
27
+ pass
28
+
29
+ def on_processed(self, msg):
30
+ pass
31
+
32
+ app = QtWidgets.QApplication([])
33
+ session = EzSession()
34
+ window = MyWidget(session)
35
+ window.show()
36
+
37
+ with session:
38
+ app.exec()
39
+ """
40
+
41
+ from .chain import ProcessorChain
42
+ from .gate import GateMessage
43
+ from .gate import MessageGate
44
+ from .gate import MessageGateSettings
45
+ from .publisher import EzPublisher
46
+ from .session import EzSession
47
+ from .settings_form import SettingsForm
48
+ from .subscriber import EzSubscriber
49
+
50
+ __all__ = [
51
+ "EzSession",
52
+ "EzPublisher",
53
+ "EzSubscriber",
54
+ "ProcessorChain",
55
+ "SettingsForm",
56
+ "GateMessage",
57
+ "MessageGate",
58
+ "MessageGateSettings",
59
+ ]
@@ -0,0 +1,34 @@
1
+ # file generated by setuptools-scm
2
+ # don't change, don't track in version control
3
+
4
+ __all__ = [
5
+ "__version__",
6
+ "__version_tuple__",
7
+ "version",
8
+ "version_tuple",
9
+ "__commit_id__",
10
+ "commit_id",
11
+ ]
12
+
13
+ TYPE_CHECKING = False
14
+ if TYPE_CHECKING:
15
+ from typing import Tuple
16
+ from typing import Union
17
+
18
+ VERSION_TUPLE = Tuple[Union[int, str], ...]
19
+ COMMIT_ID = Union[str, None]
20
+ else:
21
+ VERSION_TUPLE = object
22
+ COMMIT_ID = object
23
+
24
+ version: str
25
+ __version__: str
26
+ __version_tuple__: VERSION_TUPLE
27
+ version_tuple: VERSION_TUPLE
28
+ commit_id: COMMIT_ID
29
+ __commit_id__: COMMIT_ID
30
+
31
+ __version__ = version = '0.2.0'
32
+ __version_tuple__ = version_tuple = (0, 2, 0)
33
+
34
+ __commit_id__ = commit_id = None
ezmsg/qt/adapter.py ADDED
@@ -0,0 +1,43 @@
1
+ """TransformerAdapter - Wrap ezmsg-baseproc transformers as ez.Unit."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import typing
6
+ from collections.abc import AsyncGenerator
7
+
8
+ import ezmsg.core as ez
9
+
10
+
11
+ class TransformerAdapter(ez.Unit):
12
+ """Wraps a BaseProcessor instance as an ez.Unit.
13
+
14
+ This adapter allows ezmsg-baseproc processors (BaseTransformer, etc.)
15
+ to be used in ProcessorChain alongside native ez.Unit classes.
16
+
17
+ Mirrors key features of BaseTransformerUnit:
18
+ - zero_copy=True for performance with large messages
19
+ - Compatible with ezmsg's pub/sub system
20
+
21
+ Note: This adapter does not support runtime settings updates.
22
+ The transformer should be fully configured before being passed.
23
+ """
24
+
25
+ INPUT = ez.InputStream(typing.Any)
26
+ OUTPUT = ez.OutputStream(typing.Any)
27
+
28
+ def __init__(self, transformer: typing.Any):
29
+ """Create an adapter wrapping a transformer instance.
30
+
31
+ Args:
32
+ transformer: A BaseProcessor instance (or similar) with __acall__ method.
33
+ """
34
+ super().__init__()
35
+ self._transformer = transformer
36
+
37
+ @ez.subscriber(INPUT, zero_copy=True)
38
+ @ez.publisher(OUTPUT)
39
+ async def process(self, msg: typing.Any) -> AsyncGenerator:
40
+ """Process incoming messages through the wrapped transformer."""
41
+ result = await self._transformer.__acall__(msg)
42
+ if result is not None:
43
+ yield self.OUTPUT, result
ezmsg/qt/chain.py ADDED
@@ -0,0 +1,258 @@
1
+ """ProcessorChain - Fluent API for compiled processing pipelines."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Callable
6
+ from dataclasses import dataclass
7
+ from dataclasses import field
8
+ from enum import Enum
9
+ from typing import Any
10
+ from typing import Literal
11
+ from typing import TYPE_CHECKING
12
+
13
+ import ezmsg.core as ez
14
+ from qtpy import QtWidgets
15
+
16
+ if TYPE_CHECKING:
17
+ from .session import EzSession
18
+
19
+ # Type alias for processor specifications
20
+ # A processor can be specified as:
21
+ # - Unit class: LowPassFilter
22
+ # - Unit class with settings: (LowPassFilter, LowPassSettings(...))
23
+ # - Transformer instance: MyTransformer(factor=2)
24
+ ProcessorSpec = type[ez.Unit] | tuple[type[ez.Unit], ez.Settings] | Any
25
+
26
+
27
+ def _is_process_safe(spec: ProcessorSpec) -> bool:
28
+ if isinstance(spec, ez.Unit):
29
+ return True
30
+ if isinstance(spec, tuple):
31
+ unit_class, _settings = spec
32
+ return isinstance(unit_class, type) and issubclass(unit_class, ez.Unit)
33
+ return isinstance(spec, type) and issubclass(spec, ez.Unit)
34
+
35
+
36
+ def _to_unit(spec: ProcessorSpec) -> ez.Unit:
37
+ """Convert a ProcessorSpec to an ez.Unit instance.
38
+
39
+ Args:
40
+ spec: A Unit instance, Unit class, (class, settings) tuple,
41
+ or transformer instance.
42
+
43
+ Returns:
44
+ An instantiated ez.Unit ready for use.
45
+
46
+ Raises:
47
+ TypeError: If spec is not a recognized processor type.
48
+ """
49
+ if isinstance(spec, ez.Unit):
50
+ # Already instantiated unit (settings already applied)
51
+ return spec
52
+ elif isinstance(spec, tuple):
53
+ # (UnitClass, settings) tuple
54
+ unit_class, settings = spec
55
+ unit = unit_class()
56
+ unit.apply_settings(settings)
57
+ return unit
58
+ elif isinstance(spec, type) and issubclass(spec, ez.Unit):
59
+ # Unit class without settings
60
+ return spec()
61
+ elif hasattr(spec, "__acall__"):
62
+ # BaseProcessor instance (has async call method)
63
+ from .adapter import TransformerAdapter
64
+
65
+ return TransformerAdapter(spec)
66
+ else:
67
+ raise TypeError(
68
+ f"Expected Unit class, (class, settings) tuple, or processor instance "
69
+ f"with __acall__, got {type(spec)}"
70
+ )
71
+
72
+
73
+ @dataclass
74
+ class ProcessorGroup:
75
+ """A group of processors that run together in the same execution context."""
76
+
77
+ processors: list[ProcessorSpec] = field(default_factory=list)
78
+ mode: Literal["shared", "process"] = "shared"
79
+
80
+
81
+ class ProcessorChain:
82
+ """
83
+ Fluent builder for processor chains.
84
+
85
+ ProcessorChain accumulates processor groups that will be executed
86
+ in sequence inside a sidecar ezmsg runtime owned by :class:`EzSession`.
87
+
88
+ - ``parallel()`` runs a group in its own sidecar process.
89
+ - ``local()`` runs a group in the shared sidecar process.
90
+
91
+ Neither mode runs work on the Qt UI thread.
92
+
93
+ Example:
94
+ # Using Unit classes
95
+ chain = (
96
+ ProcessorChain(Topic.RAW, parent=widget)
97
+ .parallel(LowPassFilter, ScaleProcessor)
98
+ .local(ThresholdDetector)
99
+ .connect(widget.on_data)
100
+ )
101
+
102
+ # Using Unit classes with settings
103
+ chain = (
104
+ ProcessorChain(Topic.RAW, parent=widget)
105
+ .parallel((LowPassFilter, LowPassSettings(alpha=0.5)))
106
+ .connect(widget.on_data)
107
+ )
108
+
109
+ # Using transformer instances
110
+ chain = (
111
+ ProcessorChain(Topic.RAW, parent=widget)
112
+ .parallel(LowPassFilter(), ScaleProcessor(factor=2))
113
+ .connect(widget.on_data)
114
+ )
115
+ """
116
+
117
+ def __init__(
118
+ self,
119
+ source_topic: Enum | str,
120
+ parent: QtWidgets.QWidget | None = None,
121
+ auto_gate: bool = True,
122
+ ):
123
+ """Create a processor chain.
124
+
125
+ Args:
126
+ source_topic: The topic name to subscribe to.
127
+ parent: Optional parent widget for auto-gating.
128
+ auto_gate: If True, gate based on parent widget visibility.
129
+ """
130
+ self._source_topic = source_topic
131
+ self._parent_widget = parent
132
+ self._auto_gate = auto_gate
133
+ self._groups: list[ProcessorGroup] = []
134
+ self._handler: Callable[[Any], None] | None = None
135
+ self._chain_id: str | None = None
136
+ self._session: EzSession | None = None
137
+ self._attached = False
138
+
139
+ @property
140
+ def source_topic(self) -> Enum | str:
141
+ """The source topic this chain subscribes to."""
142
+ return self._source_topic
143
+
144
+ @property
145
+ def groups(self) -> list[ProcessorGroup]:
146
+ """The processor groups in this chain."""
147
+ return self._groups
148
+
149
+ @property
150
+ def parent_widget(self) -> QtWidgets.QWidget | None:
151
+ """The parent widget for auto-gating."""
152
+ return self._parent_widget
153
+
154
+ @property
155
+ def auto_gate(self) -> bool:
156
+ """Whether auto-gating based on visibility is enabled."""
157
+ return self._auto_gate
158
+
159
+ @property
160
+ def handler(self) -> Callable[[Any], None] | None:
161
+ """The Qt handler connected to this chain's output."""
162
+ return self._handler
163
+
164
+ def parallel(self, *processors: ProcessorSpec) -> ProcessorChain:
165
+ """Add processors to run in an isolated sidecar process.
166
+
167
+ Multiple processors passed to a single parallel() call will be
168
+ grouped together in the same process.
169
+
170
+ Args:
171
+ *processors: Unit classes, (class, settings) tuples, or
172
+ ez.Unit instances.
173
+
174
+ Returns:
175
+ Self for method chaining.
176
+
177
+ Example:
178
+ chain.parallel(LowPassFilter, ScaleProcessor) # same process
179
+ chain.parallel(FFT) # different process
180
+
181
+ Note:
182
+ ``parallel()`` only supports ez.Unit-based processors. Transformer
183
+ instances with ``__acall__`` are only supported by ``local()``.
184
+ """
185
+ self._groups.append(ProcessorGroup(processors=list(processors), mode="process"))
186
+ return self
187
+
188
+ def local(self, *processors: ProcessorSpec) -> ProcessorChain:
189
+ """Add processors to run in the shared sidecar process.
190
+
191
+ Multiple processors passed to a single local() call will be
192
+ grouped together.
193
+
194
+ Args:
195
+ *processors: Unit classes, (class, settings) tuples, or
196
+ transformer instances.
197
+
198
+ Returns:
199
+ Self for method chaining.
200
+
201
+ Example:
202
+ chain.local(ThresholdDetector) # runs in shared sidecar process
203
+ """
204
+ self._groups.append(ProcessorGroup(processors=list(processors), mode="shared"))
205
+ return self
206
+
207
+ def connect(self, slot: Callable[[Any], None]) -> ProcessorChain:
208
+ """Connect the chain output to a Qt handler.
209
+
210
+ This finalizes the chain configuration. The handler will be
211
+ called with each processed message.
212
+
213
+ Args:
214
+ slot: A callable that receives processed messages.
215
+ """
216
+ self._handler = slot
217
+ return self
218
+
219
+ @property
220
+ def session(self) -> EzSession | None:
221
+ """The session this pipeline is attached to, if any."""
222
+ return self._session
223
+
224
+ @property
225
+ def attached(self) -> bool:
226
+ """Whether this pipeline has been attached to a session."""
227
+ return self._attached
228
+
229
+ def attach(self, session: EzSession) -> ProcessorChain:
230
+ """Attach this pipeline to a session.
231
+
232
+ The pipeline must be fully configured before attachment.
233
+ """
234
+ session.attach(self)
235
+ return self
236
+
237
+ def _bind_session(self, session: EzSession) -> None:
238
+ if self._session is not None and self._session is not session:
239
+ raise RuntimeError(
240
+ "ProcessorChain is already attached to a different session"
241
+ )
242
+ self._session = session
243
+ self._attached = True
244
+
245
+ def _validate(self) -> None:
246
+ if not self._groups:
247
+ raise ValueError("ProcessorChain must define at least one processor group")
248
+ if self._handler is None:
249
+ raise ValueError("ProcessorChain must connect a handler before attachment")
250
+ for group in self._groups:
251
+ if group.mode != "process":
252
+ continue
253
+ for spec in group.processors:
254
+ if not _is_process_safe(spec):
255
+ raise TypeError(
256
+ "parallel() only supports ez.Unit classes, ez.Unit instances, "
257
+ "or (UnitClass, Settings) tuples"
258
+ )
ezmsg/qt/gate.py ADDED
@@ -0,0 +1,63 @@
1
+ """Gate unit for controlling message flow in processor chains."""
2
+
3
+ import logging
4
+ from collections.abc import AsyncGenerator
5
+ from dataclasses import dataclass
6
+ from typing import Any
7
+
8
+ import ezmsg.core as ez
9
+
10
+ logger = logging.getLogger(__name__)
11
+
12
+
13
+ @dataclass
14
+ class GateMessage:
15
+ """Control message for opening/closing a gate."""
16
+
17
+ open: bool
18
+
19
+
20
+ class MessageGateSettings(ez.Settings):
21
+ """Settings for MessageGate unit."""
22
+
23
+ start_open: bool = True
24
+
25
+
26
+ class MessageGateState(ez.State):
27
+ """Runtime state for MessageGate unit."""
28
+
29
+ is_open: bool
30
+
31
+
32
+ class MessageGate(ez.Unit):
33
+ """
34
+ Gate unit that passes or blocks messages based on control input.
35
+
36
+ When the gate is open, messages flow through. When closed, messages
37
+ are dropped. Gate state is controlled via INPUT_GATE stream.
38
+ """
39
+
40
+ SETTINGS = MessageGateSettings
41
+ STATE = MessageGateState
42
+
43
+ INPUT = ez.InputStream(Any)
44
+ OUTPUT = ez.OutputStream(Any)
45
+ INPUT_GATE = ez.InputStream(GateMessage)
46
+
47
+ async def initialize(self) -> None:
48
+ self.STATE.is_open = self.SETTINGS.start_open
49
+ logger.debug(f"MessageGate initialized: is_open={self.STATE.is_open}")
50
+
51
+ @ez.subscriber(INPUT_GATE)
52
+ async def on_gate(self, msg: GateMessage) -> None:
53
+ """Handle gate control messages."""
54
+ old_state = self.STATE.is_open
55
+ self.STATE.is_open = msg.open
56
+ logger.info(f"Gate state changed: {old_state} -> {msg.open}")
57
+
58
+ @ez.subscriber(INPUT)
59
+ @ez.publisher(OUTPUT)
60
+ async def on_message(self, msg: Any) -> AsyncGenerator:
61
+ """Pass message through if gate is open."""
62
+ if self.STATE.is_open:
63
+ yield self.OUTPUT, msg