notebookJS: seamless JavaScript integration in Python Notebooks

Overview

notebookJS: seamless JavaScript integration in Python Notebooks

made-with-python Open In Collab PyPI version

notebookJS enables the execution of custom JavaScript code in Python Notebooks (Jupyter Notebook and Google Colab). This Python library can be useful for implementing and reusing interactive Data Visualizations in the Notebook environment.

notebookJS takes care of downloading and handling Javascript libraries and CSS stylesheets from the web. Furthermore, it supports bidirectional communication between Python and JavaScript. User interactions in HTML/JavaScript can trigger Python callbacks that process data on demand and send the results back to the front-end code.

Implementation details in our paper.

See our blog post.

ScatterPlot

Install

To install, run: pip install notebookjs

Or clone this repository and run: python setup.py install

API

execute_js

This method executes a javascript function and sets up the infrastructure for bidirectional communication between Python and Javascript using callbacks.

execute_js(
    library_list,
    main_function,
    data_dict={},
    callbacks={},
    css_list=[],
)

Parameters

  • library_list : list of str. List of strings containing either 1) URL to a javascript library, 2) javascript code, 3) javascript bundle (Plain JS only - No support for ES6 Modules)
  • main_function : str. Name of the main function to be called. The function will be called with two parameters: , for example "#my_div", and .
  • data_dict : dict. Dictionary containing the data to be passed to
  • callbacks : dict. Dictionary of the form { : }. The javascript library can use callbacks to talk to python.
  • css_list : list of str. List of strings containing either 1) URL to a CSS stylesheet or 2) CSS styles

Main Function

main_function is the javascript function that will be run when execute_js is called. It has the following signature:

function main_function(div_id, data_dict)

Example of Main Function

As a simple example, we can use D3 to add a circular div to the output cell:

function draw_circle(div_id, data){
  // Function that draws a circle of color  inside the div  using D3
  d3.select(div_id)
    .append("div")
    .style("width", "50px")
    .style("height", "50px")
    .style("background-color", data.color)
    .style("border-radius", "50px")
}

Callbacks

callbacks contains a dictionary that maps an identifier string to a Python function. Data is passed to/from callbacks using json/dicts.

For example, the following callback computes the number to the power of 2.

def compute_power_2(data){
    n = data.n
    n2 = n**2
    return {"power2": n2}
}

callbacks = {
    "compute_power_2": compute_power_2
}

execute_js(..., callbacks=callbacks)

In Javascript, we can call this callback with the class CommAPI. CommAPI is automatically injected in the Javascript by notebookJS.

let comm = new CommAPI("compute_power_2", (ret)=>{alert("The returned value is " + ret.power2)})

comm.call({n: 3}) 
// An alert will be shown with the message: "The returned value is 9"

Jupyter Notebook and Google Colab have different APIs for sending data to/from Javascript/Python. CommAPI abstracts the different APIs in a single convenient class.

save_html

This method creates a standalone HTML bundle (containing all data, JS and CSS resources) and saves it to disk. It accepts all parameters of execute_js, with the addition of html_dest, the path to the output file. For example, html_dest="./output.html"

save_html(,
    html_dest,
    library_list,
    main_function,
    data_dict={},
    callbacks=None,
    css_list=[],
)

Warning: callbacks do not work in standalone HTML files. This parameter only exists to make execute_js and save_html interoperable.

Examples

Hello World - Python Callbacks

In this example, we show how to display "hello world" in multiple languages using Javascript and Python. The Javascript is responsible for updating the front end and requesting a new message from Python. Python returns a random message every time the callback is invoked.

Hello World Output Gif

Javascript to update the div with a hello world message

helloworld_js = """
function helloworld(div_id, data){
    comm = new CommAPI("get_hello", (ret) => {
      document.querySelector(div_id).textContent = ret.text;
    });
    setInterval(() => {comm.call({})}, 1000);
    comm.call({});
}
"""

Defining the Python Callback

import random
def hello_world_random(data):
  hello_world_languages = [
      "Ola Mundo", # Portuguese
      "Hello World", # English
      "Hola Mundo", # Spanish
      "Geiá sou Kósme", # Greek
      "Kon'nichiwa sekai", # Japanese
      "Hallo Welt", # German
      "Namaste duniya", # Hindi
      "Ni hao, shijiè" # Chinese
  ]
  i = random.randint(0, len(hello_world_languages)-1)
  return {'text': hello_world_languages[i]}

Invoking the function helloworld in notebook

from notebookjs import execute_js
execute_js(helloworld_js, "helloworld", callbacks={"get_hello": hello_world_random})

See this colab notebook for a live demo.

Radial Bar Chart - Running D3 code in the Notebook

Plotting a Radial Bar Chart with data loaded from Python. Adapted from this bl.ock. See Examples/3_RadialBarChart.

# Loading libraries
d3_lib_url = "https://d3js.org/d3.v3.min.js"

with open("radial_bar.css", "r") as f:
    radial_bar_css = f.read()
    
with open ("radial_bar_lib.js", "r") as f:
    radial_bar_lib = f.read()

# Loading data
import pandas as pd
energy = pd.read_csv("energy.csv")

# Plotting the Radial Bar Chart
from notebookjs import execute_js
execute_js(library_list=[d3_lib_url, radial_bar_lib], main_function="radial_bar", 
             data_dict=energy.to_dict(orient="records"), css_list=[radial_bar_css])

Radial Bar Chart

More examples

Please see the Examples/ folder for more examples.

Reference

If you use notebookJS, please reference the following work:

"Interactive Data Visualization in Jupyter Notebooks. JP Ono, J Freire, CT Silva - Computing in Science & Engineering, 2021"

Bibtex:

@article{ono2021interactive,
  title={Interactive Data Visualization in Jupyter Notebooks},
  author={Ono, Jorge Piazentin and Freire, Juliana and Silva, Claudio T},
  journal={Computing in Science \& Engineering},
  volume={23},
  number={2},
  pages={99--106},
  year={2021},
  publisher={IEEE}
}
You might also like...
cottonformation is a Python tool providing best development experience and highest productivity
cottonformation is a Python tool providing best development experience and highest productivity

Welcome to cottonformation Documentation Full Documentatioin Here cottonformation is a Python tool providing best development experience and highest p

Live coding in Python with PyCharm, Emacs, Sublime Text, or even a browser
Live coding in Python with PyCharm, Emacs, Sublime Text, or even a browser

Live Coding in Python Visualize your Python code while you type it in PyCharm, Emacs, Sublime Text, or even your browser. To see how to use one of the

An amazing simple Python IDE for developers!
An amazing simple Python IDE for developers!

PyHub An amazing simple Python IDE for developers! Get ready to compile and run your code in the most simplest and easiest IDE of the ancient world! T

JavaScript Raider is a coverage-guided JavaScript fuzzing framework designed for the v8 JavaScript engine

JavaScript Raider is a coverage-guided JavaScript fuzzing framework designed for the v8 JavaScript engine

Python for .NET is a package that gives Python programmers nearly seamless integration with the .NET Common Language Runtime (CLR) and provides a powerful application scripting tool for .NET developers.

pythonnet - Python.NET Python.NET is a package that gives Python programmers nearly seamless integration with the .NET Common Language Runtime (CLR) a

Run your jupyter notebooks as a REST API endpoint. This isn't a jupyter server but rather just a way to run your notebooks as a REST API Endpoint.

Jupter Notebook REST API Run your jupyter notebooks as a REST API endpoint. This isn't a jupyter server but rather just a way to run your notebooks as

pybind11 — Seamless operability between C++11 and Python
pybind11 — Seamless operability between C++11 and Python

pybind11 — Seamless operability between C++11 and Python Setuptools example • Scikit-build example • CMake example pybind11 is a lightweight header-on

Implementation for
Implementation for "Seamless Manga Inpainting with Semantics Awareness" (SIGGRAPH 2021 issue)

Seamless Manga Inpainting with Semantics Awareness [SIGGRAPH 2021](To appear) | Project Website | BibTex Introduction: Manga inpainting fills up the d

Roboflow makes managing, preprocessing, augmenting, and versioning datasets for computer vision seamless.
Roboflow makes managing, preprocessing, augmenting, and versioning datasets for computer vision seamless.

Roboflow makes managing, preprocessing, augmenting, and versioning datasets for computer vision seamless. This is the official Roboflow python package that interfaces with the Roboflow API.

docTR by Mindee (Document Text Recognition) - a seamless, high-performing & accessible library for OCR-related tasks powered by Deep Learning.
docTR by Mindee (Document Text Recognition) - a seamless, high-performing & accessible library for OCR-related tasks powered by Deep Learning.

docTR by Mindee (Document Text Recognition) - a seamless, high-performing & accessible library for OCR-related tasks powered by Deep Learning.

Command line utility for converting images to seamless tiles
Command line utility for converting images to seamless tiles

img2texture Command line utility for converting images to seamless tiles. The resulting tiles can be used as textures in games, compositing and 3D mod

The Research PACS on AWS solution facilitates researchers' access medical images stored in the clinical PACS in a secure and seamless manner
The Research PACS on AWS solution facilitates researchers' access medical images stored in the clinical PACS in a secure and seamless manner

Research PACS on AWS Challenge to solve Solution presentation Deploy the solution Further reading Releases License Challenge to solve The rise of new

Seamless deployment and management of cybersecurity solutions 🏗️
Seamless deployment and management of cybersecurity solutions 🏗️

Description 🖼️ Background 👴🏼 Vision 📜 Concepts 💬 Solutions' Lifecycle. Operations ⭕ Functionalities 🚀 Supported Cybersecurity Solutions 📦 Insta

Launched in 2018 Actively developed and supported. Supports tkinter, Qt, WxPython, Remi (in browser). Create custom layout GUI's simply.  Python 2.7 & 3 Support. 200+ Demo programs & Cookbook for rapid start. Extensive documentation.  Examples using Machine Learning(GUI, OpenCV Integration,  Chatterbot), Floating Desktop Widgets, Matplotlib + Pyplot integration, add GUI to command line scripts, PDF & Image Viewer. For both beginning and advanced programmers . Learn to build a Python Desktop GUI app using pywebview, Python, JavaScript, HTML, & CSS.
Learn to build a Python Desktop GUI app using pywebview, Python, JavaScript, HTML, & CSS.

Python Desktop App Learn how to make a desktop GUI application using Python, JavaScript, HTML, & CSS all thanks to pywebview. pywebview is essentially

Todos os exercícios do Curso de Python, do canal Curso em Vídeo, resolvidos em Python, Javascript, Java, C++, C# e mais...
Todos os exercícios do Curso de Python, do canal Curso em Vídeo, resolvidos em Python, Javascript, Java, C++, C# e mais...

Exercícios - CeV Oferecido por Linguagens utilizadas atualmente O que vai encontrar aqui? 👀 Esse repositório é dedicado a armazenar todos os enunciad

✨ Voici un code en Python par moi, et en français qui permet d'exécuter du Javascript en Python.
✨ Voici un code en Python par moi, et en français qui permet d'exécuter du Javascript en Python.

JavaScript In Python ❗ Voici un code en Python par moi, et en français qui permet d'exécuter du Javascript en Python. 🔮 Une vidéo pour vous expliquer

Python & JavaScript Obfuscator made in Python 3.

Python Code Obfuscator A script that converts code into full on random numerical expressions. Simple Scripts: Python Mode... Input: Function that deco

A Python & JavaScript Obfuscator made in Python 3.

Python Code Obfuscator A script that converts code into full on random numerical expressions. Simple Scripts: Python Mode... Input: Function that deco

Owner
jorgehpo
jorgehpo
VSCode extension to sort and refactor python imports using reorder-python-imports.

reorder-python-imports VSCode extension to sort and refactor python imports using reorder-python-imports. Unlike other import organizers, reorder-pyth

Ryan Butler 3 Aug 26, 2022
Python Indent - Correct python indentation in Visual Studio Code.

Python Indent Correct python indentation in Visual Studio Code. See the extension on the VSCode Marketplace and its source code on GitHub. Please cons

Kevin Rose 57 Dec 15, 2022
Spyder - The Scientific Python Development Environment

Spyder is a powerful scientific environment written in Python, for Python, and designed by and for scientists, engineers and data analysts. It offers a unique combination of the advanced editing, analysis, debugging, and profiling functionality of a comprehensive development tool with the data exploration, interactive execution, deep inspection, and beautiful visualization capabilities of a scientific package.

Spyder IDE 7.3k Jan 8, 2023
Gaphor is a UML and SysML modeling application written in Python.

Gaphor is a UML and SysML modeling application written in Python. It is designed to be easy to use, while still being powerful. Gaphor implements a fully-compliant UML 2 data model, so it is much more than a picture drawing tool. You can use Gaphor to quickly visualize different aspects of a system as well as create complete, highly complex models.

Gaphor 1.3k Jan 7, 2023
Mu - A Simple Python Code Editor

A small, simple editor for beginner Python programmers. Written in Python and Qt5.

Mu 1.2k Jan 3, 2023
A GitHub Action hosted Python IDE!

What is this ? This is an IDE running on GitHub Actions which can help in..... Running small snippets. Running codes whenever PC is not available and

Jainam Oswal 21 Nov 9, 2022
Python 3 patcher for Sublime Text v4107-4114 Windows x64

sublime-text-4-patcher Python 3 patcher for Sublime Text v4107-4114 Windows x64 Credits for signatures and patching logic goes to https://github.com/l

null 187 Dec 27, 2022
Python IDE or notebook to generate a basic Kepler.gl data visualization

geospatial-data-analysis [readme] Use this code in your Python IDE or notebook to generate a basic Kepler.gl data visualization, without pre-configura

null 2 Sep 5, 2022
A Python code editor that looks like GNU Emacs.

?? WARNING ?? : Under development... Testing is not recommended! Welcome to Snake Editor! Hi! This is our repository, we are here to present our new p

Marcio Dantas 5 May 20, 2022
This is code for IDLE python/ Magic8Ball Code

Magic8Ball this is code for IDLE python/ Magic8Ball Code this code is for beginers i hope you can learn code form this don't ever be a script kiddie a

null 1 Nov 5, 2021