transcript.md 0.1.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.
- transcript/__init__.py +35 -0
- transcript/_rule/__init__.py +0 -0
- transcript/_rule/archive.py +128 -0
- transcript/_rule/conda.py +52 -0
- transcript/_rule/container.py +290 -0
- transcript/_rule/core.py +524 -0
- transcript/_rule/lambdas.py +120 -0
- transcript/_rule/registry.py +54 -0
- transcript/_rule/serialize.py +26 -0
- transcript/_rule/snakefile.py +81 -0
- transcript/_rule/wildcards.py +110 -0
- transcript/cli.py +363 -0
- transcript/document.py +56 -0
- transcript/execute.py +240 -0
- transcript/html/__init__.py +17 -0
- transcript/html/_assets/.frontend.sha256 +1 -0
- transcript/html/_assets/__init__.py +21 -0
- transcript/html/_assets/style.min.css +1 -0
- transcript/html/_assets/transcript.min.js +21 -0
- transcript/html/_island.py +72 -0
- transcript/html/_navigate.py +198 -0
- transcript/html/_output.py +100 -0
- transcript/html/_resources.py +171 -0
- transcript/html/_review.py +34 -0
- transcript/html/markup.py +26 -0
- transcript/html/page.py +107 -0
- transcript/output.py +308 -0
- transcript/parse.py +256 -0
- transcript/renderers/__init__.py +126 -0
- transcript/renderers/bitmap.py +166 -0
- transcript/renderers/compose.py +174 -0
- transcript/renderers/compose_runtime.js +233 -0
- transcript/renderers/datavzrd.py +321 -0
- transcript/renderers/datavzrd_runtime.js +362 -0
- transcript/renderers/label.py +211 -0
- transcript/renderers/markdown.py +45 -0
- transcript/renderers/table.py +32 -0
- transcript/renderers/vegalite.py +250 -0
- transcript/review/__init__.py +13 -0
- transcript/review/_block.py +167 -0
- transcript/review/_migrate.py +212 -0
- transcript/review/_records.py +238 -0
- transcript/review/_span.py +287 -0
- transcript/review/load.py +64 -0
- transcript/tmd.py +159 -0
- transcript_md-0.1.0.dist-info/METADATA +17 -0
- transcript_md-0.1.0.dist-info/RECORD +49 -0
- transcript_md-0.1.0.dist-info/WHEEL +4 -0
- transcript_md-0.1.0.dist-info/entry_points.txt +2 -0
transcript/output.py
ADDED
|
@@ -0,0 +1,308 @@
|
|
|
1
|
+
"""Snapshot explicitly selected rich outputs into portable record blocks."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
from collections.abc import Iterable, Sequence
|
|
7
|
+
from logging import warning
|
|
8
|
+
from typing import TYPE_CHECKING, NamedTuple, Protocol, runtime_checkable
|
|
9
|
+
|
|
10
|
+
from .renderers import get
|
|
11
|
+
|
|
12
|
+
if TYPE_CHECKING:
|
|
13
|
+
from .parse import Slot
|
|
14
|
+
|
|
15
|
+
_FENCE = re.compile(
|
|
16
|
+
r"(?P<fence>[ \t]*```(`*))transcript-output"
|
|
17
|
+
r"[ \t]+(?P<renderer>\w+)"
|
|
18
|
+
r"((?P<op>==|>=|<=|>|<|=)(?P<version>\d+(?:\.\d+)*))?"
|
|
19
|
+
r"[ \t]*\r?\n?$"
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def fence(renderer: Renderer, data: str):
|
|
24
|
+
"""Wrap serialized renderer *data* in a ``transcript-output`` fence."""
|
|
25
|
+
header = renderer.name
|
|
26
|
+
version = getattr(renderer, "version", None)
|
|
27
|
+
if version is not None:
|
|
28
|
+
header += "=" + ".".join(str(part) for part in version)
|
|
29
|
+
body = data.rstrip("\n")
|
|
30
|
+
marker = "```"
|
|
31
|
+
while marker in body:
|
|
32
|
+
marker += "`"
|
|
33
|
+
return f"{marker}transcript-output {header}\n{body}\n{marker}\n"
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@runtime_checkable
|
|
37
|
+
class Renderer(Protocol):
|
|
38
|
+
"""Adapter that serializes, validates, and renders one kind of output.
|
|
39
|
+
|
|
40
|
+
An instance wraps a Python object
|
|
41
|
+
- ``serialize`` converts it to a reloadable string that
|
|
42
|
+
can be reladed by corresponding method ``to_html``
|
|
43
|
+
- ``to_tmd`` add fence arround the serialized string for storage in a report
|
|
44
|
+
- ``to_html`` turns the reloadable string to HTML,
|
|
45
|
+
also extra files for the report.
|
|
46
|
+
- ``STYLE`` and ``runtime`` contribute browser assets only when the renderer
|
|
47
|
+
occurs in a document; ``sources`` adds CSP sources required by its runtime.
|
|
48
|
+
"""
|
|
49
|
+
|
|
50
|
+
name: str
|
|
51
|
+
version: tuple[int, ...] | None = None
|
|
52
|
+
STYLE = ""
|
|
53
|
+
"""CSS needed by this renderer in exported HTML."""
|
|
54
|
+
|
|
55
|
+
def __init__(self):
|
|
56
|
+
"""Wrap the Python object this renderer serializes."""
|
|
57
|
+
...
|
|
58
|
+
|
|
59
|
+
def serialize(self) -> str:
|
|
60
|
+
"""Return the renderer's data, ready for the output fence."""
|
|
61
|
+
...
|
|
62
|
+
|
|
63
|
+
def to_tmd(self):
|
|
64
|
+
"""Return the archived ``transcript-output`` representation."""
|
|
65
|
+
return fence(self, self.serialize())
|
|
66
|
+
|
|
67
|
+
def __repr__(self):
|
|
68
|
+
return self.to_tmd().removesuffix("\n")
|
|
69
|
+
|
|
70
|
+
@classmethod
|
|
71
|
+
def _htmlout(
|
|
72
|
+
cls,
|
|
73
|
+
text: str,
|
|
74
|
+
files: dict[str, tuple[str, bytes]] | None = None,
|
|
75
|
+
children=(),
|
|
76
|
+
*,
|
|
77
|
+
boxed=True,
|
|
78
|
+
origins=(),
|
|
79
|
+
):
|
|
80
|
+
"""Quickly return a ``Rendered`` for the given HTML and report files."""
|
|
81
|
+
return Rendered(text, files or {}, children, boxed, origins)
|
|
82
|
+
|
|
83
|
+
@classmethod
|
|
84
|
+
def to_html(cls, slot: Slot) -> Rendered:
|
|
85
|
+
"""Validate stored *slot* and return a rendered output tree."""
|
|
86
|
+
...
|
|
87
|
+
|
|
88
|
+
@classmethod
|
|
89
|
+
def render_node(cls, output: RecordedOutput, child_blocks: Iterable[str]):
|
|
90
|
+
"""Render one output node after its child reports have been rendered.
|
|
91
|
+
This method is called recursively from ``RecordedOutput.to_report``
|
|
92
|
+
to produce the final HTML.
|
|
93
|
+
"""
|
|
94
|
+
text = output.rendered.text
|
|
95
|
+
for block in child_blocks:
|
|
96
|
+
text += "\n" + block
|
|
97
|
+
return text
|
|
98
|
+
|
|
99
|
+
runtime = None
|
|
100
|
+
"""Browser script serving the embedded report"""
|
|
101
|
+
|
|
102
|
+
sources = []
|
|
103
|
+
"""Extra Content-Security-Policy sources for this renderer"""
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
class Report:
|
|
107
|
+
"""A report to embed in the HTML output.
|
|
108
|
+
|
|
109
|
+
The report is identified by its *renderer* name and a unique *id*.
|
|
110
|
+
The *files* dictionary maps file names to ``(mime, data)`` pairs.
|
|
111
|
+
"""
|
|
112
|
+
|
|
113
|
+
def __init__(self, chunk: RecordedOutput, id: str, span: tuple[int, int]):
|
|
114
|
+
self.chunk = chunk
|
|
115
|
+
self.id = id
|
|
116
|
+
self.span = span
|
|
117
|
+
if self.files and not chunk.renderer.runtime:
|
|
118
|
+
raise RuntimeError(
|
|
119
|
+
f"Renderer {self.name!r} has report files but no offline HTML runtime"
|
|
120
|
+
)
|
|
121
|
+
|
|
122
|
+
@property
|
|
123
|
+
def name(self):
|
|
124
|
+
return self.chunk.renderer.name
|
|
125
|
+
|
|
126
|
+
@property
|
|
127
|
+
def files(self):
|
|
128
|
+
return self.chunk.rendered.files
|
|
129
|
+
|
|
130
|
+
@property
|
|
131
|
+
def boxed(self):
|
|
132
|
+
return self.chunk.rendered.boxed
|
|
133
|
+
|
|
134
|
+
@property
|
|
135
|
+
def block(self):
|
|
136
|
+
start, end = self.span
|
|
137
|
+
return (
|
|
138
|
+
'<div class="transcript-report"'
|
|
139
|
+
f' data-tmd-report="{self.id}"'
|
|
140
|
+
f' data-tmd-renderer="{self.name}"'
|
|
141
|
+
f' data-tmd-span="{start},{end}">'
|
|
142
|
+
f"{self.chunk.rendered.text}</div>"
|
|
143
|
+
)
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
class Rendered(NamedTuple):
|
|
147
|
+
"""A renderer's output, before the archive gives it a position."""
|
|
148
|
+
|
|
149
|
+
text: str
|
|
150
|
+
"""Rendered HTML, with optional ``{{i}}`` slots for ``children[i]``."""
|
|
151
|
+
files: dict[str, tuple[str, bytes]]
|
|
152
|
+
"""Report-relative file names mapped to their MIME type and byte content."""
|
|
153
|
+
children: Sequence[RecordedOutput] = ()
|
|
154
|
+
"""Nested outputs substituted into the corresponding slots in ``text``."""
|
|
155
|
+
boxed: bool = True
|
|
156
|
+
"""Initial state of the statement code and its surrounding output box."""
|
|
157
|
+
origins: tuple[str, ...] = ()
|
|
158
|
+
"""Online image origins this output can render, for the page's CSP."""
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
class RecordedOutput(NamedTuple):
|
|
162
|
+
"""A rendered output at one archive occurrence, with its body range."""
|
|
163
|
+
|
|
164
|
+
renderer: type[Renderer]
|
|
165
|
+
"""Renderer class that owns this output and contributes its browser assets."""
|
|
166
|
+
rendered: Rendered
|
|
167
|
+
span: tuple[int, int]
|
|
168
|
+
"""This output's body range relative to its parent."""
|
|
169
|
+
|
|
170
|
+
@classmethod
|
|
171
|
+
def validate(
|
|
172
|
+
cls,
|
|
173
|
+
renderer_name: str,
|
|
174
|
+
body: Slot,
|
|
175
|
+
op: str | None = None,
|
|
176
|
+
version: str | None = None,
|
|
177
|
+
):
|
|
178
|
+
"""Render the stored *body* for the named renderer and version.
|
|
179
|
+
|
|
180
|
+
Return ``((renderer, rendered), None)`` on success
|
|
181
|
+
or ``(None, reason)`` for an unusable stored body.
|
|
182
|
+
"""
|
|
183
|
+
if not isinstance(renderer_name, str) or not renderer_name:
|
|
184
|
+
return None, f"requires a renderer name, got {renderer_name!r}"
|
|
185
|
+
renderer = get(renderer_name)
|
|
186
|
+
if renderer is None:
|
|
187
|
+
return None, f"unknown renderer: {renderer_name}"
|
|
188
|
+
current = getattr(renderer, "version", None)
|
|
189
|
+
if current is not None and version is not None:
|
|
190
|
+
declared = _parse_version(version)
|
|
191
|
+
if not _version_ok(op, declared, current):
|
|
192
|
+
supported = ".".join(str(part) for part in current)
|
|
193
|
+
return None, (
|
|
194
|
+
f"unsupported version: {version} for renderer "
|
|
195
|
+
f"{renderer.name} (supported: {op}{supported})"
|
|
196
|
+
)
|
|
197
|
+
try:
|
|
198
|
+
rendered = renderer.to_html(body)
|
|
199
|
+
except Exception as error:
|
|
200
|
+
return None, f"renderer {renderer.name} failed to render: {error}"
|
|
201
|
+
if not isinstance(rendered, Rendered):
|
|
202
|
+
return None, f"renderer {renderer.name} did not return Rendered"
|
|
203
|
+
return (renderer, rendered), None
|
|
204
|
+
|
|
205
|
+
def __repr__(self):
|
|
206
|
+
return self.rendered.text.removesuffix("\n")
|
|
207
|
+
|
|
208
|
+
__str__ = __repr__
|
|
209
|
+
|
|
210
|
+
def to_report(self, ireport: str, reports: list[Report], shift: int):
|
|
211
|
+
"""Render this output, substituting nested report blocks for child tokens.
|
|
212
|
+
|
|
213
|
+
*shift* is the absolute archive start of this output's parent,
|
|
214
|
+
each child's range is relative to this output and is shifted by ``span[0]``.
|
|
215
|
+
"""
|
|
216
|
+
span = shift + self.span[0], shift + self.span[1]
|
|
217
|
+
child_blocks = [
|
|
218
|
+
child.to_report(f"{ireport}-{i}", reports, span[0]).block
|
|
219
|
+
for i, child in enumerate(self.rendered.children)
|
|
220
|
+
]
|
|
221
|
+
html = self.renderer.render_node(self, child_blocks)
|
|
222
|
+
rendered = self.rendered._replace(text=html, children=())
|
|
223
|
+
report = Report(self._replace(rendered=rendered), ireport, span)
|
|
224
|
+
reports.append(report)
|
|
225
|
+
return report
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def _parse_version(value: str):
|
|
229
|
+
return tuple(int(part) for part in value.split("."))
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def _version_ok(op, declared, current):
|
|
233
|
+
"""Whether the installed *current* version satisfies the declared constraint."""
|
|
234
|
+
if op is None:
|
|
235
|
+
return True
|
|
236
|
+
if op in ("=", "=="):
|
|
237
|
+
return current == declared
|
|
238
|
+
if op == ">":
|
|
239
|
+
return current > declared
|
|
240
|
+
if op == ">=":
|
|
241
|
+
return current >= declared
|
|
242
|
+
if op == "<":
|
|
243
|
+
return current < declared
|
|
244
|
+
if op == "<=":
|
|
245
|
+
return current <= declared
|
|
246
|
+
return False
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def split_output(slot: Slot):
|
|
250
|
+
"""Split output, retaining each recognized block's archive occurrence."""
|
|
251
|
+
text = slot.raw
|
|
252
|
+
lines = text.splitlines(keepends=True)
|
|
253
|
+
starts: list[int] = []
|
|
254
|
+
cursor = 0
|
|
255
|
+
for line in lines:
|
|
256
|
+
starts.append(cursor)
|
|
257
|
+
cursor += len(line)
|
|
258
|
+
plain_start = index = 0
|
|
259
|
+
while index < len(lines):
|
|
260
|
+
header = _FENCE.fullmatch(lines[index])
|
|
261
|
+
if not header:
|
|
262
|
+
index += 1
|
|
263
|
+
continue
|
|
264
|
+
close_fence = re.compile(r"^" + header.group("fence") + r"[ \t]*(?:\r?\n)?$")
|
|
265
|
+
for end in range(index + 1, len(lines)):
|
|
266
|
+
if close_fence.fullmatch(lines[end]):
|
|
267
|
+
break
|
|
268
|
+
else:
|
|
269
|
+
warning(f"Incomplete transcript-output block: {lines[index].rstrip()}")
|
|
270
|
+
yield slot.dedent(lines[plain_start:])
|
|
271
|
+
return
|
|
272
|
+
if plain_start < index:
|
|
273
|
+
yield slot.dedent(lines[plain_start:index])
|
|
274
|
+
body_start = (
|
|
275
|
+
starts[index + 1]
|
|
276
|
+
if index + 1 < len(lines)
|
|
277
|
+
else starts[index] + len(lines[index])
|
|
278
|
+
)
|
|
279
|
+
body_end = starts[end]
|
|
280
|
+
while body_end > body_start and text[body_end - 1] in "\r\n":
|
|
281
|
+
body_end -= 1
|
|
282
|
+
body = slot.slice(body_start, body_end)
|
|
283
|
+
output, reason = RecordedOutput.validate(
|
|
284
|
+
header.group("renderer"), body, header.group("op"), header.group("version")
|
|
285
|
+
)
|
|
286
|
+
if output is None:
|
|
287
|
+
warning(f"Invalid transcript-output block: {reason}")
|
|
288
|
+
yield slot.dedent(lines[index : end + 1])
|
|
289
|
+
else:
|
|
290
|
+
yield RecordedOutput(*output, (body_start, body_end))
|
|
291
|
+
plain_start = index = end + 1
|
|
292
|
+
if plain_start < len(lines):
|
|
293
|
+
yield slot.dedent(lines[plain_start:])
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
def dataframe_csv(frame):
|
|
297
|
+
"""Export pandas or polars through their public CSV methods, without imports."""
|
|
298
|
+
if callable(getattr(frame, "to_csv", None)) and hasattr(frame, "index"):
|
|
299
|
+
index = frame.index
|
|
300
|
+
include_index = index.name is not None or type(index).__name__ != "RangeIndex"
|
|
301
|
+
content = frame.to_csv(index=include_index, lineterminator="\n")
|
|
302
|
+
elif callable(getattr(frame, "write_csv", None)):
|
|
303
|
+
content = frame.write_csv(line_terminator="\n")
|
|
304
|
+
else:
|
|
305
|
+
raise TypeError("expects a pandas or polars DataFrame")
|
|
306
|
+
if not isinstance(content, str):
|
|
307
|
+
raise TypeError("DataFrame CSV export must return a string")
|
|
308
|
+
return content
|
transcript/parse.py
ADDED
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
"""Locate report blocks, their markdown, code statements, and output slots."""
|
|
2
|
+
|
|
3
|
+
import ast
|
|
4
|
+
import io
|
|
5
|
+
import re
|
|
6
|
+
import tokenize
|
|
7
|
+
from collections.abc import Callable
|
|
8
|
+
from typing import NamedTuple, TypeGuard
|
|
9
|
+
|
|
10
|
+
REPORT_MARKER = "transcript.md"
|
|
11
|
+
REPORT_MARKER_COMMENT = f"# {REPORT_MARKER}"
|
|
12
|
+
|
|
13
|
+
_STRING_PREFIXES = "rRbBuUfF"
|
|
14
|
+
_ESCAPE = re.compile(r"\\([\\\"'rt]|x[0-9a-fA-F]{2})")
|
|
15
|
+
_ESCAPE_TEXT = {"\\": "\\", '"': '"', "'": "'", "r": "\r", "t": "\t"}
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _decode_escapes(raw: str):
|
|
19
|
+
"""Reverse the shared escape set (``\\``, quotes, ``\\r``, ``\\t``, ``\\xNN``).
|
|
20
|
+
LF and unknown escapes stays literal.
|
|
21
|
+
|
|
22
|
+
Mirrors the browser runtime's ``decodeEscapes`` and ``tmd.escape_slot``,
|
|
23
|
+
the set that appears in machine-generated slot literals.
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
if "\\" not in raw:
|
|
27
|
+
return raw
|
|
28
|
+
|
|
29
|
+
def replace(match: re.Match):
|
|
30
|
+
escape = match.group(1)
|
|
31
|
+
if escape[0] == "x":
|
|
32
|
+
return chr(int(escape[1:], 16))
|
|
33
|
+
return _ESCAPE_TEXT[escape]
|
|
34
|
+
|
|
35
|
+
return _ESCAPE.sub(replace, raw)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class Slot(NamedTuple):
|
|
39
|
+
"""A recorded output body and its coordinates in the source."""
|
|
40
|
+
|
|
41
|
+
raw: str
|
|
42
|
+
"""the text inside the string delimiters"""
|
|
43
|
+
start: int
|
|
44
|
+
"""absolute offset of .raw in the source"""
|
|
45
|
+
indent: str
|
|
46
|
+
literal: tuple[int, int]
|
|
47
|
+
"""the whole string-literal span, to replace during py2tmd"""
|
|
48
|
+
|
|
49
|
+
@property
|
|
50
|
+
def end(self):
|
|
51
|
+
return self.start + len(self.raw)
|
|
52
|
+
|
|
53
|
+
@property
|
|
54
|
+
def shift(self):
|
|
55
|
+
"""How far the literal delimiters extend beyond the body on each side."""
|
|
56
|
+
return self.literal[0] - self.start, self.literal[1] - self.end
|
|
57
|
+
|
|
58
|
+
def dedent(self, text: list[str]):
|
|
59
|
+
return "".join(_decode_escapes(line.removeprefix(self.indent)) for line in text)
|
|
60
|
+
|
|
61
|
+
@property
|
|
62
|
+
def value(self):
|
|
63
|
+
"""The decoded text with its archive indentation removed."""
|
|
64
|
+
return self.dedent(self.raw.splitlines(keepends=True)).removeprefix("\n")
|
|
65
|
+
|
|
66
|
+
def slice(self, start, end):
|
|
67
|
+
return self.__class__(self.raw[start:end], 0, self.indent, (0, end - start))
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class Statement(NamedTuple):
|
|
71
|
+
node: ast.stmt
|
|
72
|
+
start: int
|
|
73
|
+
end: int
|
|
74
|
+
slot: Slot | None
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
class ReportBlock(NamedTuple):
|
|
78
|
+
node: ast.If | ast.With
|
|
79
|
+
body_start: int
|
|
80
|
+
body_end: int
|
|
81
|
+
markdown: tuple[int, int] | None
|
|
82
|
+
statements: list[Statement]
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def line_offsets(source: str):
|
|
86
|
+
"""Return a ``(lineno, column) -> character offset`` mapper for *source*."""
|
|
87
|
+
|
|
88
|
+
lines = source.splitlines(keepends=True)
|
|
89
|
+
starts = [0]
|
|
90
|
+
for line in lines:
|
|
91
|
+
starts.append(starts[-1] + len(line))
|
|
92
|
+
|
|
93
|
+
def position(lineno: int, column: int):
|
|
94
|
+
# AST columns count UTF-8 bytes; source slicing counts characters.
|
|
95
|
+
return starts[lineno - 1] + len(lines[lineno - 1].encode()[:column].decode())
|
|
96
|
+
|
|
97
|
+
return position
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _span_start(node: ast.stmt | ast.expr, position: Callable[[int, int], int]):
|
|
101
|
+
return position(node.lineno, node.col_offset)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _span_end(node: ast.stmt | ast.expr, position: Callable[[int, int], int]):
|
|
105
|
+
assert node.end_lineno is not None and node.end_col_offset is not None
|
|
106
|
+
return position(node.end_lineno, node.end_col_offset)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def span(node: ast.stmt | ast.expr, position: Callable[[int, int], int]):
|
|
110
|
+
return _span_start(node, position), _span_end(node, position)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _is_report_if(node: ast.stmt) -> TypeGuard[ast.If]:
|
|
114
|
+
return (
|
|
115
|
+
isinstance(node, ast.If)
|
|
116
|
+
and isinstance(node.test, ast.Constant)
|
|
117
|
+
and node.test.value == REPORT_MARKER
|
|
118
|
+
)
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def with_marker_text(source: str, node: ast.With, position: Callable[[int, int], int]):
|
|
122
|
+
"""Return the ``(start, end, colon, comment)`` after a ``with`` header.
|
|
123
|
+
|
|
124
|
+
*comment* is the stripped text between the statement colon and the end of
|
|
125
|
+
its physical line, empty when there is none.
|
|
126
|
+
"""
|
|
127
|
+
start = _span_start(node, position)
|
|
128
|
+
end = _span_start(node.body[0], position)
|
|
129
|
+
tokens = list(tokenize.generate_tokens(io.StringIO(source[start:end]).readline))
|
|
130
|
+
colon = None
|
|
131
|
+
for token in tokens:
|
|
132
|
+
# The header may contain colons (dict, slice, lambda); the statement
|
|
133
|
+
# colon is the last one before the body.
|
|
134
|
+
if token.type == tokenize.OP and token.string == ":":
|
|
135
|
+
colon = token
|
|
136
|
+
if colon is None:
|
|
137
|
+
raise ValueError(f"line {node.lineno}: could not find colon in with statement")
|
|
138
|
+
after_colon = colon.line[colon.end[1] :].lstrip()
|
|
139
|
+
return start, end, colon, after_colon.strip()
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def with_report_marker(
|
|
143
|
+
source: str, node: ast.With, position: Callable[[int, int], int]
|
|
144
|
+
):
|
|
145
|
+
start, end, colon, comment = with_marker_text(source, node, position)
|
|
146
|
+
return start, end, colon, comment == REPORT_MARKER_COMMENT
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _string_expr(node: ast.stmt):
|
|
150
|
+
if (
|
|
151
|
+
isinstance(node, ast.Expr)
|
|
152
|
+
and isinstance(node.value, ast.Constant)
|
|
153
|
+
and isinstance(node.value.value, str)
|
|
154
|
+
):
|
|
155
|
+
return node.value
|
|
156
|
+
return None
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def _string_interior(source: str, span: tuple[int, int]):
|
|
160
|
+
"""Return the span of a string literal's content, between its delimiters."""
|
|
161
|
+
start, end = span
|
|
162
|
+
index = start
|
|
163
|
+
while index < end and source[index] in _STRING_PREFIXES:
|
|
164
|
+
index += 1
|
|
165
|
+
quote = source[index]
|
|
166
|
+
run = 0
|
|
167
|
+
while index + run < end and source[index + run] == quote:
|
|
168
|
+
run += 1
|
|
169
|
+
width = 3 if run >= 3 else 1
|
|
170
|
+
return index + width, end - width
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
class Region(NamedTuple):
|
|
174
|
+
"""A module-level report entry (``if "transcript.md":`` or a top-level ``with``)."""
|
|
175
|
+
|
|
176
|
+
node: ast.If | ast.With
|
|
177
|
+
marker: bool # the comment right after the ``with`` colon is ``# transcript.md``
|
|
178
|
+
|
|
179
|
+
@property
|
|
180
|
+
def kind(self):
|
|
181
|
+
return "if" if isinstance(self.node, ast.If) else "with"
|
|
182
|
+
|
|
183
|
+
def parse_block(self, source: str, position: Callable[[int, int], int]):
|
|
184
|
+
"""Compute a block from its region; called when a report block is reached."""
|
|
185
|
+
node = self.node
|
|
186
|
+
body = node.body
|
|
187
|
+
if not body:
|
|
188
|
+
raise ValueError(f"line {node.lineno}: a report block must have a body")
|
|
189
|
+
if body[0].lineno == node.lineno:
|
|
190
|
+
raise ValueError(
|
|
191
|
+
f"line {node.lineno}: a report block body must start on the next line; "
|
|
192
|
+
"put the body on its own line"
|
|
193
|
+
)
|
|
194
|
+
markdown = None
|
|
195
|
+
index = 0
|
|
196
|
+
first = _string_expr(body[0])
|
|
197
|
+
if first is not None:
|
|
198
|
+
markdown = _string_interior(source, span(first, position))
|
|
199
|
+
index = 1
|
|
200
|
+
statements: list[Statement] = []
|
|
201
|
+
previous_end_line = 0
|
|
202
|
+
while index < len(body):
|
|
203
|
+
statement = body[index]
|
|
204
|
+
if _string_expr(statement) is not None:
|
|
205
|
+
# A docstring that does not follow a code statement has no slot role.
|
|
206
|
+
# warnings.warn(
|
|
207
|
+
# f"line {statement.lineno}: stray record docstring ignored",
|
|
208
|
+
# stacklevel=2,
|
|
209
|
+
# )
|
|
210
|
+
index += 1
|
|
211
|
+
continue
|
|
212
|
+
if statement.lineno <= previous_end_line:
|
|
213
|
+
raise ValueError(
|
|
214
|
+
f"line {statement.lineno}: multiple statements on one line are "
|
|
215
|
+
"not supported in report blocks; put each statement on its own line"
|
|
216
|
+
)
|
|
217
|
+
previous_end_line = statement.end_lineno or 0
|
|
218
|
+
start = _span_start(statement, position)
|
|
219
|
+
line_start = source.rfind("\n", 0, start) + 1
|
|
220
|
+
indent = source[line_start:start]
|
|
221
|
+
slot = None
|
|
222
|
+
if index + 1 < len(body):
|
|
223
|
+
constant = _string_expr(body[index + 1])
|
|
224
|
+
if constant is not None:
|
|
225
|
+
literal = span(constant, position)
|
|
226
|
+
slot_start, slot_end = _string_interior(source, literal)
|
|
227
|
+
if slot_start < slot_end and source[slot_start] == "\n":
|
|
228
|
+
slot_start += 1
|
|
229
|
+
slot = Slot(
|
|
230
|
+
source[slot_start:slot_end], slot_start, indent, literal
|
|
231
|
+
)
|
|
232
|
+
index += 1
|
|
233
|
+
end = _span_end(statement, position)
|
|
234
|
+
statements.append(Statement(statement, start, end, slot))
|
|
235
|
+
index += 1
|
|
236
|
+
body_start = _span_start(body[0], position)
|
|
237
|
+
body_end = _span_end(body[-1], position)
|
|
238
|
+
return ReportBlock(node, body_start, body_end, markdown, statements)
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def locate(source: str, filename: str):
|
|
242
|
+
"""Locate module-level report regions without computing any block.
|
|
243
|
+
|
|
244
|
+
A ``with`` block is a region only when it has a single item; the comment
|
|
245
|
+
after its colon decides whether it is a report block.
|
|
246
|
+
"""
|
|
247
|
+
tree = ast.parse(source, filename=filename)
|
|
248
|
+
position = line_offsets(source)
|
|
249
|
+
regions = {}
|
|
250
|
+
for i, node in enumerate(tree.body):
|
|
251
|
+
if _is_report_if(node):
|
|
252
|
+
regions[i] = Region(node, True)
|
|
253
|
+
elif isinstance(node, ast.With) and len(node.items) == 1:
|
|
254
|
+
marker = with_report_marker(source, node, position)
|
|
255
|
+
regions[i] = Region(node, marker[-1])
|
|
256
|
+
return tree, position, regions
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
"""Registry of ``transcript-output`` renderer classes.
|
|
2
|
+
|
|
3
|
+
The ``Renderer`` protocol and the fence format live in :mod:`transcript.output`;
|
|
4
|
+
this package only maps renderer names to their classes and is imported by the
|
|
5
|
+
individual renderer modules.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import math
|
|
11
|
+
from collections.abc import Mapping
|
|
12
|
+
from datetime import date, datetime
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import TYPE_CHECKING, Any, overload
|
|
15
|
+
|
|
16
|
+
if TYPE_CHECKING:
|
|
17
|
+
from ..output import Renderer
|
|
18
|
+
|
|
19
|
+
RENDERERS: dict[str, type[Renderer]] = {}
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def register[R: Renderer](renderer: type[R]):
|
|
23
|
+
if not renderer.name:
|
|
24
|
+
renderer.name = renderer.__name__.lower()
|
|
25
|
+
if renderer.name in RENDERERS:
|
|
26
|
+
raise ValueError(f"duplicate renderer: {renderer.name}")
|
|
27
|
+
RENDERERS[renderer.name] = renderer
|
|
28
|
+
return renderer
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def get(name: str):
|
|
32
|
+
"""Return the registered renderer class, or ``None`` for an unknown name."""
|
|
33
|
+
return RENDERERS.get(name)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@overload
|
|
37
|
+
def jsonify(value: Mapping[str, Any], *, context: str = ...) -> dict[str, Any]: ...
|
|
38
|
+
@overload
|
|
39
|
+
def jsonify(value: list[Any] | tuple[Any, ...], *, context: str = ...) -> list[Any]: ...
|
|
40
|
+
@overload
|
|
41
|
+
def jsonify(value: Any, *, context: str = ...) -> Any: ...
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def jsonify(value: Any, *, context: str = "JSON") -> Any:
|
|
45
|
+
"""Copy *value* into JSON-compatible data.
|
|
46
|
+
|
|
47
|
+
- ``Mapping`` -> ``dict`` (keys must be strings)
|
|
48
|
+
- ``list``/``tuple`` -> ``list`` (recursively)
|
|
49
|
+
- non-finite ``float`` -> ``None`` (Vega-Lite's missing value)
|
|
50
|
+
- ``date``/``datetime`` -> ISO-8601 string
|
|
51
|
+
- objects with a callable ``.item`` (numpy scalars, ...) are unwrapped
|
|
52
|
+
- everything else raises ``ValueError``
|
|
53
|
+
"""
|
|
54
|
+
if value is None or isinstance(value, (str, bool, int)):
|
|
55
|
+
return value
|
|
56
|
+
|
|
57
|
+
if isinstance(value, float):
|
|
58
|
+
return value if math.isfinite(value) else None
|
|
59
|
+
|
|
60
|
+
if isinstance(value, Mapping):
|
|
61
|
+
if not all(isinstance(key, str) for key in value):
|
|
62
|
+
raise ValueError(f"{context} keys must be strings")
|
|
63
|
+
return {key: jsonify(item, context=context) for key, item in value.items()}
|
|
64
|
+
|
|
65
|
+
if isinstance(value, (list, tuple)):
|
|
66
|
+
return [jsonify(item, context=context) for item in value]
|
|
67
|
+
|
|
68
|
+
if isinstance(value, (datetime, date)):
|
|
69
|
+
return value.isoformat()
|
|
70
|
+
|
|
71
|
+
item = getattr(value, "item", None)
|
|
72
|
+
if callable(item):
|
|
73
|
+
return jsonify(item(), context=context)
|
|
74
|
+
|
|
75
|
+
raise ValueError(f"{context} value is not JSON-compatible: {value!r}")
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
ConfigType = Mapping[str, Any] | str | Path
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def load_spec(spec: ConfigType, *, format=None) -> Mapping[str, Any]:
|
|
82
|
+
"""Return a spec mapping, loading a configfile if needed.
|
|
83
|
+
|
|
84
|
+
``spec`` may already be a mapping (returned unchanged) or a ``str``/``Path``
|
|
85
|
+
pointing at a ``.json`` or YAML file. ``context`` appears in error messages
|
|
86
|
+
(e.g. ``"Datavzrd configuration"``); ``extra`` names the optional
|
|
87
|
+
dependency group advertised when PyYAML is missing (e.g. ``"datavzrd"``).
|
|
88
|
+
"""
|
|
89
|
+
if not isinstance(spec, (str, Path)):
|
|
90
|
+
return spec
|
|
91
|
+
path = Path(spec)
|
|
92
|
+
text = path.read_text(encoding="utf-8")
|
|
93
|
+
if format is None:
|
|
94
|
+
format = path.suffix
|
|
95
|
+
format = format.lower().strip(".")
|
|
96
|
+
if format == "json":
|
|
97
|
+
import json
|
|
98
|
+
|
|
99
|
+
try:
|
|
100
|
+
loaded = json.loads(text)
|
|
101
|
+
except json.JSONDecodeError as error:
|
|
102
|
+
raise ValueError(f"Broken {format} file: {path}") from error
|
|
103
|
+
elif format in {"yaml", "yml"}:
|
|
104
|
+
import yaml
|
|
105
|
+
|
|
106
|
+
try:
|
|
107
|
+
loaded = yaml.safe_load(text)
|
|
108
|
+
except yaml.YAMLError as error:
|
|
109
|
+
raise ValueError(f"Broken {format} file: {path}") from error
|
|
110
|
+
elif format == "toml":
|
|
111
|
+
import tomli
|
|
112
|
+
|
|
113
|
+
try:
|
|
114
|
+
loaded = tomli.loads(text)
|
|
115
|
+
except tomli.TOMLDecodeError as error:
|
|
116
|
+
raise ValueError(f"Broken {format} file: {path}") from error
|
|
117
|
+
else: # assume "ini":
|
|
118
|
+
import configparser
|
|
119
|
+
|
|
120
|
+
parser = configparser.ConfigParser()
|
|
121
|
+
try:
|
|
122
|
+
parser.read_string(text)
|
|
123
|
+
except configparser.Error as error:
|
|
124
|
+
raise ValueError(f"Invalid {format} file: {path}") from error
|
|
125
|
+
loaded = {section: dict(parser[section]) for section in parser.sections()}
|
|
126
|
+
return loaded
|