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.

improvement: support Path in mo.image() (#3788)

Myles Scolnick0dfc80faeaa0
diff --git a/marimo/_plugins/stateless/image.py b/marimo/_plugins/stateless/image.py
index 3e91a13546..a4c048051c 100644
--- a/marimo/_plugins/stateless/image.py
+++ b/marimo/_plugins/stateless/image.py
@@ -3,6 +3,7 @@ from __future__ import annotations
import io
import os
+from pathlib import Path
from typing import Any, Optional, Union
import marimo._output.data.data as mo_data
@@ -13,7 +14,7 @@ from marimo._output.rich_help import mddoc
from marimo._output.utils import create_style, normalize_dimension
from marimo._plugins.core.media import io_to_data_url
-Image = Union[str, bytes, io.BytesIO, io.BufferedReader]
+Image = Union[str, bytes, io.BytesIO, io.BufferedReader, Path]
# Union[list, torch.Tensor, jax.numpy.ndarray,
# np.ndarray, scipy.sparse.spmatrix]
Tensor = Any
@@ -74,7 +75,7 @@ def _normalize_image(src: ImageLike) -> Image:
img.save(normalized_src, format="PNG")
return normalized_src
# Verify that this is a image object
- if not isinstance(src, (str, bytes, io.BytesIO, io.BufferedReader)):
+ if not isinstance(src, (str, bytes, io.BytesIO, io.BufferedReader, Path)):
raise ValueError(
f"Expected an image object, but got {type(src)} instead."
)
@@ -135,13 +136,13 @@ def image(
resolved_src = mo_data.image(src.read()).url
elif isinstance(src, bytes):
resolved_src = mo_data.image(src).url
+ elif isinstance(src, Path):
+ resolved_src = mo_data.image(src.read_bytes(), ext=src.suffix).url
elif isinstance(src, str) and os.path.isfile(
expanded_path := os.path.expanduser(src)
):
- with open(expanded_path, "rb") as f:
- resolved_src = mo_data.image(
- f.read(), ext=os.path.splitext(expanded_path)[1]
- ).url
+ src = Path(expanded_path)
+ resolved_src = mo_data.image(src.read_bytes(), ext=src.suffix).url
else:
resolved_src = io_to_data_url(src, fallback_mime_type="image/png")
diff --git a/tests/_plugins/stateless/test_image.py b/tests/_plugins/stateless/test_image.py
index 1bd8b3e806..ab68aff7aa 100644
--- a/tests/_plugins/stateless/test_image.py
+++ b/tests/_plugins/stateless/test_image.py
@@ -21,6 +21,51 @@ async def test_image() -> None:
assert result.text == "<img src='https://marimo.io/logo.png' />"
+async def test_image_filename(k: Kernel, exec_req: ExecReqProvider) -> None:
+ await k.run(
+ [
+ exec_req.get(
+ """
+ import marimo as mo
+ import os
+ with open("test_image.png", "wb") as f:
+ f.write(b"hello")
+ image = mo.image("test_image.png")
+ # Delete the file
+ os.remove("test_image.png")
+ """
+ ),
+ ]
+ )
+
+ assert len(get_context().virtual_file_registry.registry) == 1
+ for fname in get_context().virtual_file_registry.registry.keys():
+ assert fname.endswith(".png")
+
+
+async def test_image_path(k: Kernel, exec_req: ExecReqProvider) -> None:
+ await k.run(
+ [
+ exec_req.get(
+ """
+ import marimo as mo
+ from pathlib import Path
+ import os
+ # Create the image file
+ with open("test_image.png", "wb") as f:
+ f.write(b"hello")
+ image = mo.image(Path("test_image.png"))
+ # Delete the file
+ os.remove("test_image.png")
+ """
+ ),
+ ]
+ )
+ assert len(get_context().virtual_file_registry.registry) == 1
+ for fname in get_context().virtual_file_registry.registry.keys():
+ assert fname.endswith(".png")
+
+
async def test_image_bytes_io(k: Kernel, exec_req: ExecReqProvider) -> None:
await k.run(
[