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
improvement: include PIL images in mo.ui.table() (#4285)
Myles Scolnickd01ab115e5ee
diff --git a/frontend/src/components/data-table/url-detector.tsx b/frontend/src/components/data-table/url-detector.tsxindex 21968b221e..ac86f64ec7 100644--- a/frontend/src/components/data-table/url-detector.tsx+++ b/frontend/src/components/data-table/url-detector.tsx@@ -1,5 +1,10 @@/* Copyright 2024 Marimo. All rights reserved. */import { Events } from "@/utils/events";+import {+ Popover,+ PopoverTrigger,+ PopoverContent,+} from "@/components/ui/popover";import { useState } from "react";const urlRegex = /(https?:\/\/\S+)/g;@@ -9,20 +14,42 @@ const knownImageDomains = ["avatars.githubusercontent.com"];const ImageWithFallback = ({ url }: { url: string }) => {const [error, setError] = useState(false);+ const [open, setOpen] = useState(false);if (error) {return <URLAnchor url={url} />;}return (- <div className="flex max-h-[20px] overflow-hidden">- <img- src={url}- alt="URL preview"- className="object-contain max-h-full max-w-full rounded"- onError={() => setError(true)}- />- </div>+ <Popover open={open} onOpenChange={setOpen}>+ <PopoverTrigger asChild={true}>+ <div+ className="flex max-h-[80px] overflow-hidden cursor-pointer flex"+ onMouseEnter={() => setOpen(true)}+ onMouseLeave={() => setOpen(false)}+ >+ <img+ src={url}+ alt="URL preview"+ className="object-contain rounded max-h-[80px]"+ onError={() => setError(true)}+ />+ </div>+ </PopoverTrigger>++ <PopoverContent+ className="z-50 p-2 bg-popover rounded-md shadow-lg border w-fit"+ align="start"+ side="right"+ >+ <img+ src={url}+ alt="URL preview"+ className="object-contain max-h-[500px] rounded"+ onError={() => setError(true)}+ />+ </PopoverContent>+ </Popover>);};diff --git a/marimo/_ai/llm/_impl.py b/marimo/_ai/llm/_impl.pyindex 1d4fdb1b88..1f26a4512b 100644--- a/marimo/_ai/llm/_impl.py+++ b/marimo/_ai/llm/_impl.py@@ -133,7 +133,7 @@ class openai(ChatModel):else:client = OpenAI(api_key=self._require_api_key,- base_url=self.base_url,+ base_url=self.base_url or None,)openai_messages = convert_to_openai_messages(diff --git a/marimo/_plugins/ui/_impl/tables/narwhals_table.py b/marimo/_plugins/ui/_impl/tables/narwhals_table.pyindex 4c26dda10c..1b2869d043 100644--- a/marimo/_plugins/ui/_impl/tables/narwhals_table.py+++ b/marimo/_plugins/ui/_impl/tables/narwhals_table.py@@ -10,6 +10,8 @@ from narwhals.stable.v1.typing import IntoFrameTfrom marimo import _loggersfrom marimo._data.models import ColumnSummary, ExternalDataType+from marimo._dependencies.dependencies import DependencyManager+from marimo._plugins.core.media import io_to_data_urlfrom marimo._plugins.ui._impl.tables.format import (FormatMapping,format_value,@@ -407,3 +409,21 @@ class NarwhalsTableManager(if rows is None:return f"{df_type}: {columns:,} columns"return f"{df_type}: {rows:,} rows x {columns:,} columns"++ def _sanitize_table_value(self, value: Any) -> Any:+ """+ Sanitize a value for display in a table cell.++ Most values are unchanged, but some values are for better+ display such as Images.+ """+ if value is None:+ return None++ # Handle Pillow images+ if DependencyManager.pillow.imported():+ from PIL import Image++ if isinstance(value, Image.Image):+ return io_to_data_url(value, "image/png")+ return valuediff --git a/marimo/_plugins/ui/_impl/tables/pandas_table.py b/marimo/_plugins/ui/_impl/tables/pandas_table.pyindex f937edb504..6ffc1e8cf1 100644--- a/marimo/_plugins/ui/_impl/tables/pandas_table.py+++ b/marimo/_plugins/ui/_impl/tables/pandas_table.py@@ -78,6 +78,7 @@ class PandasTableManagerFactory(TableManagerFactory):) -> bytes:from pandas.api.types import (is_complex_dtype,+ is_object_dtype,is_timedelta64_dtype,is_timedelta64_ns_dtype,)@@ -95,6 +96,10 @@ class PandasTableManagerFactory(TableManagerFactory):dtype) or is_timedelta64_ns_dtype(dtype):result[col] = result[col].apply(str)+ if is_object_dtype(dtype):+ result[col] = result[col].apply(+ self._sanitize_table_value+ )except Exception as e:LOGGER.error(diff --git a/marimo/_plugins/ui/_impl/tables/polars_table.py b/marimo/_plugins/ui/_impl/tables/polars_table.pyindex 2abfc66ee2..59850e6158 100644--- a/marimo/_plugins/ui/_impl/tables/polars_table.py+++ b/marimo/_plugins/ui/_impl/tables/polars_table.py@@ -159,7 +159,10 @@ class PolarsTableManagerFactory(TableManagerFactory):return df.with_columns(# As of writing this, cast(pl.String) doesn't work# for pl.Object types, so we use map_elements- column.map_elements(str, return_dtype=pl.String)+ column.map_elements(+ lambda v: str(self._sanitize_table_value(v)),+ return_dtype=pl.String,+ ))def apply_formatting(diff --git a/marimo/_server/ai/providers.py b/marimo/_server/ai/providers.pyindex bf4e15d32c..228bee134f 100644--- a/marimo/_server/ai/providers.py+++ b/marimo/_server/ai/providers.py@@ -262,7 +262,7 @@ class OpenAIProvider(import httpxfrom openai import AzureOpenAI, OpenAI- base_url = config.base_url+ base_url = config.base_url or Nonekey = config.api_key# Add SSL parameters/valuesdiff --git a/marimo/_smoke_tests/tables/images.py b/marimo/_smoke_tests/tables/images.pynew file mode 100644index 0000000000..3931588a38--- /dev/null+++ b/marimo/_smoke_tests/tables/images.py@@ -0,0 +1,52 @@+import marimo++__generated_with = "0.11.30"+app = marimo.App(width="medium")+++def _():+ import polars as pl+ from PIL import Image+ import io+ import requests+ import pandas as pd+++ def load_image(url):+ response = requests.get(url)+ img = Image.open(io.BytesIO(response.content))+ print(isinstance(img, bytes))+ return img+++ df = pl.DataFrame(+ {+ "id": [1, 2, 3],+ "str": ["foo", "bar", "baz"],+ "image": [+ load_image("https://picsum.photos/400"),+ load_image("https://picsum.photos/400"),+ load_image("https://picsum.photos/400"),+ ],+ }+ )++ df+ return Image, df, io, load_image, pd, pl, requests+++def _(df):+ df.to_pandas()+ return+++def _(Image, io, requests):+ Image.open(io.BytesIO(requests.get("https://picsum.photos/200").content))+ return+++if __name__ == "__main__":+ app.run()diff --git a/tests/_plugins/ui/_impl/tables/test_pandas_table.py b/tests/_plugins/ui/_impl/tables/test_pandas_table.pyindex fbb2fe3787..8da2b368dd 100644--- a/tests/_plugins/ui/_impl/tables/test_pandas_table.py+++ b/tests/_plugins/ui/_impl/tables/test_pandas_table.py@@ -1015,3 +1015,29 @@ class TestPandasTableManager(unittest.TestCase):assert sample_values == [1, 2, 3]sample_values = manager.get_sample_values("B")assert sample_values == ["a", "b", "c"]++ @pytest.mark.skipif(+ not DependencyManager.pillow.has(), reason="pillow not installed"+ )+ def test_get_field_types_with_pil_images(self):+ import numpy as np+ import pandas as pd+ from PIL import Image++ # Create a simple image+ img_array = np.zeros((10, 10, 3), dtype=np.uint8)+ img = Image.fromarray(img_array)++ # Create a dataframe with an image column+ data = pd.DataFrame(+ {"image_col": [img, img, img], "text_col": ["a", "b", "c"]}+ )++ manager = self.factory.create()(data)++ # PIL images should be treated as objects+ assert manager.get_field_type("image_col") == ("string", "object")+ assert manager.get_field_type("text_col") == ("string", "object")++ as_json = manager.to_json()+ assert "data:image\\/png" in as_json.decode("utf-8")diff --git a/tests/_plugins/ui/_impl/tables/test_polars_table.py b/tests/_plugins/ui/_impl/tables/test_polars_table.pyindex d3d6654612..c1c98753ec 100644--- a/tests/_plugins/ui/_impl/tables/test_polars_table.py+++ b/tests/_plugins/ui/_impl/tables/test_polars_table.py@@ -843,3 +843,29 @@ class TestPolarsTableManagerFactory(unittest.TestCase):"datetime[μs]",)assert manager.get_field_type("time_col") == ("time", "Time")++ @pytest.mark.skipif(+ not DependencyManager.pillow.has(), reason="pillow not installed"+ )+ def test_get_field_types_with_pil_images(self):+ import numpy as np+ import polars as pl+ from PIL import Image++ # Create a simple image+ img_array = np.zeros((10, 10, 3), dtype=np.uint8)+ img = Image.fromarray(img_array)++ # Create a dataframe with an image column+ data = pl.DataFrame(+ {"image_col": [img, img, img], "text_col": ["a", "b", "c"]}+ )++ manager = self.factory.create()(data)++ # PIL images should be treated as objects+ assert manager.get_field_type("image_col") == ("unknown", "object")+ assert manager.get_field_type("text_col") == ("string", "str")++ as_json = manager.to_json()+ assert "data:image/png" in as_json.decode("utf-8")