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: mo.download button (#68)

Myles Scolnick6b80219f206c
diff --git a/docs/api/media/download.md b/docs/api/media/download.md
new file mode 100644
index 0000000000..57ff5ea96c
--- /dev/null
+++ b/docs/api/media/download.md
@@ -0,0 +1,9 @@
+# Download Media
+
+<!-- TODO: add interactive marimo.download 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=download" frameborder="no"></iframe> -->
+
+```{eval-rst}
+.. autofunction:: marimo.download
+```
diff --git a/docs/api/media/index.md b/docs/api/media/index.md
index cc6ac3a8df..5ddee3e17c 100644
--- a/docs/api/media/index.md
+++ b/docs/api/media/index.md
@@ -8,6 +8,7 @@
image
audio
pdf
+ download
```
Use `mo.image`, `mo.audio`, and `mo.pdf` to embed media in your outputs.
@@ -19,4 +20,5 @@ Use `mo.image`, `mo.audio`, and `mo.pdf` to embed media in your outputs.
marimo.image
marimo.audio
marimo.pdf
+ marimo.download
```
diff --git a/frontend/src/components/ui/button.tsx b/frontend/src/components/ui/button.tsx
index f020ca864f..e3ad4b9ef1 100644
--- a/frontend/src/components/ui/button.tsx
+++ b/frontend/src/components/ui/button.tsx
@@ -8,7 +8,10 @@ import { cn } from "@/lib/utils";
const activeCommon = "active:shadow-xsSolid";
const buttonVariants = cva(
- "inline-flex mb-1 items-center justify-center rounded-md text-sm font-medium focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:opacity-50 disabled:pointer-events-none ring-offset-background",
+ cn(
+ "disabled:opacity-50 disabled:pointer-events-none",
+ "inline-flex mb-1 items-center justify-center rounded-md text-sm font-medium focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-2 ring-offset-background"
+ ),
{
variants: {
variant: {
@@ -68,6 +71,9 @@ const buttonVariants = cva(
lg: "h-11 px-8 rounded-md",
icon: "h-6 w-6",
},
+ disabled: {
+ true: "opacity-50 pointer-events-none",
+ },
},
defaultVariants: {
variant: "default",
@@ -78,7 +84,7 @@ const buttonVariants = cva(
export interface ButtonProps
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
- VariantProps<typeof buttonVariants> {
+ Omit<VariantProps<typeof buttonVariants>, "disabled"> {
asChild?: boolean;
}
@@ -87,7 +93,9 @@ const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
const Comp = asChild ? Slot : "button";
return (
<Comp
- className={cn(buttonVariants({ variant, size, className }))}
+ className={cn(
+ buttonVariants({ variant, size, className, disabled: props.disabled })
+ )}
ref={ref}
{...props}
/>
diff --git a/frontend/src/plugins/layout/DownloadPlugin.tsx b/frontend/src/plugins/layout/DownloadPlugin.tsx
new file mode 100644
index 0000000000..bb39ea5511
--- /dev/null
+++ b/frontend/src/plugins/layout/DownloadPlugin.tsx
@@ -0,0 +1,55 @@
+/* Copyright 2023 Marimo. All rights reserved. */
+
+import { z } from "zod";
+import { IStatelessPlugin, IStatelessPluginProps } from "../stateless-plugin";
+import { DownloadIcon } from "lucide-react";
+import { buttonVariants } from "@/components/ui/button";
+import { cn } from "@/lib/utils";
+
+interface Data {
+ /**
+ * The href to download
+ */
+ data: string;
+ /**
+ * Filename
+ */
+ filename?: string | null;
+ /**
+ * Disabled
+ */
+ disabled?: boolean;
+ /**
+ * Button label
+ */
+ label?: string | null;
+}
+
+export class DownloadPlugin implements IStatelessPlugin<Data> {
+ tagName = "marimo-download";
+
+ validator = z.object({
+ data: z.string(),
+ disabled: z.boolean().default(false),
+ filename: z.string().nullish(),
+ label: z.string().nullish(),
+ });
+
+ render({ data }: IStatelessPluginProps<Data>): JSX.Element {
+ return (
+ <a
+ href={data.data}
+ download={data.filename || true}
+ target="_blank"
+ rel="noopener noreferrer"
+ className={buttonVariants({
+ variant: "secondary",
+ disabled: data.disabled,
+ })}
+ >
+ <DownloadIcon className={cn("w-3 h-3", data.label && "mr-2")} />
+ {data.label ?? "Download"}
+ </a>
+ );
+ }
+}
diff --git a/frontend/src/plugins/plugins.ts b/frontend/src/plugins/plugins.ts
index 4a2e49c8e6..bbcc9ad9a0 100644
--- a/frontend/src/plugins/plugins.ts
+++ b/frontend/src/plugins/plugins.ts
@@ -26,6 +26,7 @@ import { TabsPlugin } from "./layout/TabsPlugin";
import { TexPlugin } from "./layout/TexPlugin";
import { RefreshPlugin } from "./impl/RefreshPlugin";
import { MicrophonePlugin } from "./impl/MicrophonePlugin";
+import { DownloadPlugin } from "./layout/DownloadPlugin";
// List of UI plugins
const UI_PLUGINS: Array<IPlugin<any, unknown>> = [
@@ -52,6 +53,7 @@ const UI_PLUGINS: Array<IPlugin<any, unknown>> = [
const LAYOUT_PLUGINS: Array<IStatelessPlugin<unknown>> = [
new AccordionPlugin(),
new CalloutPlugin(),
+ new DownloadPlugin(),
new JsonOutputPlugin(),
new TabsPlugin(),
new TexPlugin(),
diff --git a/marimo/__init__.py b/marimo/__init__.py
index 9582831ca3..db0f2b0938 100644
--- a/marimo/__init__.py
+++ b/marimo/__init__.py
@@ -23,6 +23,7 @@ __all__ = [
"config",
"defs",
"doc",
+ "download",
"hstack",
"Html",
"image",
@@ -51,6 +52,7 @@ from marimo._plugins import ui
from marimo._plugins.stateless.accordion import accordion
from marimo._plugins.stateless.audio import audio
from marimo._plugins.stateless.callout_output import callout
+from marimo._plugins.stateless.download import download
from marimo._plugins.stateless.flex import hstack, vstack
from marimo._plugins.stateless.image import image
from marimo._plugins.stateless.pdf import pdf
diff --git a/marimo/_plugins/core/media.py b/marimo/_plugins/core/media.py
new file mode 100644
index 0000000000..8d6817323c
--- /dev/null
+++ b/marimo/_plugins/core/media.py
@@ -0,0 +1,57 @@
+# Copyright 2023 Marimo. All rights reserved.
+import base64
+import io
+import mimetypes
+from typing import Optional, Union
+
+
+def guess_mime_type(src: Union[str, bytes, io.BytesIO, None]) -> Optional[str]:
+ """Guess the MIME type of a file."""
+ if src is None:
+ return None
+
+ if isinstance(src, str) and src.startswith("data:"):
+ return src.split(";")[0].split(":")[1]
+
+ if isinstance(src, str):
+ return mimetypes.guess_type(src)[0]
+
+ if isinstance(src, io.FileIO):
+ return mimetypes.guess_type(src.name)[0]
+
+ return None
+
+
+def io_to_data_url(
+ src: Union[str, bytes, io.BytesIO, None], fallback_mime_type: str
+) -> Optional[str]:
+ """Convert a file-like object to a data URL."""
+ if src is None:
+ return None
+
+ if isinstance(src, io.BytesIO):
+ # clone before reading, so we don't consume the stream
+ src = io.BytesIO(src.getvalue())
+ base64_string = base64.b64encode(src.read()).decode("utf-8")
+ file_type = guess_mime_type(src) or fallback_mime_type
+ return f"data:{file_type};base64,{base64_string}"
+
+ if isinstance(src, bytes):
+ base64_string = base64.b64encode(src).decode("utf-8")
+ return f"data:{fallback_mime_type};base64,{base64_string}"
+
+ return src
+
+
+def is_data_empty(data: Union[str, bytes, io.BytesIO]) -> bool:
+ """Check if a data object is empty."""
+ if isinstance(data, str):
+ return data == ""
+
+ if isinstance(data, bytes):
+ return data == b""
+
+ if isinstance(data, io.BytesIO):
+ return data.getbuffer().nbytes == 0
+
+ return False
diff --git a/marimo/_plugins/core/test_media.py b/marimo/_plugins/core/test_media.py
new file mode 100644
index 0000000000..f1dc3826e5
--- /dev/null
+++ b/marimo/_plugins/core/test_media.py
@@ -0,0 +1,40 @@
+# Copyright 2023 Marimo. All rights reserved.
+import io
+
+from marimo._plugins.core.media import (
+ guess_mime_type,
+ io_to_data_url,
+ is_data_empty,
+)
+
+
+def test_guess_mime_type() -> None:
+ assert guess_mime_type(None) is None
+ assert (
+ guess_mime_type("data:text/plain;base64,SGVsbG8sIFdvcmxkIQ==")
+ == "text/plain"
+ )
+ assert guess_mime_type("example.txt") == "text/plain"
+ assert guess_mime_type(io.BytesIO(b"Hello, World!")) is None
+
+
+def test_io_to_data_url() -> None:
+ assert io_to_data_url(None, "text/plain") is None
+ assert (
+ io_to_data_url(io.BytesIO(b"Hello, World!"), "text/plain")
+ == "data:text/plain;base64,SGVsbG8sIFdvcmxkIQ=="
+ )
+ assert (
+ io_to_data_url(b"Hello, World!", "text/plain")
+ == "data:text/plain;base64,SGVsbG8sIFdvcmxkIQ=="
+ )
+ assert io_to_data_url("Hello, World!", "text/plain") == "Hello, World!"
+
+
+def test_is_data_empty() -> None:
+ assert is_data_empty("") is True
+ assert is_data_empty(b"") is True
+ assert is_data_empty(io.BytesIO(b"")) is True
+ assert is_data_empty("Hello, World!") is False
+ assert is_data_empty(b"Hello, World!") is False
+ assert is_data_empty(io.BytesIO(b"Hello, World!")) is False
diff --git a/marimo/_plugins/stateless/audio.py b/marimo/_plugins/stateless/audio.py
index 6df0c28a17..c8aa9720a5 100644
--- a/marimo/_plugins/stateless/audio.py
+++ b/marimo/_plugins/stateless/audio.py
@@ -1,18 +1,18 @@
# Copyright 2023 Marimo. All rights reserved.
from __future__ import annotations
-import base64
import io
from typing import Union
from marimo._output.builder import h
from marimo._output.hypertext import Html
from marimo._output.rich_help import mddoc
+from marimo._plugins.core.media import io_to_data_url
@mddoc
def audio(
- src: Union[str, io.IOBase],
+ src: Union[str, io.BytesIO],
) -> Html:
"""Render an audio file as HTML.
@@ -35,42 +35,6 @@ def audio(
An audio player as an `Html` object.
"""
- resolved_src = src if isinstance(src, str) else _io_to_data_url(src)
+ resolved_src = io_to_data_url(src, fallback_mime_type="audio/wav")
audio = h.audio(src=resolved_src, controls=True)
return Html(audio)
-
-
-def _io_to_data_url(readable: io.IOBase) -> str:
- base64_string = base64.b64encode(readable.read()).decode("utf-8")
- file_type = _guess_mime_type(readable)
- return f"data:{file_type};base64,{base64_string}"
-
-
-def _guess_mime_type(src: Union[str, io.IOBase]) -> str:
- file_name: str
- if isinstance(src, str):
- file_name = src
- elif isinstance(src, io.FileIO):
- src_name = src.name
- if isinstance(src_name, str):
- file_name = src_name
- else:
- # If we can't guess the file type, default to audio/wav
- return "audio/wav"
- else:
- return "audio/wav"
-
- file_type = file_name.split(".")[-1]
- if file_type in INCONSISTENT_AUDIO_MIME_TYPES:
- return f"audio/{INCONSISTENT_AUDIO_MIME_TYPES[file_type]}"
- return f"audio/{file_type}"
-
-
-# Reference here:
-# https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types
-INCONSISTENT_AUDIO_MIME_TYPES = {
- "mp3": "mpeg",
- "oga": "ogg",
- "mid": "midi",
- "weba": "webm",
-}
diff --git a/marimo/_plugins/stateless/download.py b/marimo/_plugins/stateless/download.py
new file mode 100644
index 0000000000..ae37338eeb
--- /dev/null
+++ b/marimo/_plugins/stateless/download.py
@@ -0,0 +1,81 @@
+# Copyright 2023 Marimo. All rights reserved.
+from __future__ import annotations
+
+import io
+from typing import Optional, Union
+
+from marimo._output.hypertext import Html
+from marimo._output.rich_help import mddoc
+from marimo._plugins.core.media import (
+ guess_mime_type,
+ io_to_data_url,
+ is_data_empty,
+)
+from marimo._plugins.core.web_component import build_stateless_plugin
+
+
+@mddoc
+def download(
+ data: Union[str, bytes, io.BytesIO],
+ filename: Optional[str] = None,
+ mimetype: Optional[str] = None,
+ disabled: bool = False,
+ *,
+ label: str = "Download",
+) -> Html:
+ """
+ Show a download button for a url, bytes, or file-like object.
+
+ **Examples.**
+
+ ```python
+ download_txt = mo.download(
+ data="Hello, world!".encode("utf-8"),
+ filename="hello.txt",
+ mimetype="text/plain",
+ )
+
+ download_image = mo.download(
+ data=open("hello.png", "rb"),
+ )
+ ```
+
+ **Args.**
+
+ - `data`: The data to download. Can be a string, bytes,
+ or a file-like object.
+ - `filename`: The name of the file to download.
+ If not provided, the name will be guessed from the data.
+ - `mimetype`: The mimetype of the file to download, for example,
+ (e.g. "text/csv", "image/png"). If not provided,
+ the mimetype will be guessed from the filename.
+
+ **Returns.**
+
+ An `Html` object for a download button.
+ """
+ # name used to guess mimetype
+ name_for_mime = data if isinstance(data, str) else filename
+ resolved_mimetype = (
+ mimetype or guess_mime_type(name_for_mime) or "text/plain"
+ )
+ disabled = disabled or is_data_empty(data)
+
+ # TODO: for large files or external URLs, we should create a
+ # temporary file URL at /api/kernel/download/<resource_id> that
+ # the frontend can use to download the file. This will
+ # lazily read the file and avoid loading it into memory.
+
+ return Html(
+ build_stateless_plugin(
+ component_name="marimo-download",
+ args={
+ "data": io_to_data_url(
+ data, fallback_mime_type=resolved_mimetype
+ ),
+ "filename": filename,
+ "disabled": disabled,
+ "label": label,
+ },
+ )
+ )
diff --git a/marimo/_plugins/stateless/image.py b/marimo/_plugins/stateless/image.py
index f3f9375f59..9b6b19042d 100644
--- a/marimo/_plugins/stateless/image.py
+++ b/marimo/_plugins/stateless/image.py
@@ -1,7 +1,6 @@
# Copyright 2023 Marimo. All rights reserved.
from __future__ import annotations
-import base64
import io
from typing import Any, Optional, Union
@@ -9,11 +8,12 @@ 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
+from marimo._plugins.core.media import io_to_data_url
@mddoc
def image(
- src: Union[str, io.IOBase],
+ src: Union[str, io.BytesIO],
alt: Optional[str] = None,
width: Optional[int] = None,
height: Optional[int] = None,
@@ -50,7 +50,7 @@ def image(
`Html` object
"""
- resolved_src = src if isinstance(src, str) else _io_to_data_url(src)
+ resolved_src = io_to_data_url(src, fallback_mime_type="image/png")
styles = create_style(
{
"width": width,
@@ -61,8 +61,3 @@ def image(
)
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/_smoke_tests/audio.py b/marimo/_smoke_tests/audio.py
deleted file mode 100644
index 32b8eacd61..0000000000
--- a/marimo/_smoke_tests/audio.py
+++ /dev/null
@@ -1,34 +0,0 @@
-# Copyright 2023 Marimo. All rights reserved.
-import marimo
-
-__generated_with = "0.1.4"
-app = marimo.App()
-
-
-def __():
- import marimo as mo
- return mo,
-
-
-def __(mo):
- mic = mo.ui.microphone(label="What is your name?")
- mic
- return mic,
-
-
-def __(mic, mo):
- mo.audio(mic.value)
- return
-
-
-def __(mo):
- mo.audio(src="https://samplelib.com/lib/preview/mp3/sample-3s.mp3")
- return
-
-
-if __name__ == "__main__":
- app.run()
diff --git a/marimo/_smoke_tests/media.py b/marimo/_smoke_tests/media.py
new file mode 100644
index 0000000000..a4dd351baa
--- /dev/null
+++ b/marimo/_smoke_tests/media.py
@@ -0,0 +1,68 @@
+# Copyright 2023 Marimo. All rights reserved.
+import marimo
+
+__generated_with = "0.1.4"
+app = marimo.App()
+
+
+def __():
+ import marimo as mo
+ import requests
+ from io import BytesIO
+ return BytesIO, mo, requests
+
+
+def __(mo):
+ mic = mo.ui.microphone(label="What is your name?")
+ mic
+ return mic,
+
+
+def __(mic, mo):
+ mo.hstack(
+ [mo.audio(mic.value), mo.download(data=mic.value, mimetype="audio/wav")]
+ )
+ return
+
+
+def __(mo):
+ # Note, chrome does not support cross-origin download, so this wont auto download until we proxy the download through the backend
+ _src = "https://samplelib.com/lib/preview/mp3/sample-3s.mp3"
+ mo.hstack(
+ [
+ mo.audio(src=_src),
+ mo.download(data=_src, label=""),
+ ]
+ )
+ return
+
+
+def __(BytesIO, mo, requests):
+ _src = (
+ "https://images.pexels.com/photos/86596/owl-bird-eyes-eagle-owl-86596.jpeg"
+ )
+ _response = requests.get(_src)
+ image_data = BytesIO(_response.content)
+
+ mo.vstack(
+ [
+ mo.image(src=_src, rounded=True, height="300px"),
+ # Note, chrome does not support cross-origin download, so this wont auto download until we proxy the download through the backend
+ mo.download(data=_src, label="Download via URL"),
+ mo.download(
+ data=image_data,
+ label="Download via BytesIO",
+ mimetype="image/jpeg",
+ ),
+ ]
+ )
+ return image_data,
+
+
+if __name__ == "__main__":
+ app.run()