%load_ext streamlit_jupyter
Streamlit
Streamlit turns Python code into shareable web applications, without the need for front end knowledge. With some extra configuration, you can create Streamlit dashboards based on Jupyter notebooks in TileDB. The following steps will guide you through creating a basic Streamlit dashboard.
Launch a new notebook server
To start, launch a new notebook server. Select the image and server size based on your needs. After opening the server, open the launcher. Under the Other section, select Terminal.
Create the streamlit_jupyter
plugin
Create a new file named streamlit_jupyter.py
in your home directory:
touch ~/streamlit_jupyter.py
nano ~/streamlit_jupyter.py
Paste the following code into the file:
streamlit_jupyter.py
import os
import socket
import subprocess
import tempfile
import threading
import time
from IPython.core.magic import Magics, cell_magic, magics_class
def find_free_port():
"""Find an available port for the Streamlit app."""
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
"", 0))
s.bind((1)
s.listen(= s.getsockname()[1]
port return port
def start_streamlit_app(script_path, port):
"""Start a Streamlit app in a separate thread."""
def run_streamlit():
subprocess.run(
["~/.local/bin/streamlit"),
os.path.expanduser("run",
script_path,"--server.port",
str(port),
"--browser.gatherUsageStats",
"false",
">/dev/null",
"2>&1",
]
)
= threading.Thread(target=run_streamlit, daemon=True)
thread
thread.start()3) # Give the app a moment to start
time.sleep(return thread
@magics_class
class StreamlitMagics(Magics):
@cell_magic
def streamlit(self, line, cell):
"""
Jupyter cell magic to run Streamlit apps.
Args:
line (str): Magic command line arguments (unused)
cell (str): Cell content containing Streamlit code
Returns:
IPython.display.IFrame: An iframe displaying the Streamlit app
"""
from IPython.display import IFrame
# Create a temporary file
with tempfile.NamedTemporaryFile(
="w", suffix=".py", delete=False
modeas temp_file:
) # Ensure necessary imports are present
= "import streamlit as st\n"
imports
# Write imports and cell content to the temp file
+ cell)
temp_file.write(imports = temp_file.name
temp_file_path
# Find an available port
= find_free_port()
port
# Start the Streamlit app
start_streamlit_app(temp_file_path, port)
# Create an iframe pointing to the Streamlit app
# Create an iframe pointing to the Streamlit app
if os.getenv("JUPYTERHUB_API_URL"):
= os.getenv("JUPYTERHUB_USER")
user = f"/user/{user}/proxy/{port}/"
url else:
= f"http://localhost:{port}/"
url return IFrame(src=url, width="100%", height="600px")
def load_ipython_extension(ipython):
"""
Register the Streamlit magic command.
Args:
ipython (InteractiveShell): IPython shell instance
"""
ipython.register_magics(StreamlitMagics)
def unload_ipython_extension(ipython):
"""
Unregister the Streamlit magic command.
Args:
ipython (InteractiveShell): IPython shell instance
"""
# No direct way to unregister, but this prevents further use
try:
del ipython.magics_manager.magics["cell"]["streamlit"]
except KeyError:
pass
Now save the file:
- Press Ctrl-OCtrl-O to write out the changes.
- Press EnterEnter or ReturnReturn to use the existing filename.
- Press Ctrl-XCtrl-X to exit the editor.
Create a new notebook
Start by creating a new notebook in TileDB. In the first cell, you’ll load the streamlit_jupyter
plugin you created earlier.
Next, install Streamlit into your user directory:
Finally, add the %%streamlit
cell magic, and add the rest of your code to build your dashboard:
Convert notebook to dashboard
Convert the notebook to a dashboard, and launch the dashboard in the existing server.
Your dashboard should look something like this: