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.

mo.image (#25)

Myles Scolnick734a572f8039
diff --git a/docs/api/layouts/image.md b/docs/api/layouts/image.md
new file mode 100644
index 0000000000..eec7181f98
--- /dev/null
+++ b/docs/api/layouts/image.md
@@ -0,0 +1,9 @@
+# Image
+
+<!-- TODO: add interactive marimo.image doc.
+At the moment, our components app uses released versions of marimo, so these changes will lag behind. -->
+<!-- <iframe class="demo" src="https://components.marimo.io/?component=refresh" frameborder="no"></iframe> -->
+
+```{eval-rst}
+.. autofunction:: marimo.image
+```
diff --git a/docs/api/layouts/index.md b/docs/api/layouts/index.md
index 74d812d1f4..07fc3b5415 100644
--- a/docs/api/layouts/index.md
+++ b/docs/api/layouts/index.md
@@ -7,6 +7,7 @@
accordion
callout
+ image
stacks
tabs
tree
@@ -22,6 +23,7 @@ certain way.
marimo.accordion
marimo.callout
+ marimo.image
marimo.hstack
marimo.vstack
marimo.tabs
diff --git a/docs/apps/output.py b/docs/apps/output.py
index 28b07f158b..bfbd2c4d8c 100644
--- a/docs/apps/output.py
+++ b/docs/apps/output.py
@@ -23,7 +23,7 @@ def __(array, ax, dictionary, mo, plots, table, text):
\]
"""
+ f"""
- You can even interpolate arbitrary Python values and marimo
+ You can even interpolate arbitrary Python values and marimo
elements into your markdown. Try typing your name below:
{mo.hstack([
@@ -44,7 +44,7 @@ def __(array, ax, dictionary, mo, plots, table, text):
"accordion": mo.accordion(
{
"Tip!": f"""
- Express yourself with outputs! Put anything in accordions,
+ Express yourself with outputs! Put anything in accordions,
like plots:
{mo.as_html(ax)}.
@@ -108,14 +108,14 @@ def __(mo):
{
"first_name": "Michael",
"last_name": "Scott",
- "ability": mo.ui.slider(1, 10, value=3),
- "favorite place": mo.md("![img](https://picsum.photos/100)"),
+ "skill": mo.ui.slider(1, 10, value=3),
+ "favorite place": mo.image(src="https://picsum.photos/100"),
},
{
"first_name": "Jim",
"last_name": "Halpert",
- "ability": mo.ui.slider(1, 10, value=7),
- "favorite place": mo.md("![img](https://picsum.photos/100)"),
+ "skill": mo.ui.slider(1, 10, value=7),
+ "favorite place": mo.image(src="https://picsum.photos/100"),
},
],
selection="single"
@@ -135,7 +135,7 @@ def __(mo, np, plt):
x = np.linspace(-2, 2, 100)
linear = plot(x, x, "$x$")
quadratic = plot(x, x**2, "$x^2$")
- sine = plot(x, np.sin(x), "$\sin(x)$")
+ sine = plot(x, np.sin(x), "$\sin(x)$")
cos = plot(x, np.cos(x), "$\cos(x)$")
exp = plot(x, np.exp(x), "$\exp(x)$")
diff --git a/examples/ai/openai.py b/examples/ai/openai.py
index f4a6de82b1..9abbb33745 100644
--- a/examples/ai/openai.py
+++ b/examples/ai/openai.py
@@ -118,9 +118,9 @@ def __(mo, openai, superhero):
mo.md(
f"""
💬 Create a catchphrase for {superhero.value}
-
+
🤖 Response:
-
+
{catchphrase}
"""
) if superhero.value else None
@@ -147,7 +147,7 @@ def __(generate_image_button, mo, openai, superhero):
)
url = res["data"][0]["url"]
- mo.Html(f"<img src={url} />") if url else None
+ mo.image(src=url) if url else None
return res, url
diff --git a/examples/optimization/signals/modules/layout.py b/examples/optimization/signals/modules/layout.py
index 179c4410ca..05ebd97698 100644
--- a/examples/optimization/signals/modules/layout.py
+++ b/examples/optimization/signals/modules/layout.py
@@ -14,4 +14,4 @@ def _pillow_image_to_base64_string(img):
def image(path: str) -> str:
img = Image.open(path)
data_url = "data:image/png;base64," + _pillow_image_to_base64_string(img)
- return f"<img src='{data_url}' />"
+ return mo.image(src=data_url)
diff --git a/examples/table.py b/examples/table.py
index 6c63948738..45d0c3b7b4 100644
--- a/examples/table.py
+++ b/examples/table.py
@@ -1,6 +1,6 @@
import marimo
-__generated_with = "0.1.0"
+__generated_with = "0.1.2"
app = marimo.App()
@@ -89,122 +89,122 @@ def __(mo):
{
"first_name": "Michael",
"last_name": "Scott",
- "ability": mo.ui.slider(1, 10, value=3),
- "favorite place": mo.md("![img](https://picsum.photos/100)"),
+ "skill": mo.ui.slider(1, 10, value=3),
+ "favorite place": mo.image(src="https://picsum.photos/100", rounded=True),
},
{
"first_name": "Jim",
"last_name": "Halpert",
- "ability": mo.ui.slider(1, 10, value=7),
- "favorite place": mo.md("![img](https://picsum.photos/100)"),
+ "skill": mo.ui.slider(1, 10, value=7),
+ "favorite place": mo.image(src="https://picsum.photos/100"),
},
{
"first_name": "Pam",
"last_name": "Beesly",
- "ability": mo.ui.slider(1, 10, value=3),
- "favorite place": mo.md("![img](https://picsum.photos/100)"),
+ "skill": mo.ui.slider(1, 10, value=3),
+ "favorite place": mo.image(src="https://picsum.photos/100"),
},
{
"first_name": "Dwight",
"last_name": "Schrute",
- "ability": mo.ui.slider(1, 10, value=7),
- "favorite place": mo.md("![img](https://picsum.photos/100)"),
+ "skill": mo.ui.slider(1, 10, value=7),
+ "favorite place": mo.image(src="https://picsum.photos/100"),
},
{
"first_name": "Angela",
"last_name": "Martin",
- "ability": mo.ui.slider(1, 10, value=5),
- "favorite place": mo.md("![img](https://picsum.photos/100)"),
+ "skill": mo.ui.slider(1, 10, value=5),
+ "favorite place": mo.image(src="https://picsum.photos/100"),
},
{
"first_name": "Kevin",
"last_name": "Malone",
- "ability": mo.ui.slider(1, 10, value=3),
- "favorite place": mo.md("![img](https://picsum.photos/100)"),
+ "skill": mo.ui.slider(1, 10, value=3),
+ "favorite place": mo.image(src="https://picsum.photos/100"),
},
{
"first_name": "Oscar",
"last_name": "Martinez",
- "ability": mo.ui.slider(1, 10, value=3),
- "favorite place": mo.md("![img](https://picsum.photos/100)"),
+ "skill": mo.ui.slider(1, 10, value=3),
+ "favorite place": mo.image(src="https://picsum.photos/100"),
},
{
"first_name": "Stanley",
"last_name": "Hudson",
- "ability": mo.ui.slider(1, 10, value=5),
- "favorite place": mo.md("![img](https://picsum.photos/100)"),
+ "skill": mo.ui.slider(1, 10, value=5),
+ "favorite place": mo.image(src="https://picsum.photos/100"),
},
{
"first_name": "Phyllis",
"last_name": "Vance",
- "ability": mo.ui.slider(1, 10, value=5),
- "favorite place": mo.md("![img](https://picsum.photos/100)"),
+ "skill": mo.ui.slider(1, 10, value=5),
+ "favorite place": mo.image(src="https://picsum.photos/100"),
},
{
"first_name": "Meredith",
"last_name": "Palmer",
- "ability": mo.ui.slider(1, 10, value=7),
- "favorite place": mo.md("![img](https://picsum.photos/100)"),
+ "skill": mo.ui.slider(1, 10, value=7),
+ "favorite place": mo.image(src="https://picsum.photos/100"),
},
{
"first_name": "Creed",
"last_name": "Bratton",
- "ability": mo.ui.slider(1, 10, value=3),
- "favorite place": mo.md("![img](https://picsum.photos/100)"),
+ "skill": mo.ui.slider(1, 10, value=3),
+ "favorite place": mo.image(src="https://picsum.photos/100"),
},
{
"first_name": "Ryan",
"last_name": "Howard",
- "ability": mo.ui.slider(1, 10, value=5),
- "favorite place": mo.md("![img](https://picsum.photos/100)"),
+ "skill": mo.ui.slider(1, 10, value=5),
+ "favorite place": mo.image(src="https://picsum.photos/100"),
},
{
"first_name": "Kelly",
"last_name": "Kapoor",
- "ability": mo.ui.slider(1, 10, value=3),
- "favorite place": mo.md("![img](https://picsum.photos/100)"),
+ "skill": mo.ui.slider(1, 10, value=3),
+ "favorite place": mo.image(src="https://picsum.photos/100"),
},
{
"first_name": "Toby",
"last_name": "Flenderson",
- "ability": mo.ui.slider(1, 10, value=3),
- "favorite place": mo.md("![img](https://picsum.photos/100)"),
+ "skill": mo.ui.slider(1, 10, value=3),
+ "favorite place": mo.image(src="https://picsum.photos/100"),
},
{
"first_name": "Darryl",
"last_name": "Philbin",
- "ability": mo.ui.slider(1, 10, value=7),
- "favorite place": mo.md("![img](https://picsum.photos/100)"),
+ "skill": mo.ui.slider(1, 10, value=7),
+ "favorite place": mo.image(src="https://picsum.photos/100"),
},
{
"first_name": "Erin",
"last_name": "Hannon",
- "ability": mo.ui.slider(1, 10, value=5),
- "favorite place": mo.md("![img](https://picsum.photos/100)"),
+ "skill": mo.ui.slider(1, 10, value=5),
+ "favorite place": mo.image(src="https://picsum.photos/100"),
},
{
"first_name": "Andy",
"last_name": "Bernard",
- "ability": mo.ui.slider(1, 10, value=5),
- "favorite place": mo.md("![img](https://picsum.photos/100)"),
+ "skill": mo.ui.slider(1, 10, value=5),
+ "favorite place": mo.image(src="https://picsum.photos/100"),
},
{
"first_name": "Jan",
"last_name": "Levinson",
- "ability": mo.ui.slider(1, 10, value=5),
- "favorite place": mo.md("![img](https://picsum.photos/100)"),
+ "skill": mo.ui.slider(1, 10, value=5),
+ "favorite place": mo.image(src="https://picsum.photos/100"),
},
{
"first_name": "David",
"last_name": "Wallace",
- "ability": mo.ui.slider(1, 10, value=3),
- "favorite place": mo.md("![img](https://picsum.photos/100)"),
+ "skill": mo.ui.slider(1, 10, value=3),
+ "favorite place": mo.image(src="https://picsum.photos/100"),
},
{
"first_name": "Holly",
"last_name": "Flax",
- "ability": mo.ui.slider(1, 10, value=7),
- "favorite place": mo.md("![img](https://picsum.photos/100)"),
+ "skill": mo.ui.slider(1, 10, value=7),
+ "favorite place": mo.image(src="https://picsum.photos/100"),
},
]
return office_characters,
diff --git a/marimo/__init__.py b/marimo/__init__.py
index aea0075156..ade40efa71 100644
--- a/marimo/__init__.py
+++ b/marimo/__init__.py
@@ -23,6 +23,7 @@ __all__ = [
"doc",
"hstack",
"Html",
+ "image",
"md",
"refs",
"stop",
@@ -43,6 +44,7 @@ from marimo._plugins import ui
from marimo._plugins.stateless.accordion import accordion
from marimo._plugins.stateless.callout_output import callout
from marimo._plugins.stateless.flex import hstack, vstack
+from marimo._plugins.stateless.image import image
from marimo._plugins.stateless.tabs import tabs
from marimo._plugins.stateless.tree import tree
from marimo._runtime.control_flow import MarimoStopError, stop
diff --git a/marimo/_output/builder.py b/marimo/_output/builder.py
new file mode 100644
index 0000000000..06d54ef381
--- /dev/null
+++ b/marimo/_output/builder.py
@@ -0,0 +1,49 @@
+# Copyright 2023 Marimo. All rights reserved.
+from typing import List, Optional, Tuple, Union
+
+
+class _HTMLBuilder:
+ @staticmethod
+ def div(
+ children: Union[str, List[str]], style: Optional[str] = None
+ ) -> str:
+ resolved_children = (
+ [children] if isinstance(children, str) else children
+ )
+
+ params: List[Tuple[str, str]] = []
+ if style:
+ params.append(("style", style))
+
+ children_html = "".join(resolved_children)
+
+ if len(params) == 0:
+ return f"<div>{children_html}</div>"
+ else:
+ return f"<div {_join_params(params)}>{children_html}</div>"
+
+ @staticmethod
+ def img(
+ src: Optional[str] = None,
+ alt: Optional[str] = None,
+ style: Optional[str] = None,
+ ) -> str:
+ params: List[Tuple[str, str]] = []
+ if src:
+ params.append(("src", src))
+ if alt:
+ params.append(("alt", alt))
+ if style:
+ params.append(("style", style))
+
+ if len(params) == 0:
+ return "<img />"
+ else:
+ return f"<img {_join_params(params)} />"
+
+
+def _join_params(params: List[Tuple[str, str]]) -> str:
+ return " ".join([f"{k}='{v}'" for k, v in params])
+
+
+h = _HTMLBuilder()
diff --git a/marimo/_output/test_builder.py b/marimo/_output/test_builder.py
new file mode 100644
index 0000000000..62f42a63d2
--- /dev/null
+++ b/marimo/_output/test_builder.py
@@ -0,0 +1,24 @@
+# Copyright 2023 Marimo. All rights reserved.
+from marimo._output.builder import _join_params, h
+
+
+def test_div() -> None:
+ assert h.div("Hello") == "<div>Hello</div>"
+ assert h.div(["Hello", "World"]) == "<div>HelloWorld</div>"
+ assert h.div("Hello", "color:red") == "<div style='color:red'>Hello</div>"
+
+
+def test_img() -> None:
+ assert h.img() == "<img />"
+ assert (
+ h.img(src="image.jpg", alt="image", style="width:100px")
+ == "<img src='image.jpg' alt='image' style='width:100px' />"
+ )
+
+
+def test_join_params() -> None:
+ assert (
+ _join_params([("style", "color:red"), ("class", "myClass")])
+ == "style='color:red' class='myClass'"
+ )
+ assert _join_params([]) == ""
diff --git a/marimo/_output/utils.py b/marimo/_output/utils.py
index 0e0484b7f2..bf6171ca38 100644
--- a/marimo/_output/utils.py
+++ b/marimo/_output/utils.py
@@ -1,6 +1,8 @@
# Copyright 2023 Marimo. All rights reserved.
from __future__ import annotations
+from typing import Dict, Union
+
def build_data_url(mimetype: str, data: bytes) -> str:
str_repr = data.decode("utf-8").replace("\n", "")
@@ -9,3 +11,7 @@ def build_data_url(mimetype: str, data: bytes) -> str:
def flatten_string(text: str) -> str:
return "".join([line.strip() for line in text.split("\n")])
+
+
+def create_style(pairs: Dict[str, Union[str, int, float, None]]) -> str:
+ return ";".join([f"{k}: {v}" for k, v in pairs.items() if v is not None])
diff --git a/marimo/_plugins/stateless/flex.py b/marimo/_plugins/stateless/flex.py
index 6873d176ce..f28cfeba78 100644
--- a/marimo/_plugins/stateless/flex.py
+++ b/marimo/_plugins/stateless/flex.py
@@ -4,9 +4,11 @@ from __future__ import annotations
from collections.abc import Sequence
from typing import Literal, Optional
+from marimo._output.builder import h
from marimo._output.formatting import as_html
from marimo._output.hypertext import Html
from marimo._output.rich_help import mddoc
+from marimo._output.utils import create_style
def _flex(
@@ -34,20 +36,18 @@ def _flex(
"stretch": "stretch",
None: "normal",
}
- style = ";".join(
- [
- "display: flex",
- f"flex-direction: {direction}",
- f"justify-content: {justify_content_map[justify]}",
- f"align-items: {align_items_map[align]}",
- f"flex-wrap: {'wrap' if wrap else 'nowrap'}",
- f"gap: {gap}rem",
- ]
+ style = create_style(
+ {
+ "display": "flex",
+ "flex-direction": direction,
+ "justify-content": justify_content_map[justify],
+ "align-items": align_items_map[align],
+ "flex-wrap": "wrap" if wrap else "nowrap",
+ "gap": f"{gap}rem",
+ }
)
- grid_items = "".join(
- ["<div>" + as_html(item).text + "</div>" for item in items]
- )
- return Html(f"<div style='{style}'>" + grid_items + "</div>")
+ grid_items = [h.div(as_html(item).text) for item in items]
+ return Html(h.div(grid_items, style=style))
@mddoc
@@ -174,17 +174,15 @@ def _spaced(
- An `Html` object.
"""
items_per_row = len(items) if items_per_row is None else items_per_row
- style = ";".join(
- [
- "display: grid",
- f"grid-template-columns: repeat({items_per_row}, 1fr)",
- f"column-gap: {column_gap}rem",
- f"row-gap: {row_gap}rem",
- f"justify-items: {justify}",
- "overflow: auto",
- ]
- )
- grid_items = "".join(
- ["<div>" + as_html(item).text + "</div>" for item in items]
+ style = create_style(
+ {
+ "display": "grid",
+ "grid-template-columns": f"repeat({items_per_row}, 1fr)",
+ "column-gap": f"{column_gap}rem",
+ "row-gap": f"{row_gap}rem",
+ "justify-items": justify,
+ "overflow": "auto",
+ }
)
- return Html(f"<div style='{style}'>" + grid_items + "</div>")
+ grid_items = [h.div(as_html(item).text) for item in items]
+ return Html(h.div(grid_items, style=style))
diff --git a/marimo/_plugins/stateless/image.py b/marimo/_plugins/stateless/image.py
new file mode 100644
index 0000000000..f3f9375f59
--- /dev/null
+++ b/marimo/_plugins/stateless/image.py
@@ -0,0 +1,68 @@
+# Copyright 2023 Marimo. All rights reserved.
+from __future__ import annotations
+
+import base64
+import io
+from typing import Any, Optional, Union
+
+from marimo._output.builder import h
+from marimo._output.hypertext import Html
+from marimo._output.rich_help import mddoc
+from marimo._output.utils import create_style
+
+
+@mddoc
+def image(
+ src: Union[str, io.IOBase],
+ alt: Optional[str] = None,
+ width: Optional[int] = None,
+ height: Optional[int] = None,
+ rounded: bool = False,
+ style: Optional[dict[str, Any]] = None,
+) -> Html:
+ """Render an image as HTML.
+
+ **Example.**
+
+ ```python3
+ mo.image(
+ src="https://marimo.io/logo.png",
+ alt="Marimo logo",
+ width=100,
+ 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
+ - `alt`: the alt text of the image
+ - `width`: the width of the image
+ - `height`: the height of the image
+ - `rounded`: whether to round the corners of the image
+ - `style`: a dictionary of CSS styles to apply to the image
+
+ **Returns.**
+
+ `Html` object
+ """
+ resolved_src = src if isinstance(src, str) else _io_to_data_url(src)
+ styles = create_style(
+ {
+ "width": width,
+ "height": height,
+ "border-radius": "4px" if rounded else None,
+ **(style or {}),
+ }
+ )
+ img = h.img(src=resolved_src, alt=alt, style=styles)
+ return Html(img)
+
+
+def _io_to_data_url(readable: io.IOBase) -> str:
+ base64_string = base64.b64encode(readable.read()).decode("utf-8")
+ return f"data:image/png;base64,{base64_string}"
diff --git a/marimo/_plugins/stateless/test_flex.py b/marimo/_plugins/stateless/test_flex.py
new file mode 100644
index 0000000000..d8d89d8513
--- /dev/null
+++ b/marimo/_plugins/stateless/test_flex.py
@@ -0,0 +1,18 @@
+# Copyright 2023 Marimo. All rights reserved.
+from marimo._plugins.stateless.flex import hstack, vstack
+
+
+def test_vstack() -> None:
+ result = vstack(["item1", "item2"], align="center", gap=1)
+ assert (
+ result.text
+ == "<div style='display: flex;flex-direction: column;justify-content: flex-start;align-items: center;flex-wrap: nowrap;gap: 1rem'><div><span>item1</span></div><div><span>item2</span></div></div>" # noqa: E501
+ )
+
+
+def test_hstack() -> None:
+ result = hstack(["item1", "item2"], justify="center", gap=1, wrap=True)
+ assert (
+ result.text
+ == "<div style='display: flex;flex-direction: row;justify-content: center;align-items: normal;flex-wrap: wrap;gap: 1rem'><div><span>item1</span></div><div><span>item2</span></div></div>" # noqa: E501
+ )