Rendering API¶
Import rendering functions from lectrace:
Renderings are attached to the step where the call appears. When that step is active in the viewer, the rendering replaces the code line with its visual output.
text()¶
Render Markdown with optional LaTeX math.
text("# Heading")
text("**Bold**, _italic_, `code`")
text("Euler's identity: $e^{i\\pi} + 1 = 0$")
text("Display math: $$\\sum_{k=0}^{n} k = \\frac{n(n+1)}{2}$$")
Multi-line strings — including triple-quoted docstrings — are automatically dedented and trimmed, so you can write naturally without worrying about indentation:
text("""
# Gradient Descent
Training a model means finding parameters that minimize a loss function.
Gradient descent is how we do it — follow the slope downhill, step by step.
The update rule: $w \\leftarrow w - \\eta \\nabla L(w)$
""")
For monospace output that preserves whitespace, use verbatim=True:
Signature:
image()¶
Display an image from a local file or URL.
image("figures/diagram.png")
image("figures/chart.png", width=400)
image("https://example.com/figure.png", width="50%")
Remote images are downloaded and cached in ~/.cache/lectrace/ on first use.
Signature:
video()¶
Embed a video from a local file or URL.
Signature:
link()¶
Add a reference link with a hover card, or a jump-to-source link.
External reference¶
link(
title="Attention Is All You Need",
url="https://arxiv.org/abs/1706.03762",
authors=["Vaswani", "Shazeer", "Parmar"],
date="2017",
description="Introduced the Transformer architecture.",
)
Renders as a [Vaswani+ 2017]-style citation. Hovering shows the full card.
URL shorthand¶
Jump to source¶
Pass a class or function and clicking navigates to its definition in the viewer:
Reference object¶
ref = Reference(
title="Deep Learning",
authors=["Goodfellow", "Bengio", "Courville"],
url="https://www.deeplearningbook.org",
date="2016",
)
link(ref)
Signature:
link(
arg: type | Reference | str | None = None,
title: str | None = None,
url: str | None = None,
authors: list[str] | None = None,
date: str | None = None,
description: str | None = None,
organization: str | None = None,
notes: str | None = None,
style: dict | None = None,
) -> None
plot()¶
Embed a chart in the lectrace browser viewer. This call is a no-op when the script is run directly — use plt.show() in your script for the standalone matplotlib window.
import matplotlib.pyplot as plt
import lectrace
def main():
fig, ax = plt.subplots()
ax.bar(["A", "B", "C"], [3, 7, 2])
lectrace.plot(fig) # shows in lectrace viewer
plt.show() # shows matplotlib window when run as a standalone script
matplotlib¶
Pass a Figure or an Axes object — both are accepted:
Any matplotlib chart type works — line, scatter, histogram, heatmap, subplots, etc. The figure is rendered as a crisp SVG and closed automatically after capture.
Vega-Lite spec¶
For interactive charts (zoom, pan, tooltips), pass a raw Vega-Lite dict:
plot({
"$schema": "https://vega.github.io/schema/vega-lite/v5.json",
"width": 400,
"height": 250,
"data": {"values": [{"x": 1, "y": 2}, {"x": 2, "y": 4}, {"x": 3, "y": 1}]},
"mark": "point",
"encoding": {
"x": {"field": "x", "type": "quantitative"},
"y": {"field": "y", "type": "quantitative"},
},
})
Signature:
note()¶
Add a presenter annotation rendered as a styled callout beside the line.
values = [5, 3, 7, 1] # @inspect values
note("deliberately unsorted — worst case is sorted input")
# or multi-line:
note("""
This is the classic birthday paradox setup.
With 23 people, collision probability exceeds 50%.
Ask the audience to guess before revealing.
""")
Notes appear inline as callout boxes with a left accent border. Use them for speaker context, questions to pose to the audience, or caveats that would be distracting as main text. Like text(), triple-quoted strings are dedented automatically.
Signature:
table()¶
Display structured data as a formatted table.
# List of dicts — keys become headers automatically
table([
{"name": "quicksort", "avg": "O(n log n)", "worst": "O(n²)", "space": "O(log n)"},
{"name": "mergesort", "avg": "O(n log n)", "worst": "O(n log n)", "space": "O(n)"},
{"name": "heapsort", "avg": "O(n log n)", "worst": "O(n log n)", "space": "O(1)"},
{"name": "timsort", "avg": "O(n log n)", "worst": "O(n log n)", "space": "O(n)"},
])
With an optional caption:
table(
[{"epoch": 1, "loss": 2.31, "acc": 0.42},
{"epoch": 2, "loss": 1.87, "acc": 0.61},
{"epoch": 3, "loss": 1.42, "acc": 0.74}],
caption="Training metrics",
)
From a list of lists — headers is required:
table(
[[1, 0.92, "cat"], [2, 0.87, "dog"], [3, 0.73, "bird"]],
headers=["id", "confidence", "label"],
)
From a pandas DataFrame:
import pandas as pd
df = pd.DataFrame({"city": ["London", "Tokyo", "NYC"], "pop_m": [9.0, 13.9, 8.3]})
table(df, caption="City populations (millions)")
Column alignment is inferred automatically — numeric columns right-align, text columns left-align. Null/None cells render as —.
Signature:
table(
rows: list[dict] | list[list] | DataFrame,
headers: list[str] | None = None,
caption: str | None = None,
style: dict | None = None,
) -> None
system_text()¶
Run a shell command and display its output as verbatim text.
system_text(["python3", "--version"])
system_text(["date"])
system_text(["git", "log", "--oneline", "-5"])
ANSI color codes are stripped automatically.
Signature:
Reference¶
The Reference dataclass holds metadata for an external source.
from lectrace import Reference
ref = Reference(
title="The Art of Computer Programming",
authors=["Knuth"],
date="1968",
url="https://www-cs-faculty.stanford.edu/~knuth/taocp.html",
description="Volume 1: Fundamental Algorithms",
organization=None,
notes=None,
)
| Field | Type | Description |
|---|---|---|
title | str \| None | Full title of the work |
authors | list[str] \| None | Author surnames or full names |
organization | str \| None | Team or organization name (shown instead of authors) |
date | str \| None | Year or full date string |
url | str \| None | Link opened when the citation is clicked |
description | str \| None | Short description shown in the hover card |
notes | str \| None | Additional multi-line notes |
The citation label is derived automatically:
- One author →
[Knuth 1968] - Multiple authors →
[Knuth+ 1968] - Organization →
[DeepMind 2023] - No authors → full title