sier2 0.29__py2.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.

Potentially problematic release.


This version of sier2 might be problematic. Click here for more details.

sier2/__init__.py ADDED
@@ -0,0 +1,4 @@
1
+ from ._block import Block, BlockError, BlockValidateError
2
+ from ._dag import Connection, Dag, BlockState
3
+ from ._library import Library, Info
4
+ from ._version import __version__
sier2/__main__.py ADDED
@@ -0,0 +1,96 @@
1
+ import argparse
2
+ from importlib.metadata import version
3
+
4
+ from sier2 import Library
5
+ from ._library import _find_blocks, _find_dags, run_dag
6
+ from ._util import block_doc_text, dag_doc_text
7
+
8
+ BOLD = '' # '\x1b[1;37m'
9
+ NORM = '' # '\x1b[0m'
10
+
11
+ def _pkg(module):
12
+ return module.split('.')[0]
13
+
14
+ def blocks_cmd(args):
15
+ """Display the blocks found via plugin entry points."""
16
+
17
+ seen = set()
18
+ curr_ep = None
19
+ for entry_point, gi in _find_blocks():
20
+ show = not args.block or gi.key.endswith(args.block)
21
+ if curr_ep is None or entry_point!=curr_ep:
22
+ if show:
23
+ pkg = _pkg(entry_point.module)
24
+ s = f'In {pkg} v{version(pkg)}'
25
+ u = '' # '\n' + '#' * len(s)
26
+ print(f'\n{BOLD}{s}{u}{NORM}')
27
+ # print(f'\x1b[1mIn {entry_point.module} v{version(entry_point.module)}:\x1b[0m')
28
+ curr_ep = entry_point
29
+
30
+ if show:
31
+ dup = f' (DUPLICATE)' if gi.key in seen else ''
32
+ print(f' {BOLD}{gi.key}: {gi.doc}{NORM}{dup}')
33
+
34
+ if args.verbose:
35
+ block = Library.get_block(gi.key)
36
+ print(block_doc_text(block))
37
+ print()
38
+
39
+ seen.add(gi.key)
40
+
41
+ def dags_cmd(args):
42
+ """Display the dags found via plugin entry points."""
43
+
44
+ seen = set()
45
+ curr_ep = None
46
+ for entry_point, gi in _find_dags():
47
+ show = not args.dag or gi.key.endswith(args.dag)
48
+ if curr_ep is None or entry_point!=curr_ep:
49
+ if show:
50
+ pkg = _pkg(entry_point.module)
51
+ s = f'In {pkg} v{version(pkg)}'
52
+ u = '' # '\n' + '#' * len(s)
53
+ print(f'\n{BOLD}{s}{u}{NORM}')
54
+ curr_ep = entry_point
55
+
56
+ if show:
57
+ dup = f' (DUPLICATE)' if gi.key in seen else ''
58
+ print(f' {BOLD}{gi.key}: {gi.doc}{NORM}{dup}')
59
+
60
+ if args.verbose:
61
+ # We have to instantiate the dag to get the documentation.
62
+ #
63
+ dag = Library.get_dag(gi.key)
64
+ print(dag_doc_text(dag))
65
+
66
+ seen.add(gi.key)
67
+
68
+ def run_cmd(args):
69
+ run_dag(args.dag)
70
+
71
+ def main():
72
+ parser = argparse.ArgumentParser()
73
+ subparsers = parser.add_subparsers(help='sub-command help')
74
+
75
+ run = subparsers.add_parser('run', help='Run a dag')
76
+ run.add_argument('dag', type=str, help='A dag to run')
77
+ run.set_defaults(func=run_cmd)
78
+
79
+ blocks = subparsers.add_parser('blocks', help='Show available blocks')
80
+ blocks.add_argument('-v', '--verbose', action='store_true', help='Show help')
81
+ blocks.add_argument('block', nargs='?', help='Show all blocks ending with this string')
82
+ blocks.set_defaults(func=blocks_cmd)
83
+
84
+ dags = subparsers.add_parser('dags', help='Show available dags')
85
+ dags.add_argument('-v', '--verbose', action='store_true', help='Show help')
86
+ dags.add_argument('dag', nargs='?', help='Show all dags ending with this string')
87
+ dags.set_defaults(func=dags_cmd)
88
+
89
+ args = parser.parse_args()
90
+ if 'func' in args:
91
+ args.func(args)
92
+ else:
93
+ parser.print_help()
94
+
95
+ if __name__=='__main__':
96
+ main()
sier2/_block.py ADDED
@@ -0,0 +1,221 @@
1
+ from enum import StrEnum
2
+ import inspect
3
+ import param
4
+ from typing import Any
5
+
6
+ from . import _logger
7
+
8
+ class BlockError(Exception):
9
+ """Raised if a Block configuration is invalid.
10
+
11
+ If this exception is raised, the executing dag sets its stop
12
+ flag (which must be manually reset), and displays a stacktrace.
13
+ """
14
+
15
+ pass
16
+
17
+ class BlockState(StrEnum):
18
+ """The current state of a block; also used for logging."""
19
+
20
+ DAG = 'DAG' # Dag logging.
21
+ BLOCK = 'BLOCK' # Block logging.
22
+ INPUT = 'INPUT'
23
+ READY = 'READY'
24
+ EXECUTING = 'EXECUTING'
25
+ WAITING = 'WAITING'
26
+ SUCCESSFUL = 'SUCCESSFUL'
27
+ INTERRUPTED = 'INTERRUPTED'
28
+ ERROR = 'ERROR'
29
+
30
+ _PAUSE_EXECUTION_DOC = '''If True, a block executes in two steps.
31
+
32
+ When the block is executed by a dag, the dag first sets the input
33
+ params, then calls ``prepare()``. Execution of the dag then stops.
34
+
35
+ The dag is then restarted using ``dag.execute_after_input(input_block)``.
36
+ (An input block must be specified because it is not required that the
37
+ same input block be used immediately.) This causes the block's
38
+ ``execute()`` method to be called without resetting the input params.
39
+
40
+ Dag execution then continues as normal.
41
+ '''
42
+
43
+ class Block(param.Parameterized):
44
+ """The base class for blocks.
45
+
46
+ A block is implemented as:
47
+
48
+ .. code-block:: python
49
+
50
+ class MyBlock(Block):
51
+ ...
52
+
53
+ A typical block will have at least one input parameter, and an ``execute()``
54
+ method that is called when an input parameter value changes.
55
+
56
+ .. code-block:: python
57
+
58
+ class MyBlock(Block):
59
+ value_in = param.String(label='Input Value')
60
+
61
+ def execute(self):
62
+ print(f'New value is {self.value_in}')
63
+ """
64
+
65
+ block_pause_execution = param.Boolean(default=False, label='Pause execution', doc=_PAUSE_EXECUTION_DOC)
66
+
67
+ _block_state = param.String(default=BlockState.READY)
68
+
69
+ SIER2_KEY = '_sier2__key'
70
+
71
+ def __init__(self, *args, block_pause_execution=False, continue_label='Continue', **kwargs):
72
+ super().__init__(*args, **kwargs)
73
+
74
+ if not self.__doc__:
75
+ raise BlockError(f'Class {self.__class__} must have a docstring')
76
+
77
+ self.block_pause_execution = block_pause_execution
78
+ self.continue_label = continue_label
79
+ # self._block_state = BlockState.READY
80
+ self.logger = _logger.get_logger(self.name)
81
+
82
+ # Maintain a map of "block+output parameter being watched" -> "input parameter".
83
+ # This is used by _block_event() to set the correct input parameter.
84
+ #
85
+ self._block_name_map: dict[tuple[str, str], str] = {}
86
+
87
+ # Record this block's output parameters.
88
+ # If this is an input block, we need to trigger
89
+ # the output values before executing the next block,
90
+ # in case the user didn't change anything.
91
+ #
92
+ self._block_out_params = []
93
+
94
+ # self._block_context = _EmptyContext()
95
+
96
+ # self._progress = None
97
+
98
+ @classmethod
99
+ def block_key(cls):
100
+ """The unique key of this block class.
101
+
102
+ Blocks require a unique key so they can be identified in the block library.
103
+ The default implementation should be sufficient, but can be overridden
104
+ in case of refactoring or name clashes.
105
+ """
106
+
107
+ im = inspect.getmodule(cls)
108
+
109
+ if hasattr(cls, Block.SIER2_KEY):
110
+ return getattr(cls, Block.SIER2_KEY)
111
+
112
+ return f'{im.__name__}.{cls.__qualname__}'
113
+
114
+ def prepare(self):
115
+ """If blockpause_execution is True, called by a dag before calling ``execute()```.
116
+
117
+ This gives the block author an opportunity to validate the
118
+ input params and set up a user inteface.
119
+
120
+ After the dag restarts on this block, ``execute()`` will be called.
121
+ """
122
+
123
+ pass
124
+
125
+ def execute(self, *_, **__):
126
+ """This method is called when one or more of the input parameters causes an event.
127
+
128
+ Override this method in a Block subclass.
129
+
130
+ The ``execute()`` method can have arguments. The arguments can be specified
131
+ in any order. It is not necessary to specify all, or any, arguments.
132
+ Arguments will not be passed via ``*args`` or ``**kwargs``.
133
+
134
+ * ``stopper`` - an indicator that the dag has been stopped. This may be
135
+ set while the block is executing, in which case the block should
136
+ stop executing as soon as possible.
137
+ * ``events`` - the param events that caused execute() to be called.
138
+ """
139
+
140
+ # print(f'** EXECUTE {self.__class__=}')
141
+ pass
142
+
143
+ # def __panel__(self):
144
+ # """A default Panel component.
145
+
146
+ # When run in a Panel context, a block will typically implement
147
+ # its own __panel__() method. If it doesn't, this method will be
148
+ # used as a default. When a block without a __panel__() is wrapped
149
+ # in a Card, self.progress will be assigned a pn.indicators.Progress()
150
+ # widget which is returned here. The Panel context will make it active
151
+ # before executing the block, and non-active after executing the block.
152
+ # (Why not have a default Progress()? Because we don't want any
153
+ # Panel-related code in the core implementation.)
154
+
155
+ # If the block implements __panel__(), this will obviously be overridden.
156
+
157
+ # When run in non-Panel context, this will remain unused.
158
+ # """
159
+
160
+ # return self._progress
161
+
162
+ def __call__(self, **kwargs) -> dict[str, Any]:
163
+ """Allow a block to be called directly."""
164
+
165
+ in_names = [name for name in self.__class__.param if name.startswith('in_')]
166
+ if len(kwargs)!=len(in_names) or any(name not in in_names for name in kwargs):
167
+ names = ', '.join(in_names)
168
+ raise BlockError(f'All input params must be specified: {names}')
169
+
170
+ for name, value in kwargs.items():
171
+ setattr(self, name, value)
172
+
173
+ self.execute()
174
+
175
+ out_names = [name for name in self.__class__.param if name.startswith('out_')]
176
+ result = {name: getattr(self, name) for name in out_names}
177
+
178
+ return result
179
+
180
+ # class InputBlock(Block):
181
+ # """A ``Block`` that accepts user input.
182
+
183
+ # An ``InputBlock`` executes in two steps().
184
+
185
+ # When the block is executed by a dag, the dag first sets the input
186
+ # params, then calls ``prepare()``. Execution of the dag then stops.
187
+
188
+ # The dag is then restarted using ``dag.execute_after_input(input_block)``.
189
+ # (An input block must be specified because it is not required that the
190
+ # same input block be used immediately.) This causes the block's
191
+ # ``execute()`` method to be called without resetting the input params.
192
+
193
+ # Dag execution then continues as normal.
194
+ # """
195
+
196
+ # def __init__(self, *args, continue_label='Continue', **kwargs):
197
+ # super().__init__(*args, continue_label=continue_label, **kwargs)
198
+ # self._block_state = BlockState.INPUT
199
+
200
+ # def prepare(self):
201
+ # """Called by a dag before calling ``execute()```.
202
+
203
+ # This gives the block author an opportunity to validate the
204
+ # input params and set up a user inteface.
205
+
206
+ # After the dag restarts on this block, ``execute()`` will be called.
207
+ # """
208
+
209
+ # pass
210
+
211
+ class BlockValidateError(BlockError):
212
+ """Raised if ``Block.prepare()`` or ``Block.execute()`` determines that input data is invalid.
213
+
214
+ If this exception is raised, it will be caught by the executing dag.
215
+ The dag will not set its stop flag, no stacktrace will be displayed,
216
+ and the error message will be displayed.
217
+ """
218
+
219
+ def __init__(self, *, block_name: str, error: str):
220
+ super().__init__(error)
221
+ self.block_name = block_name