samplekit 1.0.0rc2__cp315-cp315-win_amd64.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.
Binary file
samplekit/_script.py ADDED
@@ -0,0 +1,231 @@
1
+ """The command line's script.
2
+
3
+ ``samplekit run`` starts this module in the model's environment, writes one
4
+ JSON request in a file whose path ``SAMPLEKIT_SCRIPT_REQUEST`` holds, and
5
+ waits. The script prints as it runs, and its standard input is the
6
+ terminal's, or the TUI's line: ``input()`` asks there, each question and its
7
+ answer named in the reply. What it returns is printed after it, and what it
8
+ would save is held, not written, and named in the reply file for the command
9
+ to show and ask about. The exit code is the command's.
10
+
11
+ {"script": "dilute", "samples": [...], "options": {"factor": "0.8"},
12
+ "style": null, "reply": "/tmp/…/reply.json"}
13
+ """
14
+
15
+ import builtins
16
+ import json
17
+ import os
18
+ import sys
19
+ import traceback
20
+ import warnings
21
+
22
+ REFUSED, FAILED, INTERRUPTED = 1, 2, 130
23
+
24
+
25
+ def main():
26
+ with open(os.environ["SAMPLEKIT_SCRIPT_REQUEST"], encoding="utf-8") as asked:
27
+ request = json.load(asked)
28
+ warnings.showwarning = _said
29
+ builtins.input = _asking
30
+ try:
31
+ return _run(request)
32
+ except KeyboardInterrupt:
33
+ return INTERRUPTED
34
+
35
+
36
+ def _run(request):
37
+ import samplekit
38
+ from samplekit import _native, _scripts
39
+
40
+ if request.get("version") not in (None, samplekit.__version__):
41
+ return refuse(
42
+ f"this environment holds samplekit {samplekit.__version__}, and the command "
43
+ f"is {request['version']}: install the same version in both"
44
+ )
45
+ name = request["script"]
46
+ try:
47
+ samples = [samplekit.Sample(path) for path in request["samples"]]
48
+ except Exception:
49
+ traceback.print_exc()
50
+ return FAILED
51
+ if not samples:
52
+ return refuse("no sample is selected: nothing to run", code=FAILED)
53
+ models = {type(sample) for sample in samples}
54
+ model = type(samples[0])
55
+ try:
56
+ scripts = _scripts.scripts_of(model)
57
+ except TypeError as error:
58
+ return refuse(str(error))
59
+ script = scripts.get(name)
60
+ if script is None:
61
+ return refuse(
62
+ f"no script named '{name}' in {model.__name__}: "
63
+ + (", ".join(scripts) if scripts else "the model marks none with @sk.script")
64
+ )
65
+ if script.collection and len(models) > 1:
66
+ return refuse(
67
+ f"'{name}' runs on one model's samples, and the selection holds "
68
+ + ", ".join(sorted(kind.__name__ for kind in models))
69
+ )
70
+ for other in models - {model}:
71
+ if name not in _scripts.scripts_of(other):
72
+ return refuse(f"{other.__name__}, the model of some samples selected, declares "
73
+ f"no script '{name}'")
74
+ try:
75
+ arguments = _scripts.arguments(script, request.get("options") or {})
76
+ except ValueError as error:
77
+ return refuse(str(error))
78
+
79
+ # From here, a save is held for the command to show.
80
+ _native._hold_saves()
81
+ results = []
82
+ running = None
83
+ try:
84
+ if script.collection:
85
+ results.append((None, getattr(model, name)(samplekit.SampleList(samples),
86
+ **arguments)))
87
+ else:
88
+ for sample in samples:
89
+ running = sample
90
+ results.append((sample, getattr(sample, name)(**arguments)))
91
+ running = None
92
+ # What the script changed and did not save is saved as it would be.
93
+ for sample in samples:
94
+ if sample._changed:
95
+ sample.save()
96
+ except KeyboardInterrupt:
97
+ raise
98
+ except Exception:
99
+ _said_failure()
100
+ # On which sample, and that nothing is written: the traceback alone
101
+ # left the reader to guess which of the selection raised.
102
+ if running is not None:
103
+ print(f"error: '{name}' raised on {_path(running)}: nothing is written",
104
+ file=sys.stderr)
105
+ else:
106
+ print(f"error: '{name}' raised: nothing is written", file=sys.stderr)
107
+ return FAILED
108
+
109
+ style = request.get("style")
110
+ several = sum(1 for _, result in results if result is not None) > 1
111
+ for sample, result in results:
112
+ text = shown(result, style)
113
+ if text is None:
114
+ continue
115
+ if several and sample is not None:
116
+ if "\n" in text:
117
+ print(f"{sample.name}\n{_indented(text)}")
118
+ else:
119
+ print(f"{sample.name} {text}")
120
+ else:
121
+ print(text)
122
+ sys.stdout.flush()
123
+
124
+ held = [{"path": path, "before": before, "after": after}
125
+ for path, before, after in _native._held_saves()]
126
+ with open(request["reply"], "w", encoding="utf-8") as reply:
127
+ json.dump({"held": held, "answers": _ANSWERS}, reply)
128
+ return 0
129
+
130
+
131
+ _ANSWERS = []
132
+ _INPUT = builtins.input
133
+
134
+
135
+ def _asking(prompt=""):
136
+ """``input()`` as the script calls it: answered from the terminal, or the
137
+ TUI's line, and kept for the preview and the history. With nothing to
138
+ read, the question is named, and how a script is given a value."""
139
+ try:
140
+ answer = _INPUT(prompt)
141
+ except EOFError:
142
+ raise EOFError(
143
+ f"the script asked {str(prompt).strip()!r}, and no terminal can answer it: "
144
+ "--set NAME=VALUE gives a script its values"
145
+ ) from None
146
+ _ANSWERS.append({"prompt": str(prompt), "answer": answer})
147
+ return answer
148
+
149
+
150
+ def shown(result, style=None):
151
+ """What a script returned, as text: None for nothing."""
152
+ import samplekit
153
+
154
+ if result is None:
155
+ return None
156
+ if isinstance(result, str):
157
+ return result
158
+ if isinstance(result, samplekit.SampleList):
159
+ return "\n".join(_path(sample) for sample in result)
160
+ if isinstance(result, (list, tuple)):
161
+ parts = [shown(item, style) for item in result]
162
+ return "\n".join(part for part in parts if part is not None)
163
+ if isinstance(result, (samplekit.Property, samplekit.Table, samplekit.Sample,
164
+ samplekit.Summary)):
165
+ return result.to_text(style)
166
+ return str(result)
167
+
168
+
169
+ def _path(sample):
170
+ path = sample.path
171
+ if path is None:
172
+ return sample.name or "(no file)"
173
+ try:
174
+ return os.path.relpath(path)
175
+ except ValueError:
176
+ return str(path)
177
+
178
+
179
+ def _indented(text):
180
+ return "\n".join(f" {line}" if line else line for line in text.splitlines())
181
+
182
+
183
+ def _said(message, category, filename, lineno, file=None, line=None):
184
+ """A warning as the command line says one: its words, without the source
185
+ line it was raised on."""
186
+ text = str(message).replace("compute() runs it", "samplekit compute runs it")
187
+ # Said once: a value read twice warned twice.
188
+ if text in _SAID:
189
+ return
190
+ _SAID.add(text)
191
+ print(_painted("warning:", text), file=sys.stderr)
192
+
193
+
194
+ _SAID = set()
195
+
196
+
197
+ def _said_failure():
198
+ """The script's traceback, from its own code: what printed before it
199
+ first, and none of this module's frames."""
200
+ kind, error, trace = sys.exc_info()
201
+ while trace is not None and trace.tb_frame.f_code.co_filename == __file__:
202
+ trace = trace.tb_next
203
+ sys.stdout.flush()
204
+ traceback.print_exception(kind, error, trace)
205
+
206
+
207
+ def refuse(message, code=REFUSED):
208
+ print(_painted("error:", message), file=sys.stderr)
209
+ return code
210
+
211
+ def _painted(prefix, text):
212
+ """`prefix` and `text` as the command line paints them where it gave its
213
+ colours: the prefix in its own, advice at the end muted."""
214
+ import os
215
+ reset = os.environ.get("SAMPLEKIT_PAINT_RESET")
216
+ if not reset:
217
+ return f"{prefix} {text}"
218
+ style = os.environ.get(
219
+ "SAMPLEKIT_PAINT_WARNING" if prefix == "warning:" else "SAMPLEKIT_PAINT_ERROR", ""
220
+ )
221
+ muted = os.environ.get("SAMPLEKIT_PAINT_MUTED", "")
222
+ fact, mark, tip = text.rpartition(" — ")
223
+ if mark and ("samplekit " in tip or any(
224
+ word.startswith("--") and len(word) > 2 and word[2].isalpha() for word in tip.split()
225
+ )):
226
+ text = f"{fact} — {muted}{tip}{reset}"
227
+ return f"{style}{prefix}{reset} {text}"
228
+
229
+
230
+ if __name__ == "__main__":
231
+ sys.exit(main())
samplekit/_scripts.py ADDED
@@ -0,0 +1,212 @@
1
+ """A model's scripts: methods marked ``@sk.script``, run by ``samplekit run``.
2
+
3
+ A script on a method acts on one sample; above ``@classmethod``, on the
4
+ selection. Its keyword parameters are the command's options, typed by the
5
+ signature, and its docstring its description.
6
+ """
7
+
8
+ import inspect
9
+
10
+ # The types an option is read as, by the name the signature gives.
11
+ TYPES = {"int": int, "float": float, "bool": bool, "str": str}
12
+ TRUE, FALSE = ("true", "yes", "on", "1"), ("false", "no", "off", "0")
13
+
14
+
15
+ class Script:
16
+ """A model's method marked ``@sk.script``. It still behaves as the method
17
+ it marks: ``steel.classify(15)`` runs as written."""
18
+
19
+ def __init__(self, method):
20
+ if isinstance(method, staticmethod):
21
+ raise TypeError(
22
+ "a script acts on a sample or a selection: mark an instance method, or a "
23
+ "class method (@sk.script above @classmethod), not a static method"
24
+ )
25
+ self.method = method
26
+ self.collection = isinstance(method, classmethod)
27
+ function = method.__func__ if self.collection else method
28
+ self.name = getattr(function, "__name__", None)
29
+ self.__doc__ = getattr(function, "__doc__", None)
30
+ self.options = _options_of(function, self.collection)
31
+
32
+ def __set_name__(self, owner, name):
33
+ self.name = name
34
+
35
+ def __get__(self, instance, owner=None):
36
+ return self.method.__get__(instance, owner)
37
+
38
+ @property
39
+ def description(self):
40
+ """The docstring's first paragraph, on one line."""
41
+ return first_paragraph(self.__doc__)
42
+
43
+
44
+ def first_paragraph(doc):
45
+ """A docstring's first paragraph, on one line: a script's or a figure's
46
+ description."""
47
+ text = inspect.cleandoc(doc or "")
48
+ return " ".join(text.split("\n\n")[0].split())
49
+
50
+
51
+ def script(method):
52
+ """Mark a method of a model as a script.
53
+
54
+ ``samplekit run NAME`` runs it, and ``r`` in the workbench: a method acts
55
+ on one sample, each selected in turn; placed above ``@classmethod``, it
56
+ receives the selection. Its keyword parameters are the command's options,
57
+ ``--set offset=0.002``, read as their annotation or their default says;
58
+ its docstring is its description. What it changes in the samples is
59
+ shown, and written once the change is accepted; what it returns is shown.
60
+
61
+ Args:
62
+ method: The method.
63
+
64
+ Returns:
65
+ The method, marked.
66
+
67
+ Raises:
68
+ TypeError: The method is a static method, or takes ``*args`` or
69
+ ``**kwargs``.
70
+
71
+ Example:
72
+ >>> class Specimen(sk.Sample):
73
+ ... @sk.script
74
+ ... def classify(self, limit: float = 20.0):
75
+ ... "Class the specimen's ductility by its elongation at break."
76
+ ... self.ductility = "high" if self.elongation.value >= limit else "low"
77
+ """
78
+ return Script(method)
79
+
80
+
81
+ def scripts_of(cls):
82
+ """The scripts a model declares, by name, a subclass's over its base's: a
83
+ subclass that redefines the name as something else takes the script away."""
84
+ found = {}
85
+ for klass in reversed(cls.__mro__):
86
+ for name, value in vars(klass).items():
87
+ if isinstance(value, Script):
88
+ found[name] = value
89
+ elif isinstance(value, classmethod) and isinstance(value.__func__, Script):
90
+ raise TypeError(
91
+ f"{klass.__name__}.{name}: @sk.script goes above @classmethod, "
92
+ "not beneath it"
93
+ )
94
+ elif name in found:
95
+ del found[name]
96
+ return found
97
+
98
+
99
+ def described(script):
100
+ """What the model's description says of a script: its name, what it acts
101
+ on, its description and its options."""
102
+ return {
103
+ "name": script.name,
104
+ "acts": "collection" if script.collection else "sample",
105
+ "description": script.description,
106
+ "options": [
107
+ {"name": name, "type": kind, "default": default}
108
+ for name, kind, default, _ in script.options
109
+ ],
110
+ }
111
+
112
+
113
+ def _options_of(function, collection):
114
+ """Each option: its name, its type's name, its default as text or None
115
+ where it is required, and the default itself."""
116
+ parameters = list(inspect.signature(function).parameters.values())
117
+ # `self`, or `cls` and the selection.
118
+ taken = 2 if collection else 1
119
+ if len(parameters) < taken:
120
+ raise TypeError(
121
+ f"{function.__name__}: a script on the selection takes it after cls, "
122
+ f"def {function.__name__}(cls, samples)"
123
+ )
124
+ options = []
125
+ for parameter in parameters[taken:]:
126
+ if parameter.kind in (parameter.VAR_POSITIONAL, parameter.VAR_KEYWORD):
127
+ raise TypeError(
128
+ f"{function.__name__}: a script's options are named parameters, and "
129
+ f"*{parameter.name} names none"
130
+ )
131
+ if parameter.kind == parameter.POSITIONAL_ONLY:
132
+ raise TypeError(
133
+ f"{function.__name__}: '{parameter.name}' is positional only, and an "
134
+ "option is given by its name"
135
+ )
136
+ missing = parameter.default is parameter.empty
137
+ options.append((
138
+ parameter.name,
139
+ _type_name(parameter),
140
+ None if missing else _as_text(parameter.default),
141
+ parameter.default,
142
+ ))
143
+ return options
144
+
145
+
146
+ def _type_name(parameter):
147
+ annotation = parameter.annotation
148
+ if isinstance(annotation, str) and annotation in TYPES:
149
+ return annotation
150
+ for name, kind in TYPES.items():
151
+ if annotation is kind:
152
+ return name
153
+ default = parameter.default
154
+ if default is not parameter.empty and default is not None:
155
+ for name in ("bool", "int", "float", "str"):
156
+ if type(default) is TYPES[name]:
157
+ return name
158
+ return "str"
159
+
160
+
161
+ def _as_text(value):
162
+ if value is None:
163
+ return "None"
164
+ if isinstance(value, bool):
165
+ return "true" if value else "false"
166
+ return str(value)
167
+
168
+
169
+ def arguments(script, given):
170
+ """The keyword arguments `given` — each option's text, by name — read as
171
+ the signature types them. A name the script does not take, a text its
172
+ type refuses, or a required option not given is a ValueError naming it."""
173
+ known = {name: (kind, default) for name, kind, default, _ in script.options}
174
+ unknown = [name for name in given if name not in known]
175
+ if unknown:
176
+ return _refused(
177
+ f"'{script.name}' takes no option '{unknown[0]}'",
178
+ script,
179
+ )
180
+ missing = [name for name, (_, default) in known.items()
181
+ if default is None and name not in given]
182
+ if missing:
183
+ return _refused(
184
+ f"'{script.name}' needs {', '.join(missing)}: --set {missing[0]}=VALUE",
185
+ script,
186
+ )
187
+ read = {}
188
+ for name, text in given.items():
189
+ kind = known[name][0]
190
+ if kind == "bool":
191
+ lowered = text.strip().lower()
192
+ if lowered not in TRUE + FALSE:
193
+ raise ValueError(f"--set {name}={text}: a yes or no, true or false")
194
+ read[name] = lowered in TRUE
195
+ elif kind in ("int", "float"):
196
+ try:
197
+ read[name] = TYPES[kind](text.strip())
198
+ except ValueError:
199
+ raise ValueError(
200
+ f"--set {name}={text}: {'an integer' if kind == 'int' else 'a number'}"
201
+ ) from None
202
+ else:
203
+ read[name] = text
204
+ return read
205
+
206
+
207
+ def _refused(message, script):
208
+ options = ", ".join(
209
+ name if default is None else f"{name}={default}"
210
+ for name, _, default, _ in script.options
211
+ )
212
+ raise ValueError(f"{message} — its options: {options or 'none'}")