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: mo.download button (#68)
Myles Scolnick6b80219f206c
diff --git a/docs/api/media/download.md b/docs/api/media/download.mdnew file mode 100644index 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.mdindex cc6ac3a8df..5ddee3e17c 100644--- a/docs/api/media/index.md+++ b/docs/api/media/index.md@@ -8,6 +8,7 @@imageaudio+ 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.imagemarimo.audiomarimo.pdf+ marimo.download```diff --git a/frontend/src/components/ui/button.tsx b/frontend/src/components/ui/button.tsxindex 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 ButtonPropsextends 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.tsxnew file mode 100644index 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.tsindex 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 pluginsconst 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__.pyindex 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 uifrom marimo._plugins.stateless.accordion import accordionfrom marimo._plugins.stateless.audio import audiofrom marimo._plugins.stateless.callout_output import callout+from marimo._plugins.stateless.download import downloadfrom marimo._plugins.stateless.flex import hstack, vstackfrom marimo._plugins.stateless.image import imagefrom marimo._plugins.stateless.pdf import pdfdiff --git a/marimo/_plugins/core/media.py b/marimo/_plugins/core/media.pynew file mode 100644index 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 Falsediff --git a/marimo/_plugins/core/test_media.py b/marimo/_plugins/core/test_media.pynew file mode 100644index 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 Falsediff --git a/marimo/_plugins/stateless/audio.py b/marimo/_plugins/stateless/audio.pyindex 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 base64import iofrom typing import Unionfrom marimo._output.builder import hfrom marimo._output.hypertext import Htmlfrom marimo._output.rich_help import mddoc+from marimo._plugins.core.media import io_to_data_url@mddocdef 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.pynew file mode 100644index 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.pyindex 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 base64import iofrom typing import Any, Optional, Union@@ -9,11 +8,12 @@ from marimo._output.builder import hfrom marimo._output.hypertext import Htmlfrom marimo._output.rich_help import mddocfrom marimo._output.utils import create_style+from marimo._plugins.core.media import io_to_data_url@mddocdef 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.pydeleted file mode 100644index 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.pynew file mode 100644index 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()