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.

feat: add `mo.image_compare()` | image comparison slider (#5091)

Srihari Thyagarajan48fb76150bcd
diff --git a/docs/api/media/image_compare.md b/docs/api/media/image_compare.md
new file mode 100644
index 0000000000..34f9d8352e
--- /dev/null
+++ b/docs/api/media/image_compare.md
@@ -0,0 +1,23 @@
+# Image Compare
+
+/// marimo-embed
+ size: medium
+
+```python
+def __():
+ before_image = "https://picsum.photos/200/301.jpg"
+ after_image = "https://picsum.photos/200/300.jpg"
+
+ mo.image_compare(
+ before_image=before_image,
+ after_image=after_image,
+ value=30,
+ direction="horizontal"
+ )
+ return
+```
+
+///
+
+::: marimo.image_compare
diff --git a/docs/api/media/index.md b/docs/api/media/index.md
index cfb6a5b646..3bb3ffc45b 100644
--- a/docs/api/media/index.md
+++ b/docs/api/media/index.md
@@ -5,6 +5,7 @@ Use these functions to embed media in your outputs.
| Function | Description |
|----------|-------------|
| [`marimo.image`](image.md) | Display images |
+| [`marimo.image_compare`](image_compare.md) | Compare two images side by side |
| [`marimo.audio`](audio.md) | Play audio files |
| [`marimo.video`](video.md) | Play videos |
| [`marimo.pdf`](pdf.md) | Display PDFs |
diff --git a/examples/ui/image_comparison_demo.py b/examples/ui/image_comparison_demo.py
new file mode 100644
index 0000000000..9662aec708
--- /dev/null
+++ b/examples/ui/image_comparison_demo.py
@@ -0,0 +1,100 @@
+#!/usr/bin/env python3
+# /// script
+# requires-python = ">=3.11"
+# dependencies = [
+# "marimo",
+# ]
+# ///
+# Copyright 2024 Marimo. All rights reserved.
+
+import marimo
+
+__generated_with = "0.13.11"
+app = marimo.App()
+
+
[email protected](hide_code=True)
+def _(mo):
+ mo.md(
+ """
+ # Image Comparison Demo
+
+ This demo showcases the `mo.image_compare` feature, which allows for side-by-side comparison of images.
+
+ ## Basic Usage - Horizontal Comparison
+
+ The default orientation is horizontal, where you can slide left and right to compare images:
+ """
+ )
+ return
+
+
+def _():
+ before_image_path = "https://picsum.photos/200/301.jpg"
+ after_image_path = "https://picsum.photos/200/300.jpg"
+ return after_image_path, before_image_path
+
+
+def _(after_image_path, before_image_path, mo):
+ # Basic horizontal comparison with default settings
+ mo.image_compare(before_image=before_image_path, after_image=after_image_path)
+ return
+
+
[email protected](hide_code=True)
+def _(mo):
+ mo.md(
+ r"""
+ ## Custom Initial Position
+
+ You can set the initial position of the slider:
+ """
+ )
+ return
+
+
+def _(after_image_path, before_image_path, mo):
+ mo.image_compare(
+ before_image=before_image_path,
+ after_image=after_image_path,
+ direction="horizontal",
+ value=20, # Start at 25% position
+ )
+ return
+
+
[email protected](hide_code=True)
+def _(mo):
+ mo.md(
+ r"""
+ ## Vertical Comparison
+
+ You can also use a vertical comparison slider:
+ """
+ )
+ return
+
+
+def _(after_image_path, before_image_path, mo):
+ mo.image_compare(
+ before_image=before_image_path,
+ after_image=after_image_path,
+ direction="vertical",
+ value=75, # Start at 75% position
+ height=400,
+ )
+ return
+
+
+def _():
+ import marimo as mo
+ return (mo,)
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/frontend/package.json b/frontend/package.json
index d56cfee347..64e57e8f0f 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -37,6 +37,7 @@
"@emotion/cache": "^11.14.0",
"@emotion/react": "^11.14.0",
"@hookform/resolvers": "^3.10.0",
+ "@img-comparison-slider/react": "^8.0.2",
"@internationalized/date": "^3.8.0",
"@lezer/common": "^1.2.3",
"@lezer/highlight": "^1.2.1",
@@ -249,4 +250,4 @@
"react-plotly.js": "patches/react-plotly.js.patch"
}
}
-}
+}
\ No newline at end of file
diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yaml
index d3ca21ad0b..eba652fa7f 100644
--- a/frontend/pnpm-lock.yaml
+++ b/frontend/pnpm-lock.yaml
@@ -87,9 +87,12 @@ importers:
'@hookform/resolvers':
specifier: ^3.10.0
+ '@img-comparison-slider/react':
+ specifier: ^8.0.2
+ version: 8.0.2
'@internationalized/date':
specifier: ^3.8.0
- version: 3.8.0
+ version: 3.8.1
'@lezer/common':
specifier: ^1.2.3
version: 1.2.3
@@ -1443,8 +1446,11 @@ packages:
'@iconify/[email protected]':
resolution: {integrity: sha512-jP9h6v/g0BIZx0p7XGJJVtkVnydtbgTgt9mVNcGDYwaa7UhdHdI9dvoq+gKj9sijMSJKxUPEG2JyjsgXjxL7Kw==}
- '@internationalized/[email protected]':
- resolution: {integrity: sha512-J51AJ0fEL68hE4CwGPa6E0PO6JDaVLd8aln48xFCSy7CZkZc96dGEGmLs2OEEbBxcsVZtfrqkXJwI2/MSG8yKw==}
+ '@img-comparison-slider/[email protected]':
+ resolution: {integrity: sha512-Him0yhbXpMXdnV6R3XE3LiXcMRhSXFMsbk6I7ct5HxO2YpK/BAGz3ub+7+akJRnK2XI7c3vQqvoIE507N1K4SA==}
+
+ '@internationalized/[email protected]':
+ resolution: {integrity: sha512-PgVE6B6eIZtzf9Gu5HvJxRK3ufUFz9DhspELuhW/N0GuMGMTLvPQNRkHP2hTuP9lblOk+f+1xi96sPiPXANXAA==}
'@internationalized/[email protected]':
resolution: {integrity: sha512-gLQlhEW4iO7DEFPf/U7IrIdA3UyLGS0opeqouaFwlMObLUzwexRjbygONHDVbC9G9oFLXsLyGKYkJwqXw/QADg==}
@@ -5910,6 +5916,9 @@ packages:
engines: {node: '>=0.10.0'}
hasBin: true
+ resolution: {integrity: sha512-ej4de7mWyjcXZvDgHq8K2a/dG8Vv+qYTdUjZa3cVILf316rLtDrHyGbh9fPvixmAFgbs30zTLfmaRDa7abjtzw==}
+
resolution: {integrity: sha512-veYYhQa+D1QBKznvhUHxb8faxlrwUnxseDAbAp457E0wLNio2bOSKnjYDhMj+YiAq61xrMGhQk9iXVk5FzgQMw==}
engines: {node: '>=6'}
@@ -10139,7 +10148,11 @@ snapshots:
transitivePeerDependencies:
- supports-color
- '@internationalized/[email protected]':
+ '@img-comparison-slider/[email protected]':
+ dependencies:
+ img-comparison-slider: 8.0.6
+
+ '@internationalized/[email protected]':
dependencies:
'@swc/helpers': 0.5.1
@@ -11247,7 +11260,7 @@ snapshots:
dependencies:
- '@internationalized/date': 3.8.0
+ '@internationalized/date': 3.8.1
'@react-aria/interactions': 3.25.0([email protected]([email protected]))([email protected])
'@react-aria/live-announcer': 3.4.2
@@ -11328,7 +11341,7 @@ snapshots:
dependencies:
- '@internationalized/date': 3.8.0
+ '@internationalized/date': 3.8.1
'@internationalized/number': 3.6.1
'@internationalized/string': 3.2.6
@@ -11441,7 +11454,7 @@ snapshots:
dependencies:
- '@internationalized/date': 3.8.0
+ '@internationalized/date': 3.8.1
'@internationalized/message': 3.1.7
'@internationalized/number': 3.6.1
'@internationalized/string': 3.2.6
@@ -11849,7 +11862,7 @@ snapshots:
dependencies:
- '@internationalized/date': 3.8.0
+ '@internationalized/date': 3.8.1
'@react-stately/utils': 3.10.6([email protected])
'@react-types/calendar': 3.7.0([email protected])
'@react-types/shared': 3.29.0([email protected])
@@ -11905,7 +11918,7 @@ snapshots:
dependencies:
- '@internationalized/date': 3.8.0
+ '@internationalized/date': 3.8.1
'@internationalized/string': 3.2.6
'@react-stately/form': 3.1.3([email protected])
'@react-stately/overlays': 3.6.15([email protected])
@@ -12119,7 +12132,7 @@ snapshots:
dependencies:
- '@internationalized/date': 3.8.0
+ '@internationalized/date': 3.8.1
'@react-types/shared': 3.29.0([email protected])
react: 18.3.1
@@ -12141,7 +12154,7 @@ snapshots:
dependencies:
- '@internationalized/date': 3.8.0
+ '@internationalized/date': 3.8.1
'@react-types/calendar': 3.7.0([email protected])
'@react-types/overlays': 3.8.14([email protected])
'@react-types/shared': 3.29.0([email protected])
@@ -15752,6 +15765,8 @@ snapshots:
optional: true
+
dependencies:
parent-module: 1.0.1
@@ -17420,7 +17435,7 @@ snapshots:
dependencies:
- '@internationalized/date': 3.8.0
+ '@internationalized/date': 3.8.1
'@internationalized/string': 3.2.6
'@react-aria/autocomplete': 3.0.0-beta.2([email protected]([email protected]))([email protected])
'@react-aria/collections': 3.0.0-rc.0([email protected]([email protected]))([email protected])
diff --git a/frontend/src/plugins/impl/image-comparison/ImageComparisonComponent.tsx b/frontend/src/plugins/impl/image-comparison/ImageComparisonComponent.tsx
new file mode 100644
index 0000000000..da7f22ca8c
--- /dev/null
+++ b/frontend/src/plugins/impl/image-comparison/ImageComparisonComponent.tsx
@@ -0,0 +1,38 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import React from "react";
+import { ImgComparisonSlider } from "@img-comparison-slider/react";
+
+export interface ImageComparisonData {
+ beforeSrc: string;
+ afterSrc: string;
+ value: number;
+ direction: "horizontal" | "vertical";
+ width?: string;
+ height?: string;
+}
+
+const ImageComparisonComponent: React.FC<ImageComparisonData> = ({
+ beforeSrc,
+ afterSrc,
+ value,
+ direction,
+ width,
+ height,
+}) => {
+ const containerStyle: React.CSSProperties = {
+ width: width || "100%",
+ height: height || (direction === "vertical" ? "400px" : "auto"),
+ maxWidth: "100%",
+ };
+
+ return (
+ <div style={containerStyle}>
+ <ImgComparisonSlider value={value} direction={direction}>
+ <img slot="first" src={beforeSrc} alt="Before" width="100%" />
+ <img slot="second" src={afterSrc} alt="After" width="100%" />
+ </ImgComparisonSlider>
+ </div>
+ );
+};
+
+export default ImageComparisonComponent;
diff --git a/frontend/src/plugins/layout/ImageComparisonPlugin.tsx b/frontend/src/plugins/layout/ImageComparisonPlugin.tsx
new file mode 100644
index 0000000000..74f574c041
--- /dev/null
+++ b/frontend/src/plugins/layout/ImageComparisonPlugin.tsx
@@ -0,0 +1,35 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import React from "react";
+import { z } from "zod";
+import type {
+ IStatelessPlugin,
+ IStatelessPluginProps,
+} from "../stateless-plugin";
+import type { ImageComparisonData } from "../impl/image-comparison/ImageComparisonComponent";
+
+const LazyImageComparisonComponent = React.lazy(
+ () => import("../impl/image-comparison/ImageComparisonComponent"),
+);
+
+export class ImageComparisonPlugin
+ implements IStatelessPlugin<ImageComparisonData>
+{
+ tagName = "marimo-image-comparison";
+
+ validator = z.object({
+ beforeSrc: z.string(),
+ afterSrc: z.string(),
+ value: z.number().min(0).max(100).default(50),
+ direction: z.enum(["horizontal", "vertical"]).default("horizontal"),
+ width: z.string().optional(),
+ height: z.string().optional(),
+ });
+
+ render(props: IStatelessPluginProps<ImageComparisonData>): JSX.Element {
+ return (
+ <React.Suspense fallback={<div>Loading image comparison...</div>}>
+ <LazyImageComparisonComponent {...props.data} />
+ </React.Suspense>
+ );
+ }
+}
diff --git a/frontend/src/plugins/plugins.ts b/frontend/src/plugins/plugins.ts
index b773e64463..5fed8bbde2 100644
--- a/frontend/src/plugins/plugins.ts
+++ b/frontend/src/plugins/plugins.ts
@@ -49,6 +49,7 @@ import { MimeRendererPlugin } from "./layout/MimeRenderPlugin";
import { ChatPlugin } from "./impl/chat/ChatPlugin";
import { DataEditorPlugin } from "./impl/DataEditorPlugin";
import { PanelPlugin } from "./impl/panel/PanelPlugin";
+import { ImageComparisonPlugin } from "./layout/ImageComparisonPlugin";
// List of UI plugins
export const UI_PLUGINS: Array<IPlugin<any, unknown>> = [
@@ -92,6 +93,7 @@ const LAYOUT_PLUGINS: Array<IStatelessPlugin<unknown>> = [
new AccordionPlugin(),
new CalloutPlugin(),
new CarouselPlugin(),
+ new ImageComparisonPlugin(),
new JsonOutputPlugin(),
new MimeRendererPlugin(),
new MermaidPlugin(),
diff --git a/marimo/__init__.py b/marimo/__init__.py
index d47c8744a9..a219fac699 100644
--- a/marimo/__init__.py
+++ b/marimo/__init__.py
@@ -47,6 +47,7 @@ __all__ = [
"icon",
"iframe",
"image",
+ "image_compare",
"json",
"latex",
"lazy",
@@ -108,6 +109,7 @@ from marimo._plugins.stateless.download import download
from marimo._plugins.stateless.flex import hstack, vstack
from marimo._plugins.stateless.icon import icon
from marimo._plugins.stateless.image import image
+from marimo._plugins.stateless.image_compare import image_compare
from marimo._plugins.stateless.json_component import json
from marimo._plugins.stateless.lazy import lazy
from marimo._plugins.stateless.mermaid import mermaid
diff --git a/marimo/_plugins/stateless/image_compare.py b/marimo/_plugins/stateless/image_compare.py
new file mode 100644
index 0000000000..84ec5fe2ae
--- /dev/null
+++ b/marimo/_plugins/stateless/image_compare.py
@@ -0,0 +1,131 @@
+# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+import io
+import os
+from pathlib import Path
+from typing import Literal, Optional, Union
+
+import marimo._output.data.data as mo_data
+from marimo._output.hypertext import Html
+from marimo._output.rich_help import mddoc
+from marimo._output.utils import normalize_dimension
+from marimo._plugins.core.media import io_to_data_url
+from marimo._plugins.core.web_component import build_stateless_plugin
+from marimo._plugins.stateless.image import ImageLike, _normalize_image
+
+
+@mddoc
+def image_compare(
+ before_image: ImageLike,
+ after_image: ImageLike,
+ value: float = 50,
+ direction: Literal["horizontal", "vertical"] = "horizontal",
+ width: Optional[Union[int, str]] = None,
+ height: Optional[Union[int, str]] = None,
+) -> Html:
+ """Render an image comparison slider to compare two images side by side.
+
+ Examples:
+ ```python3
+ # Basic usage with two images
+ mo.image_compare(before_image="before.jpg", after_image="after.jpg")
+ ```
+
+ ```python3
+ # With custom settings
+ mo.image_compare(
+ before_image="original.png",
+ after_image="processed.png",
+ value=30, # Initial slider position at 30%
+ direction="vertical",
+ width=500,
+ height=400,
+ )
+ ```
+
+ Args:
+ before_image: The "before" image to show in the comparison slider.
+ Can be a path, URL, or array-like object.
+ after_image: The "after" image to show in the comparison slider.
+ Can be a path, URL, or array-like object.
+ value: Initial position of the slider (0-100), defaults to 50.
+ direction: Orientation of the slider, either "horizontal" or "vertical".
+ Defaults to "horizontal".
+ width: Width of the component in pixels or CSS units.
+ height: Height of the component in pixels or CSS units.
+
+ Returns:
+ `Html` object with the image comparison slider.
+ """
+ # Process the before and after images
+ before_src = _process_image_to_url(before_image)
+ after_src = _process_image_to_url(after_image)
+
+ normalized_value = max(0, min(100, float(value)))
+
+ # Prepare dimensions
+ width_str = normalize_dimension(width) if width is not None else None
+ height_str = normalize_dimension(height) if height is not None else None
+
+ # Build the plugin arguments
+ args = {
+ "before-src": before_src,
+ "after-src": after_src,
+ "value": normalized_value,
+ "direction": direction,
+ }
+
+ # Add optional dimensions
+ if width_str is not None:
+ args["width"] = width_str
+ if height_str is not None:
+ args["height"] = height_str
+
+ return Html(
+ build_stateless_plugin(
+ component_name="marimo-image-comparison",
+ args=args,
+ )
+ )
+
+
+def _process_image_to_url(src: ImageLike) -> str:
+ """Process an image-like object to a URL that can be used in an <img> tag.
+
+ Args:
+ src: An image-like object.
+
+ Returns:
+ A string URL that can be used in an <img> tag.
+ """
+ try:
+ src = _normalize_image(src)
+
+ # different types handling
+ if isinstance(src, io.BufferedReader) or isinstance(src, io.BytesIO):
+ src.seek(0)
+ return mo_data.image(src.read()).url
+ elif isinstance(src, bytes):
+ return mo_data.image(src).url
+ elif isinstance(src, Path):
+ return mo_data.image(src.read_bytes(), ext=src.suffix).url
+ elif isinstance(src, str) and os.path.isfile(
+ expanded_path := os.path.expanduser(src)
+ ):
+ path = Path(expanded_path)
+ return mo_data.image(path.read_bytes(), ext=path.suffix).url
+ else:
+ # If it's a URL or other string, try to use it directly
+ result = io_to_data_url(src, fallback_mime_type="image/png")
+ return (
+ result
+ if result is not None
+ else f"data:text/plain,Unable to process image: {src}"
+ )
+ except Exception as e:
+ # return an error message otherwise
+ error_message = f"Error processing image: {str(e)}"
+ # Using a comment instead of print for logging
+ # print(f"Warning: {error_message}")
+ return f"data:text/plain,{error_message}"
diff --git a/tests/_plugins/stateless/test_image_compare.py b/tests/_plugins/stateless/test_image_compare.py
new file mode 100644
index 0000000000..df249e36d5
--- /dev/null
+++ b/tests/_plugins/stateless/test_image_compare.py
@@ -0,0 +1,301 @@
+# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+import sys
+
+import pytest
+
+from marimo._dependencies.dependencies import DependencyManager
+from marimo._plugins.stateless.image_compare import image_compare
+from marimo._runtime.context import get_context
+from marimo._runtime.runtime import Kernel
+from tests.conftest import ExecReqProvider
+
+HAS_DEPS = DependencyManager.numpy.has() and DependencyManager.pillow.has()
+
+
+async def test_image_compare_basic() -> None:
+ result = image_compare(
+ before_image="https://marimo.io/logo.png",
+ after_image="https://marimo.io/logo.png",
+ )
+ assert "marimo-image-comparison" in result.text
+ assert "before-src" in result.text
+ assert "after-src" in result.text
+ assert "value" in result.text
+ assert "direction" in result.text
+
+
+async def test_image_compare_with_value() -> None:
+ result = image_compare(
+ before_image="https://marimo.io/logo.png",
+ after_image="https://marimo.io/logo.png",
+ value=75,
+ )
+ assert "marimo-image-comparison" in result.text
+ assert "data-value='75.0'" in result.text
+
+
+async def test_image_compare_vertical() -> None:
+ result = image_compare(
+ before_image="https://marimo.io/logo.png",
+ after_image="https://marimo.io/logo.png",
+ direction="vertical",
+ )
+ assert "marimo-image-comparison" in result.text
+ assert "data-direction='&quot;vertical&quot;'" in result.text
+
+
+async def test_image_compare_with_dimensions() -> None:
+ result = image_compare(
+ before_image="https://marimo.io/logo.png",
+ after_image="https://marimo.io/logo.png",
+ width=500,
+ height=400,
+ )
+ assert "marimo-image-comparison" in result.text
+ assert "data-width='&quot;500px&quot;'" in result.text
+ assert "data-height='&quot;400px&quot;'" in result.text
+
+
+async def test_image_compare_with_string_dimensions() -> None:
+ result = image_compare(
+ before_image="https://marimo.io/logo.png",
+ after_image="https://marimo.io/logo.png",
+ width="50%",
+ height="300px",
+ )
+ assert "marimo-image-comparison" in result.text
+ assert "data-width='&quot;50%&quot;'" in result.text
+ assert "data-height='&quot;300px&quot;'" in result.text
+
+
+async def test_image_compare_value_bounds() -> None:
+ # Test value below 0
+ result = image_compare(
+ before_image="https://marimo.io/logo.png",
+ after_image="https://marimo.io/logo.png",
+ value=-10,
+ )
+ assert "data-value='0'" in result.text
+
+ # Test value above 100
+ result = image_compare(
+ before_image="https://marimo.io/logo.png",
+ after_image="https://marimo.io/logo.png",
+ value=150,
+ )
+ assert "data-value='100'" in result.text
+
+
+async def test_image_compare_filename(
+ k: Kernel, exec_req: ExecReqProvider
+) -> None:
+ await k.run(
+ [
+ exec_req.get(
+ """
+ import marimo as mo
+ import os
+ # Create test images
+ with open("test_before.png", "wb") as f:
+ f.write(b"before_image_data")
+ with open("test_after.png", "wb") as f:
+ f.write(b"after_image_data")
+
+ comparison = mo.image_compare("test_before.png", "test_after.png")
+
+ # Clean up
+ os.remove("test_before.png")
+ os.remove("test_after.png")
+ """
+ ),
+ ]
+ )
+
+ assert len(get_context().virtual_file_registry.registry) == 2
+ for fname in get_context().virtual_file_registry.registry.keys():
+ assert fname.endswith(".png")
+
+
+async def test_image_compare_path(
+ k: Kernel, exec_req: ExecReqProvider
+) -> None:
+ await k.run(
+ [
+ exec_req.get(
+ """
+ import marimo as mo
+ from pathlib import Path
+ import os
+
+ # Create test images
+ with open("test_before.png", "wb") as f:
+ f.write(b"before_image_data")
+ with open("test_after.png", "wb") as f:
+ f.write(b"after_image_data")
+
+ comparison = mo.image_compare(
+ Path("test_before.png"),
+ Path("test_after.png")
+ )
+
+ # Clean up
+ os.remove("test_before.png")
+ os.remove("test_after.png")
+ """
+ ),
+ ]
+ )
+
+ assert len(get_context().virtual_file_registry.registry) == 2
+ for fname in get_context().virtual_file_registry.registry.keys():
+ assert fname.endswith(".png")
+
+
+async def test_image_compare_bytes_io(
+ k: Kernel, exec_req: ExecReqProvider
+) -> None:
+ await k.run(
+ [
+ exec_req.get(
+ """
+ import io
+ import marimo as mo
+
+ before_stream = io.BytesIO(b"before_image_data")
+ after_stream = io.BytesIO(b"after_image_data")
+ comparison = mo.image_compare(before_stream, after_stream)
+ """
+ ),
+ ]
+ )
+
+ assert len(get_context().virtual_file_registry.registry) == 2
+ for fname in get_context().virtual_file_registry.registry.keys():
+ assert fname.endswith(".png")
+
+
+async def test_image_compare_mixed_sources(
+ k: Kernel, exec_req: ExecReqProvider
+) -> None:
+ await k.run(
+ [
+ exec_req.get(
+ """
+ import io
+ import marimo as mo
+ import os
+
+ # Create one file
+ with open("test_before.png", "wb") as f:
+ f.write(b"before_image_data")
+
+ # Use file for before, BytesIO for after
+ after_stream = io.BytesIO(b"after_image_data")
+ comparison = mo.image_compare("test_before.png", after_stream)
+
+ # Clean up
+ os.remove("test_before.png")
+ """
+ ),
+ ]
+ )
+
+ assert len(get_context().virtual_file_registry.registry) == 2
+
+
+async def test_image_compare_str(k: Kernel, exec_req: ExecReqProvider) -> None:
+ await k.run(
+ [
+ exec_req.get(
+ """
+ import marimo as mo
+ comparison = mo.image_compare(
+ "https://marimo.io/logo.png",
+ "https://marimo.io/logo.png"
+ )
+ """
+ ),
+ ]
+ )
+
+ # URLs should not be registered
+ assert len(get_context().virtual_file_registry.registry) == 0
+
+
[email protected](not HAS_DEPS, reason="optional dependencies not installed")
+async def test_image_compare_array(
+ k: Kernel, exec_req: ExecReqProvider
+) -> None:
+ await k.run(
+ [
+ exec_req.get(
+ """
+ import marimo as mo
+
+ before_data = [[[255, 0, 0], [0, 255, 0], [0, 0, 255]]]
+ after_data = [[[0, 255, 0], [255, 0, 0], [0, 0, 255]]]
+ comparison = mo.image_compare(before_data, after_data)
+ """
+ ),
+ ]
+ )
+
+ assert len(get_context().virtual_file_registry.registry) == 2
+ for fname in get_context().virtual_file_registry.registry.keys():
+ assert fname.endswith(".png")
+
+
[email protected](not HAS_DEPS, reason="optional dependencies not installed")
+async def test_image_compare_numpy(
+ k: Kernel, exec_req: ExecReqProvider
+) -> None:
+ await k.run(
+ [
+ exec_req.get(
+ """
+ import marimo as mo
+ import numpy as np
+
+ before_data = np.random.rand(10, 10, 3)
+ after_data = np.random.rand(10, 10, 3)
+ comparison = mo.image_compare(before_data, after_data)
+ """
+ ),
+ ]
+ )
+
+ assert len(get_context().virtual_file_registry.registry) == 2
+ for fname in get_context().virtual_file_registry.registry.keys():
+ assert fname.endswith(".png")
+
+
[email protected](sys.platform == "win32", reason="Failing on Windows CI")
+async def test_image_compare_local_file(
+ k: Kernel, exec_req: ExecReqProvider
+) -> None:
+ # Use this test file itself as a dummy image
+ with open(__file__, encoding="utf-8") as f: # noqa: ASYNC230
+ await k.run(
+ [
+ exec_req.get(
+ f"""
+ import marimo as mo
+ comparison = mo.image_compare('{f.name}', '{f.name}')
+ """
+ ),
+ ]
+ )
+ assert len(get_context().virtual_file_registry.registry) == 2
+
+
+async def test_image_compare_error_handling() -> None:
+ # This should not raise an exception, but handle the error gracefully
+ result = image_compare(
+ before_image="invalid_path_that_does_not_exist.png",
+ after_image="another_invalid_path.png",
+ )
+
+ # Should still generate HTML even with invalid images
+ assert "marimo-image-comparison" in result.text
diff --git a/tests/snapshots/api.txt b/tests/snapshots/api.txt
index 301921e326..430cf0f4e0 100644
--- a/tests/snapshots/api.txt
+++ b/tests/snapshots/api.txt
@@ -34,6 +34,7 @@ hstack
icon
iframe
image
+image_compare
islands
MarimoIslandGenerator
MarimoIslandStub