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.

improvement: use VirtualFile in mo.download() (#192)

Myles Scolnick57f02ccedc79
diff --git a/marimo/_output/data/data.py b/marimo/_output/data/data.py
index 6cb82de28d..d37add7208 100644
--- a/marimo/_output/data/data.py
+++ b/marimo/_output/data/data.py
@@ -1,6 +1,17 @@
# Copyright 2023 Marimo. All rights reserved.
+import base64
+import io
+from typing import Union
+
+from marimo._plugins.core.media import (
+ is_data_empty,
+)
from marimo._runtime.context import get_context
-from marimo._runtime.virtual_file import VirtualFile, VirtualFileLifecycleItem
+from marimo._runtime.virtual_file import (
+ EMPTY_VIRTUAL_FILE,
+ VirtualFile,
+ VirtualFileLifecycleItem,
+)
def pdf(data: bytes) -> VirtualFile:
@@ -33,3 +44,52 @@ def image(data: bytes, ext: str = "png") -> VirtualFile:
item = VirtualFileLifecycleItem(ext=ext, buffer=data)
get_context().cell_lifecycle_registry.add(item)
return item.virtual_file
+
+
+def any_data(data: Union[str, bytes, io.BytesIO], ext: str) -> VirtualFile:
+ """Create a virtual file from any data.
+ It can be a string, bytes, or a file-like object.
+ For external URLs, these are passed through as-is.
+
+ **Args.**
+
+ - data: Data in bytes
+ - ext: File extension
+
+ **Returns.**
+
+ A `VirtualFile` object.
+ """
+ if data is None:
+ return EMPTY_VIRTUAL_FILE
+
+ if is_data_empty(data):
+ return EMPTY_VIRTUAL_FILE
+
+ # Base64 encoded data
+ if isinstance(data, str) and data.startswith("data:"):
+ base64str = data.split(",")[1]
+ buffer = base64.b64decode(base64str)
+ item = VirtualFileLifecycleItem(ext=ext, buffer=buffer)
+ get_context().cell_lifecycle_registry.add(item)
+ return item.virtual_file
+
+ # URL
+ if isinstance(data, str):
+ return VirtualFile(url=data, filename=data, buffer=b"")
+
+ # Bytes
+ if isinstance(data, bytes):
+ item = VirtualFileLifecycleItem(ext=ext, buffer=data)
+ get_context().cell_lifecycle_registry.add(item)
+ return item.virtual_file
+
+ # BytesIO
+ if isinstance(data, io.BytesIO):
+ # clone before reading, so we don't consume the stream
+ buffer = io.BytesIO(data.getvalue()).read()
+ item = VirtualFileLifecycleItem(ext=ext, buffer=buffer)
+ get_context().cell_lifecycle_registry.add(item)
+ return item.virtual_file
+
+ raise ValueError(f"Unsupported data type: {type(data)}")
diff --git a/marimo/_plugins/core/media.py b/marimo/_plugins/core/media.py
index 8d6817323c..47d9e8f6dc 100644
--- a/marimo/_plugins/core/media.py
+++ b/marimo/_plugins/core/media.py
@@ -5,7 +5,9 @@ import mimetypes
from typing import Optional, Union
-def guess_mime_type(src: Union[str, bytes, io.BytesIO, None]) -> Optional[str]:
+def guess_mime_type(
+ src: Union[str, bytes, io.BytesIO, io.BufferedReader, None]
+) -> Optional[str]:
"""Guess the MIME type of a file."""
if src is None:
return None
@@ -19,11 +21,19 @@ def guess_mime_type(src: Union[str, bytes, io.BytesIO, None]) -> Optional[str]:
if isinstance(src, io.FileIO):
return mimetypes.guess_type(src.name)[0]
+ if isinstance(src, io.BufferedReader):
+ return mimetypes.guess_type(src.name)[0]
+
return None
+def mime_type_to_ext(mime_type: str) -> Optional[str]:
+ return mimetypes.guess_extension(mime_type, strict=False)
+
+
def io_to_data_url(
- src: Union[str, bytes, io.BytesIO, None], fallback_mime_type: str
+ 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:
diff --git a/marimo/_plugins/stateless/download.py b/marimo/_plugins/stateless/download.py
index ae37338eeb..07e8a22b46 100644
--- a/marimo/_plugins/stateless/download.py
+++ b/marimo/_plugins/stateless/download.py
@@ -4,19 +4,20 @@ from __future__ import annotations
import io
from typing import 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._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
@mddoc
def download(
- data: Union[str, bytes, io.BytesIO],
+ data: Union[str, bytes, io.BytesIO, io.BufferedReader],
filename: Optional[str] = None,
mimetype: Optional[str] = None,
disabled: bool = False,
@@ -54,25 +55,29 @@ def download(
An `Html` object for a download button.
"""
+
+ # 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)
- # 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.
+ # 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",
args={
- "data": io_to_data_url(
- data, fallback_mime_type=resolved_mimetype
- ),
+ "data": file.url,
"filename": filename,
"disabled": disabled,
"label": label,
diff --git a/marimo/_plugins/stateless/image.py b/marimo/_plugins/stateless/image.py
index efd2ebfbfc..9eded5ae05 100644
--- a/marimo/_plugins/stateless/image.py
+++ b/marimo/_plugins/stateless/image.py
@@ -13,7 +13,7 @@ from marimo._plugins.core.media import io_to_data_url
@mddoc
def image(
- src: Union[str, io.BytesIO],
+ src: Union[str, bytes, io.BytesIO, io.BufferedReader],
alt: Optional[str] = None,
width: Optional[int] = None,
height: Optional[int] = None,
@@ -50,6 +50,11 @@ def image(
`Html` object
"""
+ # Convert to bytes right away since can only be read once
+ if isinstance(src, io.BufferedReader):
+ src.seek(0)
+ src = src.read()
+
resolved_src = io_to_data_url(src, fallback_mime_type="image/png")
styles = create_style(
{
diff --git a/marimo/_runtime/virtual_file.py b/marimo/_runtime/virtual_file.py
index e38f3492c0..889868b52c 100644
--- a/marimo/_runtime/virtual_file.py
+++ b/marimo/_runtime/virtual_file.py
@@ -34,15 +34,22 @@ class VirtualFile:
filename: str
buffer: bytes
- def __init__(self, filename: str, buffer: bytes) -> None:
+ def __init__(self, filename: str, url: str, buffer: bytes) -> None:
self.filename = filename
- self.url = f"/@file/{filename}"
+ self.url = url
self.buffer = buffer
+EMPTY_VIRTUAL_FILE = VirtualFile(
+ filename="empty.txt",
+ url="/@file/empty.txt",
+ buffer=b"",
+)
+
+
class VirtualFileLifecycleItem(CellLifecycleItem):
def __init__(self, ext: str, buffer: bytes) -> None:
- self.ext = ext
+ self.ext = _without_leading_dot(ext)
self.buffer = buffer
# Not resolved until added to registry
self._virtual_file: Optional[VirtualFile] = None
@@ -66,7 +73,9 @@ class VirtualFileLifecycleItem(CellLifecycleItem):
"Failed to add virtual file to registry. "
"This is a bug in marimo. Please file an issue."
)
- self._virtual_file = VirtualFile(filename, self.buffer)
+ self._virtual_file = VirtualFile(
+ filename, f"/@file/{filename}", self.buffer
+ )
context.virtual_file_registry.add(self._virtual_file)
def dispose(self, context: "RuntimeContext") -> None:
@@ -128,3 +137,7 @@ class VirtualFileRegistry:
for _, shm in self.registry.items():
shm.unlink()
self.registry.clear()
+
+
+def _without_leading_dot(ext: str) -> str:
+ return ext[1:] if ext.startswith(".") else ext
diff --git a/marimo/_server/api/virtual_file.py b/marimo/_server/api/virtual_file.py
index c51cd8d5b8..deabe90e29 100644
--- a/marimo/_server/api/virtual_file.py
+++ b/marimo/_server/api/virtual_file.py
@@ -7,6 +7,9 @@ from multiprocessing import shared_memory
import tornado.web
from marimo import _loggers
+from marimo._runtime.virtual_file import (
+ EMPTY_VIRTUAL_FILE,
+)
from marimo._server.api.status import HTTPStatus
LOGGER = _loggers.marimo_logger()
@@ -16,6 +19,10 @@ class VirtualFileHandler(tornado.web.RequestHandler):
"""Handler for virtual files."""
def get(self, filename: str) -> None:
+ if filename == EMPTY_VIRTUAL_FILE.filename:
+ self.write(b"")
+ return
+
key = filename
shm = None
try:
diff --git a/marimo/_smoke_tests/media.py b/marimo/_smoke_tests/media.py
index a4dd351baa..5fd18e51bd 100644
--- a/marimo/_smoke_tests/media.py
+++ b/marimo/_smoke_tests/media.py
@@ -1,7 +1,7 @@
# Copyright 2023 Marimo. All rights reserved.
import marimo
-__generated_with = "0.1.4"
+__generated_with = "0.1.22"
app = marimo.App()
@@ -10,7 +10,8 @@ def __():
import marimo as mo
import requests
from io import BytesIO
- return BytesIO, mo, requests
+ import base64
+ return BytesIO, base64, mo, requests
@app.cell
@@ -23,7 +24,7 @@ def __(mo):
@app.cell
def __(mic, mo):
mo.hstack(
- [mo.audio(mic.value), mo.download(data=mic.value, mimetype="audio/wav")]
+ [mo.audio(mic.value), mo.download(data=mic.value, mimetype="audio/x-wav")]
)
return
@@ -42,26 +43,51 @@ def __(mo):
@app.cell
-def __(BytesIO, mo, requests):
+def __(BytesIO, base64, 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)
+ base64str = (
+ f"data:image/jpeg;base64,{base64.b64encode(_response.content).decode()}"
+ )
mo.vstack(
[
- mo.image(src=_src, rounded=True, height="300px"),
+ mo.image(src=_src, rounded=True, height=100),
# 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.image(src=image_data, rounded=True, height=100),
mo.download(
data=image_data,
label="Download via BytesIO",
mimetype="image/jpeg",
),
+ mo.image(src=base64str, rounded=True, height=100),
+ mo.download(
+ data=base64str,
+ label="Download via bytes",
+ mimetype="image/jpeg",
+ ),
]
)
- return image_data,
+ return base64str, image_data
+
+
+def __(mo):
+ import os
+
+ with open(os.path.realpath("docs/_static/array.png"), "rb") as f:
+ _image = mo.image(src=f)
+ _download = mo.download(
+ data=f,
+ label="Download local file",
+ )
+
+ mo.hstack([_image, _download])
+ return f, os
if __name__ == "__main__":