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
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
"""Renderer that wraps another output with a stable id and caption."""
|
|
2
|
+
|
|
3
|
+
import ast
|
|
4
|
+
import re
|
|
5
|
+
from collections.abc import Iterable
|
|
6
|
+
from html import escape
|
|
7
|
+
from logging import warning
|
|
8
|
+
|
|
9
|
+
from ..output import RecordedOutput, Renderer, split_output
|
|
10
|
+
from ..parse import Slot
|
|
11
|
+
from . import register
|
|
12
|
+
|
|
13
|
+
_ID = re.compile(r"[A-Za-z][A-Za-z0-9_.:-]*\Z")
|
|
14
|
+
|
|
15
|
+
_STYLE = """
|
|
16
|
+
/* labelled outputs */
|
|
17
|
+
.transcript-label { margin: .5rem 0; }
|
|
18
|
+
.transcript-label > figcaption { margin-top: .25rem; font-size: .9em; color: #888; }
|
|
19
|
+
.transcript-label-repeat-note { margin-left: .5em; white-space: nowrap; }
|
|
20
|
+
.transcript-label-repeat-note code { color: inherit; }
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@register
|
|
25
|
+
class CodeRenderer(Renderer):
|
|
26
|
+
"""Archive a Python value using the same representation as a bare expression."""
|
|
27
|
+
|
|
28
|
+
name = "code"
|
|
29
|
+
version = (1,)
|
|
30
|
+
|
|
31
|
+
def __init__(self, value):
|
|
32
|
+
self.text = repr(value)
|
|
33
|
+
|
|
34
|
+
def serialize(self):
|
|
35
|
+
return self.text
|
|
36
|
+
|
|
37
|
+
@classmethod
|
|
38
|
+
def to_html(cls, slot):
|
|
39
|
+
return cls._htmlout(
|
|
40
|
+
'<pre class="doc-text"><samp class="doc-out">'
|
|
41
|
+
+ escape(slot.value)
|
|
42
|
+
+ "</samp></pre>",
|
|
43
|
+
{},
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
code = CodeRenderer
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
_cache: dict[str, tuple[str, RecordedOutput, int]] | None = None
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def set_cache(new=None):
|
|
54
|
+
"""Reset the label cache for a new document."""
|
|
55
|
+
global _cache
|
|
56
|
+
old, _cache = _cache, new
|
|
57
|
+
return old
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def get_inner(content_iter: Iterable[str | RecordedOutput]):
|
|
61
|
+
content = list(content_iter)
|
|
62
|
+
if len(content) != 1:
|
|
63
|
+
raise ValueError(
|
|
64
|
+
"labelled output must contain exactly one renderer output after the header"
|
|
65
|
+
)
|
|
66
|
+
(inner,) = content
|
|
67
|
+
if not isinstance(inner, RecordedOutput):
|
|
68
|
+
raise ValueError(
|
|
69
|
+
"labelled output must contain a renderer output after the header"
|
|
70
|
+
)
|
|
71
|
+
return inner
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def get_cached_inner(
|
|
75
|
+
id: str, caption: str, data: str, content_iter: Iterable[str | RecordedOutput]
|
|
76
|
+
):
|
|
77
|
+
assigned_id = id
|
|
78
|
+
i = 0
|
|
79
|
+
found = None
|
|
80
|
+
if _cache is not None:
|
|
81
|
+
while (cached := _cache.get(assigned_id)) is not None:
|
|
82
|
+
if cached[0] == data:
|
|
83
|
+
found = cached
|
|
84
|
+
break
|
|
85
|
+
i += 1
|
|
86
|
+
assigned_id = f"{id}.{i}"
|
|
87
|
+
if found is None:
|
|
88
|
+
inner = get_inner(content_iter)
|
|
89
|
+
if _cache is not None:
|
|
90
|
+
_cache[assigned_id] = (data, inner, 0)
|
|
91
|
+
else:
|
|
92
|
+
inner = found[1]
|
|
93
|
+
if i:
|
|
94
|
+
if found is None:
|
|
95
|
+
warning(f"label {id!r} has different content; using {assigned_id!r}")
|
|
96
|
+
if caption:
|
|
97
|
+
caption += f" (duplicate {i} of label {id})"
|
|
98
|
+
else:
|
|
99
|
+
caption = f"duplicate {i} of label {id}"
|
|
100
|
+
return assigned_id, caption, inner
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
@register
|
|
104
|
+
class Label(Renderer):
|
|
105
|
+
"""Wrap a renderer output with an anchor *id* and an optional *caption*.
|
|
106
|
+
|
|
107
|
+
The wrapped output keeps its own rendering, runtime, and report files;
|
|
108
|
+
the label only adds a document anchor and a caption around it. Numbering
|
|
109
|
+
and cross references are resolved later by the document collector.
|
|
110
|
+
"""
|
|
111
|
+
|
|
112
|
+
name = "label"
|
|
113
|
+
version = (1,)
|
|
114
|
+
STYLE = _STYLE
|
|
115
|
+
|
|
116
|
+
def __init__(self, inner, id: str, caption=""):
|
|
117
|
+
if not isinstance(inner, Renderer):
|
|
118
|
+
inner = CodeRenderer(inner)
|
|
119
|
+
if not isinstance(id, str) or not _ID.match(id):
|
|
120
|
+
raise ValueError(f"label id must be a valid transcript id, got {id!r}")
|
|
121
|
+
if not isinstance(caption, str):
|
|
122
|
+
raise TypeError("label caption must be a string")
|
|
123
|
+
self.inner = inner
|
|
124
|
+
self.id = id
|
|
125
|
+
self.caption = caption
|
|
126
|
+
|
|
127
|
+
def serialize(self):
|
|
128
|
+
return "\n".join([self.id + " " + repr(self.caption), self.inner.to_tmd()])
|
|
129
|
+
|
|
130
|
+
@classmethod
|
|
131
|
+
def from_tmd(cls, slot: Slot):
|
|
132
|
+
"""Parse a label, reusing its cached inner output when possible.
|
|
133
|
+
The decoded body is only used as the cache key.
|
|
134
|
+
"""
|
|
135
|
+
content_iter = split_output(slot)
|
|
136
|
+
try:
|
|
137
|
+
header = next(content_iter)
|
|
138
|
+
except StopIteration:
|
|
139
|
+
header = None
|
|
140
|
+
if not isinstance(header, str):
|
|
141
|
+
raise ValueError("labelled output must contain a string header")
|
|
142
|
+
try:
|
|
143
|
+
id, encoded_caption = header.rstrip("\r\n").split(maxsplit=1)
|
|
144
|
+
caption = ast.literal_eval(encoded_caption)
|
|
145
|
+
except (ValueError, SyntaxError) as error:
|
|
146
|
+
raise ValueError("label caption must be a Python string literal") from error
|
|
147
|
+
if not _ID.fullmatch(id):
|
|
148
|
+
raise ValueError(f"label id must be a valid transcript id, got {id!r}")
|
|
149
|
+
if not isinstance(caption, str):
|
|
150
|
+
raise ValueError("label caption must decode to a string")
|
|
151
|
+
return get_cached_inner(id, caption, slot.value, content_iter)
|
|
152
|
+
|
|
153
|
+
@classmethod
|
|
154
|
+
def to_html(cls, slot):
|
|
155
|
+
"""Render the wrapped output and place it inside a labelled figure."""
|
|
156
|
+
id, caption, inner = cls.from_tmd(slot)
|
|
157
|
+
figure = f'<figure class="transcript-label" data-tmd-label="{id}">' + "{{0}}"
|
|
158
|
+
if caption:
|
|
159
|
+
figure += f"<figcaption>{escape(caption)}</figcaption>"
|
|
160
|
+
figure += "</figure>"
|
|
161
|
+
return cls._htmlout(figure, {}, (inner,), boxed=inner.rendered.boxed)
|
|
162
|
+
|
|
163
|
+
@classmethod
|
|
164
|
+
def _repeat_html(cls, text: str, id: str, occurrence: int):
|
|
165
|
+
"""Return a full repeated occurrence without duplicating its HTML id."""
|
|
166
|
+
opening = f'<figure class="transcript-label" id="{id}">'
|
|
167
|
+
repeated = (
|
|
168
|
+
'<figure class="transcript-label transcript-label-repeat"'
|
|
169
|
+
f' data-tmd-label="{id}"'
|
|
170
|
+
f' data-tmd-label-occurrence="{occurrence}">'
|
|
171
|
+
)
|
|
172
|
+
if not text.startswith(opening):
|
|
173
|
+
raise ValueError(f"label {id!r} has an invalid rendered wrapper")
|
|
174
|
+
text = repeated + text[len(opening) :]
|
|
175
|
+
label_id = escape(id)
|
|
176
|
+
note = (
|
|
177
|
+
'<span class="transcript-label-repeat-note">'
|
|
178
|
+
f'<a href="#{label_id}">↩</a></span>'
|
|
179
|
+
)
|
|
180
|
+
if text.endswith("</figcaption></figure>"): # has label
|
|
181
|
+
return text.replace("</figcaption>", " " + note + "</figcaption>", 1)
|
|
182
|
+
return text.replace("</figure>", f"<figcaption>{note}</figcaption></figure>", 1)
|
|
183
|
+
|
|
184
|
+
@classmethod
|
|
185
|
+
def render_node(cls, output, child_blocks):
|
|
186
|
+
"""Render the label around its child output."""
|
|
187
|
+
block = list(child_blocks)
|
|
188
|
+
if len(block) != 1:
|
|
189
|
+
raise ValueError("labelled output must contain exactly one inner output")
|
|
190
|
+
match = re.match(
|
|
191
|
+
r'<figure class="transcript-label" data-tmd-label="([^"]+)">',
|
|
192
|
+
output.rendered.text,
|
|
193
|
+
)
|
|
194
|
+
if match is None:
|
|
195
|
+
raise ValueError("labelled output has an invalid figure template")
|
|
196
|
+
id = match.group(1)
|
|
197
|
+
opening = match.group(0)
|
|
198
|
+
text = output.rendered.text.replace(
|
|
199
|
+
opening, f'<figure class="transcript-label" id="{id}">', 1
|
|
200
|
+
)
|
|
201
|
+
if _cache is not None:
|
|
202
|
+
cached = _cache.get(id)
|
|
203
|
+
if cached is not None:
|
|
204
|
+
data, inner, count = cached
|
|
205
|
+
_cache[id] = (data, inner, count + 1)
|
|
206
|
+
if count:
|
|
207
|
+
text = cls._repeat_html(text, id, count)
|
|
208
|
+
return text.replace("{{0}}", block[0])
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
label = Label
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
"""Renderer for output that should be interpreted as ordinary Markdown.
|
|
2
|
+
|
|
3
|
+
The Markdown source is archived verbatim;
|
|
4
|
+
the exported page renders it in the browser from the embedded archive,
|
|
5
|
+
so the server keeps no HTML here.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from ..html.markup import markdown_image_origins
|
|
9
|
+
from ..output import Renderer
|
|
10
|
+
from . import register
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class _Report(type(Renderer)):
|
|
14
|
+
def __enter__(cls):
|
|
15
|
+
return cls
|
|
16
|
+
|
|
17
|
+
def __exit__(cls, *exc):
|
|
18
|
+
return False
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@register
|
|
22
|
+
class markdown(Renderer, metaclass=_Report):
|
|
23
|
+
"""Mark a string output for normal Markdown rendering in exported HTML."""
|
|
24
|
+
|
|
25
|
+
name = "markdown"
|
|
26
|
+
version = (1,)
|
|
27
|
+
|
|
28
|
+
def __init__(self, content: str):
|
|
29
|
+
if not isinstance(content, str):
|
|
30
|
+
raise TypeError("Markdown content must be a string")
|
|
31
|
+
self.obj = content
|
|
32
|
+
|
|
33
|
+
def serialize(self):
|
|
34
|
+
"""Return the Markdown source string."""
|
|
35
|
+
return self.obj
|
|
36
|
+
|
|
37
|
+
@classmethod
|
|
38
|
+
def to_html(cls, slot):
|
|
39
|
+
"""Mark the slot for the browser runtime; the server emits no HTML.
|
|
40
|
+
|
|
41
|
+
The online image origins are carried on the output so the page CSP can
|
|
42
|
+
allow them without re-reading the archive.
|
|
43
|
+
"""
|
|
44
|
+
origins = tuple(markdown_image_origins(slot.value))
|
|
45
|
+
return cls._htmlout("", boxed=False, origins=origins)
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
"""Render pandas or polars DataFrames as GitHub-flavored Markdown tables.
|
|
2
|
+
|
|
3
|
+
``table()`` is a thin convenience over the :func:`transcript.markdown` renderer.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
import csv
|
|
7
|
+
from io import StringIO
|
|
8
|
+
|
|
9
|
+
from ..output import dataframe_csv
|
|
10
|
+
from .markdown import markdown
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _escape(text: str):
|
|
14
|
+
"""Escape a value for one Markdown table cell (line breaks become spaces)."""
|
|
15
|
+
return text.replace("\\", "\\\\").replace("|", "\\|").replace("\n", " ")
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def table(frame):
|
|
19
|
+
"""Record a pandas or polars DataFrame as a basic Markdown table."""
|
|
20
|
+
rows = list(csv.reader(StringIO(dataframe_csv(frame))))
|
|
21
|
+
if not rows:
|
|
22
|
+
raise ValueError("table expects a DataFrame with a header row")
|
|
23
|
+
header, *body = rows
|
|
24
|
+
if len(header) > 1 and not header[0]:
|
|
25
|
+
header[0] = "index"
|
|
26
|
+
lines = ["| " + " | ".join(_escape(cell) for cell in header) + " |"]
|
|
27
|
+
lines.append("| " + " | ".join("---" for _ in header) + " |")
|
|
28
|
+
for row in body:
|
|
29
|
+
if len(row) != len(header):
|
|
30
|
+
raise ValueError("table rows must match the number of columns")
|
|
31
|
+
lines.append("| " + " | ".join(_escape(cell) for cell in row) + " |")
|
|
32
|
+
return markdown("\n".join(lines))
|
|
@@ -0,0 +1,250 @@
|
|
|
1
|
+
"""Vega-Lite renderer: snapshot DataFrames as SVG or upgraded charts."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from collections.abc import Mapping
|
|
7
|
+
from typing import TYPE_CHECKING, TypeIs
|
|
8
|
+
|
|
9
|
+
from ..output import Renderer
|
|
10
|
+
from . import ConfigType, jsonify, load_spec, register
|
|
11
|
+
|
|
12
|
+
if TYPE_CHECKING:
|
|
13
|
+
import altair as alt
|
|
14
|
+
|
|
15
|
+
ConfigOrFig = ConfigType | alt.TopLevelMixin
|
|
16
|
+
|
|
17
|
+
_CDN = [
|
|
18
|
+
"https://cdn.jsdelivr.net/npm/vega@6",
|
|
19
|
+
"https://cdn.jsdelivr.net/npm/vega-lite@6.4",
|
|
20
|
+
"https://cdn.jsdelivr.net/npm/vega-embed@6",
|
|
21
|
+
]
|
|
22
|
+
|
|
23
|
+
_DEFAULT_WIDTH = 800
|
|
24
|
+
_DEFAULT_HEIGHT = 450
|
|
25
|
+
|
|
26
|
+
_STYLE = """
|
|
27
|
+
/* static and interactive Vega-Lite charts */
|
|
28
|
+
.transcript-chart { margin: .5rem 0; text-align: center; }
|
|
29
|
+
.transcript-chart svg { display: block; margin: 0 auto; max-width: 100%; height: auto; }
|
|
30
|
+
/* The action menu reserves 38px on the right; nudge back to true center. */
|
|
31
|
+
.transcript-chart .vega-embed.has-actions { transform: translateX(19px); }
|
|
32
|
+
.transcript-status { display: block; width: max-content; margin: .15rem 0 0 auto;
|
|
33
|
+
padding: .1rem .5rem;
|
|
34
|
+
font: .72rem/1.5 ui-monospace, monospace; color: #888;
|
|
35
|
+
border: 1px solid #8884; border-radius: 999px; }
|
|
36
|
+
.transcript-status[data-state="rendering"] {
|
|
37
|
+
color: #b8860b; border-color: #b8860b66;
|
|
38
|
+
}
|
|
39
|
+
.transcript-status[data-state="interactive"] {
|
|
40
|
+
color: #3984c6; border-color: #3984c666;
|
|
41
|
+
}
|
|
42
|
+
"""
|
|
43
|
+
|
|
44
|
+
# A status hint next to every chart: ``offline`` (static preview), ``rendering``
|
|
45
|
+
# (loading the runtime), ``interactive`` (the dynamic chart is live).
|
|
46
|
+
_STATUS = (
|
|
47
|
+
'<span class="transcript-status" data-state="offline" role="status">offline</span>'
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
# The report starts from the static preview and upgrades it to an interactive
|
|
51
|
+
# chart once the Vega runtime is available. Offline (or with JavaScript
|
|
52
|
+
# disabled) the preview stays, so the report keeps working without a network.
|
|
53
|
+
_LOADER_SCRIPT = """
|
|
54
|
+
(function () {
|
|
55
|
+
const charts = [];
|
|
56
|
+
document.querySelectorAll('script.transcript-vegalite-spec').forEach(node => {
|
|
57
|
+
charts.push({ node: node, container: node.parentElement });
|
|
58
|
+
});
|
|
59
|
+
if (!charts.length) return;
|
|
60
|
+
const sources = __SOURCES__;
|
|
61
|
+
const dark = window.matchMedia('(prefers-color-scheme: dark)');
|
|
62
|
+
const darkConfig = {
|
|
63
|
+
background: 'transparent',
|
|
64
|
+
axis: {
|
|
65
|
+
domainColor: '#888', gridColor: '#3a3a3a', tickColor: '#888',
|
|
66
|
+
labelColor: '#d5d5d5', titleColor: '#d5d5d5',
|
|
67
|
+
},
|
|
68
|
+
legend: {labelColor: '#d5d5d5', titleColor: '#d5d5d5'},
|
|
69
|
+
title: {color: '#d5d5d5'},
|
|
70
|
+
view: {stroke: '#888'},
|
|
71
|
+
};
|
|
72
|
+
function setState(container, state) {
|
|
73
|
+
const status = container.querySelector('.transcript-status');
|
|
74
|
+
if (status) {
|
|
75
|
+
status.dataset.state = state;
|
|
76
|
+
status.textContent = state;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
charts.forEach(chart => setState(chart.container, 'rendering'));
|
|
80
|
+
function load(src) {
|
|
81
|
+
return new Promise((resolve, reject) => {
|
|
82
|
+
const script = document.createElement('script');
|
|
83
|
+
script.src = src;
|
|
84
|
+
script.onload = resolve;
|
|
85
|
+
script.onerror = reject;
|
|
86
|
+
document.head.appendChild(script);
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
function upgrade() {
|
|
90
|
+
charts.forEach(chart => {
|
|
91
|
+
const node = chart.node;
|
|
92
|
+
const preview = chart.container.querySelector('.transcript-preview');
|
|
93
|
+
const target = document.createElement('div');
|
|
94
|
+
const spec = JSON.parse(node.textContent);
|
|
95
|
+
const config = dark.matches ? darkConfig : {background: 'transparent'};
|
|
96
|
+
vegaEmbed(target, spec, {renderer: 'svg', config}).then(
|
|
97
|
+
() => {
|
|
98
|
+
if (preview) preview.replaceWith(target);
|
|
99
|
+
else node.before(target);
|
|
100
|
+
node.remove();
|
|
101
|
+
setState(chart.container, 'interactive');
|
|
102
|
+
},
|
|
103
|
+
() => {
|
|
104
|
+
setState(chart.container, 'offline');
|
|
105
|
+
},
|
|
106
|
+
);
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
sources
|
|
110
|
+
.reduce((chain, src) => chain.then(() => load(src)), Promise.resolve())
|
|
111
|
+
.then(upgrade)
|
|
112
|
+
.catch(() => charts.forEach(chart => setState(chart.container, 'offline')));
|
|
113
|
+
})();
|
|
114
|
+
""".replace("__SOURCES__", json.dumps(_CDN))
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def _records(rows):
|
|
118
|
+
"""Export pandas or polars rows through their public methods, without imports."""
|
|
119
|
+
if callable(getattr(rows, "to_dicts", None)):
|
|
120
|
+
rows = rows.to_dicts()
|
|
121
|
+
elif callable(getattr(rows, "to_dict", None)) and hasattr(rows, "columns"):
|
|
122
|
+
rows = rows.to_dict(orient="records")
|
|
123
|
+
if not isinstance(rows, list):
|
|
124
|
+
raise TypeError("DataFrame record export must return a list")
|
|
125
|
+
return jsonify(rows, context="Vega-Lite output")
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def is_altair_chart(value) -> TypeIs[alt.TopLevelMixin]:
|
|
129
|
+
"""Return whether *value* is an Altair top-level chart object."""
|
|
130
|
+
try:
|
|
131
|
+
import altair as alt
|
|
132
|
+
except ImportError:
|
|
133
|
+
return False
|
|
134
|
+
return isinstance(value, alt.TopLevelMixin)
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def vegalite(spec: ConfigOrFig, data=None, *, offline: bool = False):
|
|
138
|
+
"""Record a Vega-Lite spec, optionally replacing its data.
|
|
139
|
+
|
|
140
|
+
``spec`` is a TopLevelMixin, Vega-Lite specification mapping or configfile.
|
|
141
|
+
When ``data`` is provided, transcript snapshots its DataFrame rows into
|
|
142
|
+
the top-level ``data`` and replaces any ``data`` or ``datasets`` already
|
|
143
|
+
in the spec. With no ``data`` argument, the complete spec is preserved.
|
|
144
|
+
Relative filenames are resolved against the current working directory,
|
|
145
|
+
like any Python file read.
|
|
146
|
+
|
|
147
|
+
By default the chart is a static preview that a browser upgrades to an
|
|
148
|
+
interactive chart (tooltips, zoom, action menu) once the Vega runtime can
|
|
149
|
+
be loaded from a CDN; a status hint next to the chart shows whether it is
|
|
150
|
+
``offline``, ``rendering``, or ``interactive``. ``offline=True`` keeps the
|
|
151
|
+
chart a pure static SVG: no dynamic rendering, no CDN, and the report keeps
|
|
152
|
+
its strict Content Security Policy.
|
|
153
|
+
"""
|
|
154
|
+
|
|
155
|
+
if is_altair_chart(spec):
|
|
156
|
+
spec = spec.to_dict()
|
|
157
|
+
else:
|
|
158
|
+
spec = load_spec(spec)
|
|
159
|
+
if not isinstance(spec, Mapping):
|
|
160
|
+
raise TypeError("Vega-Lite spec must be a mapping or a JSON/YAML filename")
|
|
161
|
+
snapshot = jsonify(spec, context="Vega-Lite output")
|
|
162
|
+
if data is not None:
|
|
163
|
+
snapshot.pop("datasets", None)
|
|
164
|
+
snapshot["data"] = {"values": _records(data)}
|
|
165
|
+
snapshot.setdefault("width", _DEFAULT_WIDTH)
|
|
166
|
+
snapshot.setdefault("height", _DEFAULT_HEIGHT)
|
|
167
|
+
return _output(snapshot, offline=offline)
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _output(spec, *, offline: bool):
|
|
171
|
+
"""Wrap a complete Vega-Lite specification in the selected renderer."""
|
|
172
|
+
snapshot = jsonify(spec, context="Vega-Lite output")
|
|
173
|
+
return (VegaliteOffline if offline else VegaliteInteractive)(snapshot)
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
class _VegaliteBase(Renderer):
|
|
177
|
+
"""Shared snapshot handling for the static and interactive renderers."""
|
|
178
|
+
|
|
179
|
+
version = (1,)
|
|
180
|
+
STYLE = _STYLE
|
|
181
|
+
|
|
182
|
+
def __init__(self, spec):
|
|
183
|
+
self._validate(spec)
|
|
184
|
+
self.spec = spec
|
|
185
|
+
|
|
186
|
+
def serialize(self):
|
|
187
|
+
"""Return the spec and data records serialized as JSON."""
|
|
188
|
+
return json.dumps(self.spec, sort_keys=True, indent=2, allow_nan=False)
|
|
189
|
+
|
|
190
|
+
@classmethod
|
|
191
|
+
def _validate(cls, data):
|
|
192
|
+
if not isinstance(data, dict):
|
|
193
|
+
raise ValueError("Vega-Lite output data must be a mapping")
|
|
194
|
+
|
|
195
|
+
@classmethod
|
|
196
|
+
def _svg(cls, parsed: dict):
|
|
197
|
+
try:
|
|
198
|
+
import vl_convert
|
|
199
|
+
except ImportError as error:
|
|
200
|
+
raise RuntimeError(
|
|
201
|
+
'Vega-Lite HTML export requires: pip install "transcript[vegalite]"'
|
|
202
|
+
) from error
|
|
203
|
+
# Keep Vega-Lite's default white background: a transparent preview
|
|
204
|
+
# would render dark text invisible on the report's dark color scheme.
|
|
205
|
+
return vl_convert.vegalite_to_svg(parsed, allowed_base_urls=[])
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
@register
|
|
209
|
+
class VegaliteOffline(_VegaliteBase):
|
|
210
|
+
"""Render a snapshot to a static SVG chart during HTML export."""
|
|
211
|
+
|
|
212
|
+
name = "vegalite_offline"
|
|
213
|
+
|
|
214
|
+
@classmethod
|
|
215
|
+
def to_html(cls, slot):
|
|
216
|
+
"""Render stored data to a static SVG chart with no report files."""
|
|
217
|
+
parsed = json.loads(slot.value)
|
|
218
|
+
cls._validate(parsed)
|
|
219
|
+
return cls._htmlout(
|
|
220
|
+
'<div class="transcript-chart"><div class="transcript-frame">'
|
|
221
|
+
f"{cls._svg(parsed)}{_STATUS}</div></div>"
|
|
222
|
+
)
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
@register
|
|
226
|
+
class VegaliteInteractive(_VegaliteBase):
|
|
227
|
+
"""Show a static preview and upgrade it online to an interactive chart."""
|
|
228
|
+
|
|
229
|
+
name = "vegalite_interactive"
|
|
230
|
+
|
|
231
|
+
@classmethod
|
|
232
|
+
def to_html(cls, slot):
|
|
233
|
+
"""Return the static preview plus the spec the browser runtime embeds."""
|
|
234
|
+
parsed = json.loads(slot.value)
|
|
235
|
+
cls._validate(parsed)
|
|
236
|
+
body = json.dumps(parsed, sort_keys=True, separators=(",", ":"))
|
|
237
|
+
body = body.replace("<", "\\u003c")
|
|
238
|
+
return cls._htmlout(
|
|
239
|
+
'<div class="transcript-chart">'
|
|
240
|
+
f'<div class="transcript-preview">{cls._svg(parsed)}</div>'
|
|
241
|
+
f"{_STATUS}"
|
|
242
|
+
'<script type="application/json" class="transcript-vegalite-spec">'
|
|
243
|
+
f"{body}</script></div>"
|
|
244
|
+
)
|
|
245
|
+
|
|
246
|
+
runtime = _LOADER_SCRIPT
|
|
247
|
+
"""Return the loader that upgrades previews when the CDN is reachable."""
|
|
248
|
+
|
|
249
|
+
sources = ["https://cdn.jsdelivr.net"]
|
|
250
|
+
"""Allow the Vega runtime scripts from the jsDelivr CDN."""
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
"""Review records stored in the trailing ``transcript.review`` block.
|
|
2
|
+
|
|
3
|
+
The package owns the whole feature: :mod:`._block` locates, rewrites, and
|
|
4
|
+
migrates the trailing block, :mod:`._span` holds the ``L``/``C`` coordinate
|
|
5
|
+
grammar with the method-based :class:`Span`, :mod:`._records`
|
|
6
|
+
the flat record schema, lookup, and serialization, :mod:`._migrate` the
|
|
7
|
+
incremental update run when an archive is regenerated, and :mod:`load` reads a
|
|
8
|
+
review source from an archive or exported page and chooses one.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from ._block import ReviewBlock
|
|
12
|
+
|
|
13
|
+
__all__ = ["ReviewBlock"]
|