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 loading image from path (#555)
Akshay Agrawal41a6959ea78f
diff --git a/marimo/_plugins/stateless/image.py b/marimo/_plugins/stateless/image.pyindex 703559de9e..98db97e7f8 100644--- a/marimo/_plugins/stateless/image.py+++ b/marimo/_plugins/stateless/image.py@@ -2,6 +2,7 @@from __future__ import annotationsimport io+import osfrom typing import Any, Optional, Unionimport marimo._output.data.data as mo_data@@ -23,9 +24,15 @@ def image() -> Html:"""Render an image as HTML.- **Example.**+ **Examples.**```python3+ # Render an image from a local file+ mo.image(src="path/to/image.png")+ ```++ ```python3+ # Render an image from a URLmo.image(src="https://marimo.io/logo.png",alt="Marimo logo",@@ -33,14 +40,12 @@ def image(height=100,rounded=True,)-- with open("logo.png", "rb") as file:- mo.image(src=file)```**Args.**- - `src`: the URL of the image or a file-like object+ - `src`: a path or URL to an image, or a file-like object+ (opened in binary mode)- `alt`: the alt text of the image- `width`: the width of the image in pixels- `height`: the height of the image in pixels@@ -58,6 +63,11 @@ def image(resolved_src = mo_data.image(src.read()).urlelif isinstance(src, bytes):resolved_src = mo_data.image(src).url+ elif isinstance(src, str) and os.path.isfile(src):+ with open(src, "rb") as f:+ resolved_src = mo_data.image(+ f.read(), ext=os.path.splitext(src)[1]+ ).urlelse: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.pyindex ed699e4c1e..897b512328 100644--- a/tests/_plugins/stateless/test_image.py+++ b/tests/_plugins/stateless/test_image.py@@ -1,4 +1,8 @@# Copyright 2023 Marimo. All rights reserved.+import sys++import pytest+from marimo._plugins.stateless.image import imagefrom marimo._runtime.context import get_contextfrom marimo._runtime.runtime import Kernel@@ -60,3 +64,22 @@ def test_image_str(k: Kernel, exec_req: ExecReqProvider) -> None:])assert len(get_context().virtual_file_registry.registry) == 0+++# TODO(akshayka): Debug on Windows[email protected](sys.platform == "win32", reason="Failing on Windows CI")+def test_image_local_file(k: Kernel, exec_req: ExecReqProvider) -> None:+ # Just opens a file that exists, and make sure it gets registered+ # in the virtual path registry+ with open(__file__, encoding="utf-8") as f:+ k.run(+ [+ exec_req.get(+ f"""+ import marimo as mo+ image = mo.image('{f.name}')+ """+ ),+ ]+ )+ assert len(get_context().virtual_file_registry.registry) == 1