### Complete conf.py Example for nbsphinx Source: https://context7.com/spatialaudio/nbsphinx/llms.txt This Python code snippet demonstrates a comprehensive configuration file for nbsphinx, a Sphinx extension for integrating Jupyter Notebooks. It covers essential settings such as required extensions, project information, notebook execution parameters, prompt customization, thumbnail generation, and intersphinx mappings. This example provides a robust starting point for setting up nbsphinx in a Sphinx project. ```python # conf.py import os # Required extension extensions = [ 'nbsphinx', 'sphinx.ext.mathjax', 'sphinx.ext.intersphinx', ] # Project information project = 'My Project' author = 'Author Name' copyright = '2024, Author Name' # Notebook execution settings bsphinx_execute = 'auto' bsphinx_timeout = 120 bsphinx_allow_errors = False bsphinx_kernel_name = 'python3' # Figure format configuration bsphinx_execute_arguments = [ "--InlineBackend.figure_formats={'svg', 'pdf'}", ] # Prompt customization bsphinx_input_prompt = 'In [%s]:' bsphinx_output_prompt = 'Out[%s]:' # Gallery thumbnails bsphinx_thumbnails = { 'examples/*': '_static/default-thumb.png', } # Prolog added before each notebook bsphinx_prolog = r"" {% set docname = env.doc2path(env.docname, base=False)|string %} .. note:: This page was generated from ``{{ docname }}``. " # MathJax configuration mathjax3_config = { 'tex': {'tags': 'ams', 'useLabelIds': True}, } # Exclude patterns exclude_patterns = ['_build', '**.ipynb_checkpoints', 'Thumbs.db'] # HTML output options html_theme = 'sphinx_rtd_theme' html_sourcelink_suffix = '' # LaTeX output options latex_elements = { 'papersize': 'a4paper', } # Intersphinx mapping intersphinx_mapping = { 'python': ('https://docs.python.org/3/', None), 'numpy': ('https://numpy.org/doc/stable/', None), } ``` -------------------------------- ### Run Sphinx Quickstart Source: https://github.com/spatialaudio/nbsphinx/blob/master/doc/usage.ipynb Command to initialize a new Sphinx project. It prompts the user for configuration details and sets up the basic directory structure and files. ```bash python3 -m sphinx.cmd.quickstart ``` -------------------------------- ### Install sphinx-autobuild Source: https://github.com/spatialaudio/nbsphinx/blob/master/doc/usage.ipynb Command to install the sphinx-autobuild package, which provides live reloading for Sphinx documentation builds. ```bash python3 -m pip install sphinx-autobuild ``` -------------------------------- ### Run sphinx-autobuild for Live HTML Source: https://github.com/spatialaudio/nbsphinx/blob/master/doc/usage.ipynb Command to start sphinx-autobuild, which automatically rebuilds HTML documentation and refreshes the browser upon detecting file changes. Serves the documentation at http://localhost:8000/. ```bash python3 -m sphinx_autobuild ``` -------------------------------- ### Create Plot for Documentation Source: https://github.com/spatialaudio/nbsphinx/blob/master/doc/gallery/thumbnail-from-conf-py.ipynb An example of generating a standard plot for display in the notebook documentation, distinct from the thumbnail generation process. ```python fig, ax = plt.subplots(figsize=[6, 3]) ax.plot([4, 9, 7, 20, 6, 33, 13, 23, 16, 62, 8], 'r:'); ``` -------------------------------- ### Python Code Block Example Source: https://github.com/spatialaudio/nbsphinx/blob/master/doc/markdown-cells.ipynb A simple example of a Python code block with syntax highlighting. ```python print("Hello, world!") ``` -------------------------------- ### Example Notebook Code Cell Source: https://github.com/spatialaudio/nbsphinx/blob/master/doc/custom-css.ipynb A simple Python code cell example within a notebook, demonstrating a calculation. ```python 6 * 7 ``` -------------------------------- ### Generate Example Data for Plotting Source: https://github.com/spatialaudio/nbsphinx/blob/master/doc/gallery/cell-metadata.ipynb Creates a 2D dataset 'z' using NumPy based on a mathematical function. This data is intended for visualization purposes, such as creating heatmaps or contour plots. ```python x, y = np.meshgrid(np.arange(-3, 3, 0.1), np.arange(-2, 2, 0.1)) z = (1 - x / 2 + x ** 5 + y ** 3) * np.exp(-x ** 2 - y ** 2) ``` -------------------------------- ### Install nbsphinx using pip Source: https://context7.com/spatialaudio/nbsphinx/llms.txt Installs the nbsphinx package using pip. This is the primary method for adding nbsphinx to your Python environment. ```bash pip install nbsphinx ``` -------------------------------- ### Install nbsphinx with Pip Source: https://github.com/spatialaudio/nbsphinx/blob/master/doc/installation.ipynb Installs or upgrades the nbsphinx package using pip, Python's package installer. This command can be used to install the latest release or update an existing installation. ```bash python3 -m pip install nbsphinx ``` ```bash python3 -m pip install --upgrade nbsphinx ``` -------------------------------- ### Python Domain Object Example Source: https://github.com/spatialaudio/nbsphinx/blob/master/doc/a-normal-rst-file.rst An example demonstrating the use of Sphinx's domain objects, specifically a Python function directive (`py:function`), for documenting code elements and enabling cross-referencing within the documentation. ```rst .. py:function:: example_python_function(foo) This is just for testing domain object links. :param str foo: Example string parameter .. seealso:: ``` -------------------------------- ### Manage Rare Library Dependencies Source: https://github.com/spatialaudio/nbsphinx/blob/master/doc/pre-executed.ipynb Shows how to include code that relies on libraries that are difficult to install or maintain in the build environment. Pre-executing ensures the result is captured without requiring the library at build time. ```python from a_very_rare_library import calculate_the_answer calculate_the_answer() ``` -------------------------------- ### Install nbsphinx with Conda Source: https://github.com/spatialaudio/nbsphinx/blob/master/doc/installation.ipynb Installs the nbsphinx package using the conda package manager from the conda-forge channel. This is recommended for users who manage their Python environments with conda. ```bash conda install -c conda-forge nbsphinx ``` -------------------------------- ### Handling Unsupported MIME Types with nbsphinx Source: https://github.com/spatialaudio/nbsphinx/blob/master/doc/code-cells.ipynb This example shows how nbsphinx handles cells that produce output with unsupported MIME types. Instead of failing silently, nbsphinx displays a warning message, providing better visibility into potential issues. The code demonstrates creating a display object with multiple MIME types. ```python display({ 'text/x-python': 'print("Hello, world!")', 'text/x-haskell': 'main = putStrLn "Hello, world!"', }, raw=True) ``` -------------------------------- ### Apply CSS to Notebooks via conf.py Source: https://github.com/spatialaudio/nbsphinx/blob/master/doc/custom-css.ipynb This Python configuration uses nbsphinx_prolog with a raw HTML directive to inject CSS styles specifically for Jupyter notebooks. The example styles the H1 tags with chartreuse color. ```python nbsphinx_prolog = """ .. raw:: html """ ``` -------------------------------- ### Set Custom Output Prompt for Nbsphinx Source: https://github.com/spatialaudio/nbsphinx/blob/master/doc/configuration.ipynb Configures the output prompt string for code cells in nbsphinx. The '%s' placeholder is replaced by the execution count. This example demonstrates how to set an output prompt similar to the Classic Notebook. ```python nbsphinx_output_prompt = 'Out[%s]:' ``` -------------------------------- ### Set Custom Input Prompt for Nbsphinx Source: https://github.com/spatialaudio/nbsphinx/blob/master/doc/configuration.ipynb Configures the input prompt string for code cells in nbsphinx. The '%s' placeholder is replaced by the execution count. This example shows how to achieve a prompt similar to the Classic Notebook interface. ```python nbsphinx_input_prompt = 'In [%s]:' ``` -------------------------------- ### Apply CSS to RST Files via conf.py Source: https://github.com/spatialaudio/nbsphinx/blob/master/doc/custom-css.ipynb This Python configuration uses rst_prolog with a raw HTML directive to inject CSS styles specifically for RST files. The example styles the H1 tags with fuchsia color. ```python rst_prolog = """ .. raw:: html """ ``` -------------------------------- ### Configure nbsphinx for Markdown files Source: https://github.com/spatialaudio/nbsphinx/blob/master/doc/a-markdown-file.md This configuration snippet enables the use of Markdown files as Sphinx source files by mapping the .md extension to Jupytext's R Markdown reader. It requires the jupytext package to be installed in the environment. ```python nbsphinx_custom_formats = { '.md': ['jupytext.reads', {'fmt': 'Rmd'}], } ``` -------------------------------- ### Example of Cells Causing Errors in nbsphinx (Python) Source: https://github.com/spatialaudio/nbsphinx/blob/master/doc/allow-errors.ipynb Demonstrates code cells within a Jupyter notebook that are expected to raise exceptions. When 'allow_errors' is enabled in the notebook's metadata or globally, these cells will execute without halting the Sphinx build process. The output shows the results of valid code alongside error indications for invalid code. ```python nonsense ``` ```python 42 / 0 ``` ```python 6 * 7 ``` -------------------------------- ### Define Environment Variables for mybinder.org Source: https://github.com/spatialaudio/nbsphinx/blob/master/doc/configuring-kernels.ipynb Configure environment variables for use with mybinder.org by creating a `.binder/start` script. This script should export the desired variables before executing the notebook. ```bash #!/bin/bash export MY_DUMMY_VARIABLE="Hello from .binder/start!" exec "$@" ``` -------------------------------- ### Execute Python Code and Display Output Source: https://github.com/spatialaudio/nbsphinx/blob/master/doc/code-cells.ipynb Demonstrates basic code cell execution, standard output, and standard error handling in Jupyter notebooks. ```python print('Hello, world!') 6 * 7 ``` ```python import sys print("I'll appear on the standard error stream", file=sys.stderr) print("I'll appear on the standard output stream") "I'm the 'normal' output" ``` -------------------------------- ### Configure Read the Docs for nbsphinx Source: https://github.com/spatialaudio/nbsphinx/blob/master/doc/usage.ipynb Configuration files for Read the Docs to build documentation. Includes the .readthedocs.yml build configuration and a requirements.txt file for dependencies. ```yaml version: 2 build: os: ubuntu-22.04 tools: python: "3" python: install: - requirements: doc/requirements.txt ``` ```text ipykernel nbsphinx git+https://github.com/spatialaudio/nbsphinx.git@master ``` -------------------------------- ### Run Sphinx build commands Source: https://context7.com/spatialaudio/nbsphinx/llms.txt Provides various commands to build Sphinx documentation, including generating HTML and LaTeX output, performing parallel builds, checking links, and forcing a full rebuild. These commands are executed from the command line. ```bash # Build HTML output python3 -m sphinx . _build/html # Parallel build with 4 processes python3 -m sphinx . _build/html -j4 # Build LaTeX/PDF output python3 -m sphinx . _build/latex -b latex # Check links in documentation python3 -m sphinx . _build/linkcheck -b linkcheck # Force rebuild all files python3 -m sphinx . _build/html -E ``` -------------------------------- ### Build HTML Documentation with Sphinx Source: https://github.com/spatialaudio/nbsphinx/blob/master/doc/usage.ipynb Command to build HTML documentation from source files, including Jupyter notebooks processed by nbsphinx. Supports parallel builds for faster processing. ```bash python3 -m sphinx ``` ```bash python3 -m sphinx -j ``` ```bash python3 -m sphinx . _build -j4 ``` -------------------------------- ### Configure GitLab CI/CD Source: https://context7.com/spatialaudio/nbsphinx/llms.txt Automates the documentation build and deployment process using GitLab CI/CD pipelines. ```yaml image: python:3-slim variables: PIP: python3 -m pip SPHINX: python3 -m sphinx -W --keep-going --color build-docs: stage: build script: - apt-get update -y - apt-get install -y --no-install-recommends pandoc - $PIP install -r doc/requirements.txt - $SPHINX -d doctrees doc html -b html artifacts: paths: - html ``` -------------------------------- ### Create and Display Xarray Dataset Source: https://github.com/spatialaudio/nbsphinx/blob/master/doc/code-cells.ipynb Demonstrates how to construct an Xarray Dataset from DataArrays and display it. The HTML representation is used in notebook environments, while LaTeX/PDF output falls back to plain text. ```python import xarray as xr a = {} for name in ["t", "q"]: da = xr.DataArray( [[[11, 12, 13], [21, 22, 23], [31, 32, 33]], [[14, 15, 16], [24, 25, 26], [34, 35, 36]]], coords={"level": ["500", "700"], "x": [1, 2, 3], "y": [4, 5, 6]}, name=name, attrs={"param": name} ) a[name] = da ds = xr.Dataset(a, attrs={"title": "Demo dataset", "year": 2024}) ds ``` -------------------------------- ### Configure GitLab CI/CD for Documentation Deployment Source: https://github.com/spatialaudio/nbsphinx/blob/master/doc/usage.ipynb A .gitlab-ci.yml configuration to build and deploy documentation using Sphinx and nbsphinx on GitLab Pages. ```yaml image: python:3-slim variables: PIP: python3 -m pip SPHINX: python3 -m sphinx -W --keep-going --color build-docs: stage: build script: - apt-get update -y - apt-get install -y --no-install-recommends pandoc - $PIP install -r doc/requirements.txt - $SPHINX -d doctrees doc html -b html - $SPHINX -d doctrees doc linkcheck -b linkcheck artifacts: when: always paths: - html - linkcheck/output.* pages: stage: deploy variables: GIT_STRATEGY: none script: - mv html public artifacts: paths: - public rules: - if: $CI_COMMIT_REF_NAME == $CI_DEFAULT_BRANCH ``` -------------------------------- ### Documenting Exceptions Source: https://github.com/spatialaudio/nbsphinx/blob/master/doc/pre-executed.ipynb Illustrates how to present code that intentionally raises an exception. Pre-executing allows the error trace to be saved and displayed in the documentation. ```python 1 / 0 ``` -------------------------------- ### Suppress Warnings Configuration in Sphinx Source: https://github.com/spatialaudio/nbsphinx/blob/master/doc/configuration.ipynb Allows silencing specific Sphinx warnings. This is useful when you are aware of a warning and choose to ignore it. The example shows how to suppress all warnings originating from 'nbsphinx' or specific nbsphinx modules. ```python suppress_warnings = [ 'nbsphinx', ] ``` ```python suppress_warnings = [ 'nbsphinx.localfile', 'nbsphinx.gallery', 'nbsphinx.thumbnail', 'nbsphinx.notebooktitle', 'nbsphinx.ipywidgets', ] ``` -------------------------------- ### Configure nbsphinx Epilog Source: https://github.com/spatialaudio/nbsphinx/blob/master/doc/markdown-cells.ipynb Demonstrates how to set the nbsphinx_epilog configuration variable in the conf.py file. ```python nbsphinx_epilog = r""" .. footbibliography:: """ ``` -------------------------------- ### Define Thumbnail via nbsphinx-thumbnail Tag Source: https://github.com/spatialaudio/nbsphinx/blob/master/doc/gallery/cell-tag.ipynb This snippet demonstrates the standard matplotlib setup for generating a plot. When this cell is tagged with 'nbsphinx-thumbnail' in the notebook metadata, nbsphinx will use this specific plot as the thumbnail for the document. ```python import matplotlib.pyplot as plt fig, ax = plt.subplots(figsize=[6, 3]) ax.plot([4, 9, 7, 20, 6, 33, 13, 23, 16, 62, 8]) ``` -------------------------------- ### Configure nbsphinx Thumbnails and Galleries Source: https://context7.com/spatialaudio/nbsphinx/llms.txt Maps notebooks to thumbnail images and uses the nbgallery directive to generate visual galleries. ```python nbsphinx_thumbnails = { 'notebooks/example': 'images/example-thumb.png', 'gallery/*': 'images/default-gallery-thumb.png', 'tutorials/*-beginner': 'images/beginner-thumb.png', 'gallery/featured': 'images/featured-thumb.png', } ``` ```rst .. nbgallery:: :caption: Example Gallery :name: example-gallery :glob: gallery/* ``` -------------------------------- ### Interactive Widgets and Linking Source: https://github.com/spatialaudio/nbsphinx/blob/master/doc/code-cells.ipynb Demonstrates creating ipywidgets, synchronizing state across multiple views, and linking widget values using kernel-based (link/dlink) or client-side (jslink/jsdlink) methods. ```python import ipywidgets as w slider = w.IntSlider() slider.value = 42 link = w.IntSlider(description='link') w.link((slider, 'value'), (link, 'value')) jslink = w.IntSlider(description='jslink') w.jslink((slider, 'value'), (jslink, 'value')) dlink = w.IntSlider(description='dlink') w.dlink((slider, 'value'), (dlink, 'value')) jsdlink = w.IntSlider(description='jsdlink') w.jsdlink((slider, 'value'), (jsdlink, 'value')) w.VBox([link, jslink, dlink, jsdlink]) ``` -------------------------------- ### Apply CSS to a Single Notebook Source: https://github.com/spatialaudio/nbsphinx/blob/master/doc/custom-css.ipynb This HTML snippet can be placed directly into a Markdown cell within a Jupyter notebook to apply custom CSS styles only to that specific notebook. This example hides the input and output prompts. ```html ``` -------------------------------- ### Display Rich Media and LaTeX Source: https://github.com/spatialaudio/nbsphinx/blob/master/doc/code-cells.ipynb Shows how to render images, SVG files, and mathematical equations using IPython display utilities. ```python from IPython.display import Image, SVG, Math, Latex i = Image(filename='images/notebook_icon.png') display(i) SVG(filename='images/python_logo.svg') eq = Math(r'\int\limits_{-\infty}^\infty f(x) \delta(x - x_0) dx = f(x_0)') display(eq) Latex(r'This is a \LaTeX{} equation: $a^2 + b^2 = c^2$') ``` -------------------------------- ### Execute Sphinx Build for LaTeX Output Source: https://github.com/spatialaudio/nbsphinx/blob/master/include-in-latex/README.md Run the Sphinx build process using a custom configuration directory to override default settings for LaTeX integration. ```bash python -m sphinx ../doc _build -c . -b latex ``` -------------------------------- ### Displaying 24-bit RGB ANSI Colors in Python Source: https://github.com/spatialaudio/nbsphinx/blob/master/doc/code-cells.ipynb This Python code generates a gradient of 24-bit RGB colors using ANSI escape sequences. It defines a start and end RGB color and interpolates between them to create a smooth color transition across the output line. ```python start = 255, 0, 0 end = 0, 0, 255 length = 79 out = [] for i in range(length): rgb = [start[c] + int(i * (end[c] - start[c]) / length) for c in range(3)] out.append('\x1b[' '38;2;{rgb[2]};{rgb[1]};{rgb[0]};' '48;2;{rgb[0]};{rgb[1]};{rgb[2]}mX\x1b[m'.format(rgb=rgb)) print(''.join(out)) ``` -------------------------------- ### Add Content with nbsphinx_prolog and nbsphinx_epilog Source: https://context7.com/spatialaudio/nbsphinx/llms.txt Add custom content before (prolog) and after (epilog) each notebook in the generated output. These strings support reStructuredText markup and Jinja2 templating, allowing dynamic content generation. ```python # conf.py # Simple static prolog bsphinx_prolog = """ .. note:: This page was generated from a Jupyter notebook. ---- """ # Dynamic prolog with Jinja2 templating bsphinx_prolog = r""" {% set docname = env.doc2path(env.docname, base=False)|string %} .. note:: Download this notebook: :download:`{{ docname }}` """ # Epilog with links bsphinx_epilog = """ ---- Generated by nbsphinx_ from a Jupyter_ notebook. .. _nbsphinx: https://nbsphinx.readthedocs.io/ .. _Jupyter: https://jupyter.org/ """ ``` -------------------------------- ### Include Local Image using Markdown Source: https://github.com/spatialaudio/nbsphinx/blob/master/doc/markdown-cells.ipynb Demonstrates how to include a local image using Markdown syntax. This is a common way to embed images in documentation. ```markdown ![Jupyter notebook icon](images/notebook_icon.png) ``` -------------------------------- ### Configure nbsphinx_thumbnails in conf.py Source: https://github.com/spatialaudio/nbsphinx/blob/master/doc/gallery/thumbnail-from-conf-py.ipynb This snippet shows the configuration syntax for mapping notebook paths to specific image files within the Sphinx conf.py file. Note that the notebook path excludes the .ipynb extension. ```python nbsphinx_thumbnails = { 'gallery/thumbnail-from-conf-py': 'gallery/a-local-file.png', } ``` -------------------------------- ### Build PDF from LaTeX with latexmk Source: https://github.com/spatialaudio/nbsphinx/blob/master/doc/usage.ipynb Command to use latexmk for automatically building a PDF from LaTeX output. The -pvc flag enables continuous viewing and rebuilding. ```bash latexmk -pdf -pvc ``` ```bash latexmk -pdf -pvc -f ``` -------------------------------- ### Capturing Client-Specific Outputs Source: https://github.com/spatialaudio/nbsphinx/blob/master/doc/pre-executed.ipynb Demonstrates how to capture outputs that are specific to certain Jupyter clients, such as help documentation, which might not be generated by nbconvert. ```python sorted? ``` -------------------------------- ### Initialize Matplotlib and NumPy for Plotting Source: https://github.com/spatialaudio/nbsphinx/blob/master/doc/gallery/default-thumbnail.ipynb Imports necessary libraries for generating plots within a Jupyter notebook. This is a prerequisite for creating image outputs that nbsphinx can use as thumbnails. ```python import matplotlib.pyplot as plt import numpy as np ``` -------------------------------- ### Embed HTML Audio Element Source: https://github.com/spatialaudio/nbsphinx/blob/master/doc/markdown-cells.ipynb Demonstrates how to embed an audio file using the HTML5 `