Using nbconvert as a library

In this notebook, you will be introduced to the programmatic API of nbconvert and how it can be used in various contexts.

A great blog post by @jakevdp will be used to demonstrate. This notebook will not focus on using the command line tool. The attentive reader will point-out that no data is read from or written to disk during the conversion process. This is because nbconvert has been designed to work in memory so that it works well in a database or web-based environment too.

Quick overview

Credit: Jonathan Frederic (@jdfreder on github)

The main principle of nbconvert is to instantiate an Exporter that controls the pipeline through which notebooks are converted.

First, download @jakevdp’s notebook (if you do not have requests, install it by running pip install requests, or if you don’t have pip installed, you can find it on PYPI):

[1]:
from urllib.request import urlopen

url = 'https://jakevdp.github.io/downloads/notebooks/XKCD_plots.ipynb'
response = urlopen(url).read().decode()
response[0:60] + ' ...'
---------------------------------------------------------------------------
gaierror                                  Traceback (most recent call last)
File /usr/lib64/python3.11/urllib/request.py:1348, in AbstractHTTPHandler.do_open(self, http_class, req, **http_conn_args)
   1347 try:
-> 1348     h.request(req.get_method(), req.selector, req.data, headers,
   1349               encode_chunked=req.has_header('Transfer-encoding'))
   1350 except OSError as err: # timeout error

File /usr/lib64/python3.11/http/client.py:1282, in HTTPConnection.request(self, method, url, body, headers, encode_chunked)
   1281 """Send a complete request to the server."""
-> 1282 self._send_request(method, url, body, headers, encode_chunked)

File /usr/lib64/python3.11/http/client.py:1328, in HTTPConnection._send_request(self, method, url, body, headers, encode_chunked)
   1327     body = _encode(body, 'body')
-> 1328 self.endheaders(body, encode_chunked=encode_chunked)

File /usr/lib64/python3.11/http/client.py:1277, in HTTPConnection.endheaders(self, message_body, encode_chunked)
   1276     raise CannotSendHeader()
-> 1277 self._send_output(message_body, encode_chunked=encode_chunked)

File /usr/lib64/python3.11/http/client.py:1037, in HTTPConnection._send_output(self, message_body, encode_chunked)
   1036 del self._buffer[:]
-> 1037 self.send(msg)
   1039 if message_body is not None:
   1040
   1041     # create a consistent interface to message_body

File /usr/lib64/python3.11/http/client.py:975, in HTTPConnection.send(self, data)
    974 if self.auto_open:
--> 975     self.connect()
    976 else:

File /usr/lib64/python3.11/http/client.py:1447, in HTTPSConnection.connect(self)
   1445 "Connect to a host on a given (SSL) port."
-> 1447 super().connect()
   1449 if self._tunnel_host:

File /usr/lib64/python3.11/http/client.py:941, in HTTPConnection.connect(self)
    940 sys.audit("http.client.connect", self, self.host, self.port)
--> 941 self.sock = self._create_connection(
    942     (self.host,self.port), self.timeout, self.source_address)
    943 # Might fail in OSs that don't implement TCP_NODELAY

File /usr/lib64/python3.11/socket.py:826, in create_connection(address, timeout, source_address, all_errors)
    825 exceptions = []
--> 826 for res in getaddrinfo(host, port, 0, SOCK_STREAM):
    827     af, socktype, proto, canonname, sa = res

File /usr/lib64/python3.11/socket.py:961, in getaddrinfo(host, port, family, type, proto, flags)
    960 addrlist = []
--> 961 for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
    962     af, socktype, proto, canonname, sa = res

gaierror: [Errno -3] Temporary failure in name resolution

During handling of the above exception, another exception occurred:

URLError                                  Traceback (most recent call last)
Cell In [1], line 4
      1 from urllib.request import urlopen
      3 url = 'https://jakevdp.github.io/downloads/notebooks/XKCD_plots.ipynb'
----> 4 response = urlopen(url).read().decode()
      5 response[0:60] + ' ...'

File /usr/lib64/python3.11/urllib/request.py:216, in urlopen(url, data, timeout, cafile, capath, cadefault, context)
    214 else:
    215     opener = _opener
--> 216 return opener.open(url, data, timeout)

File /usr/lib64/python3.11/urllib/request.py:519, in OpenerDirector.open(self, fullurl, data, timeout)
    516     req = meth(req)
    518 sys.audit('urllib.Request', req.full_url, req.data, req.headers, req.get_method())
--> 519 response = self._open(req, data)
    521 # post-process response
    522 meth_name = protocol+"_response"

File /usr/lib64/python3.11/urllib/request.py:536, in OpenerDirector._open(self, req, data)
    533     return result
    535 protocol = req.type
--> 536 result = self._call_chain(self.handle_open, protocol, protocol +
    537                           '_open', req)
    538 if result:
    539     return result

File /usr/lib64/python3.11/urllib/request.py:496, in OpenerDirector._call_chain(self, chain, kind, meth_name, *args)
    494 for handler in handlers:
    495     func = getattr(handler, meth_name)
--> 496     result = func(*args)
    497     if result is not None:
    498         return result

File /usr/lib64/python3.11/urllib/request.py:1391, in HTTPSHandler.https_open(self, req)
   1390 def https_open(self, req):
-> 1391     return self.do_open(http.client.HTTPSConnection, req,
   1392         context=self._context, check_hostname=self._check_hostname)

File /usr/lib64/python3.11/urllib/request.py:1351, in AbstractHTTPHandler.do_open(self, http_class, req, **http_conn_args)
   1348         h.request(req.get_method(), req.selector, req.data, headers,
   1349                   encode_chunked=req.has_header('Transfer-encoding'))
   1350     except OSError as err: # timeout error
-> 1351         raise URLError(err)
   1352     r = h.getresponse()
   1353 except:

URLError: <urlopen error [Errno -3] Temporary failure in name resolution>

The response is a JSON string which represents a Jupyter notebook.

Next, we will read the response using nbformat. Doing this will guarantee that the notebook structure is valid. Note that the in-memory format and on disk format are slightly different. In particular, on disk, multiline strings might be split into a list of strings.

[2]:
import nbformat
jake_notebook = nbformat.reads(response, as_version=4)
jake_notebook.cells[0]
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In [2], line 2
      1 import nbformat
----> 2 jake_notebook = nbformat.reads(response, as_version=4)
      3 jake_notebook.cells[0]

NameError: name 'response' is not defined

The nbformat API returns a special type of dictionary. For this example, you don’t need to worry about the details of the structure (if you are interested, please see the nbformat documentation).

The nbconvert API exposes some basic exporters for common formats and defaults. You will start by using one of them. First, you will import one of these exporters (specifically, the HTML exporter), then instantiate it using most of the defaults, and then you will use it to process the notebook we downloaded earlier.

[3]:
from traitlets.config import Config

# 1. Import the exporter
from nbconvert import HTMLExporter

# 2. Instantiate the exporter. We use the `classic` template for now; we'll get into more details
# later about how to customize the exporter further.
html_exporter = HTMLExporter(template_name = 'classic')

# 3. Process the notebook we loaded earlier
(body, resources) = html_exporter.from_notebook_node(jake_notebook)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In [3], line 11
      8 html_exporter = HTMLExporter(template_name = 'classic')
     10 # 3. Process the notebook we loaded earlier
---> 11 (body, resources) = html_exporter.from_notebook_node(jake_notebook)

NameError: name 'jake_notebook' is not defined

The exporter returns a tuple containing the source of the converted notebook, as well as a resources dict. In this case, the source is just raw HTML:

[4]:
print(body[:400] + '...')
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In [4], line 1
----> 1 print(body[:400] + '...')

NameError: name 'body' is not defined

If you understand HTML, you’ll notice that some common tags are omitted, like the body tag. Those tags are included in the default HtmlExporter, which is what would have been constructed if we had not modified the template_file.

The resource dict contains (among many things) the extracted .png, .jpg, etc. from the notebook when applicable. The basic HTML exporter leaves the figures as embedded base64, but you can configure it to extract the figures. So for now, the resource dict should be mostly empty, except for a key containing CSS and a few others whose content will be obvious:

[5]:
print("Resources:", resources.keys())
print("Metadata:", resources['metadata'].keys())
print("Inlining:", resources['inlining'].keys())
print("Extension:", resources['output_extension'])
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In [5], line 1
----> 1 print("Resources:", resources.keys())
      2 print("Metadata:", resources['metadata'].keys())
      3 print("Inlining:", resources['inlining'].keys())

NameError: name 'resources' is not defined

Exporters are stateless, so you won’t be able to extract any useful information beyond their configuration. You can re-use an exporter instance to convert another notebook. In addition to the from_notebook_node used above, each exporter exposes from_file and from_filename methods.

Extracting Figures using the RST Exporter

When exporting, you may want to extract the base64 encoded figures as files. While the HTML exporter does not do this by default, the RstExporter does:

[6]:
# Import the RST exproter
from nbconvert import RSTExporter
# Instantiate it
rst_exporter = RSTExporter()
# Convert the notebook to RST format
(body, resources) = rst_exporter.from_notebook_node(jake_notebook)

print(body[:970] + '...')
print('[.....]')
print(body[800:1200] + '...')
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In [6], line 6
      4 rst_exporter = RSTExporter()
      5 # Convert the notebook to RST format
----> 6 (body, resources) = rst_exporter.from_notebook_node(jake_notebook)
      8 print(body[:970] + '...')
      9 print('[.....]')

NameError: name 'jake_notebook' is not defined

Notice that base64 images are not embedded, but instead there are filename-like strings, such as output_3_0.png. The strings actually are (configurable) keys that map to the binary data in the resources dict.

Note, if you write an RST Plugin, you are responsible for writing all the files to the disk (or uploading, etc…) in the right location. Of course, the naming scheme is configurable.

As an exercise, this notebook will show you how to get one of those images. First, take a look at the 'outputs' of the returned resources dictionary. This is a dictionary that contains a key for each extracted resource, with values corresponding to the actual base64 encoding:

[7]:
sorted(resources['outputs'].keys())
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In [7], line 1
----> 1 sorted(resources['outputs'].keys())

NameError: name 'resources' is not defined

In this case, there are 5 extracted binary figures, all pngs. We can use the Image display object to actually display one of the images:

[8]:
from IPython.display import Image
Image(data=resources['outputs']['output_3_0.png'], format='png')
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In [8], line 2
      1 from IPython.display import Image
----> 2 Image(data=resources['outputs']['output_3_0.png'], format='png')

NameError: name 'resources' is not defined

Note that this image is being rendered without ever reading or writing to the disk.

Extracting Figures using the HTML Exporter

As mentioned above, by default, the HTML exporter does not extract images – it just leaves them as inline base64 encodings. However, this is not always what you might want. For example, here is a use case from @jakevdp:

I write an awesome blog using Jupyter notebooks converted to HTML, and I want the images to be cached. Having one html file with all of the images base64 encoded inside it is nice when sharing with a coworker, but for a website, not so much. I need an HTML exporter, and I want it to extract the figures!

Some theory

Before we get into actually extracting the figures, it will be helpful to give a high-level overview of the process of converting a notebook to a another format:

  1. Retrieve the notebook and it’s accompanying resources (you are responsible for this).

  2. Feed the notebook into the Exporter, which:

    1. Sequentially feeds the notebook into an array of Preprocessors. Preprocessors only act on the structure of the notebook, and have unrestricted access to it.

    2. Feeds the notebook into the Jinja templating engine, which converts it to a particular format depending on which template is selected.

  3. The exporter returns the converted notebook and other relevant resources as a tuple.

  4. You write the data to the disk using the built-in FilesWriter (which writes the notebook and any extracted files to disk), or elsewhere using a custom Writer.

Using different preprocessors

To extract the figures when using the HTML exporter, we will want to change which Preprocessors we are using. There are several preprocessors that come with nbconvert, including one called the ExtractOutputPreprocessor.

The ExtractOutputPreprocessor is responsible for crawling the notebook, finding all of the figures, and putting them into the resources directory, as well as choosing the key (i.e. filename_xx_y.extension) that can replace the figure inside the template. To enable the ExtractOutputPreprocessor, we must add it to the exporter’s list of preprocessors:

[9]:
# create a configuration object that changes the preprocessors
from traitlets.config import Config
c = Config()
c.HTMLExporter.preprocessors = ['nbconvert.preprocessors.ExtractOutputPreprocessor']

# create the new exporter using the custom config
html_exporter_with_figs = HTMLExporter(config=c)
html_exporter_with_figs.preprocessors
[9]:
['nbconvert.preprocessors.ExtractOutputPreprocessor']

We can compare the result of converting the notebook using the original HTML exporter and our new customized one:

[10]:
(_, resources)          = html_exporter.from_notebook_node(jake_notebook)
(_, resources_with_fig) = html_exporter_with_figs.from_notebook_node(jake_notebook)

print("resources without figures:")
print(sorted(resources.keys()))

print("\nresources with extracted figures (notice that there's one more field called 'outputs'):")
print(sorted(resources_with_fig.keys()))

print("\nthe actual figures are:")
print(sorted(resources_with_fig['outputs'].keys()))
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In [10], line 1
----> 1 (_, resources)          = html_exporter.from_notebook_node(jake_notebook)
      2 (_, resources_with_fig) = html_exporter_with_figs.from_notebook_node(jake_notebook)
      4 print("resources without figures:")

NameError: name 'jake_notebook' is not defined

Custom Preprocessors

There are an endless number of transformations that you may want to apply to a notebook. In particularly complicated cases, you may want to actually create your own Preprocessor. Above, when we customized the list of preprocessors accepted by the HTMLExporter, we passed in a string – this can be any valid module name. So, if you create your own preprocessor, you can include it in that same list and it will be used by the exporter.

To create your own preprocessor, you will need to subclass from nbconvert.preprocessors.Preprocessor and overwrite either the preprocess and/or preprocess_cell methods.

Example

The following demonstration adds the ability to exclude a cell by index.

Note: injecting cells is similar, and won’t be covered here. If you want to inject static content at the beginning/end of a notebook, use a custom template.

[11]:
from traitlets import Integer
from nbconvert.preprocessors import Preprocessor

class PelicanSubCell(Preprocessor):
    """A Pelican specific preprocessor to remove some of the cells of a notebook"""

    # I could also read the cells from nb.metadata.pelican if someone wrote a JS extension,
    # but for now I'll stay with configurable value.
    start = Integer(0,  help="first cell of notebook to be converted").tag(config=True)
    end   = Integer(-1, help="last cell of notebook to be converted").tag(config=True)

    def preprocess(self, nb, resources):
        self.log.info("I'll keep only cells from %d to %d", self.start, self.end)
        nb.cells = nb.cells[self.start:self.end]
        return nb, resources

Here a Pelican exporter is created that takes PelicanSubCell preprocessors and a config object as parameters. This may seem redundant, but with the configuration system you can register an inactive preprocessor on all of the exporters and activate it from config files or the command line.

[12]:
# Create a new config object that configures both the new preprocessor, as well as the exporter
c =  Config()
c.PelicanSubCell.start = 4
c.PelicanSubCell.end = 6
c.RSTExporter.preprocessors = [PelicanSubCell]

# Create our new, customized exporter that uses our custom preprocessor
pelican = RSTExporter(config=c)

# Process the notebook
print(pelican.from_notebook_node(jake_notebook)[0])
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In [12], line 11
      8 pelican = RSTExporter(config=c)
     10 # Process the notebook
---> 11 print(pelican.from_notebook_node(jake_notebook)[0])

NameError: name 'jake_notebook' is not defined

Programmatically creating templates

[13]:
from jinja2 import DictLoader

dl = DictLoader({'footer':
"""
{%- extends 'lab/index.html.j2' -%}

{% block footer %}
FOOOOOOOOTEEEEER
{% endblock footer %}
"""})


exportHTML = HTMLExporter(extra_loaders=[dl], template_file='footer')
(body, resources) = exportHTML.from_notebook_node(jake_notebook)
for l in body.split('\n')[-4:]:
    print(l)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In [13], line 14
      3 dl = DictLoader({'footer':
      4 """
      5 {%- extends 'lab/index.html.j2' -%} 
   (...)
      9 {% endblock footer %}
     10 """})
     13 exportHTML = HTMLExporter(extra_loaders=[dl], template_file='footer')
---> 14 (body, resources) = exportHTML.from_notebook_node(jake_notebook)
     15 for l in body.split('\n')[-4:]:
     16     print(l)

NameError: name 'jake_notebook' is not defined

Real World Uses

@jakevdp uses Pelican and Jupyter Notebook to blog. Pelican will use nbconvert programmatically to generate blog post. Have a look a Pythonic Preambulations for Jake’s blog post.

@damianavila wrote the Nikola Plugin to write blog post as Notebooks and is developing a js-extension to publish notebooks via one click from the web app.