### Quick Preview with uv Source: https://github.com/paw-lu/nbpreview/blob/main/docs/installation.md Installs the uv package manager and immediately renders a remote Jupyter notebook file directly in the terminal. ```console % curl -LsSf https://astral.sh/uv/install.sh | sh % curl https://raw.githubusercontent.com/paw-lu/nbpreview/refs/heads/main/docs/example_notebook_cells/hero_notebook.ipynb | uvx nbpreview ``` -------------------------------- ### Run nbpreview with a Theme Source: https://github.com/paw-lu/nbpreview/blob/main/docs/_static/examples/html/theme_one_dark.html This command uses the `nbpreview` tool to render a Jupyter notebook file named `notebook.ipynb` using the `one-dark` theme. Ensure `nbpreview` is installed and the notebook file exists in the current directory. ```shell nbpreview --theme one-dark notebook.ipynb ``` -------------------------------- ### Install nbpreview using pip Source: https://github.com/paw-lu/nbpreview/blob/main/docs/index.md This command installs the nbpreview package from PyPI. Ensure you have pip installed and configured correctly. ```bash pip install nbpreview ``` -------------------------------- ### Install nbpreview via Package Managers Source: https://github.com/paw-lu/nbpreview/blob/main/docs/installation.md Provides terminal commands to install the nbpreview tool using popular Python package managers like uv and pip. ```console % uv tool install nbpreview ``` ```console % python -m pip install nbpreview ``` -------------------------------- ### Preview Notebook with Material Theme using nbpreview Source: https://github.com/paw-lu/nbpreview/blob/main/docs/_static/examples/html/cell_magic_syntax_highlight.html This command demonstrates how to use nbpreview to render a notebook file ('notebook.ipynb') with the 'material' theme applied. It's useful for visualizing notebooks in different styles. ```bash % nbpreview --theme material notebook.ipynb ``` -------------------------------- ### Python Code Example with Monokai Theme (nbpreview) Source: https://github.com/paw-lu/nbpreview/blob/main/docs/features.md This Python code is an example of how a Jupyter notebook cell would be rendered by nbpreview when using the monokai theme. It includes type hints and a static method for calculating Fibonacci numbers. The styling reflects the monokai color scheme, with specific colors for keywords, strings, and comments. ```python from typing import Iterator class Math: """An example class.""" @staticmethod def fib(n: int) -> Iterator[int]: """Fibonacci series up to n.""" a, b = 0, 1 # Manually set first two terms while a < n: ``` -------------------------------- ### Run nbpreview with a Theme Source: https://github.com/paw-lu/nbpreview/blob/main/docs/_static/examples/html/theme_monokai.html This command previews a Jupyter notebook file using the 'monokai' theme. It requires the nbpreview tool to be installed and the specified notebook file to exist. The output will be the rendered notebook content in the terminal. ```bash nbpreview --theme monokai notebook.ipynb ``` -------------------------------- ### Import Libraries for Bayesian Analysis with Python Source: https://github.com/paw-lu/nbpreview/blob/main/docs/example_notebook_cells/hero_notebook.ipynb Imports necessary libraries including pandas for data manipulation and pymc for probabilistic programming. It also imports custom model and plots modules. ```python import pandas as pd import pymc as pm import model import plots ``` -------------------------------- ### Load Datasets for Analysis (Python) Source: https://github.com/paw-lu/nbpreview/blob/main/tests/unit/expected_outputs/test_color_notebook_file[--no-color-None-None].txt Loads the 'fmri' and 'tips' datasets using the seaborn library. These datasets are commonly used for statistical analysis and visualization examples. The `.head()` method displays the first few rows of the 'fmri' dataset. ```python fmri = sns.load_dataset("fmri") tips = sns.load_dataset("tips") f… ``` -------------------------------- ### HTML Rendering in Jupyter Notebooks Source: https://github.com/paw-lu/nbpreview/blob/main/docs/_static/examples/html/html.html This snippet shows an example of HTML content within a Jupyter notebook cell, using `%%html` magic. It includes paragraphs, emphasis, and blockquotes. nbpreview will render this HTML in the generated preview. ```python %%html

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

Sit amet consectetur adipiscing elit pellentesque habitan…

``` -------------------------------- ### nbpreview HTML Rendering Example Source: https://github.com/paw-lu/nbpreview/blob/main/docs/features.md This code snippet demonstrates how nbpreview renders HTML content within a terminal environment. It uses a combination of HTML structure and inline styling, processed by the nbpreview tool. ```bash % nbpreview --theme material notebook.ipynb ╭───────────────────────────────────────────────────────────────────────╮ [15]: │ %%html │ │ │ │

│ │ Lorem ipsum dolor sit amet, │ consectetur adipiscing elit, │ sed do eiusmod tempor │ incididunt ut labore et dolore magna aliqua.

│ │ ``` -------------------------------- ### Import required data science libraries Source: https://github.com/paw-lu/nbpreview/blob/main/docs/_static/examples/html/example_notebook.html Standard imports for data manipulation and statistical analysis using typing, arviz, matplotlib, pandas, and pymc. ```python from typing import Optional import arviz as az import matplotlib.pyplot as plt import pandas as pd import pymc as pm from arviz import InferenceData from matplotlib.axes import Axes from matplotlib.axes._subplots import Subplot from pandas import DataFrame import plots ``` -------------------------------- ### Python Code Sample within Notebook Source: https://github.com/paw-lu/nbpreview/blob/main/docs/features.md An example of a Python class containing a static method for calculating Fibonacci numbers. This snippet illustrates how code blocks within a rendered notebook appear when viewed via nbpreview. ```python from typing import Iterator class Math: """An example class.""" @staticmethod def fib(n: int) -> Iterator[int]: """Fibonacci series up to n.""" ``` -------------------------------- ### Display Stderr in Terminal Output Source: https://github.com/paw-lu/nbpreview/blob/main/docs/features.md Example of how nbpreview presents Python code execution, specifically highlighting the rendering of stderr logs within a terminal-styled environment. ```python with pm.Model() as model: pm.Normal("normal", mu=0, sd=1) trace = pm.sample(return_inferencedata=True) ``` ```bash nbpreview --theme material notebook.ipynb ``` -------------------------------- ### Load Datasets using Seaborn Source: https://github.com/paw-lu/nbpreview/blob/main/tests/unit/expected_outputs/test_positive_space_output_notebook_file[-s-None].txt Loads the 'fmri' and 'tips' datasets using Seaborn's built-in functions. These datasets are commonly used for examples and demonstrations in data analysis and visualization. The `.head()` method displays the first few rows of the 'fmri' dataset. ```python fmri = sns.load_dataset("fmri") tips = sns.load_dataset("tips") f… signal ──────────────────────────────────────────────────────── 0 s13 18 stim parietal -0.017552 1 s5 14 stim parietal -0.080883 2 s12 18 stim parietal -0.081033 3 s11 18 stim parietal -0.046134 4 s10 18 stim parietal -0.037970 ``` -------------------------------- ### Render Notebook with Theme and Image Drawing (CLI) Source: https://github.com/paw-lu/nbpreview/blob/main/docs/features.md This command uses the nbpreview tool to render a Jupyter notebook file ('notebook.ipynb') with the 'material' theme applied and image drawing enabled. It requires the nbpreview package to be installed and accessible in the system's PATH. The output is rendered directly in the terminal. ```bash % nbpreview --theme material --image-drawing block notebook.ipynb ╭───────────────────────────────────────────────────────────────────────╮ [17]: │ , ax = plt.subplots(facecolor="#1C1B1F") │ │ ( │ sns.load_dataset("fmri")).pipe( │ (sns.lineplot, "data"), │ │ x="timepoint", │ │ y="signal", │ ``` -------------------------------- ### Bayesian Model Sampling with PyMC Source: https://github.com/paw-lu/nbpreview/blob/main/docs/example_notebook_cells/hero_notebook.ipynb Defines and samples a Bayesian model for baby length using PyMC. It utilizes the `model.model_baby_length` function and samples posterior predictive distributions, returning an ArviZ InferenceData object. ```python with model.model_baby_length(babies_data): babies_idata = pm.sample(tune=2_000, return_inferencedata=True) babies_idata.extend(pm.sample_posterior_predictive(babies_idata)) ``` -------------------------------- ### Load and aggregate baby growth data with pandas Source: https://github.com/paw-lu/nbpreview/blob/main/docs/_static/examples/html/example_notebook.html Loads a CSV dataset from a URL, renames columns, and groups the data by month to calculate mean, median, standard deviation, and count of length measurements. ```python babies_data = pd.read_csv( "https://github.com/aloctavodia/BAP/blob/master/code/data/babies.csv" ).rename(columns={"Lenght": "Length"}) months_of_interest = list(range(0, 13, 4)) result = (babies_data.groupby("Month") .agg( mean_length=("Length", "mean"), median_length=("Length", "median"), mean_std=("Length", "std"), measurement_count=("Month", "count"), ) .loc[months_of_interest] ) ``` -------------------------------- ### Markdown Rendering Features (Markdown) Source: https://github.com/paw-lu/nbpreview/blob/main/docs/features.md This example showcases the markdown rendering capabilities of nbpreview, powered by libraries like Rich and markdown-it-py. It illustrates support for headings, bold text, hyperlinks, inline code, block math equations, and images. ```markdown # Lorem ipsum Lorem ipsum dolor sit amet, consectetur **adipiscing** elit, sed do eiusmod tempor incididunt ut labore et dolore magna [aliqua](https://github.com/paw-lu/nbpreview). $$ \alpha \sim \text{Normal(0, 1)} $$ _Ut enim ad minim veniam_, quis nostrud exercitation ullamco Excepteur sint occaecat `cupidatat` non proident, sunt in culpa qui. ![Turtle](emoji_u1f422.png) ``` -------------------------------- ### Render Jupyter Notebook with Monokai Theme (CLI) Source: https://github.com/paw-lu/nbpreview/blob/main/docs/features.md This command-line snippet demonstrates how to use nbpreview to render a Jupyter notebook ('notebook.ipynb') with the 'monokai' color theme. It requires the nbpreview tool to be installed and accessible in your PATH. The output shows the notebook's content, including Python code, styled according to the monokai theme. ```bash % nbpreview --theme monokai notebook.ipynb ``` -------------------------------- ### Plotting Distribution and HDI with Custom Module Source: https://github.com/paw-lu/nbpreview/blob/main/docs/example_notebook_cells/hero_notebook.ipynb Generates plots showing the distribution and Highest Density Interval (HDI) for baby lengths based on the provided data and the sampled Bayesian model. It uses custom plotting functions from the `plots` module. ```python plots.plot_dist_and_hdi( babies_data, babies_idata=babies_idata, months=months_of_interest, hdi_probs=[0.50, 0.99] ); ``` -------------------------------- ### Measure Execution Time with %%timeit in Python Source: https://github.com/paw-lu/nbpreview/blob/main/tests/unit/expected_outputs/test_notebook_non_syntax_magic_code_cell.txt The %%timeit magic command in Python is used to measure the execution time of a given code snippet. It is particularly useful for performance analysis and optimization. This example demonstrates its usage with a simple function. ```python %%timeit def foo(x: float, y: float) -> float: return x + y ``` -------------------------------- ### Load and Process Babies Data with Pandas Source: https://github.com/paw-lu/nbpreview/blob/main/docs/example_notebook_cells/hero_notebook.ipynb Loads baby length data from a CSV file into a pandas DataFrame and performs aggregation to calculate mean, median, standard deviation, and count of measurements for specific months. It handles potential column name inconsistencies. ```python babies_data = pd.read_csv( "https://github.com/aloctavodia/BAP/blob/master/code/data/babies.csv?raw=true" ).rename(columns={"Lenght": "Length"}) months_of_interest = list(range(0, 13, 4)) ( babies_data.groupby("Month") .agg( mean_length=("Length", "mean"), median_length=("Length", "median"), mean_std=("Length", "std"), measurement_count=("Month", "count") ) .loc[months_of_interest] ) ``` -------------------------------- ### Generate and Display Matplotlib Plot in Python Source: https://github.com/paw-lu/nbpreview/blob/main/tests/unit/expected_outputs/test_render_stdin[-].txt This snippet demonstrates how to create a simple plot using Matplotlib in Python and display it. It highlights the use of `plt.figure` and `plt.Axes` for plot customization. No external dependencies beyond Matplotlib are strictly required for this basic example. ```python import matplotlib.pyplot as plt fig, ax = plt.subplots() ax.plot([1, 2, 3], [4, 5, 6]) ax.set_xlabel('X-axis') ax.set_ylabel('Y-axis') plt.show() ``` -------------------------------- ### Process CSV Files with awk and sort using Bash Source: https://github.com/paw-lu/nbpreview/blob/main/docs/_static/examples/html/cell_magic_syntax_highlight.html This bash script iterates through all '.csv' files in the current directory. For each file, it extracts the 5th column, sorts the unique values, and counts their occurrences using awk, sort, and uniq. It requires files to be comma-separated. ```bash %%bash for file in *.csv; do echo "$file" awk -F ',' '{print $5}' "$file" | sort | uniq -c done ``` -------------------------------- ### nbpreview Help Source: https://github.com/paw-lu/nbpreview/blob/main/docs/usage.md Display documentation for all nbpreview options, their effects, values, and relevant environment variables. ```APIDOC ## nbpreview Help ### Description Display detailed help information for the nbpreview command. ### Method CLI Command ### Endpoint `nbpreview --help` ### Response **Output**: Prints a help message detailing all available options, arguments, and environment variables. ### Response Example ```console % nbpreview --help ``` (Help message content will be displayed here) ``` -------------------------------- ### Control Output Decoration Source: https://github.com/paw-lu/nbpreview/blob/main/docs/features.md Demonstrates how to force plain text output or decorated output, and how to set environment variables to configure default behavior. ```console % nbpreview notebook.ipynb | fgrep parietal % nbpreview --plain notebook.ipynb % nbpreview --decorated notebook.ipynb % export NBPREVIEW_PLAIN=1 ``` -------------------------------- ### General Syntax for nbpreview Source: https://github.com/paw-lu/nbpreview/blob/main/docs/usage.md General command structure for executing nbpreview with optional flags and file paths. ```shell nbpreview [OPTIONS] [FILE]... ``` -------------------------------- ### Load and Render Notebooks with Notebook.from_file Source: https://context7.com/paw-lu/nbpreview/llms.txt The Notebook.from_file method acts as the primary programmatic entry point for loading notebook files. It accepts file objects and a wide range of formatting parameters to control the Rich console output. ```python from pathlib import Path from nbpreview.notebook import Notebook from rich.console import Console with open("analysis.ipynb") as f: notebook = Notebook.from_file(f, theme="monokai", image_drawing="block") console = Console() console.print(notebook) ``` -------------------------------- ### Generate scatter plot for growth data Source: https://github.com/paw-lu/nbpreview/blob/main/docs/_static/examples/html/example_notebook.html Creates a scatter plot using the pandas plotting interface to visualize the relationship between age (Month) and height (Length). ```python babies_data.plot.scatter( x="Month", y="Length", figsize=(30, 7), s=500, xticks=[], yticks=[], ); ``` -------------------------------- ### Python: Notebook.from_file() Source: https://context7.com/paw-lu/nbpreview/llms.txt Creates a Notebook object from a Jupyter file stream with full rendering configurations. ```APIDOC ## Notebook.from_file() ### Description Factory method to load a Jupyter notebook from an open file object and configure its display properties. ### Method Class Method ### Parameters - **f** (file object) - Required - The open file handle for the .ipynb file. - **theme** (string) - Optional - Syntax highlighting theme name. - **image_drawing** (string) - Optional - Mode for image rendering ('block', 'character', 'braille'). - **hide_output** (bool) - Optional - If True, suppresses output cells. ### Request Example ```python with open("data.ipynb") as f: notebook = Notebook.from_file(f, theme="dracula", image_drawing="block") ``` ### Response - **notebook** (object) - A configured Notebook instance ready for rendering with rich.console. ``` -------------------------------- ### Use nbpreview CLI for Notebook Rendering Source: https://context7.com/paw-lu/nbpreview/llms.txt The command-line interface allows for rapid inspection of Jupyter notebooks, supporting piping, multi-file rendering, and various formatting flags. Users can customize the output appearance with themes, line numbering, and color system overrides. ```bash # Basic usage nbpreview notebook.ipynb # Pipe from stdin cat notebook.ipynb | nbpreview # Advanced options nbpreview --theme monokai --line-numbers --code-wrap notebook.ipynb # Disable paging for CI/CD integration nbpreview --no-paging notebook.ipynb | grep "def" ``` -------------------------------- ### Generate Notebook Preview with nbpreview Command Source: https://github.com/paw-lu/nbpreview/blob/main/docs/_static/examples/html/dark_plot_block.html This command-line usage demonstrates how to use nbpreview to generate a notebook preview. It specifies a theme ('material'), enables image drawing ('block'), and takes the notebook file ('notebook.ipynb') as input. The output includes a visualization of a seaborn plot generated from the fmri dataset. ```bash % nbpreview --theme material --image-drawing block notebook.ipynb ``` -------------------------------- ### Basic Usage of nbpreview CLI Source: https://github.com/paw-lu/nbpreview/blob/main/docs/usage.md Standard commands to render a Jupyter notebook using the nbpreview tool or its alias nbp. ```console % nbpreview notebook.ipynb % nbp notebook.ipynb ``` -------------------------------- ### Run nbpreview with Theme and Notebook Source: https://github.com/paw-lu/nbpreview/blob/main/docs/_static/examples/html/theme_rainbow_dash.html This command executes the nbpreview tool to render a Jupyter notebook named 'notebook.ipynb' using the 'rainbow_dash' theme. It showcases how to apply visual styles to notebook previews directly from the command line. ```bash % nbpreview --theme rainbow_dash notebook.ipynb ``` -------------------------------- ### Run nbpreview with Material Theme Source: https://github.com/paw-lu/nbpreview/blob/main/docs/_static/examples/html/dark_plot_negative_character.html This command uses the nbpreview tool to render a notebook file named 'notebook.ipynb'. It specifies the 'material' theme and enables 'image-drawing' functionality, likely for interactive plot display. The command outputs a representation of the notebook, including plot visualizations. ```bash % nbpreview --theme material --image-drawing character notebook.ipynb ``` -------------------------------- ### Preview Jupyter Notebooks with multi-language support Source: https://github.com/paw-lu/nbpreview/blob/main/docs/features.md This command demonstrates how to use the nbpreview CLI to render a Jupyter Notebook file. It highlights the capability of the tool to correctly display syntax-highlighted code blocks for languages like Julia. ```bash nbpreview --theme material notebook.ipynb ``` ```julia function printx(x) println("x = $x") return nothing end ``` -------------------------------- ### Create Side-by-Side Plots Source: https://github.com/paw-lu/nbpreview/blob/main/tests/unit/expected_outputs/test_image_notebook_file[None-1].txt Initializes a figure with two subplots and pipes dataset plotting functions to generate a line plot and a box plot. This setup customizes the axes appearance by removing labels and ticks. ```python _, (ax_line, ax_box) = plt.subplots(ncols=2, facecolor="#1C1B1F") (fmri.pipe((sns.lineplot, "data"), x="timepoint", y="signal", hue="event", ax=ax_line, err_kws={"alpha": 1}).set(xlabel=None, ylabel=None, yticks=[], xticks=[])) (tips.pipe((sns.boxplot, "data"), x="day", y="total_bill", hue="smoker", ax=ax_box).set(xlabel=None, ylabel=None, yticks=[], xticks=[])) ``` -------------------------------- ### NUTS Sampler Initialization and Sampling Progress in Python Source: https://github.com/paw-lu/nbpreview/blob/main/docs/index.md This output illustrates the progress of the NUTS (No-U-Turn Sampler) sampler during Bayesian model inference. It shows the auto-assignment of the sampler, initialization steps, and the sampling progress for multiple chains, including the number of divergences and iterations. ```python Auto-assigning NUTS sampler... Initializing NUTS using jitter+adapt_diag... Multiprocess sampling (4 chains in 4 jobs) NUTS: [alpha, beta, gamma, sigma] 100.00% [12000/12000 00:07<00:00 Sampling 4 chains, 0 divergences] Sampling 4 chains for 2_000 tune and 1_000 draw iterations (8_000 + ``` -------------------------------- ### Display nbpreview help message including environment variables Source: https://github.com/paw-lu/nbpreview/blob/main/docs/configure.md This command displays the help message for nbpreview, which includes details about command-line options and their associated environment variables. ```console % nbpreview --help ``` -------------------------------- ### Load Datasets using Seaborn Source: https://github.com/paw-lu/nbpreview/blob/main/tests/unit/expected_outputs/test_color_notebook_file[-o-None-None].txt Demonstrates loading the 'fmri' and 'tips' datasets using the seaborn library. These datasets are commonly used for data analysis and visualization tasks. ```python fmri = sns.load_dataset("fmri") tips = sns.load_dataset("tips") f…head() ``` -------------------------------- ### Define and sample a Bayesian linear model with PyMC Source: https://github.com/paw-lu/nbpreview/blob/main/docs/_static/examples/html/example_notebook.html Constructs a PyMC model where the dependent variable 'Length' is modeled against the square root of 'Month'. It includes deterministic transformations for mean and variance, and executes MCMC sampling with posterior predictive generation. ```python with pm.Model(coords={"time_idx": babies_data.index}) as babies_model: # Priors alpha = pm.Normal("alpha", sigma=10) beta = pm.Normal("beta", sigma=10) gamma = pm.HalfNormal("gamma", sigma=10) sigma = pm.HalfNormal("sigma", sigma=10) month = pm.MutableData("month", value=babies_data["Month"].astype(float)) mu = pm.Deterministic("mu", alpha + beta * month ** 0.5, dims="time_idx") epsilon = pm.Deterministic("epsilon", gamma + sigma * month, dims="time_idx") pm.Normal("length", mu=mu, sigma=epsilon, observed=babies_data["Length"], dims="time_idx") # Sample model babies_idata = pm.sample(tune=2_000, return_inferencedata=True) babies_idata.extend(pm.sample_posterior_predictive(babies_idata)) ``` -------------------------------- ### Run nbpreview with Theme and Python Code Execution Source: https://github.com/paw-lu/nbpreview/blob/main/docs/_static/examples/html/theme_paraiso_light.html This snippet shows how to execute the nbpreview command with a specific theme ('paraiso-light') and a notebook containing Python code. The Python code defines a Math class with a static method 'fib' to generate Fibonacci numbers up to a given limit and then calculates and prints the sum of these numbers. ```bash % nbpreview --theme paraiso-light notebook.ipynb ╭────────────────────────────────────────────────────────────────────────╮ [ ]: │ from typing import Iterator │ │ │ │ │ │ class Math: │ │ ``` -------------------------------- ### Preview Notebook with Material Theme Source: https://github.com/paw-lu/nbpreview/blob/main/docs/_static/examples/html/html.html This command demonstrates how to use nbpreview to render a Jupyter notebook (`notebook.ipynb`) with the 'material' theme. nbpreview processes the notebook and generates an HTML preview. ```bash nbpreview --theme material notebook.ipynb ``` -------------------------------- ### Python: Notebook Constructor Source: https://context7.com/paw-lu/nbpreview/llms.txt Instantiates a Notebook object directly from a parsed NotebookNode. ```APIDOC ## Notebook Constructor ### Description Allows direct instantiation of a Notebook object using a pre-parsed notebook node, providing granular control over formatting. ### Method Constructor ### Parameters - **notebook_node** (NotebookNode) - Required - The parsed structure from nbformat. - **relative_dir** (Path) - Optional - Base directory for resolving relative paths. ### Request Example ```python import nbformat notebook_node = nbformat.read(f, as_version=4) notebook = Notebook(notebook_node=notebook_node, theme="ansi_dark") ``` ``` -------------------------------- ### Instantiate Notebook objects from NotebookNode Source: https://context7.com/paw-lu/nbpreview/llms.txt For more granular control, developers can parse notebooks using nbformat and instantiate the Notebook class directly. This approach allows for programmatic access to notebook properties and capture of the rendered output as a string. ```python import nbformat from nbpreview.notebook import Notebook from rich.console import Console with open("example.ipynb") as f: node = nbformat.read(f, as_version=4) notebook = Notebook(notebook_node=node, theme="ansi_dark") console = Console() with console.capture() as capture: console.print(notebook) rendered_output = capture.get() ``` -------------------------------- ### Render Jupyter Notebook Files Source: https://github.com/paw-lu/nbpreview/blob/main/docs/features.md Demonstrates various ways to provide notebook files to nbpreview, including individual files, multiple files, and glob patterns. ```console % nbpreview notebook.ipynb % nbpreview notebook1.ipynb notebook2.ipynb % nbpreview notebooks/*.ipynb ``` -------------------------------- ### Manage Syntax Highlighting Themes Source: https://context7.com/paw-lu/nbpreview/llms.txt Users can discover and apply different color themes to ensure code cells are legible and styled according to personal preference. The CLI provides a utility to list available themes and apply them during execution. ```bash # List available themes nbpreview --list-themes # Apply specific theme nbpreview --theme dracula notebook.ipynb ``` -------------------------------- ### Iterating and Plotting Length Distributions Source: https://github.com/paw-lu/nbpreview/blob/main/docs/_static/examples/html/example_notebook.html This code snippet iterates through a list of months of interest (`months_of_interest`) and plots the length distribution for each month using the `plot_length_dist` function. It assigns a unique color to each plot based on its index and directs all plots to the same matplotlib Axes object (`dist_ax`). The `xticks` and `yticks` are removed for cleaner visualization. ```python for idx, month in enumerate(months_of_interest): color = f"C{idx}" plot_length_dist( babies_idata, babies_data=babies_data, month=month, color=color, ax=dist_ax, ).set(xticks=[], yticks=[]) ``` -------------------------------- ### Render Jupyter Notebook in Terminal using nbpreview Source: https://github.com/paw-lu/nbpreview/blob/main/docs/_static/examples/html/theme_dracula.html Demonstrates the command to preview a Jupyter notebook file in the terminal with a specified theme. The output shows the rendered code structure, including imported modules, class definitions, and execution logic. ```bash nbpreview --theme dracula notebook.ipynb ``` ```python from typing import Iterator class Math: """An example class.""" @staticmethod def fib(n: int) -> Iterator[int]: """Fibonacci series up to n.""" a, b = 0, 1 while a < n: yield a a, b = b, a + b result = sum(Math.fib(42)) print(f"The answer is {result}") ``` -------------------------------- ### Preview Notebook with 'paraiso-light' Theme Source: https://github.com/paw-lu/nbpreview/blob/main/docs/features.md Renders a Jupyter notebook file using the nbpreview command-line tool with the specified 'paraiso-light' theme. This command takes the notebook file path as an argument and outputs the rendered notebook, likely as HTML or a similar format, styled according to the theme. ```bash % nbpreview --theme paraiso-light notebook.ipynb ``` -------------------------------- ### Plotting Highest Density Interval (HDI) with ArviZ Source: https://github.com/paw-lu/nbpreview/blob/main/docs/_static/examples/html/example_notebook.html This code snippet visualizes the Highest Density Interval (HDI) for newborn lengths across different months using the ArviZ library. It takes inferred data and associated metadata to plot the HDI, with options for customizing fill transparency and assigning the plot to a specific matplotlib Axes object. The output is a plot displayed in the notebook. ```python az.plot_hdi( x=babies_data["Month"], y=babies_idata["posterior_predictive"]["length"], hdi_prob=0.95, fill_kwargs={\"alpha\": 1.0}, ax=hdi_ax, ).set(xticks=[], yticks=[]) ``` -------------------------------- ### Set nbpreview theme using command line Source: https://github.com/paw-lu/nbpreview/blob/main/docs/configure.md This command sets the theme for nbpreview directly via the command line. It takes the notebook file as an argument. ```console % nbpreview --theme='material' notebook.ipynb ``` -------------------------------- ### Plotting Length Distribution by Month with ArviZ Source: https://github.com/paw-lu/nbpreview/blob/main/docs/_static/examples/html/example_notebook.html This Python function, `plot_length_dist`, plots the distribution of newborn lengths for a specific month. It utilizes ArviZ's `plot_dist` function to visualize the posterior predictive distribution. The function requires `InferenceData` and `DataFrame` containing baby data, along with the month of interest and an optional matplotlib Axes object and color for customization. It handles data selection and stacking for plotting. ```python def plot_length_dist( babies_idata: InferenceData, babies_data: DataFrame, month: int, ax: Optional[Axes] = None, color: Optional[str] = None, ) -> Subplot: """Plot the length distribution given an age in months.""" if ax is None: ax = plt.gca() length_data = babies_idata.sel( time_idx=babies_data.loc[lambda df: df["Month"] == month].ind )["posterior_predictive"].stack( dim=[ "chain", "draw", "time_idx", ] ) ["length"] plot = az.plot_dist( length_data, fill_kwargs={\"alpha\": 1}, ax=ax, color=color, ) return plot ``` -------------------------------- ### Process Notebooks via stdin Source: https://github.com/paw-lu/nbpreview/blob/main/docs/features.md Shows how to pipe content directly to nbpreview. This can be used for fetching notebooks from remote URLs or filtering cell types using tools like jq. ```console % curl https://raw.githubusercontent.com/paw-lu/nbpreview/main/tests/unit/assets/notebook.ipynb | nbpreview % jq 'with_entries(if .key == "cells" then .value |= map(select(.cell_type == "markdown")) else . end)' tests/unit/assets/notebook.ipynb | nbp ``` -------------------------------- ### List terminal themes in nbpreview Source: https://github.com/paw-lu/nbpreview/blob/main/docs/features.md Displays the CLI command required to view all available themes for the nbpreview tool. This helps users customize the appearance of rendered notebooks in the terminal. ```console nbpreview --list-themes ``` -------------------------------- ### Load Datasets and Display Head (Python) Source: https://github.com/paw-lu/nbpreview/blob/main/tests/unit/assets/notebook.ipynb Loads the 'fmri' and 'tips' datasets using seaborn and displays the first few rows of the 'fmri' dataset. This is a common step in data exploration to understand the structure and content of the data. ```python fmri = sns.load_dataset("fmri") tips = sns.load_dataset("tips") fmri.head() ``` -------------------------------- ### Load Datasets for Visualization (Python) Source: https://github.com/paw-lu/nbpreview/blob/main/tests/unit/expected_outputs/test_color_notebook_file[--color-None-None].txt Loads the 'fmri' and 'tips' datasets using the seaborn library. These datasets are commonly used for demonstrating statistical plotting techniques. The .head() method displays the first few rows of the 'fmri' dataset. ```python fmri = sns.load_dataset("fmri") tips = sns.load_dataset("tips") fmi.head() ``` -------------------------------- ### Load Datasets using Seaborn (Python) Source: https://github.com/paw-lu/nbpreview/blob/main/tests/unit/expected_outputs/test_change_theme_notebook_file[--theme-light-None].txt Loads sample datasets 'fmri' and 'tips' using Seaborn's built-in dataset loading functionality. These datasets are commonly used for demonstrating statistical plots. ```python fmri = sns.load_dataset("fmri") tips = sns.load_dataset("tips") fMRI.head() ``` -------------------------------- ### Execute nbpreview with theme, code wrap, and line numbers Source: https://github.com/paw-lu/nbpreview/blob/main/docs/_static/examples/html/long_code.html This command executes the nbpreview tool to display a Jupyter notebook. It applies the 'material' theme, enables code wrapping, and shows line numbers for code cells. The input is a notebook file named 'notebook.ipynb'. ```bash nbpreview --theme material --code-wrap --line-numbers notebook.ipynb ``` -------------------------------- ### Render Jupyter Notebook in Terminal using nbpreview Source: https://github.com/paw-lu/nbpreview/blob/main/docs/_static/examples/html/images_block.html Demonstrates the command to preview a Jupyter notebook file in the terminal. It utilizes the material theme and enables block-style image rendering for plots. ```bash nbpreview --theme material --image-drawing block notebook.ipynb ``` -------------------------------- ### Sample Bayesian Model Data in Python Source: https://github.com/paw-lu/nbpreview/blob/main/docs/index.md This code snippet demonstrates how to sample data for a Bayesian model using the 'pm.sample' function. It allows specifying the number of tuning steps and whether to return inferred data. The 'extend' method is used to incorporate posterior predictive samples. ```python # Sample model babies_idata = pm.sample(tune=2_000, return_inferencedata=True) babies_idata.extend(pm.sample_posterior_predictive(babies_idata)) ``` -------------------------------- ### Run nbpreview with Dracula Theme Source: https://github.com/paw-lu/nbpreview/blob/main/docs/features.md This command demonstrates how to use the nbpreview tool to render a Jupyter notebook file ('notebook.ipynb') with the 'dracula' color theme applied. It's a command-line utility that requires the notebook file as input and outputs the rendered notebook, potentially in an HTML or other format. ```bash % nbpreview --theme dracula notebook.ipynb ╭────────────────────────────────────────────────────────────────────────╮ [ ]: │ from typing import Iterator │ │ │ │ │ │ class Math: │ """An example class.""" │ │ @staticmethod │ def fib(n: int) -> Iterator[int]: │ """Fibonacci series up to n.""" │ a, b = 0, 1 # Manually set first two terms ``` -------------------------------- ### Inspect Notebook Structure Programmatically Source: https://context7.com/paw-lu/nbpreview/llms.txt Demonstrates how to load a notebook node using nbformat and iterate through its cells to extract metadata, execution counts, source code, and cell outputs. ```python from pathlib import Path from nbpreview.notebook import Notebook import nbformat # Load notebook with open("example.ipynb") as f: notebook_node = nbformat.read(f, as_version=4) notebook = Notebook( notebook_node=notebook_node, theme="ansi_dark" ) # Access notebook metadata print(f"Kernel language: {notebook.language}") # Iterate through cells for i, cell in enumerate(notebook.cells): cell_type = cell.get("cell_type") print(f"Cell {i}: {cell_type}") if cell_type == "code": source = cell.get("source", "") execution_count = cell.get("execution_count", None) outputs = cell.get("outputs", []) print(f" Execution count: {execution_count}") print(f" Source lines: {len(source.splitlines())}") print(f" Outputs: {len(outputs)}") elif cell_type == "markdown": source = cell.get("source", "") print(f" Content length: {len(source)}") # Check for specific content types has_images = any( output.get("output_type") == "display_data" and "image/png" in output.get("data", {}) for cell in notebook.cells for output in cell.get("outputs", []) ) print(f"Contains images: {has_images}") ``` -------------------------------- ### Load Datasets using Seaborn (Python) Source: https://github.com/paw-lu/nbpreview/blob/main/tests/unit/expected_outputs/test_paging_notebook_stdout_file[None].txt Loads the 'fmri' and 'tips' datasets using the seaborn library. These datasets are commonly used for demonstrating statistical plots and data exploration. ```python fmri = sns.load_dataset("fmri") tips = sns.load_dataset("tips") f… s10 18 stim parietal -0.037970 ``` -------------------------------- ### Load Datasets using Seaborn (Python) Source: https://github.com/paw-lu/nbpreview/blob/main/tests/unit/expected_outputs/test_change_theme_notebook_file[None-None-default].txt Loads the 'fmri' and 'tips' datasets using the seaborn library. These datasets are commonly used for demonstrating statistical plotting techniques. The `head()` method displays the first few rows of the fmri dataset. ```python fmri = sns.load_dataset("fmri") tips = sns.load_dataset("tips") f… signal 0 s13 18 stim parietal -0.017552 1 s5 14 stim parietal -0.080883 2 s12 18 stim parietal -0.081033 3 s11 18 stim parietal -0.046134 4 s10 18 stim parietal -0.037970 ``` -------------------------------- ### Create Notebook from File Source: https://github.com/paw-lu/nbpreview/blob/main/docs/reference.md This method allows you to create a Notebook object from a specified Jupyter Notebook file. It offers extensive customization options for rendering, including themes, output visibility, font usage, and image/hyperlink handling. ```APIDOC ## Create Notebook from File ### Description Creates a Notebook object from a specified Jupyter Notebook file with various rendering options. ### Method `classmethod from_file` ### Endpoint N/A (This is a class method, not a REST endpoint) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None **Method Parameters:** - **file** (`Path` or `IO[AnyStr]` or `KeepOpenFile`) - Required - A path to a Jupyter Notebook file. - **theme** (`str`) - Optional - The theme to use for syntax highlighting. Defaults to `'ansi_dark'`. Can be `'ansi_light'`, `'ansi_dark'`, or any Pygments theme. - **plain** (`bool` or `None`) - Optional - If `True`, only show plain style without decorations. If `None`, autodetect. Defaults to `None`. - **unicode** (`bool` or `None`) - Optional - If `True`, use unicode characters for rendering. If `None`, autodetect. Defaults to `None`. - **hide_output** (`bool`) - Optional - If `True`, do not render the notebook outputs. Defaults to `False`. - **nerd_font** (`bool`) - Optional - If `True`, use nerd fonts when appropriate. Defaults to `False`. - **files** (`bool`) - Optional - If `True`, create files when needed to render HTML content. Defaults to `True`. - **negative_space** (`bool`) - Optional - If `True`, render character images in negative space. Defaults to `True`. - **hyperlinks** (`bool` or `None`) - Optional - If `True`, use hyperlinks. If `False`, explicitly print out the path. If `None`, autodetect. Defaults to `None`. - **hide_hyperlink_hints** (`bool`) - Optional - If `True`, hide text hints of when content is clickable. Defaults to `False`. - **images** (`bool` or `None`) - Optional - If `True`, render images. If `None`, autodetect. Defaults to `None`. - **image_drawing** (`ImageDrawingEnum` or `Literal['block', 'character', 'braille']` or `None`) - Optional - The characters used to render images. Options are `'block'`, `'character'`, `'braille'` or `None`. If `None`, autodetect. Defaults to `None`. - **color** (`bool` or `None`) - Optional - If `True`, use color. If `None`, autodetect. Defaults to `None`. - **line_numbers** (`bool`) - Optional - If `True`, render line numbers in code cells. Defaults to `False`. - **code_wrap** (`bool`) - Optional - If `True`, wrap code if it does not fit. Defaults to `False`. ### Request Example ```python from pathlib import Path from nbpreview import Notebook notebook_path = Path("path/to/your/notebook.ipynb") notebook = Notebook.from_file(notebook_path, theme="ansi_light", hide_output=True) ``` ### Response #### Success Response (200) - **Notebook object** (`Notebook`) - A Notebook object created from the file. #### Response Example ```json { "notebook_content": "..." } ``` #### Error Response - **InvalidNotebookError** - If the file is not a valid Jupyter notebook. ``` -------------------------------- ### Load Datasets using Seaborn (Python) Source: https://github.com/paw-lu/nbpreview/blob/main/tests/unit/expected_outputs/test_color_notebook_file[None-NBPREVIEW_NO_COLOR-true].txt Loads the 'fmri' and 'tips' datasets using the seaborn library. These functions fetch sample datasets provided by seaborn. The output is the loaded dataframes, which can then be inspected using methods like .head(). ```python fmri = sns.load_dataset("fmri") tips = sns.load_dataset("tips") f…i.head() ``` -------------------------------- ### Image Rendering in Notebooks (Conceptual) Source: https://github.com/paw-lu/nbpreview/blob/main/tests/unit/expected_outputs/test_files_output_notebook_file[-l-None].txt This snippet illustrates a conceptual representation of image data within a notebook environment. It highlights the structure used to define image boundaries and characteristics, potentially for display or analysis purposes. No specific rendering logic is shown. ```text │ xticks=[], │ │ ) │ ) ╰─────────────────────────────────────────────────────────────────────────╯ [3]: [Text(0.5, 0, ''), Text(0, 0.5, ''), [], []] 🖼 Image GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG GGGGGGGGGG:::GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG GGGGGGGGG:::::GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGPGGGGGGGGGGGGGG GGGGGGGGG:GG::GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGPGGGGGGGGGGGGGG GGGGGGGG:GGGG::GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGPGGGGGGGGGGGGGG GGGGGGG!:GGGGG::GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGPGGGGGG:::GGGGG GGGGGGG:!!!GGGG:GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG:::GGGGG:::?!!!G GGGGGG:!!GG!!GGG:GGGGGGGGGGGGGGGGGGGGGGGGGGGP???GGGGG!!!GG:::!!!PG:::?!!!G GG:G!!GGGGGGG!GG::GGG?!!!!!!!!!!GGGGGGGGG:::P!!!GP:::!!!GG:::!!!PGGGG?!!!G GGGGGGGGGGGGGG!!!!!!GGGGGG::::::GGGGGGGGGGGGGGGGGGGGGGGGGGGPGGGGGGGGGGGGGG GGGGGGGGGGGGGGGGGGG::::::GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGPGGGGGGGGGGGGGG GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG ```