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
improvement: lazy download and smarter downloads (#3506)
Myles Scolnick845a3358daac
diff --git a/docs/api/media/download.md b/docs/api/media/download.mdindex 1cc707c997..47d7b03393 100644--- a/docs/api/media/download.md+++ b/docs/api/media/download.md@@ -1,19 +1,7 @@# Download Media-/// marimo-embed--```python-def __():- download_txt = mo.download(- data="Hello, world!".encode("utf-8"),- filename="hello.txt",- mimetype="text/plain",- )- download_txt- return-```-+/// marimo-embed-file+ filepath: examples/ui/download.py///::: marimo.downloaddiff --git a/examples/ui/download.py b/examples/ui/download.pynew file mode 100644index 0000000000..2501123f18--- /dev/null+++ b/examples/ui/download.py@@ -0,0 +1,125 @@+# /// script+# requires-python = ">=3.12"+# dependencies = [+# "marimo",+# "pandas==2.2.3",+# ]+# ///+import marimo++__generated_with = "0.10.14"+app = marimo.App()+++def _():+ import marimo as mo+ return (mo,)++[email protected](hide_code=True)+def _(json, mo, pd):+ # Text file download+ text_download = mo.download(+ data="Hello, world!".encode("utf-8"),+ filename="hello.txt",+ mimetype="text/plain",+ label="Download text",+ )++ # CSV download using pandas+ df = pd.DataFrame({"name": ["Alice", "Bob", "Charlie"], "age": [25, 30, 35]})+ csv_download = mo.download(+ data=df.to_csv().encode("utf-8"),+ filename="data.csv",+ mimetype="text/csv",+ label="Download CSV",+ )++ # JSON download+ data = {"message": "Hello", "count": 42}+ json_download = mo.download(+ data=json.dumps(data).encode("utf-8"),+ filename="data.json",+ mimetype="application/json",+ label="Download JSON",+ )++ mo.hstack([text_download, csv_download, json_download])+ return csv_download, data, df, json_download, text_download++[email protected](hide_code=True)+def _(json, mo, pd):+ import time+ import asyncio+++ # Text file download with lazy loading+ def get_text_data():+ time.sleep(1)+ return "Hello, world!".encode("utf-8")+++ text_download_lazy = mo.download(+ data=get_text_data,+ filename="hello.txt",+ mimetype="text/plain",+ label="Download text",+ )+++ # CSV download using pandas with lazy loading+ async def get_csv_data():+ await asyncio.sleep(1)+ _df = pd.DataFrame(+ {"name": ["Alice", "Bob", "Charlie"], "age": [25, 30, 35]}+ )+ return _df+++ csv_download_lazy = mo.download(+ data=get_csv_data,+ filename="data.csv",+ mimetype="text/csv",+ label="Download CSV",+ )+++ # JSON download with lazy loading+ async def get_json_data():+ await asyncio.sleep(1)+ _data = {"message": "Hello", "count": 42}+ return json.dumps(_data).encode("utf-8")+++ json_download_lazy = mo.download(+ data=get_json_data,+ filename="data.json",+ mimetype="application/json",+ label="Download JSON",+ )+++ mo.hstack([text_download_lazy, csv_download_lazy, json_download_lazy])+ return (+ asyncio,+ csv_download_lazy,+ get_csv_data,+ get_json_data,+ get_text_data,+ json_download_lazy,+ text_download_lazy,+ time,+ )+++def _():+ import pandas as pd+ import json+ return json, pd+++if __name__ == "__main__":+ app.run()diff --git a/frontend/src/plugins/layout/DownloadPlugin.tsx b/frontend/src/plugins/layout/DownloadPlugin.tsxindex 048878d791..12d0ff923f 100644--- a/frontend/src/plugins/layout/DownloadPlugin.tsx+++ b/frontend/src/plugins/layout/DownloadPlugin.tsx@@ -1,13 +1,16 @@/* Copyright 2024 Marimo. All rights reserved. */import { z } from "zod";-import type {- IStatelessPlugin,- IStatelessPluginProps,-} from "../stateless-plugin";-import { DownloadIcon } from "lucide-react";+import { DownloadIcon, Loader2 } from "lucide-react";import { buttonVariants } from "@/components/ui/button";import { cn } from "@/utils/cn";+import { useState } from "react";+import { downloadByURL } from "@/utils/download";+import { Logger } from "@/utils/Logger";+import { toast } from "@/components/ui/use-toast";+import { createPlugin } from "../core/builder";+import { rpc } from "../core/rpc";+import { renderHTML } from "../core/RenderHTML";interface Data {/**@@ -26,33 +29,105 @@ interface Data {* Button label*/label?: string | null;+ /**+ * Whether to load data lazily+ */+ lazy?: boolean;}-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>- );- }-}+// eslint-disable-next-line @typescript-eslint/consistent-type-definitions+type Functions = {+ /**+ * Function to call for lazy loading+ */+ load: (empty: {}) => Promise<{+ /**+ * URL or data-uri+ */+ data: string;+ filename?: string | null | undefined;+ }>;+};+export const DownloadPlugin = createPlugin("marimo-download")+ .withData(+ z.object({+ data: z.string(),+ disabled: z.boolean().default(false),+ filename: z.string().nullish(),+ label: z.string().nullish(),+ lazy: z.boolean().default(false),+ }),+ )+ .withFunctions<Functions>({+ load: rpc.input(z.object({})).output(+ z.object({+ data: z.string(),+ filename: z.string().nullish(),+ }),+ ),+ })+ .renderer((props) => (+ <DownloadButton data={props.data} {...props.functions} />+ ));++const DownloadButton = ({+ data,+ load,+}: { data: Data; load: Functions["load"] }) => {+ const [isLoading, setIsLoading] = useState(false);++ const handleClick = async (e: React.MouseEvent) => {+ if (!data.lazy) {+ return;+ }++ if (data.disabled) {+ return;+ }++ e.preventDefault();+ setIsLoading(true);++ try {+ const loadedData = await load({});+ downloadByURL(+ loadedData.data,+ loadedData.filename || data.filename || "download",+ );+ } catch (error) {+ toast({+ title: "Failed to download",+ description: "Please try again.",+ });+ Logger.error("Failed to download:", error);+ } finally {+ setIsLoading(false);+ }+ };++ const Icon = isLoading ? Loader2 : DownloadIcon;+ const label = data.label ? renderHTML({ html: data.label }) : "Download";++ return (+ <a+ href={data.data}+ download={data.filename || true}+ target="_blank"+ rel="noopener noreferrer"+ onClick={handleClick}+ className={buttonVariants({+ variant: "secondary",+ disabled: data.disabled || isLoading,+ })}+ >+ <Icon+ className={cn(+ "w-3 h-3",+ data.label && "mr-2",+ isLoading && "animate-spin",+ )}+ />+ {label}+ </a>+ );+};diff --git a/frontend/src/plugins/plugins.ts b/frontend/src/plugins/plugins.tsindex abfaf0ad78..b773e64463 100644--- a/frontend/src/plugins/plugins.ts+++ b/frontend/src/plugins/plugins.ts@@ -81,6 +81,7 @@ export const UI_PLUGINS: Array<IPlugin<any, unknown>> = [DataExplorerPlugin,DataFramePlugin,LazyPlugin,+ DownloadPlugin,AnyWidgetPlugin,DataEditorPlugin,PanelPlugin,@@ -91,7 +92,6 @@ const LAYOUT_PLUGINS: Array<IStatelessPlugin<unknown>> = [new AccordionPlugin(),new CalloutPlugin(),new CarouselPlugin(),- new DownloadPlugin(),new JsonOutputPlugin(),new MimeRendererPlugin(),new MermaidPlugin(),diff --git a/frontend/src/utils/download.ts b/frontend/src/utils/download.tsindex 16d1b80e06..2cf03198a5 100644--- a/frontend/src/utils/download.ts+++ b/frontend/src/utils/download.ts@@ -43,4 +43,5 @@ export function downloadByURL(url: string, filename: string) {export function downloadBlob(blob: Blob, filename: string) {const url = URL.createObjectURL(blob);downloadByURL(url, filename);+ URL.revokeObjectURL(url);}diff --git a/marimo/_plugins/core/media.py b/marimo/_plugins/core/media.pyindex 26e8acb0ab..046487e2e5 100644--- a/marimo/_plugins/core/media.py+++ b/marimo/_plugins/core/media.py@@ -1,8 +1,22 @@# Copyright 2024 Marimo. All rights reserved.+from __future__ import annotations+import base64import ioimport mimetypes-from typing import Optional, Union+import pathlib+from typing import TYPE_CHECKING, Any, Optional, Union, cast+from urllib.parse import urlparse++import narwhals.stable.v1 as nw++from marimo._dependencies.dependencies import DependencyManager+from marimo._utils.narwhals_utils import can_narwhalify++if TYPE_CHECKING:+ import numpy.typing as npt+ from pandas import DataFrame+ from PIL.Image import Image as PILImagedef guess_mime_type(@@ -32,28 +46,100 @@ def mime_type_to_ext(mime_type: str) -> Optional[str]:def io_to_data_url(- src: Union[str, bytes, io.BytesIO, None],+ src: Union[+ str,+ bytes,+ io.BytesIO,+ io.BufferedReader,+ pathlib.Path,+ PILImage,+ "npt.NDArray[Any]",+ DataFrame,+ None,+ ],fallback_mime_type: str,) -> Optional[str]:- """Convert a file-like object to a data URL."""+ """Convert various data types to a data URL.++ Supports:+ - File-like objects (BytesIO, BufferedReader)+ - Bytes+ - Strings (URLs or file paths)+ - PIL Images+ - NumPy arrays+ - Pandas DataFrames+ - Pathlib Paths+ """if src is None:return None- if isinstance(src, (io.BufferedIOBase, io.RawIOBase)):+ # Handle existing file-like objects+ if isinstance(src, (io.BufferedIOBase, io.RawIOBase, io.BufferedReader)):pos = src.tell()base64_string = base64.b64encode(src.read()).decode("utf-8")src.seek(pos)file_type = guess_mime_type(src) or fallback_mime_typereturn f"data:{file_type};base64,{base64_string}"+ # Handle bytes directlyif isinstance(src, bytes):base64_string = base64.b64encode(src).decode("utf-8")return f"data:{fallback_mime_type};base64,{base64_string}"- return src+ # Handle PIL Images+ if DependencyManager.pillow.imported():+ from PIL import Image++ if Image and isinstance(src, Image.Image):+ img_byte_arr = io.BytesIO()+ src.save(img_byte_arr, format=src.format or "PNG")+ img_byte_arr.seek(0)+ base64_string = base64.b64encode(img_byte_arr.read()).decode(+ "utf-8"+ )+ return f"data:image/{(src.format or 'png').lower()};base64,{base64_string}"++ # Handle NumPy arrays (convert to PNG)+ if DependencyManager.numpy.imported():+ import numpy as np++ if isinstance(src, np.ndarray):+ if DependencyManager.pillow.imported():+ from PIL import Image++ img = Image.fromarray(np.uint8(src))+ return io_to_data_url(img, "image/png")++ # Handle pathlib.Path+ if isinstance(src, pathlib.Path):+ with open(src, "rb") as f:+ return io_to_data_url(f, fallback_mime_type)++ # Handle strings - check if it's a URL+ if isinstance(src, str):+ parsed = urlparse(src)+ if parsed.scheme and parsed.netloc:+ return src # Return URLs as-is++ # Try to open as a file path+ try:+ with open(src, "rb") as f:+ return io_to_data_url(f, fallback_mime_type)+ except (FileNotFoundError, IOError):+ return src++ # Handle Pandas DataFrames (convert to CSV)+ if can_narwhalify(src, eager_only=True):+ df = nw.from_native(src, strict=True, eager_only=True)+ file = io.BytesIO()+ df.write_csv(file)+ file.seek(0)+ return io_to_data_url(file, "text/csv")++ return str(src)-def is_data_empty(data: Union[str, bytes, io.BytesIO]) -> bool:+def is_data_empty(data: Union[str, bytes, io.BytesIO, Any]) -> bool:"""Check if a data object is empty."""if isinstance(data, str):return data == ""@@ -61,7 +147,7 @@ def is_data_empty(data: Union[str, bytes, io.BytesIO]) -> bool:if isinstance(data, bytes):return data == b""- if isinstance(data, io.BytesIO):- return data.getbuffer().nbytes == 0+ if hasattr(data, "getbuffer"):+ return cast(io.BytesIO, data).getbuffer().nbytes == 0return Falsediff --git a/marimo/_plugins/stateless/download.py b/marimo/_plugins/stateless/download.pyindex 993d80360d..6a126bcc39 100644--- a/marimo/_plugins/stateless/download.py+++ b/marimo/_plugins/stateless/download.py@@ -1,35 +1,43 @@# Copyright 2024 Marimo. All rights reserved.from __future__ import annotations+import asyncioimport io-from typing import Optional, Union+from dataclasses import dataclass+from typing import Any, Callable, Coroutine, Final, Optional, Union, castimport marimo._output.data.data as mo_data-from marimo._output.hypertext import Htmlfrom marimo._output.rich_help import mddocfrom marimo._plugins.core.media import (guess_mime_type,+ io_to_data_url,is_data_empty,mime_type_to_ext,)-from marimo._plugins.core.web_component import build_stateless_plugin+from marimo._plugins.ui._core.ui_element import UIElement+from marimo._runtime.functions import EmptyArgs, Function++DataType = Union[str, bytes, io.BytesIO, io.BufferedReader]+++@dataclass+class LoadResponse:+ data: str+ filename: Optional[str]@mddoc-def download(- data: Union[str, bytes, io.BytesIO, io.BufferedReader],- filename: Optional[str] = None,- mimetype: Optional[str] = None,- disabled: bool = False,- *,- label: str = "Download",-) -> Html:+class download(UIElement[None, None]):"""Show a download button for a url, bytes, or file-like object.Args:- data (Union[str, bytes, io.BytesIO]): The data to download. Can be a string (interpreted as- a URL), bytes, or a file opened in binary mode.+ data (Union[str, bytes, io.BytesIO, callable]): The data to download. Can be:+ - string (interpreted as a URL)+ - bytes+ - file opened in binary mode+ - callable returning any of the above (for lazy loading)+ - async callable returning any of the above (for lazy loading)filename (str): The name of the file to download.If not provided, the name will be guessed from the data.mimetype (str): The mimetype of the file to download, for example,@@ -38,48 +46,116 @@ def download(disabled (bool): Whether to disable the download button.label (str): The label of the download button.- Returns:- An `Html` object for a download button.-Example:```python+ # Eager loadingdownload_txt = mo.download(data="Hello, world!".encode("utf-8"),filename="hello.txt",mimetype="text/plain",)- download_image = mo.download(- data=open("hello.png", "rb"),++ # Lazy loading+ def get_large_data():+ return b"large data"+++ download_lazy = mo.download(+ data=get_large_data,+ filename="large.txt",)```"""- # Convert to bytes right away since can only be read once- if isinstance(data, io.BufferedReader):- filename = filename or data.name- data.seek(0)- data = data.read()-- # 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"- )- ext = mime_type_to_ext(resolved_mimetype) or "txt"- disabled = disabled or is_data_empty(data)-- # create a virtual file to avoid loading the data in the browser- file = mo_data.any_data(data, ext=ext)-- return Html(- build_stateless_plugin(- component_name="marimo-download",+ _name: Final[str] = "marimo-download"++ def __init__(+ self,+ data: Union[+ DataType,+ Callable[[], DataType],+ Callable[[], Coroutine[None, None, DataType]],+ ],+ filename: Optional[str] = None,+ mimetype: Optional[str] = None,+ disabled: bool = False,+ *,+ label: str = "Download",+ ) -> None:+ self._data = data+ self._filename = filename+ self._mimetype = mimetype++ data_url = ""+ is_lazy = callable(data)++ # 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"+ )+ ext = mime_type_to_ext(resolved_mimetype) or "txt"++ # Convert to bytes right away since can only be read once+ if isinstance(data, io.BufferedReader):+ filename = filename or data.name+ data.seek(0)+ data = data.read()++ # When non-lazy+ if not callable(data):+ # Maybe update disabled+ disabled = disabled or is_data_empty(data)++ # Maybe update name+ if filename is None and hasattr(data, "name"):+ filename = cast(str, cast(Any, data).name)++ # create a virtual file to avoid loading the data in the browser+ # only if the data is not lazy+ data_url = mo_data.any_data(data, ext=ext).url++ super().__init__(+ component_name=self._name,+ initial_value=None,+ label=label,+ on_change=None,args={- "data": file.url,+ "data": data_url,"filename": filename,"disabled": disabled,- "label": label,+ "lazy": is_lazy,},+ functions=(+ (+ Function(+ name="load",+ arg_cls=EmptyArgs,+ function=self._load,+ ),+ )+ ),)- )++ async def _load(self, _args: EmptyArgs) -> LoadResponse:+ if callable(self._data) and not isinstance(self._data, UIElement):+ result_or_coroutine = self._data()+ if asyncio.iscoroutine(result_or_coroutine):+ result = await result_or_coroutine+ else:+ result = result_or_coroutine+ else:+ result = self._data++ url = io_to_data_url(+ result, fallback_mime_type=self._mimetype or "text/plain"+ )++ if url is None:+ raise ValueError("Failed to convert data to data URL")++ return LoadResponse(data=url, filename=self._filename)++ def _convert_value(self, value: None) -> None:+ return valuediff --git a/tests/_plugins/core/test_media.py b/tests/_plugins/core/test_media.pyindex e739c44535..4677c7ede9 100644--- a/tests/_plugins/core/test_media.py+++ b/tests/_plugins/core/test_media.py@@ -1,12 +1,21 @@# Copyright 2024 Marimo. All rights reserved.+from __future__ import annotations+import io+from typing import TYPE_CHECKING++import pytest+from marimo._dependencies.dependencies import DependencyManagerfrom marimo._plugins.core.media import (guess_mime_type,io_to_data_url,is_data_empty,)+if TYPE_CHECKING:+ import pathlib+def test_guess_mime_type() -> None:assert guess_mime_type(None) is None@@ -31,6 +40,56 @@ def test_io_to_data_url() -> None:assert io_to_data_url("Hello, World!", "text/plain") == "Hello, World!"+ not DependencyManager.pillow.has(), reason="pillow not installed"+)+def test_pil_image() -> None:+ from PIL import Image++ # Create a small test image in memory+ img = Image.new("RGB", (10, 10), color="red")+ res = io_to_data_url(img, "image/png")+ assert res is not None+ assert res.startswith("data:image/png;base64,")+++ not DependencyManager.numpy.has(), reason="NumPy not installed"+)+def test_numpy_array() -> None:+ import numpy as np++ res = io_to_data_url(np.array([[1, 2], [3, 4]]), "image/png")+ assert res is not None+ assert res.startswith("data:image/png;base64,")+++ not DependencyManager.pandas.has(), reason="Pandas not installed"+)+def test_pandas_dataframe() -> None:+ import pandas as pd++ res = io_to_data_url(pd.DataFrame({"a": [1, 2]}), "text/csv")+ assert res is not None+ assert res.startswith("data:text/csv;base64,")+++def test_paths_and_urls(tmp_path: pathlib.Path) -> None:+ # Paths+ test_file = tmp_path / "file.txt"+ test_file.write_text("test content")+ res = io_to_data_url(test_file, "text/plain")+ assert res is not None+ assert res.startswith("data:text/plain;base64,")++ # URLs remain unchanged+ assert (+ io_to_data_url("https://example.com/image.jpg", "image/jpeg")+ == "https://example.com/image.jpg"+ )++def test_is_data_empty() -> None:assert is_data_empty("") is Trueassert is_data_empty(b"") is Truediff --git a/tests/_plugins/test_download.py b/tests/_plugins/test_download.pynew file mode 100644index 0000000000..35b9461f6d--- /dev/null+++ b/tests/_plugins/test_download.py@@ -0,0 +1,129 @@+from __future__ import annotations++import io+from typing import TYPE_CHECKING++import pytest++from marimo._plugins.stateless.download import download+from marimo._runtime.functions import EmptyArgs++if TYPE_CHECKING:+ from pathlib import Path+++def test_download_string():+ """Test downloading string data."""+ result = download("test data")+ args = result._component_args+ assert args["filename"] is None+ assert not args["disabled"]+ assert not args["lazy"]+ assert result._args.label == "Download"+++def test_download_bytes():+ """Test downloading bytes data."""+ result = download(b"test data", filename="test.txt")+ args = result._component_args+ assert args["filename"] == "test.txt"+ assert not args["disabled"]+ assert not args["lazy"]+++def test_download_bytesio():+ """Test downloading BytesIO data."""+ data = io.BytesIO(b"test data")+ result = download(data)+ args = result._component_args+ assert not args["disabled"]+ assert not args["lazy"]+ data.close()+++def test_download_file(tmp_path: Path):+ """Test downloading file data."""+ file_path = tmp_path / "test.txt"+ file_path.write_bytes(b"test data")+ with open(file_path, "rb") as f:+ result = download(f)+ args = result._component_args+ assert args["filename"] == str(file_path)+ assert not args["disabled"]+ assert not args["lazy"]+++def test_download_empty():+ """Test downloading empty data."""+ result = download(b"")+ args = result._component_args+ assert args["disabled"]+ assert not args["lazy"]+++async def test_download_lazy_sync():+ """Test lazy downloading with sync function."""++ def get_data():+ return b"test data"++ result = download(get_data)+ args = result._component_args+ assert args["lazy"]+ assert not args["disabled"]++ # Load the data+ loaded_data = await result._load(EmptyArgs())+ assert loaded_data.data.startswith("data:text/plain;base64")+ assert loaded_data.filename is None+++async def test_download_lazy_async():+ """Test lazy downloading with async function."""++ async def get_data():+ return b"test data"++ result = download(get_data)+ args = result._component_args+ assert args["lazy"]+ assert not args["disabled"]++ # Load the data+ loaded_data = await result._load(EmptyArgs())+ assert loaded_data.data.startswith("data:text/plain;base64")+ assert loaded_data.filename is None+++async def test_download_async_with_error():+ """Test async function without lazy flag raises error."""++ async def get_data():+ raise ValueError("test error")++ result = download(get_data)+ with pytest.raises(ValueError, match="test error"):+ await result._load(EmptyArgs())+++def test_download_custom_label():+ """Test custom button label."""+ result = download(b"test", label="Custom Label")+ args = result._component_args+ assert result._args.label == "Custom Label"+ assert not args["lazy"]+++def test_download_mimetype():+ """Test custom mimetype."""+ result = download(b"test", mimetype="text/csv")+ args = result._component_args+ assert args["data"].startswith("data:text/csv;base64")+++def test_download_disabled():+ """Test disabled download button."""+ result = download(b"test", disabled=True)+ args = result._component_args+ assert args["disabled"] is True+ assert not args["lazy"]