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
Fix: Altair chart fails to render after enabling PNG renderer (#9049)
Daizua492f88eb20c
diff --git a/marimo/_output/formatters/altair_formatters.py b/marimo/_output/formatters/altair_formatters.pyindex be5bf52d96..826c23e50d 100644--- a/marimo/_output/formatters/altair_formatters.py+++ b/marimo/_output/formatters/altair_formatters.py@@ -8,7 +8,7 @@ from urllib.request import urlopenfrom marimo._config.config import Themefrom marimo._dependencies.dependencies import DependencyManagerfrom marimo._loggers import marimo_logger-from marimo._messaging.mimetypes import KnownMimeType, MimeBundleOrTuple+from marimo._messaging.mimetypes import METADATA_KEY, KnownMimeType, MimeBundlefrom marimo._output.formatters.formatter_factory import FormatterFactoryfrom marimo._plugins.core.media import io_to_data_urlfrom marimo._plugins.ui._impl.altair_chart import (@@ -45,12 +45,17 @@ class AltairFormatter(FormatterFactory):# If its HTML, we want to handle this ourselves# if its svg, vega, or png, then we want to pass that instead# because that means the user has configured the that renderer- mimebundle: MimeBundleOrTuple = {}+ mimebundle: MimeBundle | tuple[MimeBundle, MimeBundle] = {}try:mimebundle = chart._repr_mimebundle_() or {} # type: ignoreexcept Exception:pass+ # When the mimebundle is a tuple, it follows the format+ # (data_dict, metadata_dict).+ if isinstance(mimebundle, tuple) and "image/png" in mimebundle[0]:+ return _format_png_mimebundle(mimebundle)+# Handle where there are multiple mime types# return as a mimebundleif len(mimebundle) > 1:@@ -106,6 +111,24 @@ class AltairFormatter(FormatterFactory):pass+def _format_png_mimebundle(+ png_mimebundle: tuple[MimeBundle, MimeBundle],+) -> tuple[KnownMimeType, str]:+ data_url = io_to_data_url(png_mimebundle[0]["image/png"], "image/png")+ metadata = png_mimebundle[1]["image/png"]++ mimebundle = {+ "image/png": data_url or "",+ METADATA_KEY: {+ "image/png": {+ "width": metadata["width"],+ "height": metadata["height"],+ }+ },+ }+ return "application/vnd.marimo+mimebundle", json.dumps(mimebundle)++# This is only needed since it seems that altair does not# handle this internally.# https://github.com/marimo-team/marimo/issues/2302diff --git a/tests/_output/formatters/test_altair_formatters.py b/tests/_output/formatters/test_altair_formatters.pyindex f2dbc5b110..7ad1ecb097 100644--- a/tests/_output/formatters/test_altair_formatters.py+++ b/tests/_output/formatters/test_altair_formatters.py@@ -177,6 +177,31 @@ def test_altair_formatter_svg():assert content == "<svg></svg>"[email protected](not HAS_DEPS, reason="altair not installed")+def test_altair_formatter_png():+ AltairFormatter().register()++ import altair as alt++ # Create a mock chart with a _repr_mimebundle_ method that returns PNG+ mock_chart = alt.Chart(get_data()).mark_point()+ with patch.object(+ alt.Chart,+ "_repr_mimebundle_",+ return_value=(+ {"image/png": b"png"},+ {"image/png": {"width": 10, "height": 20}},+ ),+ ):+ formatter = get_formatter(mock_chart)+ assert formatter is not None+ mime, content = formatter(mock_chart)++ assert mime == "application/vnd.marimo+mimebundle"+ assert content.startswith('{"image/png": "data:image/png;base64,cG5n"')+ assert content.endswith('{"image/png": {"width": 10, "height": 20}}}')++@pytest.mark.skipif(not HAS_DEPS, reason="altair not installed")@pytest.mark.parametrize("df",