--- title: NBI docs tagline: creating interactive websites date: 2022-03-28 00:00:00 description: > 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. keywords: > opensource, free, load, download, start, starter, example, high, easy, use, secure, encrypt, standard, popular, generate, create, learn, distribute, publish, deploy, beginner, advanced, expert, student, learner, writer, reader, visitor framework, toolkit, integration, extension, module, api, dynamic, static, generator, client, server, internet, local, localhost page, web, website, webdesign, material, design, responsive, javascript, nodejs, ruby, windows, linux, osx, mac, os, http, https, html, html5, css, scss, style, browser, firefox, chrome, edge, opera, safari, configuration, generator, navigation, menu, dropdown, fab, action, button application, interface, provider, api, repository, cookie, language, translation, gdpr, dsgvo, privacy, asciidoc, aciidoctor, bootstrap, jekyll, liquid, hyvor, disqus, git, github, netlify, heroku, apple, microsoft, provider, service, internet, support, google, analytics, advertising, search, console, silverlight, score, j1, template, jekyllone, comment, python, jupyter, notebook, textbook, api, app, nbinteract, nbi, integration, binder, binderhub, jupyterhub categories: [ Software, Python ] tags: [ Binder, Jupyter, Notebooks ] scrollbar: false fab_menu_id: open_toc_reload personalization: true permalink: /pages/public/jupyter/textbooks/nbinteract-docs/ regenerate: false resources: [ nbinteract, rouge ] resource_options: - attic: padding_top: 400 padding_bottom: 50 opacity: 0.5 slides: - url: /assets/images/modules/attics/john-schnobrich-2-1920x1280.jpg alt: Photo by John Schnobrich on Unsplash badge: type: unsplash author: John Schnobrich href: https://unsplash.com/@johnschno --- // Page Initializer // ============================================================================= // Enable the Liquid Preprocessor :page-liquid: // Set (local) page attributes here // ----------------------------------------------------------------------------- // :page--attr: :badges-enabled: true :binder-badge-enabled: false :binder--home: https://mybinder.org/ :binder--docs: https://mybinder.readthedocs.io/en/latest/ :binder-app-launch--tree: https://mybinder.org/v2/gh/jekyll-one/nbinteract-notebooks/main?urlpath=/tree // Load Liquid procedures // ----------------------------------------------------------------------------- {% capture load_attributes %}themes/{{site.template.name}}/procedures/global/attributes_loader.proc{%endcapture%} // Load page attributes // ----------------------------------------------------------------------------- {% include {{load_attributes}} scope="global" %} // Page content // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Include sub-documents (if any) // ----------------------------------------------------------------------------- // image:/assets/images/badges/myBinder.png[Binder, link="https://mybinder.org/", {browser-window--new}] // image:/assets/images/badges/docsBinder.png[Binder, link="https://mybinder.readthedocs.io/en/latest/", {browser-window--new}] ifeval::[{binder-badges-enabled} == true] image:https://mybinder.org/badge_logo.svg[Binder, link="{binder-app-launch--tree}", {browser-window--new}] endif::[] [NOTE] ==== This document is a port for J1 Template of the original document pages at link:{url-nbinteract--docs}[nbinteract Docs, {browser-window--new}]. 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 link:{url-binder--home}[Binder, {browser-window--new} ], which causes the original pages doesn't work anymore. On clicking the NBI button `Show Widgets`, you'll encounter that all interactive pages never change their state and get stuck in `Initializing widgets...` for an infinite initializing loop. ==== 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. == 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: [source, sh] ---- 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 ---- WARNING: 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 https://github.com[Github, {browser-window--new}] 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 https://github.com/new[create new repo at Github, {browser-window--new}]. 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: // image gh-repo-setup 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. // image gh-pages-setup 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 http://mybinder.org/[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: [source, sh] ---- # 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: [source, sh] ---- # 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. textbook::nbi_docs_tutorial_interact[] === Publishing a Webpage To convert a notebook into an HTML file, start a terminal and run the following command. [source, sh] ---- 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: [source, sh] ---- 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! textbook::nbi_docs_tutorial_monty_hall[] == 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`: [source, sh] ---- # `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: [source, sh] ---- nbinteract Hello.ipynb ---- One advantage of the command line tool is that it can convert notebooks in folders as well as individual notebooks: [source, sh] ---- # 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. [source, sh] ---- $ 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: [source, python] ---- 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`: [source, sh] ---- nbi.publish('calebs11/nbinteract-image/main', 'Hello.ipynb') ---- textbook::nbi_docs_recipes_graphing[] textbook::nbi_docs_recipes_layout[] textbook::nbi_docs_recipes_interactive_questions[] == 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. textbook::nbi_docs_empirical_distributions[] textbook::nbi_docs_examples_sampling_from_a_population[] textbook::nbi_docs_examples_variability_of_the_sample_mean[] textbook::nbi_docs_examples_correlation[] textbook::nbi_docs_examples_linear_regression[] textbook::nbi_docs_central_limit_theorem[]