A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
Add Panel support (#2719)
Philipp Rudigera0ba6041a48b
diff --git a/frontend/src/plugins/impl/panel/PanelPlugin.tsx b/frontend/src/plugins/impl/panel/PanelPlugin.tsxnew file mode 100644index 0000000000..32c0f34f69--- /dev/null+++ b/frontend/src/plugins/impl/panel/PanelPlugin.tsx@@ -0,0 +1,211 @@+/* Copyright 2024 Marimo. All rights reserved. */+/* eslint-disable @typescript-eslint/no-explicit-any */+import { z } from "zod";++import type { IPluginProps } from "@/plugins/types";+import { useEffect, useRef, useState } from "react";+import { createPlugin } from "@/plugins/core/builder";+import { rpc } from "@/plugins/core/rpc";+import { useEventListener } from "@/hooks/useEventListener";+import { MarimoIncomingMessageEvent } from "@/core/dom/events";++interface Data {+ extension: string | null;+ docs_json: any;+ render_json: any;+}++type T = Record<string, any>;++// eslint-disable-next-line @typescript-eslint/consistent-type-definitions+type PluginFunctions = {+ send_to_widget: <T>(req: { message?: any; buffers?: any }) => Promise<+ null | undefined+ >;+};++export const PanelPlugin = createPlugin<T>("marimo-panel")+ .withData(+ z.object({+ extension: z.string().nullable(),+ docs_json: z.any(),+ render_json: z.any(),+ }),+ )+ .withFunctions<PluginFunctions>({+ send_to_widget: rpc+ .input(z.object({ message: z.any(), buffers: z.array(z.any()) }))+ .output(z.null().optional()),+ })+ .renderer((props) => <PanelSlot {...props} />);++function isObject(obj: unknown): obj is object {+ const tp = typeof obj;+ return tp === "function" || (tp === "object" && !!obj);+}++function is_nullish(obj: unknown): obj is null | undefined {+ return obj == null;+}++function isPlainObject<T>(obj: unknown): obj is { [key: string]: T } {+ return (+ isObject(obj) && (is_nullish(obj.constructor) || obj.constructor === Object)+ );+}++function extract_buffers(value: unknown, buffers: ArrayBuffer[]): any {+ if (Array.isArray(value)) {+ for (const val of value) {+ extract_buffers(val, buffers);+ }+ } else if (value instanceof Map) {+ for (const key of value.keys()) {+ const v = value.get(key);+ extract_buffers(v, buffers);+ }+ } else if (value.to_base64 !== undefined) {+ const { buffer } = value;+ const id = buffers.length;+ buffers.push(buffer);+ return { id };+ } else if (isPlainObject(value)) {+ for (const key of Object.keys(value)) {+ const replaced = extract_buffers(value[key], buffers);+ if (replaced != null) {+ value[key] = replaced;+ }+ }+ }+}++type Props = IPluginProps<T, Data, PluginFunctions>;++const PanelSlot = (props: Props) => {+ const { data, functions, host } = props;+ const { extension, docs_json, render_json } = data;+ const ref = useRef<HTMLDivElement>(null);+ const blocked = useRef<boolean>(false);+ const doc = useRef<any>(null);+ const receiver = useRef<any>(null);+ const [loaded, setLoaded] = useState<boolean>(false);+ const [rendered, setRendered] = useState<string | null>(null);++ const event_buffer = [];+ let timeout = Date.now();++ const process_events = () => {+ const events = event_buffer.splice(0);+ const patch = doc.current.create_json_patch(events);+ const message = {+ ...Bokeh.protocol.Message.create("PATCH-DOC", {}, patch),+ };+ const buffers: ArrayBuffer[] = [];+ extract_buffers(message.content, buffers);+ functions.send_to_widget({ message, buffers });+ };++ useEffect(() => {+ if (loaded || rendered) {+ return;+ }+ let script: HTMLScriptElement;+ if (extension.length > 0) {+ script = document.createElement("script");+ script.innerHTML = extension;+ document.head.append(script);+ }++ const checkBokeh = setInterval(() => {+ if (window.Bokeh) {+ setLoaded(true);+ clearInterval(checkBokeh);+ }+ }, 10);++ return () => {+ clearInterval(checkBokeh);+ };+ }, [extension]);++ // Listen to incoming messages+ useEventListener(host, MarimoIncomingMessageEvent.TYPE, (e) => {+ const doc_id = Object.keys(docs_json)[0];+ const metadata = e.detail.metadata;+ const buffers = e.detail.buffers;+ const content = e.detail.message.content;+ if (content.type === "ACK") {+ if (event_buffer.length) {+ process_events();+ timeout = Date.now();+ } else {+ blocked.current = false;+ }+ return;+ }+ if (content.length > 0) {+ receiver.current.consume(content);+ } else if (buffers !== undefined && buffers.length > 0) {+ receiver.current.consume(buffers[0].buffer);+ } else {+ return;+ }+ const comm_msg = receiver.current.message;+ if (comm_msg != null && Object.keys(comm_msg.content).length > 0) {+ if (comm_msg.content.events !== undefined) {+ comm_msg.content.events = comm_msg.content.events.filter((e) =>+ doc.current._all_models.has(e.model.id),+ );+ }+ doc.current.apply_json_patch(comm_msg.content, comm_msg.buffers);+ }+ });++ useEffect(() => {+ const doc_id = Object.keys(docs_json)[0];+ if (!loaded || rendered === doc_id) {+ return;+ }+ event_buffer.length = 0;++ const sendEvent = (event) => {+ event_buffer.push(event);+ if (!blocked.current || Date.now() > timeout) {+ setTimeout(() => process_events(), 50);+ blocked.current = true;+ timeout = Date.now() + 5000;+ }+ };++ const embedItems = async () => {+ const render_item = { ...render_json };+ const roots = {};+ for (const model_id of Object.keys(render_json.roots)) {+ const root_id = render_json.roots[model_id];+ const el = ref.current.querySelector(`#${root_id}`);+ roots[model_id] = el;+ }+ render_item.roots = roots;+ const model_id = Object.keys(roots)[0];+ await Bokeh.embed.embed_items_notebook(docs_json, [render_item]);+ doc.current = Bokeh.index.get_by_id(model_id).model.document;+ receiver.current = new Bokeh.protocol.Receiver();+ doc.current.on_change(sendEvent);+ setRendered(doc_id);+ };+ embedItems();+ }, [docs_json, functions, loaded, render_json, rendered]);++ return (+ <div ref={ref}>+ {Object.keys(render_json.roots).map((model_id) => {+ const root_id = render_json.roots[model_id];+ return (+ <div key={root_id} id={root_id}>+ <div data-root-id={root_id} style={{ display: "contents" }} />+ </div>+ );+ })}+ </div>+ );+};diff --git a/frontend/src/plugins/plugins.ts b/frontend/src/plugins/plugins.tsindex 25b922b4e2..abfaf0ad78 100644--- a/frontend/src/plugins/plugins.ts+++ b/frontend/src/plugins/plugins.ts@@ -48,6 +48,7 @@ import { DateRangePickerPlugin } from "./impl/DateRangePlugin";import { MimeRendererPlugin } from "./layout/MimeRenderPlugin";import { ChatPlugin } from "./impl/chat/ChatPlugin";import { DataEditorPlugin } from "./impl/DataEditorPlugin";+import { PanelPlugin } from "./impl/panel/PanelPlugin";// List of UI pluginsexport const UI_PLUGINS: Array<IPlugin<any, unknown>> = [@@ -82,6 +83,7 @@ export const UI_PLUGINS: Array<IPlugin<any, unknown>> = [LazyPlugin,AnyWidgetPlugin,DataEditorPlugin,+ PanelPlugin,];// List of output / layout pluginsdiff --git a/marimo/_dependencies/dependencies.py b/marimo/_dependencies/dependencies.pyindex 9102939caf..aca2a98227 100644--- a/marimo/_dependencies/dependencies.py+++ b/marimo/_dependencies/dependencies.py@@ -165,6 +165,7 @@ class DependencyManager:opentelemetry = Dependency("opentelemetry")anthropic = Dependency("anthropic")google_ai = Dependency("google.generativeai")+ panel = Dependency("panel")@staticmethoddef has(pkg: str) -> bool:diff --git a/marimo/_output/formatters/formatters.py b/marimo/_output/formatters/formatters.pyindex 70e09d8a25..81ced8473a 100644--- a/marimo/_output/formatters/formatters.py+++ b/marimo/_output/formatters/formatters.py@@ -22,6 +22,7 @@ from marimo._output.formatters.leafmap_formatters import LeafmapFormatterfrom marimo._output.formatters.lets_plot_formatters import LetsPlotFormatterfrom marimo._output.formatters.matplotlib_formatters import MatplotlibFormatterfrom marimo._output.formatters.pandas_formatters import PandasFormatter+from marimo._output.formatters.panel_formatters import PanelFormatterfrom marimo._output.formatters.plotly_formatters import PlotlyFormatterfrom marimo._output.formatters.pyecharts_formatters import PyechartsFormatterfrom marimo._output.formatters.seaborn_formatters import SeabornFormatter@@ -51,6 +52,7 @@ THIRD_PARTY_FACTORIES: dict[str, FormatterFactory] = {LetsPlotFormatter.package_name(): LetsPlotFormatter(),SympyFormatter.package_name(): SympyFormatter(),PyechartsFormatter.package_name(): PyechartsFormatter(),+ PanelFormatter.package_name(): PanelFormatter(),}# Formatters for builtin types and other things that don't require adiff --git a/marimo/_output/formatters/holoviews_formatters.py b/marimo/_output/formatters/holoviews_formatters.pyindex 2646e9b4fd..5896440883 100644--- a/marimo/_output/formatters/holoviews_formatters.py+++ b/marimo/_output/formatters/holoviews_formatters.py@@ -5,8 +5,7 @@ from marimo._config.config import Themefrom marimo._dependencies.dependencies import DependencyManagerfrom marimo._messaging.mimetypes import KnownMimeTypefrom marimo._output.formatters.formatter_factory import FormatterFactory-from marimo._output.formatters.plotly_formatters import PlotlyFormatter-from marimo._output.formatting import as_html+from marimo._plugins.ui._impl.from_panel import from_panelclass HoloViewsFormatter(FormatterFactory):@@ -37,23 +36,7 @@ class HoloViewsFormatter(FormatterFactory):| hv.core.ndmapping.NdMapping),) -> tuple[KnownMimeType, str]:- backend_output = hv.render(plot)-- # If its a dict, then its a plotly figure,- # and we should convert it to a plotly object- if DependencyManager.plotly.has() and isinstance(- backend_output, dict- ):- plotly_html = PlotlyFormatter.render_plotly_dict(- backend_output- )- return ("text/html", plotly_html.text)-- # Call as_html to recurse back into the formatter- # this may be bokeh, matplotlib, or plotly- html = as_html(backend_output)-- return ("text/html", html.text)+ return from_panel(plot)._mime_()def apply_theme(self, theme: Theme) -> None:import holoviews as hv # type: ignorediff --git a/marimo/_output/formatters/panel_formatters.py b/marimo/_output/formatters/panel_formatters.pynew file mode 100644index 0000000000..95f54a6d4f--- /dev/null+++ b/marimo/_output/formatters/panel_formatters.py@@ -0,0 +1,26 @@+# Copyright 2024 Marimo. All rights reserved.+from __future__ import annotations++from typing import Any++from marimo._messaging.mimetypes import KnownMimeType+from marimo._output.formatters.formatter_factory import FormatterFactory+from marimo._plugins.ui._impl.from_panel import from_panel+++class PanelFormatter(FormatterFactory):+ @staticmethod+ def package_name() -> str:+ return "panel"++ def register(self) -> None:+ import panel # type: ignore [import-not-found]+ import param++ from marimo._output import formatting++ @formatting.formatter(param.reactive.rx)+ @formatting.formatter(panel.viewable.Viewable)+ @formatting.formatter(panel.viewable.Viewer)+ def _from(lmap: Any) -> tuple[KnownMimeType, str]:+ return from_panel(lmap)._mime_()diff --git a/marimo/_plugins/ui/__init__.py b/marimo/_plugins/ui/__init__.pyindex 20553b484b..1ab60c9cef 100644--- a/marimo/_plugins/ui/__init__.py+++ b/marimo/_plugins/ui/__init__.py@@ -29,6 +29,7 @@ __all__ = ["microphone","multiselect","number",+ "panel","plotly","radio","range_slider",@@ -58,6 +59,7 @@ from marimo._plugins.ui._impl.dates import ()from marimo._plugins.ui._impl.dictionary import dictionaryfrom marimo._plugins.ui._impl.from_anywidget import anywidget+from marimo._plugins.ui._impl.from_panel import panelfrom marimo._plugins.ui._impl.input import (button,checkbox,diff --git a/marimo/_plugins/ui/_impl/anywidget/init.py b/marimo/_plugins/ui/_impl/anywidget/init.pyindex 9219a714f6..16dd2e2266 100644--- a/marimo/_plugins/ui/_impl/anywidget/init.py+++ b/marimo/_plugins/ui/_impl/anywidget/init.py@@ -8,7 +8,7 @@ if TYPE_CHECKING:import ipywidgets # type: ignorefrom marimo._dependencies.dependencies import DependencyManager-from marimo._plugins.ui._impl.anywidget.comm import ( # pyright: ignore[reportMissingTypeStubs]+from marimo._plugins.ui._impl.comm import ( # pyright: ignore[reportMissingTypeStubs]BufferType,MarimoComm,MarimoCommManager,diff --git a/marimo/_plugins/ui/_impl/anywidget/comm.py b/marimo/_plugins/ui/_impl/comm.pysimilarity index 100%rename from marimo/_plugins/ui/_impl/anywidget/comm.pyrename to marimo/_plugins/ui/_impl/comm.pydiff --git a/marimo/_plugins/ui/_impl/from_anywidget.py b/marimo/_plugins/ui/_impl/from_anywidget.pyindex 59685a8ef2..e6c6e8e669 100644--- a/marimo/_plugins/ui/_impl/from_anywidget.py+++ b/marimo/_plugins/ui/_impl/from_anywidget.py@@ -10,7 +10,7 @@ from marimo import _loggersfrom marimo._output.rich_help import mddocfrom marimo._plugins.core.json_encoder import WebComponentEncoderfrom marimo._plugins.ui._core.ui_element import InitializationArgs, UIElement-from marimo._plugins.ui._impl.anywidget.comm import MarimoComm+from marimo._plugins.ui._impl.comm import MarimoCommfrom marimo._runtime.functions import Functionif TYPE_CHECKING:diff --git a/marimo/_plugins/ui/_impl/from_panel.py b/marimo/_plugins/ui/_impl/from_panel.pynew file mode 100644index 0000000000..5b65ededec--- /dev/null+++ b/marimo/_plugins/ui/_impl/from_panel.py@@ -0,0 +1,254 @@+# Copyright 2024 Marimo. All rights reserved.+from __future__ import annotations++import sys+from dataclasses import dataclass+from functools import partial+from typing import Any, Dict, ForwardRef, Optional, Tuple++from marimo import _loggers+from marimo._output.rich_help import mddoc+from marimo._plugins.ui._core.ui_element import InitializationArgs, UIElement+from marimo._plugins.ui._impl.comm import MarimoComm, MarimoCommManager+from marimo._runtime.functions import Function++LOGGER = _loggers.marimo_logger()++COMM_MANAGER = MarimoCommManager()++comm_class = None+loaded_extension: int = 0+loaded_extensions: list[str] = []+++def from_panel(obj: Any) -> UIElement[Any, Any]:+ """Create a UIElement from an Panel."""+ return panel(obj)+++T = Dict[str, Any]+++@dataclass+class SendToWidgetArgs:+ message: Any+ buffers: Optional[Any] = None+++def _get_comm_class() -> ForwardRef("MarimoPanelComm"):+ global comm_class+ if comm_class:+ return comm_class++ from pyviz_comms import Comm++ class MarimoPanelComm(Comm):+ def __init__(self, *args: any, **kwargs: any):+ super().__init__(*args, **kwargs)+ self._comm = MarimoComm(+ comm_id=self.id,+ target_name="panel.comms",+ data={},+ comm_manager=COMM_MANAGER,+ )+ self._comm.on_msg(self._handle_msg)+ if self._on_open:+ self._on_open({})++ @classmethod+ def decode(cls, msg: SendToWidgetArgs) -> dict[str, Any]:+ buffers = {i: v for i, v in enumerate(msg.buffers)}+ return dict(msg.message, _buffers=buffers)++ def send(self, data=None, metadata=None, buffers=None) -> None:+ buffers = buffers or []+ self.comm.send(+ {"content": data}, metadata=metadata, buffers=buffers+ )++ comm_class = MarimoPanelComm+ return comm_class+++def render_extension(load_timeout: int = 500, loaded: bool = False) -> str:+ from panel.config import panel_extension++ new_exts = [+ ext+ for ext in panel_extension._loaded_extensions+ if ext not in loaded_extensions+ ]+ if loaded and not new_exts:+ return ""++ from bokeh.io.notebook import curstate+ from panel.config import config+ from panel.io.notebook import (+ CDN,+ INLINE,+ Resources,+ _autoload_js,+ _Unset,+ bundle_resources,+ require_components,+ settings,+ state,+ )++ curstate().output_notebook()++ resources = INLINE if config.inline else CDN+ prev_resources = settings.resources(default="server")+ user_resources = settings.resources._user_value is not _Unset+ nb_endpoint = not state._is_pyodide+ resources = Resources.from_bokeh(resources, notebook=nb_endpoint)+ try:+ bundle = bundle_resources(+ None,+ resources,+ notebook=nb_endpoint,+ reloading=loaded,+ enable_mathjax="auto",+ )+ configs, requirements, exports, skip_imports = require_components()+ ipywidget = "ipywidgets_bokeh" in sys.modules+ bokeh_js = _autoload_js(+ bundle=bundle,+ configs=configs,+ requirements=requirements,+ exports=exports,+ skip_imports=skip_imports,+ ipywidget=ipywidget,+ reloading=loaded,+ load_timeout=load_timeout,+ )+ finally:+ if user_resources:+ settings.resources = prev_resources+ else:+ settings.resources.unset_value()+ loaded_extensions.extend(new_exts)+ return bokeh_js+++def render_component(obj) -> Tuple[str, dict[str, Any], dict[str, Any]]:+ from bokeh.document import Document+ from bokeh.embed.util import standalone_docs_json_and_render_items+ from panel.io.model import add_to_doc++ doc = Document()+ comm = _get_comm_class()()+ root = obj._render_model(doc, comm)+ ref = root.ref["id"]+ obj._comms[ref] = (comm, comm)+ add_to_doc(root, doc, True)+ (docs_json, [render_item]) = standalone_docs_json_and_render_items(+ [root], suppress_callback_warning=True+ )+ render_json = render_item.to_json()+ return ref, docs_json, render_json+++@mddoc+class panel(UIElement[T, T]):+ """+ Create a UIElement from a Panel component.+ This proxies all the widget's attributes and methods.++ **Example.**++ ```python+ import marimo as mo+ import panel as pn++ slider = pn.widgets.IntSlider(start=0, end=10, value=5)+ rx_stars = mo.ui.panel(slider.rx() * "*")++ # In another cell, access its value+ # This works for all widgets+ slider.value+ ```++ **Attributes.**++ - `obj`: The widget being wrapped.++ **Initialization Args.**++ - `obj`: The widget to wrap.+ """++ def __init__(self, obj: Any):+ from panel.models.comm_manager import CommManager as PanelCommManager+ from panel.pane import panel++ self.obj = obj = panel(obj)+ # This gets set to True in super().__init__()+ self._initialized = False++ ref, docs_json, render_json = render_component(obj)+ self._manager = PanelCommManager(plot_id=ref)++ global loaded_extension+ extension = render_extension(loaded=loaded_extension == id(self))+ if loaded_extension == 0:+ loaded_extension = id(self)++ super().__init__(+ component_name="marimo-panel",+ initial_value=None,+ label="",+ args={+ "extension": extension,+ "render_json": render_json,+ "docs_json": docs_json,+ },+ on_change=None,+ functions=(+ Function(+ name="send_to_widget",+ arg_cls=SendToWidgetArgs,+ function=partial(self._handle_msg, ref),+ ),+ ),+ )++ def _handle_msg(self, ref, msg) -> None:+ comm = self.obj._comms[ref][0]+ msg = comm.decode(msg)+ self.obj._on_msg(ref, self._manager, msg)+ comm.send(data={"type": "ACK"})++ def _initialize(+ self,+ initialization_args: InitializationArgs[+ Dict[str, Any], Dict[str, Any]+ ],+ ) -> None:+ super()._initialize(initialization_args)+ for comm, _ in self.obj._comms.values():+ if isinstance(comm.comm, MarimoComm):+ comm.comm.ui_element_id = self._id++ def _convert_value(self, value: T) -> T:+ return value++ # After the panel component has been initialized+ # forward all setattr to the component+ def __setattr__(self, name: str, value: Any) -> None:+ if self._initialized:+ # If the widget has the attribute, set it+ if hasattr(self.obj, name):+ return setattr(self.obj, name, value)+ return super().__setattr__(name, value)+ return super().__setattr__(name, value)++ # After the panel component has been initialized+ # forward all getattr to the component+ def __getattr__(self, name: str) -> Any:+ if name in ("widget", "_initialized"):+ try:+ return self.__getattribute__(name)+ except AttributeError:+ return None+ return getattr(self.obj, name)