Notebook posts

A page can be a Jupyter notebook. The build publishes its cells and the outputs stored in it as HTML, and runs no code unless asked with --execute.

A notebook post is a page whose content is a Jupyter notebook (index.ipynb) instead of Markdown (index.md). The build publishes the notebook as it was saved: Markdown cells as text, code cells as highlighted code, and the outputs stored in the file as HTML and images. It runs no code unless you ask it to (see "Running notebooks when building"), so what readers see is what the notebook held when you saved it.

Turning it on

A model opts in by listing "notebook" in its formats, and needs a markdown field with body = true, which receives the cells:

# models/blog-post.toml
[model]
formats = ["markdown", "notebook"]

[fields.title]
type = "string"

[fields.body]
type = "markdown"
body = true

Pages of that model may then be either format. The rules for the model's side are in Models and field types, and the file's side (where metadata.motabhai holds the page's fields, and what is an error) is in Content files. A notebook post renders through the same template as a Markdown one: {{ this.body }} prints the cells, and this.format is "notebook" or "markdown" for templates that need to tell them apart.

What is published

Each published cell is one <div>:

CellPublished as
Markdown<div class="nb-cell nb-markdown">, the cell rendered as in a Markdown field: the same extensions, highlighting and link resolution.
Code<div class="nb-cell nb-code"> holding <div class="nb-input"> with the code highlighted in the notebook's language, then one <div class="nb-output"> for each output.
RawNothing.

Execution counts (In [3]) are not shown, and a code cell with no code and no outputs is left out.

Outputs

Stream output (what the code printed) is a <pre>; adjacent chunks of the same stream are joined. Standard error gets nb-output nb-stderr. An exception's traceback gets nb-output nb-error; its terminal colour codes are removed, as they are from all text outputs.

A result or a display (a plot, a data frame) can carry the same thing in several forms. The first of these the output has is published, in this order:

  1. text/html, sanitised (see below), such as a pandas <table class="dataframe">.
  2. image/png, as a file.
  3. image/jpeg, as a file.
  4. image/svg+xml, sanitised, inline in the page.
  5. text/markdown, rendered and then sanitised.
  6. text/plain, as a <pre>.

An output with none of these publishes nothing.

Images come before SVG on purpose: a plot that Jupyter stored both ways (matplotlib's %config InlineBackend.figure_formats = ['png', 'svg']) publishes the PNG, which shows the figure exactly as drawn. A plot stored only as SVG is published inline; see "What is sanitised" for what it keeps.

Images are files

A PNG or JPEG output is not embedded in the page. It is written beside the page as nb-<hash>.png (or .jpg), where the hash is the start of the BLAKE3 hash of the image's bytes, and the page shows it with <img src="…/nb-<hash>.png" alt="">. The name depends only on the image, so an unchanged image keeps its name from build to build. Images attached to a Markdown cell (![plot](attachment:plot.png)) are published the same way. An output's width, height and alt metadata are kept.

Cell tags

Tag a cell in Jupyter (View, Cell Toolbar, Tags in classic Jupyter; the property inspector in JupyterLab) to control what is published:

TagEffect
hide-cellThe whole cell is left out.
hide-inputThe code is left out; the outputs stay.
hide-outputThe outputs are left out; the code stays.

What is sanitised

The HTML and SVG in an output were made by whatever code ran in the notebook, perhaps a library you did not write or a notebook someone else sent you, so the build keeps only what is on an allow-list and drops the rest. The list keeps what static outputs need: tables, text formatting, lists, links, images and the SVG shapes and text elements. Everything else is removed, including:

  • <script>, <iframe>, <object>, <embed> and <form>, so an output cannot run code, load a frame or submit anything. Elements that are dropped but could hold text, such as a form's labels, keep their text.
  • <style> elements, and style attributes on HTML elements, because CSS can cover the page or load files from elsewhere. Style notebook outputs from your own stylesheet instead (see below). An SVG element keeps a style that sets only how it is painted (fill, stroke and the other stroke-* properties, opacity, font and the font-* properties, text-anchor, dominant-baseline, visibility, fill-rule, clip-rule) with plain values: colours, numbers, names. Anything else in it, such as url(...), is dropped declaration by declaration.
  • A <title> outside an SVG (an output that is a whole HTML document has one), with its text. Inside an SVG it stays as the drawing's name.
  • Event handlers such as onclick, javascript: links, and srcset.
  • id and name attributes, which can overwrite names the page's own scripts use. SVG elements that need an id to point at (<use>, gradients, clip paths) go with them, so an SVG whose text is drawn as shared glyphs (matplotlib's default) loses its text; store the plot as PNG too, or set svg.fonttype to none.
  • target on links; links open in the same tab and get rel="noopener noreferrer".

Images in an output's HTML may have a data: address only for PNG and JPEG.

Markdown cells are not sanitised. They are your own writing, like a Markdown field, which is not sanitised either. Only outputs, which come from running code, are.

Styling

The built-in themes already style these classes. A site with its own theme can use them as hooks:

ClassElement
nb-cellEvery published cell.
nb-markdownA Markdown cell.
nb-codeA code cell, holding the input and its outputs.
nb-inputThe highlighted code of a code cell.
nb-outputOne output.
nb-stderr, nb-errorAn output that is standard error, or a traceback, besides nb-output.
.nb-cell { margin: 1.5rem 0; }

.nb-output {
  padding-left: 1rem;
  overflow-x: auto;                 /* wide tables and text scroll */
  border-left: 3px solid #bbb;
}
.nb-error { border-left-color: #d1242f; }

.nb-output img,
.nb-output svg { max-width: 100%; height: auto; }

table.dataframe { border-collapse: collapse; }
table.dataframe th,
table.dataframe td { padding: 0.25rem 0.6rem; text-align: right; }

Highlighted code carries its own light and dark colours, chosen by color-scheme as for code in Markdown.

Out of date and not-run cells

A build publishes what the file stores. A code cell that has code but no stored outputs was never run, and a cell can be marked out of date (metadata.motabhai.stale_at and stale_outputs on the cell, which a tool that edits notebooks sets when it changes a cell's code; running the cell in Jupyter clears it). The page shows the outputs such a cell has, which may be none or may no longer match its code. The build says so, once for each notebook:

warning: content/blog/analysis/index.ipynb: 2 cells have outputs that are out of date or were never made; the build publishes what the notebook stores and runs no code

Run the notebook and save it to clear the warning, or build with --execute, which runs the notebooks itself and prints no warning for them. A plain motabhai build never executes code.

Running notebooks when building

motabhai build --execute

runs every notebook post that is built, in every language and not the hidden ones, from a fresh kernel, top to bottom, with jupyter nbconvert. Each runs in its own directory, so a relative path such as open("data.csv") reaches the attachments beside the post. The outputs of that run are published in place of the stored ones, rendered and sanitised as stored outputs are. The notebook files are never modified, so nothing under content/ changes, and the build prints no out-of-date warning for the posts it ran. A page whose outputs come out the same as last time is not rebuilt. A later build without the flag publishes the stored outputs again.

Use it to guarantee that the published outputs come from the published code. It costs a Python process for each notebook and needs the environment that runs them, so a site that does not need the guarantee is better off saving its notebooks after running them. A site with no notebook posts builds as usual, without Jupyter.

What it needs

Jupyter with nbconvert, and the kernel each notebook names, as well as the libraries its cells import. Two settings under [notebook] in motabhai.toml (see Configuration):

[notebook]
jupyter = "/opt/jupyter/bin/jupyter"   # default "jupyter"
timeout = 120                          # seconds per cell, default 600

jupyter names the program, so a virtual environment's Jupyter can be used without activating it: a bare name such as jupyter is looked up on the PATH, and a path with a directory in it, such as .venv/bin/jupyter, is relative to the project root, whatever directory you run the build from. timeout is how long one cell may run. The flag works whether or not [notebook] execute is set, which is about running cells from the admin.

To stop an executing build, press Ctrl-C, or send motabhai SIGTERM: the nbconvert processes it started are stopped, and their kernels exit after them. (A SIGKILL stops them the same way.)

When something goes wrong

Every notebook is run, and every failure reported, before the build stops; a failed build writes nothing to the output directory.

  • A cell that raises an error fails the build with motabhai::notebook::execution_failed. It names the notebook file, the cell as "cell N" (counted among all the notebook's cells, Markdown ones too, as the admin counts them), and the error's name and message, such as ZeroDivisionError: division by zero. Several failing notebooks are all reported in the one run.
  • A cell that is meant to fail can be tagged raises-exception. The build goes on and publishes its traceback as the cell's output.
  • A cell that runs longer than timeout fails the build with motabhai::notebook::timeout, naming the notebook, the cell and the timeout.
  • Before anything is run, the build checks the tools. A missing program is motabhai::notebook::jupyter_not_found, which names the command and the [notebook] jupyter setting; Jupyter without nbconvert is motabhai::notebook::nbconvert_not_found; a kernel that is not installed is motabhai::notebook::kernel_not_installed. Each names the notebook files that need it, and nothing has been built.

Hooks, serve and deploy

The before_build hooks run first, so a hook can prepare the data the notebooks read. Only motabhai build takes --execute; serve and deploy refuse it. motabhai deploy builds the site itself, without running notebooks, so it deploys the stored outputs. To publish executed output, run motabhai build --execute and then upload the output directory with your own tools; deploy targets are not part of that build.

In CI

The machine needs Python with nbconvert, the kernels and the libraries the notebooks use, installed before the build:

python -m pip install nbconvert ipykernel pandas matplotlib
motabhai build --execute

Name your own libraries in place of pandas matplotlib. Jupyter's server is not needed, only nbconvert and the kernels.

Editing in the admin

The admin edits a notebook post as a list of cells, and writes the same index.ipynb that Jupyter reads.

The edit page of a notebook post: a Markdown cell, a code cell with a table under it and a code cell with a plot marked "Out of date"

Creating one

Choose New and a parent, as for any page. When the model allows both formats, the form has a Format choice of Markdown and Notebook, with the first format in the model's formats chosen; a model with one format has no choice. A blank notebook has one empty Markdown cell, and its kernel is the kernel set under [notebook] in motabhai.toml (python3 unless you change it, see Configuration). The form's fields are written to metadata.motabhai.

To start from work you already have, choose Notebook and pick an .ipynb file. The new post is that notebook, with its cells, outputs and metadata kept, and the form's fields go into metadata.motabhai (replacing the ones already there with the same names). A file that is not a valid version 4 notebook is refused, and nothing is written.

The cell editor

The edit page has the title and Properties of a Markdown post, with the notebook's cells in place of the body. Properties are saved to metadata.motabhai. The page is marked as a notebook.

  • A Markdown cell is the Markdown editor of a Markdown field, with its toolbar, typing shortcuts and slash menu, but it always shows the text as you wrote it: nothing is drawn in place, and there is no Source button. Preview, beside the cell's name, swaps the editor for the cell as the site will publish it, including text you have not saved; press it again, or double-click the preview, to go on editing. Each cell has its own, and a cell action (adding, moving, deleting, switching) puts every cell back in its editor. The preview drops scripts and anything else that could run in the admin, so a cell that relies on them looks different on the built page.
  • A code cell is a code editor with colours for the notebook's language, and no toolbar or slash menu. Tab indents; press Escape and then Tab to leave the editor.
  • A raw cell is plain text.

Each cell has buttons to add a Markdown or a code cell below it, move it up or down, delete it, and switch it between code and Markdown. With the cursor in a cell, Ctrl+Shift+Up or Down (Cmd on a Mac) moves it. Typing /code cell in a Markdown cell and pressing Enter adds a code cell below with the cursor in it. None of these reload the page or touch the other cells' unsaved text, and nothing is written until you Save (Ctrl/Cmd+S). A save that the model refuses writes nothing, and shows each problem at its field.

Switching a code cell to Markdown keeps its text, and drops its outputs when you save. It asks you to confirm first, since the outputs cannot be brought back. Switching Markdown to code asks nothing.

Outputs, out of date and not run

Under each code cell the page shows the outputs stored in the notebook, rendered and sanitised exactly as the build publishes them (see "What is sanitised" above), so a script in an output does not run in the admin. They are read-only: you edit code, not results.

Changing a code cell's code does not remove its outputs. They are marked Out of date at once, as you type, and typing the original code back removes the mark. When you save, the mark is stored in the notebook on that cell, as metadata.motabhai.stale_at (the cell's execution count) and metadata.motabhai.stale_outputs (a fingerprint of its outputs), so it is there when the page is opened again, and the build warns about it (see "Out of date and not-run cells" above). Running the cell in any Jupyter tool gives it a new execution count or new outputs and clears the mark, even after "Restart & Run All", which can give the same count again. Only a run that prints exactly what it printed before leaves the mark, since motabhai cannot tell that run from none. The next save that changes something else removes the record from the file.

If the notebook file changes on disk while its edit page is open (you saved it in Jupyter, or in another tab), saving the page is refused, writing nothing: the cells on the page were read from the old file, and saving them could put your text on the wrong cells. The page says so and keeps what you typed; copy what you need, then reload the page to edit the notebook as it is now. A draft kept from before the change is refused the same way after Restore. A code cell that has code and no outputs is marked Not run.

Unless running is turned on (see "Running cells in the admin"), the admin does not run code. Run cells in Jupyter, and save the notebook there; or have the build run them (see "Running notebooks when building").

What saving keeps

Saving changes what you edited: the text of edited cells, the order and set of cells, and metadata.motabhai. Everything else stays as it was: outputs, execution counts, cell ids, cell and notebook metadata, attachments, and keys motabhai does not know. A cell you add gets an id of its own when the notebook's format has ids.

A changed notebook is written in Jupyter's own style (one-space indentation, each cell's source as a list of lines, characters beyond ASCII as they are, a final newline), so a version-control diff of a notebook last saved by Jupyter shows only the cells you edited and metadata.motabhai. A save in which nothing changed does not write the file at all.

Drafts

The unsaved indicator and draft recovery cover notebook posts: the draft holds the fields and each cell's kind, text and position, and Restore puts back added, removed, moved and switched cells. A draft never holds outputs; after Restore, each cell shows the outputs the file has.

Alongside Jupyter

You can edit a notebook in the admin and in Jupyter, in turn. Save in one before you go to the other: there is no check that the file is unchanged since the form was opened, so if the notebook is edited in both at once, the last save wins, as it does for Markdown posts.

Running cells in the admin

The edit page of a notebook post can run its code cells and show what they print, so you can work on a notebook without leaving the admin.

A notebook post's edit page after a run: the Run all, Interrupt and Restart buttons, two finished cells (one with printed text, one with a plot) and a failed cell with its traceback

Turning it on

It is off by default. Turn it on in motabhai.toml:

[notebook]
execute = true

Running works only on a dev server listening on a loopback address, which is also the only place the admin itself is served. With execute off, the edit page has no working Run buttons and says that [notebook] execute = true turns them on, and the admin never starts or probes Jupyter.

It needs Jupyter Server 2 with nbconvert, and the kernel the notebook names, as well as the libraries its cells import. The jupyter setting under [notebook] names the program (see Configuration), so a virtual environment's Jupyter can be used without activating it; a path with a directory in it is relative to the site, as for the build. A Jupyter without nbconvert counts as not found. When Jupyter or the kernel is missing, the edit page says which, and Run all and Restart are disabled along with the Run buttons. Installing what was missing needs no restart of the dev server: reload the page (a Jupyter found is checked again every 30 seconds, one not found at every page).

Turning execute off, or pointing jupyter at another program, while motabhai serve runs stops the running Jupyter and its kernels the next time an admin page loads (or when the open page presses Interrupt or Restart), which ends a running cell.

What the page offers

  • Run on each code cell runs it.
  • Run all runs every code cell in order, and stops at the first one that fails. The cells after it stay as they were.
  • Interrupt stops the running cell, which keeps what it printed, and drops the cells waiting behind it. It is enabled only while something runs or waits.
  • Restart starts a fresh kernel, so what earlier cells defined is forgotten. It asks first, and a running cell is stopped. The outputs on the page stay.
  • In a code cell, Ctrl+Enter or Cmd+Enter runs the cell, and Shift+Enter runs it and moves into the next cell.

The outputs stream in under the cell as it prints them, sanitised as stored outputs are (see "What is sanitised" above). Printed text arrives in pieces at most ten times a second; a progress bar drawn with carriage returns shows as the saved output will. A cell shows its state in its head: Waiting (queued by Run all or behind another run), Running, Finished, Failed (the code raised an error, the kernel died, or the run was refused) or Interrupted, followed by its execution count. A line in the run bar says how the last run ended, for screen readers too. A run that starts a fresh kernel, the first one or one after the kernel was stopped for being idle, says that what earlier runs defined is gone.

What it starts, and when

Nothing starts until the first Run. Then motabhai serve starts jupyter server as a child process, on a loopback port with a random token that only motabhai knows. It keeps one kernel for each notebook post and language, working in the post's directory, so a relative path such as open("data.csv") reaches the attachments beside the post.

Kernels are stopped after 30 minutes without a run, and Jupyter itself 5 minutes after the last kernel went. Everything is stopped when the dev server stops. The next Run starts them again.

The browser never talks to Jupyter. It talks only to the admin, through endpoints behind the admin's same-origin guard that take POST only (the status check is read-only). It receives the rendered, sanitised outputs and the raw output data of the cell that ran, which it keeps in the form. The token and the port never reach it.

Results are part of the unsaved post

A run's results go into the form, and the page shows Unsaved changes. Nothing is written until you Save: leaving without saving keeps the outputs the file had. Draft recovery does not keep run results, so after Restore the cells need running again. If you edit a cell's code after it ran and save, the saved outputs are marked out of date, as for any edited cell (see "Outputs, out of date and not run").

Limits

  • No prompts: code that calls input() gets an error instead of waiting.
  • No widgets or other interactive outputs, and no completion or inspection in the code editor.
  • The admin cannot choose or install kernels: the notebook's own kernel is used, and a missing one is reported.
  • A save is refused when the notebook's outputs come to more than 20 MB, and so are a cell action and the preview of a form carrying more than that.
  • One printed stream (all of a cell's stdout, say, until something else is output) keeps at most 1 MiB of text, and a run 4 MiB in all; the rest is dropped and a last line says how many bytes, … output truncated (N more bytes). That line is part of the output, and is saved with it.
  • A single output larger than 32 MiB cannot be shown: the run stops with a problem saying so and the cell is interrupted; the kernel keeps what the cells defined.
  • When Jupyter or the kernel fails during a run (the kernel dies, Jupyter exits), nothing of that run is kept: a cell that had printed nothing yet shows its old outputs again, and a save keeps them; what it had printed stays on show but is not saved.
  • Windows is untested.

Security

Turning this on lets the admin execute code on your machine, as your user. That is the reason running is opt-in and limited to loopback. Read a notebook that someone else sent you before you run it, as you would a script.

Requests that run, interrupt or restart must carry the run key: a secret the dev server makes when it starts, put only into the edit pages of notebook posts while running is on. A page of another site cannot read those pages, and cannot send the key's header (the admin allows no cross-site requests), so neither another site in your browser nor a program that has not read an edit page can run code through the admin. The admin's guard also refuses requests for another host name and writes from another origin.

Jupyter's token lives in a file only your user can read, in a private directory removed when Jupyter stops; it is not in Jupyter's environment, so a cell printing its environment does not show it. That is no wall, though: code in a cell runs as your user, like any program you run, so it can read that file, talk to that Jupyter, and do anything else you can. Jupyter listens on a loopback port, which other users of the machine can connect to, but not without the token.

Feeds

A notebook post's body in a feed is the same HTML as on the page, with the links and image addresses made absolute. The image files are written beside the page, so a feed's images point at the page's own directory.