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
feat: support more mime types (#2294)
Myles Scolnick78dd4c42ac4e
diff --git a/frontend/src/components/editor/Output.tsx b/frontend/src/components/editor/Output.tsxindex 4c9bcf20f0..03e36263b4 100644--- a/frontend/src/components/editor/Output.tsx+++ b/frontend/src/components/editor/Output.tsx@@ -28,23 +28,38 @@ import { invariant } from "@/utils/invariant";import { CsvViewer } from "./file-tree/renderers";import { LazyAnyLanguageCodeMirror } from "@/plugins/impl/code/LazyAnyLanguageCodeMirror";import { MarimoTracebackOutput } from "./output/MarimoTracebackOutput";-import { useTheme } from "@emotion/react";+import { useTheme } from "@/theme/useTheme";+import { renderHTML } from "@/plugins/core/RenderHTML";+import type { TopLevelFacetedUnitSpec } from "@/plugins/impl/data-explorer/queries/types";+import { Tabs, TabsContent, TabsList, TabsTrigger } from "../ui/tabs";+import { Objects } from "@/utils/objects";+import { renderMimeIcon } from "./renderMimeIcon";++const LazyVegaLite = React.lazy(() =>+ import("react-vega").then((m) => ({ default: m.VegaLite })),+);++type MimeBundle = Record<OutputMessage["mimetype"], { [key: string]: unknown }>;+type MimeBundleOrTuple = MimeBundle | [MimeBundle, { [key: string]: unknown }];/*** Renders an output based on an OutputMessage.*/export const OutputRenderer: React.FC<{- message: OutputMessage;+ message: Pick<OutputMessage, "channel" | "data" | "mimetype">;onRefactorWithAI?: (opts: { prompt: string }) => void;}> = memo((props) => {const { message, onRefactorWithAI } = props;- const theme = useTheme();+ const { theme } = useTheme();// Memoize parsing the json dataconst parsedJsonData = useMemo(() => {const data = message.data;switch (message.mimetype) {case "application/json":+ case "application/vnd.marimo+mimebundle":+ case "application/vnd.vegalite.v5+json":+ case "application/vnd.vega.v5+json":return typeof data === "string" ? JSON.parse(data) : data;default:return;@@ -80,7 +95,6 @@ export const OutputRenderer: React.FC<{<JsonOutput className={channel} data={parsedJsonData} format="auto" />);case "image/png":- case "image/svg+xml":case "image/tiff":case "image/avif":case "image/bmp":@@ -91,6 +105,12 @@ export const OutputRenderer: React.FC<{`Expected string data for mime=${mimetype}. Got ${typeof data}`,);return <ImageOutput className={channel} src={data} alt="" />;+ case "image/svg+xml":+ invariant(+ typeof data === "string",+ `Expected string data for mime=${mimetype}. Got ${typeof data}`,+ );+ return renderHTML({ html: data });case "video/mp4":case "video/mpeg":@@ -122,6 +142,7 @@ export const OutputRenderer: React.FC<{`Expected string data for mime=${mimetype}. Got ${typeof data}`,);return <CsvViewer contents={data} />;+ case "text/latex":case "text/markdown":invariant(typeof data === "string",@@ -134,13 +155,97 @@ export const OutputRenderer: React.FC<{language="markdown"/>);+ case "application/vnd.vegalite.v5+json":+ case "application/vnd.vega.v5+json":+ return (+ <LazyVegaLite+ spec={parsedJsonData as TopLevelFacetedUnitSpec}+ theme={theme === "dark" ? "dark" : undefined}+ />+ );+ case "application/vnd.marimo+mimebundle":+ return (+ <MimeBundleOutputRenderer+ channel={channel}+ data={+ parsedJsonData as Record<OutputMessage["mimetype"], OutputMessage>+ }+ />+ );default:logNever(mimetype);- return null;+ return (+ <div className="text-destructive">Unsupported mimetype: {mimetype}</div>+ );}});OutputRenderer.displayName = "OutputRenderer";+/**+ * Renders a mimebundle output.+ */+const MimeBundleOutputRenderer: React.FC<{+ channel: OutputMessage["channel"];+ data: MimeBundleOrTuple;+}> = memo(({ data, channel }) => {+ const mimebundle = Array.isArray(data) ? data[0] : data;++ // If there is none, return null+ const first = Objects.keys(mimebundle)[0];+ if (!first) {+ return null;+ }++ // If there is only one mime type, render it directly+ if (Object.keys(mimebundle).length === 1) {+ return (+ <OutputRenderer+ message={{+ channel: channel,+ data: mimebundle[first],+ mimetype: first,+ }}+ />+ );+ }++ return (+ <Tabs defaultValue={first} orientation="vertical">+ <div className="flex">+ <TabsList className="self-start max-h-none flex flex-col gap-2 mr-4 flex-shrink-0">+ {Object.keys(mimebundle).map((mime) => (+ <TabsTrigger+ key={mime}+ value={mime}+ className="flex items-center space-x-2"+ >+ <Tooltip delayDuration={200} content={mime} side="right">+ <span>{renderMimeIcon(mime)}</span>+ </Tooltip>+ </TabsTrigger>+ ))}+ </TabsList>+ <div className="flex-1">+ {Objects.entries(mimebundle).map(([mime, output]) => (+ <TabsContent key={mime} value={mime}>+ <ErrorBoundary>+ <OutputRenderer+ message={{+ channel: channel,+ data: output,+ mimetype: mime,+ }}+ />+ </ErrorBoundary>+ </TabsContent>+ ))}+ </div>+ </div>+ </Tabs>+ );+});+MimeBundleOutputRenderer.displayName = "MimeBundleOutputRenderer";+interface OutputAreaProps {output: OutputMessage | null;cellId: CellId;diff --git a/frontend/src/components/editor/renderMimeIcon.tsx b/frontend/src/components/editor/renderMimeIcon.tsxnew file mode 100644index 0000000000..81945c68f1--- /dev/null+++ b/frontend/src/components/editor/renderMimeIcon.tsx@@ -0,0 +1,38 @@+/* Copyright 2024 Marimo. All rights reserved. */+export function renderMimeIcon(mime: string) {+ switch (mime) {+ case "text/html":+ return "🌐";+ case "text/plain":+ return "📄";+ case "application/json":+ return "📦";+ case "image/png":+ case "image/tiff":+ case "image/avif":+ case "image/bmp":+ case "image/gif":+ case "image/jpeg":+ return "🖼️";+ case "image/svg+xml":+ return "🎨";+ case "video/mp4":+ case "video/mpeg":+ return "🎥";+ case "application/vnd.marimo+error":+ return "🚨";+ case "application/vnd.marimo+traceback":+ return "🐍";+ case "text/csv":+ return "📊";+ case "text/markdown":+ return "📝";+ case "application/vnd.vegalite.v5+json":+ case "application/vnd.vega.v5+json":+ return "📊";+ case "application/vnd.marimo+mimebundle":+ return "📦";+ default:+ return "❓";+ }+}diff --git a/frontend/src/plugins/layout/MimeRenderPlugin.tsx b/frontend/src/plugins/layout/MimeRenderPlugin.tsxnew file mode 100644index 0000000000..ce71f5a010--- /dev/null+++ b/frontend/src/plugins/layout/MimeRenderPlugin.tsx@@ -0,0 +1,46 @@+/* Copyright 2024 Marimo. All rights reserved. */++import { z } from "zod";+import type {+ IStatelessPlugin,+ IStatelessPluginProps,+} from "../stateless-plugin";+import { OutputRenderer } from "../../components/editor/Output";+import type { OutputMessage } from "@/core/kernel/messages";+import { Logger } from "@/utils/Logger";++interface Data {+ mime: OutputMessage["mimetype"];+ data: string;+}++export class MimeRendererPlugin implements IStatelessPlugin<Data> {+ tagName = "marimo-mime-renderer";++ validator = z.object({+ mime: z.string().transform((val) => val as OutputMessage["mimetype"]),+ data: z.string(),+ });++ render({ data }: IStatelessPluginProps<Data>): JSX.Element {+ if (!data) {+ return <div />;+ }++ try {+ const parsed = JSON.parse(data.data);+ return (+ <OutputRenderer+ message={{+ data: parsed as OutputMessage["data"],+ channel: "output",+ mimetype: data.mime,+ }}+ />+ );+ } catch {+ Logger.error("Failed to parse data");+ return <pre>{data.data}</pre>;+ }+ }+}diff --git a/frontend/src/plugins/plugins.ts b/frontend/src/plugins/plugins.tsindex 0a648f46cb..80d158b7ca 100644--- a/frontend/src/plugins/plugins.ts+++ b/frontend/src/plugins/plugins.ts@@ -45,6 +45,7 @@ import { initializeSidebarElement } from "./core/sidebar-element";import { RoutesPlugin } from "./layout/RoutesPlugin";import { DateTimePickerPlugin } from "./impl/DateTimePickerPlugin";import { DateRangePickerPlugin } from "./impl/DateRangePlugin";+import { MimeRendererPlugin } from "./layout/MimeRenderPlugin";// List of UI pluginsexport const UI_PLUGINS: Array<IPlugin<any, unknown>> = [@@ -86,6 +87,7 @@ const LAYOUT_PLUGINS: Array<IStatelessPlugin<unknown>> = [new CarouselPlugin(),new DownloadPlugin(),new JsonOutputPlugin(),+ new MimeRendererPlugin(),new MermaidPlugin(),new NavigationMenuPlugin(),new ProgressPlugin(),diff --git a/marimo/_messaging/mimetypes.py b/marimo/_messaging/mimetypes.pyindex 2fd6d14696..01eb31f9e1 100644--- a/marimo/_messaging/mimetypes.py+++ b/marimo/_messaging/mimetypes.py@@ -1,7 +1,7 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations-from typing import Literal+from typing import Any, Dict, Literal, Tuple, Union# It is convenient to write mimetypes as strings,# but can lead to typos. This literal type@@ -10,6 +10,9 @@ KnownMimeType = Literal["application/json","application/vnd.marimo+error","application/vnd.marimo+traceback",+ "application/vnd.marimo+mimebundle",+ "application/vnd.vega.v5+json",+ "application/vnd.vegalite.v5+json","image/png","image/svg+xml","image/tiff",@@ -22,5 +25,9 @@ KnownMimeType = Literal["text/html","text/plain","text/markdown",+ "text/latex","text/csv",]++MimeBundle = Dict[KnownMimeType, Any]+MimeBundleOrTuple = Union[MimeBundle, Tuple[MimeBundle, Any]]diff --git a/marimo/_output/formatters/altair_formatters.py b/marimo/_output/formatters/altair_formatters.pyindex 574d805f27..a1d04319ff 100644--- a/marimo/_output/formatters/altair_formatters.py+++ b/marimo/_output/formatters/altair_formatters.py@@ -1,14 +1,12 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations-import html+import jsonfrom marimo._config.config import Theme-from marimo._messaging.mimetypes import KnownMimeType-from marimo._output.builder import h+from marimo._messaging.mimetypes import KnownMimeType, MimeBundleOrTuplefrom marimo._output.formatters.formatter_factory import FormatterFactory-from marimo._output.utils import flatten_string-from marimo._plugins.ui._impl.altair_chart import altair_chart+from marimo._plugins.core.media import io_to_data_urlclass AltairFormatter(FormatterFactory):@@ -31,31 +29,55 @@ class AltairFormatter(FormatterFactory):def _show_chart(chart: altair.Chart) -> tuple[KnownMimeType, str]:import altair as alt+ # Try to get the _repr_mimebundle_ method from the chart+ # 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 = {}+ try:+ mimebundle = chart._repr_mimebundle_() or {} # type: ignore+ except Exception:+ pass++ # Handle where there are multiple mime types+ # return as a mimebundle+ if len(mimebundle) > 1:+ return (+ "application/vnd.marimo+mimebundle",+ json.dumps(mimebundle),+ )++ # Handle non-HTML mime types+ non_html_mime_types: list[KnownMimeType] = [+ "image/svg+xml",+ "image/png",+ "application/vnd.vega.v5+json",+ "application/vnd.vegalite.v5+json",+ ]+ for mime_type in non_html_mime_types:+ if mime_type in mimebundle:+ mime_response = mimebundle[mime_type]+ if isinstance(mime_response, bytes):+ data_url = io_to_data_url(mime_response, mime_type)+ return (mime_type, data_url or "")+ if isinstance(mime_response, str):+ return mime_type, mime_response+ return mime_type, json.dumps(mime_response)+# If vegafusion is enabled, just wrap in altair_chartif alt.data_transformers.active.startswith("vegafusion"):- return altair_chart(- chart, chart_selection=False, legend_selection=False- )._mime_()+ return (+ "application/vnd.vega.v5+json",+ chart.to_json(format="vega"),+ )# If the user has not set the max_rows option, we set it to 20_000# since we are able to handle the larger sizes (default is 5000)if "max_rows" not in alt.data_transformers.options:alt.data_transformers.options["max_rows"] = 20_000- return (- "text/html",- (- flatten_string(- h.iframe(- # Must be srcdoc, or if you try to use src, see- # https://github.com/marimo-team/marimo/issues/1279- # and 1279.py- srcdoc=html.escape(chart.to_html()),- onload="__resizeIframe(this)",- style="width: 100%",- )- )- ),- )++ # Return the chart as a vega-lite chart+ return ("application/vnd.vegalite.v5+json", chart.to_json())def apply_theme(self, theme: Theme) -> None:import altair as alt # type: ignorediff --git a/marimo/_output/formatting.py b/marimo/_output/formatting.pyindex f8f9c3d2c7..ae85b9209b 100644--- a/marimo/_output/formatting.py+++ b/marimo/_output/formatting.py@@ -30,7 +30,9 @@ from marimo._messaging.mimetypes import KnownMimeTypefrom marimo._output.hypertext import Htmlfrom marimo._output.rich_help import mddocfrom marimo._output.utils import flatten_string+from marimo._plugins.core.media import io_to_data_urlfrom marimo._plugins.stateless.json_output import json_output+from marimo._plugins.stateless.mime import mime_rendererfrom marimo._plugins.stateless.plain_text import plain_textT = TypeVar("T")@@ -130,26 +132,68 @@ def get_formatter(for t in FORMATTERS.keys():if isinstance(obj, t):return FORMATTERS[t]- elif hasattr(obj, "_mime_"):- method = obj._mime_- if inspect.isclass(obj) and not isinstance(method, (types.MethodType)):- return None- if callable(method):-- def f(obj: T) -> tuple[KnownMimeType, str]:- return obj._mime_() # type: ignore-- return f- elif hasattr(obj, "_repr_html_"):- method = obj._repr_html_- if inspect.isclass(obj) and not isinstance(method, (types.MethodType)):- return None- if callable(method):-- def f(obj: T) -> tuple[KnownMimeType, str]:- return ("text/html", obj._repr_html_()) # type: ignore-- return f++ # Check for the MIME protocol+ if _is_callable_method(obj, "_mime_"):++ def f_mime(obj: T) -> tuple[KnownMimeType, str]:+ mime, data = obj._mime_() # type: ignore+ # Data should ideally a string, but in case it's bytes,+ # we convert it to a data URL+ if isinstance(data, bytes):+ return (mime, io_to_data_url(data, mime) or "") # type: ignore++ return (mime, data) # type: ignore++ return f_mime++ md_mime_types: list[KnownMimeType] = [+ "text/markdown",+ "text/latex",+ ]++ # Check for the misc _repr_ methods+ reprs: list[Tuple[str, KnownMimeType]] = [+ ("_repr_html_", "text/html"), # text/html is preferred first+ ("_repr_mimebundle_", "application/vnd.marimo+mimebundle"),+ ("_repr_svg_", "image/svg+xml"),+ ("_repr_json_", "application/json"),+ ("_repr_png_", "image/png"),+ ("_repr_jpeg_", "image/jpeg"),+ ("_repr_markdown_", "text/markdown"),+ ("_repr_latex_", "text/latex"),+ ("_repr_text_", "text/plain"), # last+ ]++ for attr, mime_type in reprs:+ if _is_callable_method(obj, attr):++ def f_repr(+ obj: T,+ mime_type: KnownMimeType = mime_type,+ attr: str = attr,+ ) -> tuple[KnownMimeType, str]:+ contents = getattr(obj, attr)()++ # Handle the case where the contents are bytes+ if isinstance(contents, bytes):+ # Data should ideally a string, but in case it's bytes,+ # we convert it to a data URL+ data_url = io_to_data_url(+ contents, fallback_mime_type=mime_type+ )+ return (mime_type, data_url or "")++ # Handle markdown and latex+ if mime_type in md_mime_types:+ from marimo._output.md import md++ return ("text/html", md(contents).text)++ return (mime_type, contents)++ return f_repr+return None@@ -278,8 +322,8 @@ def as_html(value: object) -> Html:return Html(flatten_string(json_output(json_data=json.loads(data)).text))- else:- raise ValueError(f"Unsupported mimetype {mimetype}")++ return mime_renderer(mimetype, data)@mddoc@@ -313,3 +357,12 @@ class Plain:def __init__(self, child: Any):self.child = child+++def _is_callable_method(obj: Any, attr: str) -> bool:+ if not hasattr(obj, attr):+ return False+ method = getattr(obj, attr)+ if inspect.isclass(obj) and not isinstance(method, (types.MethodType)):+ return False+ return callable(method)diff --git a/marimo/_output/mime.py b/marimo/_output/mime.pyindex cd9308103e..b943da9f15 100644--- a/marimo/_output/mime.py+++ b/marimo/_output/mime.py@@ -27,6 +27,8 @@ class MIME(Protocol):application/jsonapplication/vnd.marimo+errorapplication/vnd.marimo+traceback+ application/vnd.vega.v5+json+ application/vnd.vegalite.v5+jsonimage/pngimage/svg+xmlimage/tiffdiff --git a/marimo/_plugins/stateless/mime.py b/marimo/_plugins/stateless/mime.pynew file mode 100644index 0000000000..bd9fc87f6c--- /dev/null+++ b/marimo/_plugins/stateless/mime.py@@ -0,0 +1,25 @@+# Copyright 2024 Marimo. All rights reserved.+from __future__ import annotations++from marimo._output.hypertext import Html+from marimo._plugins.core.web_component import JSONType, build_stateless_plugin+++def mime_renderer(mime: str, data: JSONType) -> Html:+ """Build a mime renderer element.++ Args:+ -----+ mime: MIME type of the data+ data: data to display++ Returns:+ --------+ A string of HTML for a mime renderer element.+ """+ return Html(+ build_stateless_plugin(+ component_name="marimo-mime-renderer",+ args=({"mime": mime, "data": data}),+ )+ )diff --git a/marimo/_smoke_tests/altair/vegafusion_nb.py b/marimo/_smoke_tests/altair/vegafusion_nb.pyindex 07191bd847..0f6bc44b39 100644--- a/marimo/_smoke_tests/altair/vegafusion_nb.py+++ b/marimo/_smoke_tests/altair/vegafusion_nb.py@@ -54,6 +54,13 @@ def __(alt, flights, mo):return delay_hist,+def __(alt, delay_hist, mo):+ alt.data_transformers.enable("vegafusion")+ mo.as_html(delay_hist)+ return++@app.celldef __(alt, delay_hist):alt.data_transformers.enable("vegafusion")@@ -261,5 +268,48 @@ def __(alt, make_movie_chart, pd):return+def __(mo):+ mo.md(r"""# Vega fusion mimes""")+ return+++def __(alt, flights, vf):+ vf.enable(mimetype="html")+ alt.data_transformers.enable("vegafusion")+ alt.Chart(flights).mark_bar().encode(+ alt.X("delay", bin=alt.Bin(maxbins=30)), alt.Y("count()")+ )+ return+++def __(alt, flights, vf):+ vf.enable(mimetype="svg")+ alt.Chart(flights).mark_bar().encode(+ alt.X("delay", bin=alt.Bin(maxbins=30)), alt.Y("count()")+ )+ return+++def __(alt, flights, vf):+ vf.enable(mimetype="vega")+ alt.Chart(flights).mark_bar().encode(+ alt.X("delay", bin=alt.Bin(maxbins=30)), alt.Y("count()")+ )+ return+++def __(alt, flights, vf):+ vf.enable(mimetype="png")+ alt.Chart(flights).mark_bar().encode(+ alt.X("delay", bin=alt.Bin(maxbins=30)), alt.Y("count()")+ )+ return++if __name__ == "__main__":app.run()diff --git a/marimo/_smoke_tests/mimes.py b/marimo/_smoke_tests/mimes.pynew file mode 100644index 0000000000..f8d6bd1115--- /dev/null+++ b/marimo/_smoke_tests/mimes.py@@ -0,0 +1,199 @@+# /// script+# requires-python = ">=3.11"+# dependencies = [+# "marimo",+# "vegafusion",+# "pandas",+# "altair",+# ]+# ///++import marimo++__generated_with = "0.8.14"+app = marimo.App(width="medium")+++def __():+ import marimo as mo+ return mo,+++def __():+ class HTMLMime:+ def _mime_(self):+ return (+ "text/html",+ "<h1>Hello, World!</h1>",+ )+++ HTMLMime()+ return HTMLMime,+++def __():+ class SvgMime:+ def _mime_(self):+ return (+ "image/svg+xml",+ '<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100"><circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" /></svg>',+ )+++ SvgMime()+ return SvgMime,+++def __():+ class JSONMime:+ def _mime_(self):+ return (+ "application/json",+ '{"message": "Hello, World!"}',+ )+++ JSONMime()+ return JSONMime,+++def __():+ class PngMime:+ def _mime_(self):+ import matplotlib.pyplot as plt+ import io+ import base64++ # Create a figure+ fig, ax = plt.subplots()+ ax.plot([1, 2, 3, 4, 5], [1, 4, 9, 16, 25])++ # Save the plot to a BytesIO object+ buf = io.BytesIO()+ plt.savefig(buf, format="png")+ plt.close(fig)+ buf.seek(0)++ # Read as bytes+ data = buf.read()+ return ("image/png", data)+++ PngMime()+ return PngMime,+++def __():+ class CSVMime:+ def _mime_(self):+ return (+ "text/csv",+ "name,age\nAlice,30\nBob,25",+ )+++ CSVMime()+ return CSVMime,+++def __():+ class TextMarkdownMime:+ def _mime_(self):+ return (+ "text/markdown",+ "# Markdown Title\n\n*This text will be italic*\n\n**This text will be bold**",+ )+++ TextMarkdownMime()+ return TextMarkdownMime,+++def __():+ import altair as alt+ import pandas as pd+++ class VegaLiteMime:+ def _mime_(self):+ # Create a sample dataframe+ data = pd.DataFrame({"x": range(10), "y": [x**2 for x in range(10)]})++ # Create a chart+ chart = alt.Chart(data).mark_line().encode(x="x", y="y")++ # Return the Vega-Lite specification+ # return ("application/json", chart.to_json())+ return ("application/vnd.vegalite.v5+json", chart.to_json())+++ VegaLiteMime()+ return VegaLiteMime, alt, pd+++def __():+ class UnknownMime:+ def _mime_(self):+ return (+ "application/octet-stream",+ "This is a binary file without a specific format.",+ )+++ UnknownMime()+ return UnknownMime,+++def __(+ CSVMime,+ HTMLMime,+ JSONMime,+ SvgMime,+ TextMarkdownMime,+ UnknownMime,+ VegaLiteMime,+):+ class ReprMimeBundle:+ def __init__(self, *mimes):+ self.mimes = mimes++ def _repr_mimebundle_(self):+ bundle = {}+ for mime in self.mimes:+ mime_type, data = mime._mime_()+ bundle[mime_type] = data+ return bundle+++ # Example usage with multiple MIME types+ ReprMimeBundle(+ VegaLiteMime(),+ HTMLMime(),+ SvgMime(),+ JSONMime(),+ CSVMime(),+ TextMarkdownMime(),+ UnknownMime(),+ )+ return ReprMimeBundle,+++def __(HTMLMime, ReprMimeBundle):+ ReprMimeBundle(HTMLMime())+ return+++if __name__ == "__main__":+ app.run()diff --git a/marimo/_utils/platform.py b/marimo/_utils/platform.pyindex 0353eeebe8..37e7000251 100644--- a/marimo/_utils/platform.py+++ b/marimo/_utils/platform.py@@ -1,4 +1,6 @@# Copyright 2024 Marimo. All rights reserved.+from __future__ import annotations+import sysdiff --git a/openapi/api.yaml b/openapi/api.yamlindex 864f7487e0..ff9e9b2938 100644--- a/openapi/api.yaml+++ b/openapi/api.yaml@@ -1288,6 +1288,9 @@ components:- application/json- application/vnd.marimo+error- application/vnd.marimo+traceback+ - application/vnd.marimo+mimebundle+ - application/vnd.vega.v5+json+ - application/vnd.vegalite.v5+json- image/png- image/svg+xml- image/tiff@@ -1300,6 +1303,7 @@ components:- text/html- text/plain- text/markdown+ - text/latex- text/csvtype: stringMissingPackageAlert:diff --git a/openapi/src/api.ts b/openapi/src/api.tsindex 54817d06a9..aa8bf7efd7 100644--- a/openapi/src/api.ts+++ b/openapi/src/api.ts@@ -2385,6 +2385,9 @@ export interface components {| "application/json"| "application/vnd.marimo+error"| "application/vnd.marimo+traceback"+ | "application/vnd.marimo+mimebundle"+ | "application/vnd.vega.v5+json"+ | "application/vnd.vegalite.v5+json"| "image/png"| "image/svg+xml"| "image/tiff"@@ -2397,6 +2400,7 @@ export interface components {| "text/html"| "text/plain"| "text/markdown"+ | "text/latex"| "text/csv";MissingPackageAlert: {isolated: boolean;diff --git a/tests/_output/formatters/test_altair.py b/tests/_output/formatters/test_altair.pyindex e4b967e0d5..0401b825c9 100644--- a/tests/_output/formatters/test_altair.py+++ b/tests/_output/formatters/test_altair.py@@ -1,15 +1,20 @@from __future__ import annotations+import json+import pytestfrom marimo._dependencies.dependencies import DependencyManagerfrom marimo._runtime.runtime import Kernelfrom tests.conftest import ExecReqProvider-HAS_DEPS = DependencyManager.altair.has()+HAS_ALTAIR = DependencyManager.altair.has()+HAS_VL_CONVERT = DependencyManager.has("vl-convert")[email protected](not HAS_DEPS, reason="optional dependencies not installed")+ not HAS_ALTAIR, reason="optional dependencies not installed"+)async def test_altair(executing_kernel: Kernel, exec_req: ExecReqProvider) -> None:@@ -36,5 +41,46 @@ async def test_altair(result = executing_kernel.globals["result"]assert result is not None- assert result[0] == "text/html"- assert result[1].startswith("<iframe srcdoc=")+ assert result[0] == "application/vnd.vegalite.v5+json"+ # Valid JSON+ assert "$schema" in result[1]+ assert isinstance(result[1], str)+ assert json.loads(result[1])+++ not HAS_ALTAIR or not HAS_VL_CONVERT,+ reason="optional dependencies not installed and fails on mac",+)+async def test_altair_with_svg(+ executing_kernel: Kernel, exec_req: ExecReqProvider+) -> None:+ from marimo._output.formatters.formatters import register_formatters++ register_formatters()++ await executing_kernel.run(+ [+ exec_req.get(+ """+ import altair as alt+ import pandas as pd+ from marimo._output.formatting import get_formatter++ data = pd.DataFrame({"a": ["A", "B"], "b": [28, 55]})+ alt.renderers.enable("svg")+ chart = alt.Chart(data).mark_bar().encode(x="a", y="b")+ formatter = get_formatter(chart)+ result = formatter(chart)+ """+ )+ ]+ )++ result = executing_kernel.globals["result"]+ assert result is not None+ assert result[0] == "image/svg+xml"+ assert result[1].startswith("<svg")+++# TODO: Add tests for vegafusiondiff --git a/tests/_output/formatters/test_formatters.py b/tests/_output/formatters/test_formatters.pyindex 90825f8ac0..b9cc55fa3b 100644--- a/tests/_output/formatters/test_formatters.py+++ b/tests/_output/formatters/test_formatters.py@@ -140,3 +140,141 @@ def test_pre_imported_formatter(mock_third_party_factories):register_formatters()assert mock_factory.register.call_count == 1+++def test_repr_markdown():+ class ReprMarkdown:+ def _repr_markdown_(self):+ return "# Hello, World!"++ obj = ReprMarkdown()+ formatter = get_formatter(obj)+ assert formatter+ mime, content = formatter(obj)+ assert mime == "text/html"+ assert (+ content+ == '<span class="markdown prose dark:prose-invert"><h1 id="hello-world">Hello, World!</h1></span>' # noqa: E501+ )+++def test_repr_latex():+ class ReprLatex:+ def _repr_latex_(self):+ return r"$f(x) = e^x$"++ obj = ReprLatex()+ formatter = get_formatter(obj)+ assert formatter+ mime, content = formatter(obj)+ assert mime == "text/html"+ assert (+ content+ == '<span class="markdown prose dark:prose-invert"><span class="paragraph"><marimo-tex class="arithmatex">||(f(x) = e^x||)</marimo-tex></span></span>' # noqa: E501+ )+++def test_repr_html():+ class ReprHTML:+ def _repr_html_(self):+ return "<h1>Hello, World!</h1>"++ obj = ReprHTML()+ formatter = get_formatter(obj)+ assert formatter+ mime, content = formatter(obj)+ assert mime == "text/html"+ assert content == "<h1>Hello, World!</h1>"+++def test_repr_png():+ png = "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABaElEQVR42mNk"++ class ReprPNG:+ def _repr_png_(self):+ return png++ obj = ReprPNG()+ formatter = get_formatter(obj)+ assert formatter+ mime, content = formatter(obj)+ assert mime == "image/png"+ assert content == png+++def test_repr_jpeg():+ jpeg = "/9j/4AAQSkZJRgABAQEAYABgAAD/4QBoRXhpZgAATU0AKgAAAAgAA1IBAAAB"++ class ReprJPEG:+ def _repr_jpeg_(self):+ return jpeg++ obj = ReprJPEG()+ formatter = get_formatter(obj)+ assert formatter+ mime, content = formatter(obj)+ assert mime == "image/jpeg"+ assert content == jpeg+++def test_repr_svg():+ svg = "<svg xmlns='http://www.w3.org/2000/svg' width='100' height='100'></svg>" # noqa: E501++ class ReprSVG:+ def _repr_svg_(self):+ return svg++ obj = ReprSVG()+ formatter = get_formatter(obj)+ assert formatter+ mime, content = formatter(obj)+ assert mime == "image/svg+xml"+ assert content == svg+++def test_repr_json():+ class ReprJSON:+ def _repr_json_(self):+ return {"message": "Hello, World!"}++ obj = ReprJSON()+ formatter = get_formatter(obj)+ assert formatter+ mime, content = formatter(obj)+ assert mime == "application/json"+ assert content == {"message": "Hello, World!"}+++def test_prefer_repr_html_over_repr_markdown():+ class ReprBoth:+ def _repr_html_(self):+ return "<h6>Hello, World!</h6>"++ def _repr_markdown_(self):+ return "# Hello, World!"++ obj = ReprBoth()+ formatter = get_formatter(obj)+ assert formatter+ mime, content = formatter(obj)+ assert mime == "text/html"+ assert content == "<h6>Hello, World!</h6>"+++def test_repr_mimebundle():+ class ReprMimeBundle:+ def _repr_mimebundle_(self):+ return {+ "application/json": {"message": "Hello, World!"},+ "text/plain": "Hello, World!",+ }++ obj = ReprMimeBundle()+ formatter = get_formatter(obj)+ assert formatter+ mime, content = formatter(obj)+ assert mime == "application/vnd.marimo+mimebundle"+ assert content == {+ "application/json": {"message": "Hello, World!"},+ "text/plain": "Hello, World!",+ }