Skip to main content

No project description provided

Project description

Datalayer

Become a Sponsor

🪐 Jupyter NbModel Client

Github Actions Status PyPI - Version

Jupyter NbModel Client is a python library to interact with a live Jupyter Notebooks.

To install the library, run the following command.

pip install jupyter_nbmodel_client

Usage with Jupyter

  1. Ensure you have the needed packages in your environment to run the example here after.
pip install jupyterlab jupyter-collaboration matplotlib
  1. Start a JupyterLab server, setting a port and a token to be reused by the agent, and create a notebook test.ipynb.
# make jupyterlab
jupyter lab --port 8888 --ServerApp.port_retries 0 --IdentityProvider.token MY_TOKEN --ServerApp.root_dir ./dev
  1. Open a IPython (needed for async functions) REPL in a terminal with ipython (or jupyter console). Execute the following snippet to add a cell in the test.ipynb notebook.
from jupyter_nbmodel_client import NbModelClient, get_jupyter_notebook_websocket_url

ws_url = get_jupyter_notebook_websocket_url(
    server_url="http://localhost:8888",
    token="MY_TOKEN",
    path="test.ipynb"
)

async with NbModelClient(ws_url) as nbmodel:
    nbmodel.add_code_cell("print('hello world')")

Check test.ipynb in JupyterLab, you should see a cell with content print('hello world') appended to the notebook.

  1. The previous example does not involve kernels. Put that now in the picture, adding a cell and executing the cell code within a kernel process.
from jupyter_kernel_client import KernelClient
from jupyter_nbmodel_client import NbModelClient, get_jupyter_notebook_websocket_url

with KernelClient(server_url="http://localhost:8888", token="MY_TOKEN") as kernel:
    ws_url = get_jupyter_notebook_websocket_url(
        server_url="http://localhost:8888",
        token="MY_TOKEN",
        path="test.ipynb"
    )
    async with NbModelClient(ws_url) as notebook:
        cell_index = notebook.add_code_cell("print('hello world')")
        results = notebook.execute_cell(cell_index, kernel)
        print(results)
        assert results["status"] == "ok"
        assert len(results["outputs"]) > 0

Check test.ipynb in JupyterLab. You should see an additional cell with content print('hello world') appended to the notebook, but this time the cell is executed, so the output should show hello world.

You can go further and create a plot with eg matplotlib.

from jupyter_kernel_client import KernelClient
from jupyter_nbmodel_client import NbModelClient, get_jupyter_notebook_websocket_url

CODE = """import matplotlib.pyplot as plt

fig, ax = plt.subplots()

fruits = ['apple', 'blueberry', 'cherry', 'orange']
counts = [40, 100, 30, 55]
bar_labels = ['red', 'blue', '_red', 'orange']
bar_colors = ['tab:red', 'tab:blue', 'tab:red', 'tab:orange']

ax.bar(fruits, counts, label=bar_labels, color=bar_colors)

ax.set_ylabel('fruit supply')
ax.set_title('Fruit supply by kind and color')
ax.legend(title='Fruit color')

plt.show()
"""

with KernelClient(server_url="http://localhost:8888", token="MY_TOKEN") as kernel:
    ws_url = get_jupyter_notebook_websocket_url(
        server_url="http://localhost:8888",
        token="MY_TOKEN",
        path="test.ipynb"
    )
    async with NbModelClient(ws_url) as notebook:
        cell_index = notebook.add_code_cell(CODE)
        results = notebook.execute_cell(cell_index, kernel)
        print(results)
        assert results["status"] == "ok"
        assert len(results["outputs"]) > 0

Check test.ipynb in JupyterLab for the cell with the matplotlib.

[!NOTE]

Instead of using the nbmodel clients as context manager, you can call the start() and stop() methods.

from jupyter_nbmodel_client import NbModelClient, get_jupyter_notebook_websocket_url

kernel = KernelClient(server_url="http://localhost:8888", token="MY_TOKEN")
kernel.start()

try:
    ws_url = get_jupyter_notebook_websocket_url(
        server_url="http://localhost:8888",
        token="MY_TOKEN",
        path="test.ipynb"
    )
    notebook = NbModelClient(ws_url)
    await notebook.start()
    try:
        cell_index = notebook.add_code_cell("print('hello world')")
        results = notebook.execute_cell(cell_index, kernel)
    finally:
        await notebook.stop()
finally:
    kernel.stop()

Usage with Datalayer

To connect to a Datalayer collaborative room, you can use the helper function get_datalayer_notebook_websocket_url:

  • The server is https://prod1.datalayer.run for the Datalayer production SaaS.
  • The room_id is the id of your notebook shown in the URL browser bar.
  • The token is the assigned token for the notebook.

All those details can be retrieved from a Notebook sidebar on the Datalayer SaaS.

from jupyter_nbmodel_client import NbModelClient, get_datalayer_notebook_websocket_url

ws_url = get_datalayer_notebook_websocket_url(
    server_url=server,
    room_id=room_id,
    token=token
)

async with NbModelClient(ws_url) as notebook:
    notebook.add_code_cell("1+1")

Uninstall

To remove the library, run the following.

pip uninstall jupyter_nbmodel_client

Contributing

Development install

# Clone the repo to your local environment
# Change directory to the jupyter_nbmodel_client directory
# Install package in development mode - will automatically enable
# The server extension.
pip install -e ".[test,lint,typing]"

Running Tests

Install dependencies:

pip install -e ".[test]"

To run the python tests, use:

pytest

Development uninstall

pip uninstall jupyter_nbmodel_client

Packaging the library

See RELEASE

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

jupyter_nbmodel_client-0.14.7.tar.gz (25.9 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

jupyter_nbmodel_client-0.14.7-py3-none-any.whl (23.0 kB view details)

Uploaded Python 3

File details

Details for the file jupyter_nbmodel_client-0.14.7.tar.gz.

File metadata

  • Download URL: jupyter_nbmodel_client-0.14.7.tar.gz
  • Upload date:
  • Size: 25.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.2.0 CPython/3.12.13

File hashes

Hashes for jupyter_nbmodel_client-0.14.7.tar.gz
Algorithm Hash digest
SHA256 c9ff959ea26f5b2876271dfe37882c4674551e0e2aafc7633a4ebc57c0260563
MD5 ccc253b2043f73c29390b77eeed3e3da
BLAKE2b-256 c3f9bf5a0ba321a227ba4c94bafa3d3950f9e773658773a81e379381b8687e25

See more details on using hashes here.

File details

Details for the file jupyter_nbmodel_client-0.14.7-py3-none-any.whl.

File metadata

File hashes

Hashes for jupyter_nbmodel_client-0.14.7-py3-none-any.whl
Algorithm Hash digest
SHA256 ff9371378608dd46f5cb58e394493aa6bde4efcbabbcb988fc331f55b5b7cef3
MD5 88443adfe9cd65c38bd0edbb8345b63a
BLAKE2b-256 3d615d6ada9177f164f3ca0394af899d09a7bb82b6ba9bb5f1d559a9d9f53758

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page