Each interactive element presented on this page uses time-consuming operations that take a while to finish. The elements are built through a backend in the cloud. Please be patient to see the results. |
The package nbinteract aims to enable authors and educators to create and share interactive web pages easily. Interactive explanations of concepts are useful for communicating and explaining tricky concepts. Consider these explanations for linear regression and conditional probability, for example.
However, making an interactive web page often requires significant knowledge of web technologies, especially Javascript. While Jupyter widgets allow authors to generate interactive interfaces directly in a Jupyter notebook, sharing these demos typically requires the readers to run the notebook. Th missing knowledge causes issues when the reader’s computer lacks the correct versions of the packages required to run the notebook completely.
The library nbinteract
provides a single binary that converts Jupyter notebooks into HTML pages. The resulting HTML pages can be shared with the public, keeping any interactivity created using Jupyter widgets. For example, the interactive parts of this website are entirely generated from notebooks using nbinteract
.
In addition, nbinteract
provides a Python package. Once imported, the package provides helper methods that allow users to create simple interactive visualizations with single function calls.
This document is a port for J1 Template of the original document pages at nbinteract Docs. Some sections are rewritten for the text to improve clarity and simplify the language for future translation. Meanwhile, a lot of changes were done for the services at Binder, which causes the original pages doesn’t work anymore. On clicking the NBI button |
Getting Started
The following pages will show you how to use nbinteract
and its related tools. At the end of this tutorial, you will have a publicly accessible interactive webpage to share with others!
The pages assumes familiarity with running terminal commands and using Jupyter notebooks. The simplest way to follow this tutorial is to use the Binder service to start a notebook server. On the next page, we’ll guide you through the steps to configure Binder so that the necessary packages are available for use in notebooks.
Local installation
If you prefer to work with Jupyter Notebook on your local machine, you need to install the nbinteract
package on your PC. To install the package, run the following commands in your terminal:
pip install nbinteract
# The next two commands can be skipped for notebook version 5.3 and above
jupyter nbextension enable --py --sys-prefix bqplot
jupyter nbextension enable --py --sys-prefix widgetsnbextension
To work locally, a full setup of a Python language versions is required. |
Setup steps
Enable interactive notebooks on webpages using nbinteract
relies on the free Binder service. To configure Binder to run your webpages, we will create a GitHub repository that will allow you to host your converted webpages publicly.
Creating a public repo at Github
To begin, visit Github and create an account. If you already have an account, you should log in.
Then, create a new repo. You may do this using the GitHub UI or by visiting create new repo at Github. Name the repo nbinteract-tutorial. If you’d like a different name, feel free to name it something else; keep in mind that we will use this repo name later in the tutorial.
Make sure your repo is public, and click the checkbox to initialize your repo with a README. Your page should look like this:
Now, click on the Settings link for the repo near the top of the page, scroll down to the GitHub Pages section, and select the main branch as the GitHub pages source. Click the Save button to save your changes.
Any file you upload to this repo will have a public URL. For example, the README.md file in the repo has the following URL:
{username}.github.io/nbinteract-tutorial/README.md
Where {username}
is replaced with your GitHub username. For example, if my username is SamLau95, my URL is:
SamLau95.github.io/nbinteract-tutorial/README.md
If you can visit that URL and the page contains text (and not a 404 error), you’ve set up your GitHub repo correctly.
Cloning your repo
Now, visit Binder and paste the URL to your repo. It should look like this:
https://github.com/{username}/nbinteract-tutorial
Where {username} is replaced with your GitHub username.
Launch the Binder server to open Jupyter. If you are working locally, you should instead run the following commands in your terminal:
# Clone the repo
git clone https://github.com/{username}/nbinteract-tutorial
# Move into the repo directory
cd nbinteract-tutorial
# Start Jupyter
jupyter notebook
Initializing nbinteract
Via the notebook interface, click on New → Terminal
. On clicking, this should open a terminal prompt. Run the following commands:
# Installs nbinteract
pip install nbinteract
# Initializes nbinteract. When prompted, create a requirements.txt file. Since we aren't
# adding additional packages in this tutorial, re-run the command to finish initialization.
nbinteract init
git add -A
git commit -m "Setup nbinteract"
git push origin main
The commands initialize the nbinteract
package and push the configuration files to GitHub. If you are working locally, skip the pip install command above and run the remaining commands in your terminal.
Publishing a Webpage
To convert a notebook into an HTML file, start a terminal and run the following command.
nbinteract tutorial.ipynb
The command generates a HTML file tutorial.html
with the notebook’s contents created in the previous section. Now, push your files to GitHub by running:
git add -A
git commit -m "Publish nb"
git push origin main
After pushing, you now have a URL you can view and share:
{username}.github.io/nbinteract-tutorial/tutorial.html
Where {username}
is replaced with your GitHub username. For example, if my username is SamLau95, my URL is:
SamLau95.github.io/nbinteract-tutorial/tutorial.html
Publishing to a different URL
To change the URL of the page you publish, you can rename your notebook before you convert it. For example, if you rename tutorial.ipynb
to hello.ipynb
and convert the notebook, the resulting URL becomes:
{username}.github.io/nbinteract-tutorial/hello.html
To change the path segment before the filename (nbinteract-tutorial), you can create a new GitHub repo with the subpath name you want. Then, you may create and convert notebooks in this repo. For example, if you create a new repo called blog-posts and convert a notebook called tutorial.ipynb, the resulting URL becomes:
{username}.github.io/blog-posts/tutorial.html
Workflow
You have learned a simple workflow to create interactive webpages:
-
write a Jupyter notebook containing Python functions
-
use interact to create UI elements to interact with the functions.
-
zun nbinteract {notebook} in a terminal to generate an interactive webpage using your notebook code.
-
publish your webpage to GitHub pages to make it publicly accessible.
In the next section, you will create an interactive simulation of the Monty Hall Problem. Onward!
Recipes
The Recipes section shows in simple steps how to use nbinteract
. In addition to the classic widgets provided by Juypter Notebook, nbinteract
offers additional interactive elements.
Exporting with nbinteract
Installing the nbinteract
package installs a command-line tool for converting notebooks into HTML pages. For example, to convert a notebook called Hello.ipynb
using the Binder spec calebs11/nbinteract-image/main
:
# `main` is optional since it is the default
nbinteract Hello.ipynb -s calebs11/nbinteract-image
After running nbinteract init, you may omit the -s flag and simply write:
nbinteract Hello.ipynb
One advantage of the command line tool is that it can convert notebooks in folders as well as individual notebooks:
# Using the -r flag tells nbinteract to recursively search for .ipynb files
# in nb_folder
nbinteract -r nb_folder/
For the complete set of options, run nbinteract --help.
$ nbinteract --help
`nbinteract NOTEBOOKS ...` converts notebooks into HTML pages. Note that running this command outside a GitHub project initialized with `nbinteract init` requires you to specify the --spec SPEC option. Arguments: NOTEBOOKS List of notebooks or folders to convert. If folders are passed in, all the notebooks in each folder are converted. The resulting HTML files are created adjacent to their originating notebooks and will clobber existing files of the same name. By default, notebooks in subfolders will not be converted; use the --recursive flag to recursively convert notebooks in subfolders. Options: -h --help Show this screen -s SPEC --spec SPEC BinderHub spec for Jupyter image. Must be in the format: `{username}/{repo}/{branch}`. For example: 'SamLau95/nbinteract-image/master'. This flag is **required** unless a .nbinteract.json file exists in the project root with the "spec" key. If branch is not specified, default to `main`. -t TYPE --template TYPE Specifies the type of HTML page to generate. Valid types: full (standalone page), partial (embeddable page with library), or plain (embeddable page without JS). [default: full] -B --no-top-button If set, doesn't generate button at top of page. -r --recursive Recursively convert notebooks in subdirectories. -o FOLDER --output=FOLDER Outputs HTML files into FOLDER instead of outputting files adjacent to their originating notebooks. All files will be direct descendants of the folder even if --recursive is set. -i FOLDER --images=FOLDER Extracts images from HTML and writes into FOLDER instead of encoding images in base64 in the HTML. Requires -o option to be set as well. -e --execute Executes the notebook before converting to HTML, functioning like the equivalent flag for nbconvert. Configure NbiExecutePreprocessor to change conversion instead of the base ExecutePreprocessor.
The method nbi.publish()
The nbi.publish()
method can be run inside a Jupyter notebook cell. It has the following signature:
import nbinteract as nbi
nbi.publish(spec, nb_name, template='full', save_first=True)
Converts nb_name to an HTML file. Preserves widget functionality. Outputs a link to download HTML file after conversion if called in a notebook environment. Equivalent to running `nbinteract ${spec} ${nb_name}` on the command line. Args: spec (str): BinderHub spec for Jupyter image. Must be in the format: `${username}/${repo}/${branch}`. nb_name (str): Complete name of the notebook file to convert. Can be a relative path (eg. './foo/test.ipynb'). template (str): Template to use for conversion. Valid templates: - 'full': Outputs a complete standalone HTML page with default styling. Automatically loads the nbinteract JS library. - 'partial': Outputs an HTML partial that can be embedded in another page. Automatically loads the nbinteract JS library. - 'gitbook': Outputs an HTML partial used to embed in a Gitbook or other environments where the nbinteract JS library is already loaded. save_first (bool): If True, saves the currently opened notebook before converting nb_name. Used to ensure notebook is written to filesystem before starting conversion. Does nothing if not in a notebook environment. Returns: None
For example, to convert a notebook called Hello.ipynb using the Binder spec calebs11/nbinteract-image/main
:
nbi.publish('calebs11/nbinteract-image/main', 'Hello.ipynb')
Examples
For more examples of interactive notebooks, see this section. The examples show a selection of specific learning content at colleges and universities on statistical issues.