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: marimo export html (#1141)

Myles Scolnick99dcddd299ac
diff --git a/frontend/src/components/editor/renderers/vertical-layout/vertical-layout.tsx b/frontend/src/components/editor/renderers/vertical-layout/vertical-layout.tsx
index 1bdbfe3d61..798866fa5b 100644
--- a/frontend/src/components/editor/renderers/vertical-layout/vertical-layout.tsx
+++ b/frontend/src/components/editor/renderers/vertical-layout/vertical-layout.tsx
@@ -29,7 +29,7 @@ const VerticalLayoutRenderer: React.FC<VerticalLayoutProps> = ({
return isStaticNotebook();
});
const evaluateCanShowCode = () => {
- const cellsHaveCode = cells.some((cell) => cell.code);
+ const cellsHaveCode = cells.some((cell) => Boolean(cell.code));
// Only show code if in read mode and there is at least one cell with code
diff --git a/frontend/src/components/static-html/static-banner.tsx b/frontend/src/components/static-html/static-banner.tsx
index c8415e04d3..13d942fcfc 100644
--- a/frontend/src/components/static-html/static-banner.tsx
+++ b/frontend/src/components/static-html/static-banner.tsx
@@ -25,6 +25,11 @@ export const StaticBanner: React.FC = () => {
return null;
}
+ const code = getMarimoCode();
+ if (!code) {
+ return null;
+ }
+
return (
<div className="px-4 py-2 bg-[var(--sky-2)] border-b border-[var(--sky-7)] text-md text-[var(--sky-11)] font-semibold flex justify-between items-center gap-4">
<span>
@@ -41,13 +46,13 @@ export const StaticBanner: React.FC = () => {
Some interactive features may not work, see ways to run or edit this.
</span>
<span className="flex-shrink-0">
- <StaticBannerDialog />
+ <StaticBannerDialog code={code} />
</span>
</div>
);
};
-const StaticBannerDialog = () => {
+const StaticBannerDialog = ({ code }: { code: string }) => {
let filename = getFilenameFromDOM() || "notebook.py";
// Trim the path
const lastSlash = filename.lastIndexOf("/");
@@ -56,7 +61,6 @@ const StaticBannerDialog = () => {
}
const href = window.location.href;
- const code = getMarimoCode();
const wasmLink = createShareableLink({ code });
return (
diff --git a/marimo/_cli/cli.py b/marimo/_cli/cli.py
index df92af9e3c..00ef877467 100644
--- a/marimo/_cli/cli.py
+++ b/marimo/_cli/cli.py
@@ -15,7 +15,9 @@ from marimo import __version__, _loggers
from marimo._ast import codegen
from marimo._cli import ipynb_to_marimo
from marimo._cli.envinfo import get_system_info
+from marimo._cli.export.commands import export
from marimo._cli.file_path import validate_name
+from marimo._cli.print import red
from marimo._cli.upgrade import check_for_updates
from marimo._server.file_router import AppFileRouter
from marimo._server.model import SessionMode
@@ -25,21 +27,12 @@ DEVELOPMENT_MODE = False
QUIET = False
-def colorize(string: str, color: Literal["red"]) -> str:
- if color == "red":
- color_code = "31"
- else:
- raise ValueError("Unrecognized color ", color)
-
- return f"\033[;{color_code}m{string}\033[0m"
-
-
def helpful_usage_error(self: Any, file: Any = None) -> None:
if file is None:
file = click.get_text_stream("stderr")
color = None
click.echo(
- colorize("Error", "red") + ": %s\n" % self.format_message(),
+ red("Error") + ": %s\n" % self.format_message(),
file=file,
color=color,
)
@@ -532,3 +525,6 @@ def env() -> None:
marimo env
"""
print(json.dumps(get_system_info(), indent=2))
+
+
+main.add_command(export)
diff --git a/marimo/_cli/export/commands.py b/marimo/_cli/export/commands.py
new file mode 100644
index 0000000000..cc9c2eae28
--- /dev/null
+++ b/marimo/_cli/export/commands.py
@@ -0,0 +1,115 @@
+# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+import asyncio
+from pathlib import Path
+
+import click
+
+from marimo._cli.print import green
+from marimo._server.export.utils import run_app_then_export_as_html
+from marimo._utils.file_watcher import FileWatcher
+from marimo._utils.paths import maybe_make_dirs
+
+
[email protected](help="""Export a notebook to various formats.""")
+def export() -> None:
+ pass
+
+
+ help="""Run a notebook and export it as an HTML file.
+
+Example:
+
+ \b
+ * marimo export html notebook.py -o notebook.html
+"""
+)
+ "--include-code/--no-include-code",
+ default=True,
+ show_default=True,
+ type=bool,
+ help="Include notebook code in the exported HTML file.",
+)
+ "--watch/--no-watch",
+ default=False,
+ show_default=True,
+ type=bool,
+ help="""
+ Watch notebook for changes and regenerate HTML on modification.
+ If watchdog is installed, it will be used to watch the file.
+ Otherwise, file watcher will poll the file every 1s.
+ """,
+)
+ "-o",
+ "--output",
+ type=str,
+ default=None,
+ help="""
+ Output file to save the HTML to.
+ If not provided, the HTML will be printed to stdout.
+ """,
+)
[email protected]("name", required=True)
+def html(
+ name: str,
+ include_code: bool,
+ output: str,
+ watch: bool,
+) -> None:
+ """
+ Run a notebook and export it as an HTML file.
+ """
+ if watch and not output:
+ raise click.UsageError(
+ "Cannot use --watch without providing "
+ + "an output file with --output."
+ )
+
+ def write_html(html: str) -> None:
+ if output:
+ # Make dirs if needed
+ maybe_make_dirs(output)
+ with open(output, "w") as f:
+ f.write(html)
+ f.close()
+ else:
+ click.echo(html)
+
+ # No watch, just run once
+ if not watch:
+ (html, _filename) = asyncio.run(
+ run_app_then_export_as_html(name, include_code=include_code)
+ )
+ write_html(html)
+ return
+
+ async def on_file_changed(file_path: Path) -> None:
+ click.echo(
+ f"File {str(file_path)} changed. Re-exporting to {green(output)}"
+ )
+ (html, _filename) = await run_app_then_export_as_html(
+ str(file_path), include_code=include_code
+ )
+ write_html(html)
+
+ async def start() -> None:
+ # Watch the file for changes
+ watcher = FileWatcher.create(Path(name), on_file_changed)
+ click.echo(f"Watching {green(name)} for changes...")
+ watcher.start()
+ try:
+ # Run forever
+ while True:
+ await asyncio.sleep(1)
+ except KeyboardInterrupt:
+ watcher.stop()
+
+ asyncio.run(start())
+
+
+export.add_command(html)
diff --git a/marimo/_cli/print.py b/marimo/_cli/print.py
index cb697d8cb1..27873474a8 100644
--- a/marimo/_cli/print.py
+++ b/marimo/_cli/print.py
@@ -1,5 +1,7 @@
# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
# Print helpers
@@ -9,3 +11,7 @@ def green(text: str) -> str:
def orange(text: str) -> str:
return "\033[33m" + text + "\033[0m"
+
+
+def red(text: str) -> str:
+ return "\033[31m" + text + "\033[0m"
diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.py
index d75cfa25a4..c1cc92bf0a 100644
--- a/marimo/_runtime/runtime.py
+++ b/marimo/_runtime/runtime.py
@@ -1403,6 +1403,7 @@ def launch_kernel(
configs: dict[CellId_t, CellConfig],
app_metadata: AppMetadata,
user_config: MarimoConfig,
+ virtual_files_supported: bool,
) -> None:
LOGGER.debug("Launching kernel")
if is_edit_mode:
@@ -1456,6 +1457,7 @@ def launch_kernel(
initialize_context(
kernel=kernel,
stream=stream,
+ virtual_files_supported=virtual_files_supported,
)
if is_edit_mode:
diff --git a/marimo/_server/export/exporter.py b/marimo/_server/export/exporter.py
index aeb29a8079..532b8c8bc4 100644
--- a/marimo/_server/export/exporter.py
+++ b/marimo/_server/export/exporter.py
@@ -1,3 +1,4 @@
+# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
import mimetypes
diff --git a/marimo/_server/export/utils.py b/marimo/_server/export/utils.py
new file mode 100644
index 0000000000..610d55b7f0
--- /dev/null
+++ b/marimo/_server/export/utils.py
@@ -0,0 +1,83 @@
+# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+import asyncio
+from typing import Callable
+
+from marimo._config.manager import UserConfigManager
+from marimo._messaging.ops import MessageOperation
+from marimo._messaging.types import KernelMessage
+from marimo._runtime.requests import AppMetadata
+from marimo._server.export.exporter import Exporter
+from marimo._server.file_router import AppFileRouter
+from marimo._server.model import ConnectionState, SessionConsumer, SessionMode
+from marimo._server.models.export import ExportAsHTMLRequest
+from marimo._server.models.models import InstantiateRequest
+from marimo._server.sessions import Session
+
+
+async def run_app_then_export_as_html(
+ filename: str,
+ include_code: bool,
+) -> tuple[str, str]:
+ # Create a file router and file manager
+ file_router = AppFileRouter.from_filename(filename)
+ file_key = file_router.get_unique_file_key()
+ assert file_key is not None
+ file_manager = file_router.get_file_manager(file_key)
+
+ instantiated_event = asyncio.Event()
+
+ # Create a no-op session consumer
+ class NoopSessionConsumer(SessionConsumer):
+ def on_start(
+ self,
+ check_alive: Callable[[], None],
+ ) -> Callable[[KernelMessage], None]:
+ del check_alive
+
+ def listener(message: KernelMessage) -> None:
+ if message[0] == "completed-run":
+ instantiated_event.set()
+
+ return listener
+
+ def on_stop(self) -> None:
+ pass
+
+ async def write_operation(self, op: MessageOperation) -> None:
+ pass
+
+ def connection_state(self) -> ConnectionState:
+ return ConnectionState.OPEN
+
+ config = UserConfigManager()
+
+ # Create a session
+ session = Session.create(
+ initialization_id=file_key,
+ session_consumer=NoopSessionConsumer(),
+ mode=SessionMode.RUN,
+ app_metadata=AppMetadata(query_params={}, filename=file_manager.path),
+ app_file_manager=file_manager,
+ user_config_manager=config,
+ virtual_files_supported=False,
+ )
+
+ # Run the app to completion once
+ session.instantiate(InstantiateRequest(object_ids=[], values=[]))
+ await instantiated_event.wait()
+
+ # Export the session as HTML
+ html, filename = Exporter().export_as_html(
+ file_manager=session.app_file_manager,
+ session_view=session.session_view,
+ display_config=config.get_config()["display"],
+ request=ExportAsHTMLRequest(
+ include_code=include_code,
+ download=False,
+ files=[],
+ ),
+ )
+
+ return html, filename
diff --git a/marimo/_server/sessions.py b/marimo/_server/sessions.py
index 3e44809c88..01f9109b9a 100644
--- a/marimo/_server/sessions.py
+++ b/marimo/_server/sessions.py
@@ -30,6 +30,7 @@ from uuid import uuid4
from marimo import _loggers
from marimo._ast.cell import CellConfig, CellId_t
+from marimo._cli.print import red
from marimo._config.manager import UserConfigManager
from marimo._messaging.ops import Alert, MessageOperation, Reload
from marimo._messaging.types import KernelMessage
@@ -124,6 +125,7 @@ class KernelManager:
configs: dict[CellId_t, CellConfig],
app_metadata: AppMetadata,
user_config_manager: UserConfigManager,
+ virtual_files_supported: bool,
) -> None:
self.kernel_task: Optional[threading.Thread] | Optional[mp.Process]
self.queue_manager = queue_manager
@@ -132,6 +134,7 @@ class KernelManager:
self.app_metadata = app_metadata
self.user_config_manager = user_config_manager
self._read_conn: Optional[TypedConnection[KernelMessage]] = None
+ self._virtual_files_supported = virtual_files_supported
def start_kernel(self) -> None:
# Need to use a socket for windows compatibility
@@ -153,6 +156,7 @@ class KernelManager:
self.configs,
self.app_metadata,
self.user_config_manager.config,
+ self._virtual_files_supported,
),
# The process can't be a daemon, because daemonic processes
# can't create children
@@ -189,6 +193,7 @@ class KernelManager:
self.configs,
self.app_metadata,
self.user_config_manager.config,
+ self._virtual_files_supported,
),
# daemon threads can create child processes, unlike
# daemon processes
@@ -248,12 +253,18 @@ class Session:
app_metadata: AppMetadata,
app_file_manager: AppFileManager,
user_config_manager: UserConfigManager,
+ virtual_files_supported: bool,
) -> Session:
configs = app_file_manager.app.cell_manager.config_map()
use_multiprocessing = mode == SessionMode.EDIT
queue_manager = QueueManager(use_multiprocessing)
kernel_manager = KernelManager(
- queue_manager, mode, configs, app_metadata, user_config_manager
+ queue_manager,
+ mode,
+ configs,
+ app_metadata,
+ user_config_manager,
+ virtual_files_supported=virtual_files_supported,
)
return cls(
initialization_id,
@@ -302,7 +313,7 @@ class Session:
LOGGER.debug("Closing session because kernel died")
self.close()
print()
- print_tabbed("\033[31mThe Python kernel died unexpectedly.\033[0m")
+ print_tabbed(red("The Python kernel died unexpectedly."))
print()
sys.exit()
@@ -469,6 +480,7 @@ class SessionManager:
),
app_file_manager=app_file_manager,
user_config_manager=self.user_config_manager,
+ virtual_files_supported=True,
)
return self.sessions[session_id]
diff --git a/marimo/_utils/paths.py b/marimo/_utils/paths.py
index 96cf10f567..5828adff5a 100644
--- a/marimo/_utils/paths.py
+++ b/marimo/_utils/paths.py
@@ -1,4 +1,6 @@
# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
import os
import sys
from typing import Any
@@ -29,3 +31,12 @@ def pretty_path(filename: str) -> str:
if not relpath.startswith(".."):
return relpath
return filename
+
+
+def maybe_make_dirs(filepath: str) -> None:
+ """
+ Create directories if they don't exist.
+ """
+ dirname = os.path.dirname(filepath)
+ if dirname:
+ os.makedirs(os.path.dirname(filepath), exist_ok=True)
diff --git a/tests/_cli/test_cli_export.py b/tests/_cli/test_cli_export.py
new file mode 100644
index 0000000000..cdd7eee54c
--- /dev/null
+++ b/tests/_cli/test_cli_export.py
@@ -0,0 +1,99 @@
+# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+import subprocess
+from os import path
+
+from tests._server.templates.utils import normalize_index_html
+from tests.mocks import snapshotter
+
+snapshot = snapshotter(__file__)
+
+
+def test_cli_export_html(temp_marimo_file: str) -> None:
+ p = subprocess.run(
+ ["marimo", "export", "html", temp_marimo_file],
+ capture_output=True,
+ )
+ assert p.returncode == 0, p.stderr.decode()
+ html = normalize_index_html(p.stdout.decode())
+ # Remove folder path
+ dirname = path.dirname(temp_marimo_file)
+ html = html.replace(dirname, "path")
+ assert '<marimo-code hidden=""></marimo-code>' not in html
+
+
+def test_cli_export_html_no_code(temp_marimo_file: str) -> None:
+ p = subprocess.run(
+ ["marimo", "export", "html", temp_marimo_file, "--no-include-code"],
+ capture_output=True,
+ )
+ assert p.returncode == 0, p.stderr.decode()
+ html = normalize_index_html(p.stdout.decode())
+ # Remove folder path
+ dirname = path.dirname(temp_marimo_file)
+ html = html.replace(dirname, "path")
+ assert '<marimo-code hidden=""></marimo-code>' in html
+
+
+async def test_export_watch(temp_marimo_file: str) -> None:
+ temp_out_file = temp_marimo_file.replace(".py", ".html")
+ p = subprocess.Popen( # noqa: ASYNC101
+ [
+ "marimo",
+ "export",
+ "html",
+ temp_marimo_file,
+ "--watch",
+ "--output",
+ temp_out_file,
+ ],
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ )
+
+ # Wait for the message
+ while True:
+ line = p.stdout.readline().decode()
+ if line:
+ assert f"Watching {temp_marimo_file}" in line
+ break
+
+ assert not path.exists(temp_out_file)
+
+ # Modify file
+ with open(temp_marimo_file, "a") as f: # noqa: ASYNC101
+ f.write("\n# comment\n")
+
+ assert p.poll() is None
+ # Wait for rebuild
+ while True:
+ line = p.stdout.readline().decode()
+ if line:
+ assert "Re-exporting" in line
+ break
+
+
+def test_export_watch_no_out_dir(temp_marimo_file: str) -> None:
+ p = subprocess.Popen(
+ [
+ "marimo",
+ "export",
+ "html",
+ temp_marimo_file,
+ "--watch",
+ ],
+ stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE,
+ )
+
+ # Should return an error
+ while True:
+ line = p.stderr.readline().decode()
+ if line:
+ assert (
+ "Cannot use --watch without providing "
+ + "an output file with --output."
+ in line
+ )
+ break
diff --git a/tests/_server/api/endpoints/test_files.py b/tests/_server/api/endpoints/test_files.py
index 2f1be06c6d..7970515c9b 100644
--- a/tests/_server/api/endpoints/test_files.py
+++ b/tests/_server/api/endpoints/test_files.py
@@ -3,14 +3,17 @@ from __future__ import annotations
import os
import random
+from typing import TYPE_CHECKING
import pytest
-from starlette.testclient import TestClient
from marimo._server.api.status import HTTPException
from tests._server.conftest import get_session_manager
from tests._server.mocks import with_session
+if TYPE_CHECKING:
+ from fastapi.testclient import TestClient
+
SESSION_ID = "session-123"
HEADERS = {
"Marimo-Session-Id": SESSION_ID,
diff --git a/tests/_server/mocks.py b/tests/_server/mocks.py
index 02669f04f8..15e070c4e6 100644
--- a/tests/_server/mocks.py
+++ b/tests/_server/mocks.py
@@ -2,16 +2,17 @@
from __future__ import annotations
import tempfile
-from typing import Any, Callable, cast
+from typing import TYPE_CHECKING, Any, Callable, cast
from unittest.mock import MagicMock
-from starlette.testclient import TestClient
-
from marimo._config.manager import UserConfigManager
from marimo._server.file_router import AppFileRouter
from marimo._server.model import SessionMode
from marimo._server.sessions import LspServer, SessionManager
+if TYPE_CHECKING:
+ from fastapi.testclient import TestClient
+
def get_session_manager(client: TestClient) -> SessionManager:
return client.app.state.session_manager # type: ignore
diff --git a/tests/_server/test_sessions.py b/tests/_server/test_sessions.py
index b28531eae6..cfc367543d 100644
--- a/tests/_server/test_sessions.py
+++ b/tests/_server/test_sessions.py
@@ -59,7 +59,12 @@ def test_kernel_manager() -> None:
# Instantiate a KernelManager
kernel_manager = KernelManager(
- queue_manager, mode, {}, app_metadata, UserConfigManager()
+ queue_manager,
+ mode,
+ {},
+ app_metadata,
+ UserConfigManager(),
+ virtual_files_supported=True,
)
kernel_manager.start_kernel()
@@ -84,7 +89,12 @@ def test_session() -> None:
session_consumer.connection_state.return_value = ConnectionState.OPEN
queue_manager = QueueManager(use_multiprocessing=False)
kernel_manager = KernelManager(
- queue_manager, SessionMode.RUN, {}, app_metadata, UserConfigManager()
+ queue_manager,
+ SessionMode.RUN,
+ {},
+ app_metadata,
+ UserConfigManager(),
+ virtual_files_supported=True,
)
# Instantiate a Session
@@ -129,6 +139,7 @@ def test_session_disconnect_reconnect() -> None:
{},
AppMetadata(query_params={}),
UserConfigManager(),
+ virtual_files_supported=True,
)
# Instantiate a Session
diff --git a/tests/mocks.py b/tests/mocks.py
index 7e4a5e3308..c02c78dc58 100644
--- a/tests/mocks.py
+++ b/tests/mocks.py
@@ -4,6 +4,8 @@ import difflib
import os
from typing import Callable
+from marimo._utils.paths import maybe_make_dirs
+
def snapshotter(current_file: str) -> Callable[[str, str], None]:
"""
@@ -22,8 +24,7 @@ def snapshotter(current_file: str) -> Callable[[str, str], None]:
)
# If snapshot directory doesn't exist, create it
- if not os.path.exists(os.path.dirname(filepath)):
- os.makedirs(os.path.dirname(filepath))
+ maybe_make_dirs(filepath)
# If doesn't exist, create snapshot
if not os.path.exists(filepath):