Convert Jupyter notebooks to and from Python files, and render.


Keywords
datascience, machine-learning, python, python3
License
BSD-1-Clause
Install
pip install wvpy==0.1.7

Documentation

wvpy tools for converting Jupyter notebooks to and from Python files.

Video tutorial here: here.

Many of the data science functions have been moved to wvu https://github.com/WinVector/wvu.

wvpy is a very effective personal Jupyter workflow for data science development.

Jupyter (nee IPython) workbooks are JSON documents that allow a data scientist to mix: code, markdown, results, images, and graphs. They are a great contribution to scientific reproducibility, as they can contain a number of steps that can all be re-run in batch. They serve a similar role to literate programming, SWEAVE, and rmarkdown/knitr. The main design difference is Jupyter notebooks do not separate specification from presentation, which causes a number of friction points. They are not legible without a tool (such as JupyterLab, Jupyter Notebook, Visual Studio Code, PyCharm, or other IDEs), they are fairly incompatible with source control (as they may contain images as binary blobs, and many of the tools alter the notebook on opening), and they make greping/searching difficult.

The above issues are fortunately all inessential difficulties. Python is a very code-oriented work environment, so most tools expose a succinct programable interface. The tooling exposed by the Python packages IPython, nbformat, and nbconvert are very powerful and convenient. With only a little organizing code we were able to build a very powerful personal data science workflow that we have found works very well for clients.

The two features wvpy provides are:

  • Converting Juypter notebooks to/from vanilla Python files. We have an article on the technique here, and a short video demonstration here.
  • Running many Jupyter notebooks with many different inputs, or parameterized. We have a short video on the technique here.

The first wvpy feature is: converting Jupyter notebooks (which are JSON files ending with a .ipynb suffix) to and from simple Python code that is more compatible with source control (such as Git). A video describing

Let's start with a simple example Jupyter notebook: plot.ipynb. If we install (using a shell such as bask, or zsh) wvpy from PyPi.

pip install wvpy

And we download plot.ipynb

wget https://raw.githubusercontent.com/WinVector/wvpy/main/examples/worksheets/plot.ipynb

Then we can convert the Jupyter notebook to the Python formatted file as follows (we discuss this format a bit here).

python -m wvpy.pysheet --delete plot.ipynb

The tool reports the steps it takes in the conversion.

from "plot.ipynb" to "plot.py"
   copying previous output target "plot.py" to "plot.py~"
   converting Jupyter notebook "plot.ipynb" to Python "plot.py"
   moving input plot.ipynb to plot.ipynb~

The resulting Python file is shown here. The idea is: the entire file is pure Python, with the non-python blocks in multi-line strings. This file has all results and meta-data stripped out, and a small amount of whitespace regularization. This ".py" format is exactly the right format for source control, we get reliable and legible differences. In my personal practice I don't always check ".ipynb" files in to source control, but only the matching ".py" files. This discipline makes greping and searching for items in the project as easy as finding items in code.

In the ".py" file "begin text", "end text", and "end code" markers show where the Jupyter cell boundaries are. This allows reliable conversion from the ".py" file back to a Jupyter notebook. PyCharm and others have a similar notebook representation strategy.

We can convert back from ".py" to ".ipynb" as follows.

python -m wvpy.pysheet --delete plot
from "plot.py" to "plot.ipynb"
   converting Python plot.py to Jupyter notebook plot.ipynb
   moving input plot.py to plot.py~

Notice this time we did not specify the file suffix (the ".py" or ".ipynb"). The tooling checks that exactly one of these exists and converts one to another. This allows easy conversion back and forth reusing command history.

Either form of the worksheet can be executed and rendered by HTML from the command line as follows.

python -m wvpy.render_workbook plot
start render_as_html "plot.ipynb"  2022-08-20 12:19:06.669369
	done render_as_html "plot.html" 2022-08-20 12:19:10.080226

This produces what we expect to see from a Jupyter notebook as a presentation.

Screen Shot 2022 08 20 at 12 45 27 PM

There is also an option in the HTML renderer that strips out input blocks. This isn't fully presentation ready, but it makes for very good in progress work reports.

python -m wvpy.render_workbook --strip_input plot
start render_as_html "plot.ipynb"  2022-08-20 12:19:35.251560
	done render_as_html "plot.html" 2022-08-20 12:19:38.478107

This gives a simplified output as below.

Screen Shot 2022 08 20 at 12 43 40 PM

For already executed sheets one would use the standard Juypter supplied command jupyter nbconvert --to html plot.ipynb, the merit of the rendering here is parameterization of notebooks and stripping of input and prompt ids. The strategy here is to be lightweight stand-alone, and not a plug in such as the strategy pursued by jupytext or nbdev, or targeting fully camera ready reports via Quarto. We feel the wvpy approach maximizes productivity during development, with minimal plug-in and install burdens.

We also supply a simple class for holding render tasks, including inserting arbitrary initialization code for each run. This makes it very easy to render the same Jupyter workbook for different targets (say the same analysis for each city in a state) and even parallelize the rendering using standard Python tools such as multiprocessing.Pool. This parameterized running allows simple management of fairly large projects. If we need to run a great many variations of a notebook we use the JTask container and either a for loop or multiprocessing.Pool over the tasks in Python (remember, when we have Python we don't have to perform all steps at the GUI or even in a shell!). A small example of the method is found here, where a single Jupyter notebook ParamExample.ipynb is used by run_examples.py to produce the multiple per-date HTML, PDF, and PNG files found in the directory.

We have found the quickest development workflow is to work with the ".ipynb" Jupyter notebooks (usually in Visual Studio Code, and settng any values that were supposed to come from the wvpy.render_workbook by hand after checking they are not set in globals()). Then when the worksheet is working we convert it to ".py" using wvpy.pysheet and check that in to source control.

As a side-note, I find Python is a developer first community, which is very refreshing. Capabilities (such as Jupyter, nbconvert, and nbformat) are released as code under generous open source licenses and documentation instead of being trapped in monolithic applications. This means one can take advantage of their capabilities using only a small amount of code. And under the mentioned assumption that Python is a developer first community, small amounts of code are considered easy integrations. wvpy is offered in the same spirit, it is available for use from PyPi here under a BSD 3-clause License and has it code available here for re-use or adaption here under the same license. It isn't a big project, but it has made working on client projects and teaching data science a bit easier for me.

Win Vector LLC will be offering private (and hopefully someday public) training on the work flow (including notebook parameterization to run many jobs from a single source, use of multiprocessing.Pool for speedup, and IPython.display.display; IPython.display.Markdown for custom results) going forward.