Skip to content

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.

fix: ipynb export matplotlib (#7696)

Akshay Agrawal831edcc47a1c
diff --git a/marimo/_messaging/mimetypes.py b/marimo/_messaging/mimetypes.py
index 5fac14f505..a4870aae9e 100644
--- a/marimo/_messaging/mimetypes.py
+++ b/marimo/_messaging/mimetypes.py
@@ -38,3 +38,6 @@ ConsoleMimeType = Literal[
MimeBundle = dict[KnownMimeType, Any]
MimeBundleOrTuple = Union[MimeBundle, tuple[MimeBundle, Any]]
+
+# Used for metadata in a marimo mimebundle
+METADATA_KEY = "__metadata__"
diff --git a/marimo/_output/mpl.py b/marimo/_output/mpl.py
index 1af1ee0962..0b5b8cae74 100644
--- a/marimo/_output/mpl.py
+++ b/marimo/_output/mpl.py
@@ -27,7 +27,7 @@ from matplotlib.backend_bases import (
from matplotlib.backends.backend_agg import FigureCanvasAgg
from marimo._messaging.cell_output import CellChannel
-from marimo._messaging.mimetypes import KnownMimeType
+from marimo._messaging.mimetypes import METADATA_KEY, KnownMimeType
from marimo._messaging.notification_utils import CellNotificationUtils
from marimo._utils.data_uri import build_data_url
@@ -88,7 +88,7 @@ def _render_figure_mimebundle(
width, height = _extract_png_dimensions(png_bytes)
mimebundle = {
"image/png": data_url,
- "__metadata__": {
+ METADATA_KEY: {
"image/png": {
"width": width // 2,
"height": height // 2,
diff --git a/marimo/_server/export/exporter.py b/marimo/_server/export/exporter.py
index 3fbcd422ef..86274815f8 100644
--- a/marimo/_server/export/exporter.py
+++ b/marimo/_server/export/exporter.py
@@ -4,16 +4,11 @@ from __future__ import annotations
import asyncio
import base64
import io
+import json
import mimetypes
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
-from typing import (
- TYPE_CHECKING,
- Any,
- Literal,
- Optional,
- cast,
-)
+from typing import TYPE_CHECKING, Any, Literal, Optional, cast
from marimo import _loggers
from marimo._ast.app import InternalApp
@@ -29,7 +24,7 @@ from marimo._config.utils import deep_copy
from marimo._convert.utils import get_markdown_from_cell
from marimo._dependencies.dependencies import DependencyManager
from marimo._messaging.cell_output import CellChannel, CellOutput
-from marimo._messaging.mimetypes import KnownMimeType
+from marimo._messaging.mimetypes import METADATA_KEY, KnownMimeType
from marimo._runtime import dataflow
from marimo._runtime.virtual_file import read_virtual_file
from marimo._schemas.notebook import NotebookV1
@@ -522,6 +517,17 @@ def get_html_contents() -> str:
return index_html.read_text(encoding="utf-8")
+def _maybe_extract_dataurl(data: Any) -> Any:
+ if (
+ isinstance(data, str)
+ and data.startswith("data:")
+ and ";base64," in data
+ ):
+ return data.split(";base64,")[1]
+ else:
+ return data
+
+
def _convert_marimo_output_to_ipynb(
output: Optional[CellOutput], console_outputs: list[CellOutput]
) -> list[NotebookNode]:
@@ -571,22 +577,26 @@ def _convert_marimo_output_to_ipynb(
# Handle rich output
data: dict[str, Any] = {}
+ metadata: dict[str, Any] = {}
if output.mimetype == "application/vnd.marimo+error":
# Captured by stdout/stderr
return ipynb_outputs
elif output.mimetype == "application/vnd.marimo+mimebundle":
- for mime, content in cast(dict[str, Any], output.data).items():
- data[mime] = content
- else:
- if (
- isinstance(output.data, str)
- and output.data.startswith("data:")
- and ";base64," in output.data
- ):
- data[output.mimetype] = output.data.split(";base64,")[1]
+ if isinstance(output.data, dict):
+ mimebundle = output.data
+ elif isinstance(output.data, str):
+ mimebundle = json.loads(output.data)
else:
- data[output.mimetype] = output.data
+ raise ValueError(f"Invalid data type: {type(output.data)}")
+
+ for mime, content in mimebundle.items():
+ if mime == METADATA_KEY and isinstance(content, dict):
+ metadata = content
+ else:
+ data[mime] = _maybe_extract_dataurl(content)
+ else:
+ data[output.mimetype] = _maybe_extract_dataurl(output.data)
if data:
ipynb_outputs.append(
@@ -595,7 +605,7 @@ def _convert_marimo_output_to_ipynb(
nbformat.v4.new_output( # type: ignore[no-untyped-call]
"display_data",
data=data,
- metadata={},
+ metadata=metadata,
),
)
)
diff --git a/marimo/_smoke_tests/ipython/mpl_plot.py b/marimo/_smoke_tests/ipython/mpl_plot.py
new file mode 100644
index 0000000000..58b7472b14
--- /dev/null
+++ b/marimo/_smoke_tests/ipython/mpl_plot.py
@@ -0,0 +1,16 @@
+import marimo
+
+__generated_with = "0.18.4"
+app = marimo.App()
+
+
+def _():
+ import matplotlib.pyplot as plt
+ plt.plot([1, 2])
+ plt.gca()
+ return
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/tests/_server/export/snapshots/run_until_completion_with_stack_trace.txt b/tests/_server/export/snapshots/run_until_completion_with_stack_trace.txt
index acf331dd59..5fe3ef520c 100644
--- a/tests/_server/export/snapshots/run_until_completion_with_stack_trace.txt
+++ b/tests/_server/export/snapshots/run_until_completion_with_stack_trace.txt
@@ -27,4 +27,4 @@
],
"status": "idle"
}
-]
+]
\ No newline at end of file
diff --git a/tests/_server/export/test_exporter.py b/tests/_server/export/test_exporter.py
index 1839da2922..aff097b45e 100644
--- a/tests/_server/export/test_exporter.py
+++ b/tests/_server/export/test_exporter.py
@@ -19,7 +19,11 @@ from marimo._server.export import (
run_app_then_export_as_ipynb,
run_app_until_completion,
)
-from marimo._server.export.exporter import Exporter
+from marimo._server.export.exporter import (
+ Exporter,
+ _convert_marimo_output_to_ipynb,
+ _maybe_extract_dataurl,
+)
from marimo._server.models.export import ExportAsHTMLRequest
from marimo._session.notebook import AppFileManager
from marimo._session.state.session_view import SessionView
@@ -1145,3 +1149,441 @@ def test_export_html_replaces_multiple_virtual_files_complex(
# Virtual file URLs should be replaced (though they may be URL-encoded in JSON)
# So we just check that the base64 data is present, which proves replacement worked
+
+
+# Tests for marimo mimebundle ipynb export support
+
+
+def test_maybe_extract_dataurl_with_base64_data():
+ """Test that _maybe_extract_dataurl extracts base64 data from data URLs."""
+ data_url = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA"
+ result = _maybe_extract_dataurl(data_url)
+ assert result == "iVBORw0KGgoAAAANSUhEUgAAAAUA"
+
+
+def test_maybe_extract_dataurl_without_base64():
+ """Test that _maybe_extract_dataurl returns non-data-URL strings as-is."""
+ regular_string = "hello world"
+ result = _maybe_extract_dataurl(regular_string)
+ assert result == "hello world"
+
+
+def test_maybe_extract_dataurl_with_non_string():
+ """Test that _maybe_extract_dataurl returns non-string data as-is."""
+ data = {"key": "value"}
+ result = _maybe_extract_dataurl(data)
+ assert result == {"key": "value"}
+
+ data = 123
+ result = _maybe_extract_dataurl(data)
+ assert result == 123
+
+
+def test_maybe_extract_dataurl_with_data_prefix_but_no_base64():
+ """Test that _maybe_extract_dataurl handles data: prefix without base64."""
+ data_url = "data:text/plain,hello"
+ result = _maybe_extract_dataurl(data_url)
+ assert result == "data:text/plain,hello"
+
+
[email protected](not HAS_NBFORMAT, reason="nbformat is not installed")
+def test_convert_marimo_mimebundle_to_ipynb_with_known_mimetypes():
+ """Test that marimo mimebundle with known mimetypes are converted correctly."""
+ mimebundle_data = json.dumps(
+ {
+ "text/plain": "Hello",
+ "text/html": "<p>Hello</p>",
+ "image/png": "data:image/png;base64,iVBORw0KGgo=",
+ }
+ )
+
+ output = CellOutput(
+ channel=CellChannel.OUTPUT,
+ mimetype="application/vnd.marimo+mimebundle",
+ data=mimebundle_data,
+ )
+
+ result = _convert_marimo_output_to_ipynb(output, [])
+
+ assert len(result) == 1
+ assert result[0]["output_type"] == "display_data"
+ assert "text/plain" in result[0]["data"]
+ assert result[0]["data"]["text/plain"] == "Hello"
+ assert "text/html" in result[0]["data"]
+ assert result[0]["data"]["text/html"] == "<p>Hello</p>"
+ assert "image/png" in result[0]["data"]
+ # Base64 data should be extracted from data URL
+ assert result[0]["data"]["image/png"] == "iVBORw0KGgo="
+
+
[email protected](not HAS_NBFORMAT, reason="nbformat is not installed")
+def test_convert_marimo_mimebundle_with_multiple_formats():
+ """Test marimo mimebundle with multiple output formats."""
+ mimebundle_data = json.dumps(
+ {
+ "text/plain": "Figure(640x480)",
+ "text/html": "<div>Chart</div>",
+ "image/png": "data:image/png;base64,PNG_BASE64_DATA",
+ "image/svg+xml": "<svg>...</svg>",
+ "application/json": {"data": [1, 2, 3]},
+ }
+ )
+
+ output = CellOutput(
+ channel=CellChannel.OUTPUT,
+ mimetype="application/vnd.marimo+mimebundle",
+ data=mimebundle_data,
+ )
+
+ result = _convert_marimo_output_to_ipynb(output, [])
+
+ assert len(result) == 1
+ assert result[0]["output_type"] == "display_data"
+ assert result[0]["data"]["text/plain"] == "Figure(640x480)"
+ assert result[0]["data"]["text/html"] == "<div>Chart</div>"
+ assert result[0]["data"]["image/png"] == "PNG_BASE64_DATA"
+ assert result[0]["data"]["image/svg+xml"] == "<svg>...</svg>"
+ assert result[0]["data"]["application/json"] == {"data": [1, 2, 3]}
+
+
[email protected](not HAS_NBFORMAT, reason="nbformat is not installed")
+def test_convert_regular_output_extracts_dataurl():
+ """Test that regular outputs also extract data URLs."""
+ output = CellOutput(
+ channel=CellChannel.OUTPUT,
+ mimetype="image/png",
+ data="data:image/png;base64,REGULAR_PNG_DATA",
+ )
+
+ result = _convert_marimo_output_to_ipynb(output, [])
+
+ assert len(result) == 1
+ assert result[0]["output_type"] == "display_data"
+ assert result[0]["data"]["image/png"] == "REGULAR_PNG_DATA"
+
+
[email protected](not HAS_NBFORMAT, reason="nbformat is not installed")
+def test_convert_regular_output_without_dataurl():
+ """Test that regular outputs without data URLs are passed through."""
+ output = CellOutput(
+ channel=CellChannel.OUTPUT,
+ mimetype="text/plain",
+ data="Hello World",
+ )
+
+ result = _convert_marimo_output_to_ipynb(output, [])
+
+ assert len(result) == 1
+ assert result[0]["output_type"] == "display_data"
+ assert result[0]["data"]["text/plain"] == "Hello World"
+
+
[email protected](not HAS_NBFORMAT, reason="nbformat is not installed")
+def test_convert_marimo_mimebundle_empty():
+ """Test that empty marimo mimebundle produces no output."""
+ mimebundle_data = json.dumps({})
+
+ output = CellOutput(
+ channel=CellChannel.OUTPUT,
+ mimetype="application/vnd.marimo+mimebundle",
+ data=mimebundle_data,
+ )
+
+ result = _convert_marimo_output_to_ipynb(output, [])
+
+ # Empty mimebundle should not produce any output
+ assert len(result) == 0
+
+
[email protected](not HAS_NBFORMAT, reason="nbformat is not installed")
+def test_convert_marimo_mimebundle_with_console_output():
+ """Test that console outputs (stdout/stderr) are converted correctly."""
+ # Test just console outputs without main output
+ console_outputs = [
+ CellOutput(
+ channel=CellChannel.STDOUT,
+ mimetype="text/plain",
+ data="Console output\n",
+ ),
+ CellOutput(
+ channel=CellChannel.STDERR,
+ mimetype="text/plain",
+ data="Warning message\n",
+ ),
+ ]
+
+ result = _convert_marimo_output_to_ipynb(None, console_outputs)
+
+ # Should have stdout and stderr outputs
+ assert len(result) == 2
+ assert result[0]["output_type"] == "stream"
+ assert result[0]["name"] == "stdout"
+ assert result[0]["text"] == "Console output\n"
+ assert result[1]["output_type"] == "stream"
+ assert result[1]["name"] == "stderr"
+ assert result[1]["text"] == "Warning message\n"
+
+
[email protected](not HAS_NBFORMAT, reason="nbformat is not installed")
+def test_convert_marimo_mimebundle_with_both_output_and_console():
+ """Test marimo mimebundle with both cell output and console outputs."""
+ mimebundle_data = json.dumps(
+ {
+ "text/plain": "Result",
+ "image/png": "PNG_DATA",
+ }
+ )
+
+ main_output = CellOutput(
+ channel=CellChannel.OUTPUT,
+ mimetype="application/vnd.marimo+mimebundle",
+ data=mimebundle_data,
+ )
+
+ console_outputs = [
+ CellOutput(
+ channel=CellChannel.STDOUT,
+ mimetype="text/plain",
+ data="Console output\n",
+ ),
+ ]
+
+ # First convert console outputs
+ console_result = _convert_marimo_output_to_ipynb(None, console_outputs)
+ # Then convert main output
+ main_result = _convert_marimo_output_to_ipynb(main_output, [])
+
+ # Verify console output
+ assert len(console_result) == 1
+ assert console_result[0]["output_type"] == "stream"
+ assert console_result[0]["name"] == "stdout"
+
+ # Verify main output
+ assert len(main_result) == 1
+ assert main_result[0]["output_type"] == "display_data"
+ assert main_result[0]["data"]["text/plain"] == "Result"
+ assert main_result[0]["data"]["image/png"] == "PNG_DATA"
+
+
+# Tests for metadata in ipynb export
+
+
[email protected](not HAS_NBFORMAT, reason="nbformat is not installed")
+def test_convert_marimo_mimebundle_with_metadata():
+ """Test that metadata from __metadata__ key is included in ipynb output."""
+ mimebundle_data = json.dumps(
+ {
+ "text/plain": "Figure",
+ "image/png": "PNG_DATA",
+ "__metadata__": {
+ "width": 640,
+ "height": 480,
+ "dpi": 100,
+ },
+ }
+ )
+
+ output = CellOutput(
+ channel=CellChannel.OUTPUT,
+ mimetype="application/vnd.marimo+mimebundle",
+ data=mimebundle_data,
+ )
+
+ result = _convert_marimo_output_to_ipynb(output, [])
+
+ assert len(result) == 1
+ assert result[0]["output_type"] == "display_data"
+ assert result[0]["data"]["text/plain"] == "Figure"
+ assert result[0]["data"]["image/png"] == "PNG_DATA"
+ # Verify metadata is included
+ assert "metadata" in result[0]
+ assert result[0]["metadata"] == {
+ "width": 640,
+ "height": 480,
+ "dpi": 100,
+ }
+
+
[email protected](not HAS_NBFORMAT, reason="nbformat is not installed")
+def test_convert_marimo_mimebundle_without_metadata():
+ """Test that outputs without metadata have empty metadata dict."""
+ mimebundle_data = json.dumps(
+ {
+ "text/plain": "Figure",
+ "image/png": "PNG_DATA",
+ }
+ )
+
+ output = CellOutput(
+ channel=CellChannel.OUTPUT,
+ mimetype="application/vnd.marimo+mimebundle",
+ data=mimebundle_data,
+ )
+
+ result = _convert_marimo_output_to_ipynb(output, [])
+
+ assert len(result) == 1
+ assert result[0]["output_type"] == "display_data"
+ assert result[0]["data"]["text/plain"] == "Figure"
+ assert result[0]["data"]["image/png"] == "PNG_DATA"
+ # Verify metadata is empty
+ assert "metadata" in result[0]
+ assert result[0]["metadata"] == {}
+
+
[email protected](not HAS_NBFORMAT, reason="nbformat is not installed")
+def test_convert_marimo_mimebundle_with_non_dict_metadata():
+ """Test that non-dict metadata is ignored."""
+ mimebundle_data = json.dumps(
+ {
+ "text/plain": "Figure",
+ "image/png": "PNG_DATA",
+ "__metadata__": "not a dict", # This should be ignored
+ }
+ )
+
+ output = CellOutput(
+ channel=CellChannel.OUTPUT,
+ mimetype="application/vnd.marimo+mimebundle",
+ data=mimebundle_data,
+ )
+
+ result = _convert_marimo_output_to_ipynb(output, [])
+
+ assert len(result) == 1
+ assert result[0]["output_type"] == "display_data"
+ # Verify metadata is empty when non-dict value is provided
+ assert "metadata" in result[0]
+ assert result[0]["metadata"] == {}
+
+
[email protected](not HAS_NBFORMAT, reason="nbformat is not installed")
+def test_convert_marimo_mimebundle_with_nested_metadata():
+ """Test that nested metadata structures are preserved."""
+ mimebundle_data = json.dumps(
+ {
+ "text/plain": "Figure",
+ "image/png": "PNG_DATA",
+ "__metadata__": {
+ "figure": {
+ "width": 640,
+ "height": 480,
+ },
+ "plot": {
+ "type": "line",
+ "color": "blue",
+ },
+ "tags": ["important", "experiment-1"],
+ },
+ }
+ )
+
+ output = CellOutput(
+ channel=CellChannel.OUTPUT,
+ mimetype="application/vnd.marimo+mimebundle",
+ data=mimebundle_data,
+ )
+
+ result = _convert_marimo_output_to_ipynb(output, [])
+
+ assert len(result) == 1
+ assert result[0]["output_type"] == "display_data"
+ # Verify nested metadata is preserved
+ assert result[0]["metadata"] == {
+ "figure": {
+ "width": 640,
+ "height": 480,
+ },
+ "plot": {
+ "type": "line",
+ "color": "blue",
+ },
+ "tags": ["important", "experiment-1"],
+ }
+
+
[email protected](not HAS_NBFORMAT, reason="nbformat is not installed")
+def test_convert_marimo_mimebundle_metadata_not_in_data():
+ """Test that __metadata__ key is not included in output data."""
+ mimebundle_data = json.dumps(
+ {
+ "text/plain": "Figure",
+ "image/png": "PNG_DATA",
+ "__metadata__": {
+ "width": 640,
+ "height": 480,
+ },
+ }
+ )
+
+ output = CellOutput(
+ channel=CellChannel.OUTPUT,
+ mimetype="application/vnd.marimo+mimebundle",
+ data=mimebundle_data,
+ )
+
+ result = _convert_marimo_output_to_ipynb(output, [])
+
+ assert len(result) == 1
+ assert result[0]["output_type"] == "display_data"
+ # Verify __metadata__ is not in the data dict
+ assert "__metadata__" not in result[0]["data"]
+ assert "text/plain" in result[0]["data"]
+ assert "image/png" in result[0]["data"]
+ # But metadata should be in the metadata field
+ assert result[0]["metadata"] == {
+ "width": 640,
+ "height": 480,
+ }
+
+
[email protected](not HAS_NBFORMAT, reason="nbformat is not installed")
+def test_convert_marimo_mimebundle_dict():
+ """Handle the case when the mimebundle is a dict, not JSON-dumped string"""
+ mimebundle_data = {
+ "text/plain": "Figure",
+ "image/png": "PNG_DATA",
+ "__metadata__": {
+ "width": 640,
+ "height": 480,
+ },
+ }
+
+ output = CellOutput(
+ channel=CellChannel.OUTPUT,
+ mimetype="application/vnd.marimo+mimebundle",
+ data=mimebundle_data,
+ )
+
+ result = _convert_marimo_output_to_ipynb(output, [])
+
+ assert len(result) == 1
+ assert result[0]["output_type"] == "display_data"
+ # Verify __metadata__ is not in the data dict
+ assert "__metadata__" not in result[0]["data"]
+ assert "text/plain" in result[0]["data"]
+ assert "image/png" in result[0]["data"]
+ # But metadata should be in the metadata field
+ assert result[0]["metadata"] == {
+ "width": 640,
+ "height": 480,
+ }
+
+
[email protected](not HAS_NBFORMAT, reason="nbformat is not installed")
+def test_convert_regular_output_has_empty_metadata():
+ """Test that regular outputs (non-mimebundle) have empty metadata."""
+ output = CellOutput(
+ channel=CellChannel.OUTPUT,
+ mimetype="text/plain",
+ data="Hello World",
+ )
+
+ result = _convert_marimo_output_to_ipynb(output, [])
+
+ assert len(result) == 1
+ assert result[0]["output_type"] == "display_data"
+ assert result[0]["data"]["text/plain"] == "Hello World"
+ # Regular outputs should have empty metadata
+ assert "metadata" in result[0]
+ assert result[0]["metadata"] == {}