50 lines
2.3 KiB
Python
50 lines
2.3 KiB
Python
"""Renders a notebook to a self-contained HTML page with Quarto, running it first.
|
|
|
|
`QUARTO_BIN` names the `quarto` executable when it isn't on the `PATH`. Quarto runs notebooks through a Python that has
|
|
Jupyter (`nbformat`, `nbclient`); under `uv run` the first one on the `PATH` is this package's, which doesn't, so
|
|
`QUARTO_PYTHON` names one that does. The notebook runs with the kernel its metadata
|
|
names, or `kernel` if given, in the environment given: that's how a report points the notebook at a database, a
|
|
cohort folder and a build's file. Quarto writes next to its input, so the notebook is copied to a temporary folder
|
|
first and the source folder is left untouched.
|
|
"""
|
|
|
|
import json
|
|
import os
|
|
import shutil
|
|
import subprocess
|
|
import tempfile
|
|
from pathlib import Path
|
|
|
|
QUARTO_ENV = "QUARTO_BIN"
|
|
|
|
|
|
class RenderError(RuntimeError):
|
|
"""Quarto failed: a cell raised, the kernel is missing, or Quarto isn't installed."""
|
|
|
|
|
|
def quarto() -> str:
|
|
found = os.environ.get(QUARTO_ENV) or shutil.which("quarto")
|
|
if not found:
|
|
raise RenderError(f"quarto isn't installed: put it on the PATH or set {QUARTO_ENV}")
|
|
return found
|
|
|
|
|
|
def render_notebook(notebook: dict, name: str, output: Path, *, env: dict[str, str] | None = None,
|
|
kernel: str | None = None) -> Path:
|
|
"""Runs and renders `notebook` (its JSON) as `name`, and writes the page to `output`."""
|
|
command = quarto()
|
|
if kernel:
|
|
notebook = {**notebook, "metadata": {**notebook.get("metadata", {}),
|
|
"kernelspec": {"name": kernel, "display_name": kernel, "language": "python"}}}
|
|
with tempfile.TemporaryDirectory(prefix="render-") as folder:
|
|
source = Path(folder) / f"{name}.ipynb"
|
|
source.write_text(json.dumps(notebook, ensure_ascii=False))
|
|
done = subprocess.run([command, "render", source.name, "--execute", "--to", "html", "-M", "embed-resources:true"],
|
|
cwd=folder, env={**os.environ, **(env or {})}, capture_output=True, text=True)
|
|
page = source.with_suffix(".html")
|
|
if done.returncode or not page.exists():
|
|
raise RenderError(f"quarto couldn't render {name}: {(done.stderr or done.stdout)[-2000:]}")
|
|
output.parent.mkdir(parents=True, exist_ok=True)
|
|
shutil.move(page, output)
|
|
return output
|