let's convert a notebook to a <var>pyscript</var> document.
we'll using `nbconvert and jinja2` to transform a notebook into a standalone interactive document.
3
let's convert a notebook to a
pyscript document.
we'll using
nbconvert and jinja2
to transform a notebook into a standalone interactive document.
[include <var>pyscript</var> css and javascript assets][getting-started] in the `<head>`
[getting-started]: https://docs.pyscript.net/latest/tutorials/getting-started.html#your-first-pyscript-html-file
[<var>requirejs</var> and <var>pyscript</var> do not play well together][require-issue], and the block below prevents <var>requirejs</var> from loading.
[require-issue]: https://github.com/pyscript/pyscript/issues/317
from a notebook's source we can infer the packages it needs to run.
the packages are placed in the `<py-config>` tag.
> continue reading to see how the `get_imports_from_cells` filter is defined.
4
from a notebook's source we can infer the packages it needs to run.
the packages are placed in the
<py-config>
tag.
continue reading to see how the
get_imports_from_cells
filter is defined.
## `nbconvert` exporting machinery`nbconvert` is the primary machinery used to transform notebook documents into other file formats. it is a wrapper around the shape of the notebook and a `jinja2` environment.
nbconvert
is the primary machinery used to transform notebook documents into other file formats. it is a wrapper around the shape of the notebook and a
jinja2
environment.
defget_imports_from_cells(nb):imports=set()forcellinnb.cells:imports.update(get_imports_from_cell(cell))ifimports.intersection({"requests","httpx","urllib"}):# add more laterimports.add("pyodide-http")returnlist(imports)defget_imports_from_cell(cell):importdepfinder__import__("requests_cache").install_cache()ifcell["cell_type"]=="code":try:yield fromdepfinder.inspection.get_imported_libs(textwrap.dedent("".join(cell["source"]))).required_modulesexceptBaseExceptionase:pass
`get_exporter` generates a new notebook file converter.
*adds filters used in `template`*puts a template on the `jinja2.DictLoader` with our custom template
4
get_exporter
generates a new notebook file converter.
adds filters used in
template
puts a template on the
jinja2.DictLoader
with our custom template
defpyscript(file:Path,target:Path=None,write:bool=True):"""generate a pyscript version of a notebook"""body=get_pyscript(file)ifwrite:ifnottarget:target=file.with_suffix(F"{file.suffix}.html")target.write_text(body)print(F"created {target}")