Hey o1, can you please design a python code which takes in a python notebook, and then uses the web browser to display all the plots in the python notebook. The program should be able to ready both matplotlib and plotly graphs.
Assistant
Certainly! Below is a Python script that takes a Jupyter Notebook (.ipynb file), executes it, extracts all matplotlib and Plotly plots, and displays them in a web browser. The script uses the following libraries:
nbformat and nbclient to read and execute the notebook.
webbrowser to open the generated HTML file.
plotly to handle Plotly plots.
os and base64 for handling image data.
Before running the script, make sure to install the required libraries:
bash
pip install nbformat nbclient plotly
Here's the complete script:
python
import nbformat
from nbclient import NotebookClient
import sys
import os
import base64
import webbrowser
from pathlib import Path
from datetime import datetime
def extract_plots(notebook_path, output_html='output_plots.html'):
# Load the notebook
with open(notebook_path, 'r', encoding='utf-8') as f:
nb = nbformat.read(f, as_version=4)
# Execute the notebook
client = NotebookClient(nb, timeout=600, kernel_name='python3')
try:
client.execute()
except Exception as e:
print(f"Error executing the notebook: {e}")
sys.exit(1)
# Prepare HTML content
html_content = """
<html>
<head>
<title>Extracted Plots</title>
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<style>
body { font-family: Arial, sans-serif; margin: 40px; }
.plot { margin-bottom: 50px; }
h2 { border-bottom: 1px solid #ccc; padding-bottom: 10px; }
</style>
</head>
<body>
<h1>Extracted Plots</h1>
<p>Generated on {}</p>
""".format(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
plot_count = 0
# Iterate through cells and extract plots
for cell_idx, cell in enumerate(nb.cells):
if cell.get('outputs'):
for output in cell['outputs']:
# Handle matplotlib plots (image/png)
if output.output_type == 'display_data' or output.output_type == 'execute_result':
data = output.get('data', {})
# Matplotlib image
if 'image/png' in data:
img_data = data['image/png']
html_content += f'<div class="plot"><h2>Plot {plot_count + 1} (Matplotlib)</h2>'
html_content += f'<img src="data:image/png;base64,{img_data}" alt="Matplotlib Plot"/></div>'
plot_count += 1
# Plotly plots
elif 'application/vnd.plotly.v1+json' in data:
plotly_json = data['application/vnd.plotly.v1+json']
# Use Plotly to generate HTML div
import plotly.io as pio
fig = pio.from_json(plotly_json)
plot_html = pio.to_html(fig, include_plotlyjs=False, full_html=False)
html_content += f'<div class="plot"><h2>Plot {plot_count + 1} (Plotly)</h2>'
html_content += plot_html
html_content += '</div>'
plot_count += 1
# Alternative Plotly output formats
elif 'text/html' in data and 'plotly' in data['text/html']:
plot_html = data['text/html']
html_content += f'<div class="plot"><h2>Plot {plot_count + 1} (Plotly)</h2>'
html_content += plot_html
html_content += '</div>'
plot_count += 1
html_content += """
</body>
</html>
"""
# Write HTML to file
with open(output_html, 'w', encoding='utf-8') as f:
f.write(html_content)
# Open the HTML file in the default web browser
full_path = Path(output_html).absolute().as_uri()
webbrowser.open(full_path)
print(f"Extracted {plot_count} plots. Opening {output_html} in web browser.")
if __name__ == "__main__":
if len(sys.argv) != 2:
print("Usage: python extract_plots.py <notebook_path.ipynb>")
sys.exit(1)
notebook_path = sys.argv[1]
if not os.path.exists(notebook_path):
print(f"Notebook file '{notebook_path}' does not exist.")
sys.exit(1)
extract_plots(notebook_path)
How It Works
Load and Execute the Notebook:
The script reads the notebook using nbformat.
It executes the notebook using NotebookClient from nbclient. This ensures that all cells are run, and outputs (including plots) are generated.
Extract Plots:
After execution, the script iterates through each cell and its outputs.
For matplotlib plots, it looks for outputs with MIME type image/png, which contains the base64-encoded image data.
For Plotly plots, it searches for outputs with MIME type application/vnd.plotly.v1+json or text/html containing Plotly plots. It uses Plotly's to_html method to generate the necessary HTML.
Generate HTML Content:
The extracted plots are embedded into an HTML structure.
Each plot is enclosed in a <div> with a heading indicating the plot number and type.
The script includes Plotly's JavaScript library via a CDN to ensure interactive Plotly plots work correctly.
Display in Web Browser:
The final HTML content is written to a file (output_plots.html by default).
The script automatically opens this HTML file in the default web browser, displaying all the extracted plots.
Usage
Save the Script:
Save the above script to a file, e.g., extract_plots.py.
Run the Script:
Open a terminal or command prompt.
Navigate to the directory containing both the script and your target notebook.
Execute the script with the notebook path as an argument:
bash
python extract_plots.py your_notebook.ipynb
View the Plots:
After execution, your default web browser will open the output_plots.html file displaying all the matplotlib and Plotly plots extracted from the notebook.
Notes
Plotly Integration:
The script includes Plotly's latest JavaScript library via CDN to render interactive Plotly plots. Ensure you have an active internet connection when viewing the HTML file.
Customization:
You can change the output HTML filename by modifying the output_html parameter in the extract_plots function.
The script currently handles basic scenarios. Depending on your notebook's complexity, you might need to enhance error handling or support additional plot types.
Dependencies:
Ensure that the notebook doesn't require any interactive widgets or non-standard libraries, as executing the notebook programmatically might require additional setup.
This script provides a straightforward way to extract and view all plots from a Jupyter Notebook in a consolidated web page, supporting both static matplotlib images and interactive Plotly graphs.