|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import os |
| 4 | +import re |
| 5 | +import subprocess |
| 6 | +from pathlib import Path |
| 7 | +from typing import Literal |
| 8 | + |
| 9 | +import click |
| 10 | + |
| 11 | +import afterpython as ap |
| 12 | +from afterpython.tools.pyproject import read_metadata |
| 13 | + |
| 14 | +MarimoExportMode = Literal["wasm", "static"] |
| 15 | + |
| 16 | + |
| 17 | +def _get_molab_badge() -> str: |
| 18 | + return "https://marimo.io/molab-shield.svg" |
| 19 | + |
| 20 | + |
| 21 | +def _create_molab_url(github_url: str, content_path: Path) -> str: |
| 22 | + """Create a molab URL for a marimo notebook at content_path (relative to afterpython/).""" |
| 23 | + github_url = github_url.replace("https://github.com/", "github/") |
| 24 | + return f"https://molab.marimo.io/{github_url}/blob/main/afterpython/{content_path.as_posix()}" |
| 25 | + |
| 26 | + |
| 27 | +def is_marimo_notebook(path: Path) -> bool: |
| 28 | + """Check if a Python file is a marimo notebook. |
| 29 | +
|
| 30 | + Looks for marimo's two reliable signature lines (`__generated_with` and |
| 31 | + `marimo.App(`) — both are emitted by marimo for any notebook file, and |
| 32 | + a plain script that just `import`s marimo won't match. |
| 33 | + """ |
| 34 | + if not path.exists() or not path.is_file(): |
| 35 | + return False |
| 36 | + try: |
| 37 | + # marimo's signature is at the top of the file, no need to read all |
| 38 | + head = path.read_text(encoding="utf-8", errors="ignore")[:2048] |
| 39 | + except OSError: |
| 40 | + return False |
| 41 | + return "__generated_with" in head and "marimo.App(" in head |
| 42 | + |
| 43 | + |
| 44 | +def _export_marimo(source: Path, output_html: Path, mode: MarimoExportMode): |
| 45 | + """Run `marimo export` to produce HTML at `output_html`.""" |
| 46 | + output_html.parent.mkdir(parents=True, exist_ok=True) |
| 47 | + subcommand = "html-wasm" if mode == "wasm" else "html" |
| 48 | + cmd = ["marimo", "export", subcommand, str(source), "-o", str(output_html)] |
| 49 | + # WASM-only flag: --mode edit shows code cells (interactive). Without it, |
| 50 | + # marimo's html-wasm subcommand defaults to "run" which hides them. |
| 51 | + if mode == "wasm": |
| 52 | + cmd += ["--mode", "edit"] |
| 53 | + result = subprocess.run(cmd, check=False) |
| 54 | + if result.returncode != 0: |
| 55 | + raise click.ClickException(f"marimo export failed for {source}") |
| 56 | + |
| 57 | + |
| 58 | +def _inject_molab_badge(html_path: Path, molab_url: str): |
| 59 | + """Insert a fixed-position molab badge near the top of the exported HTML body. |
| 60 | +
|
| 61 | + Used so users can run the notebook on a real Python server (molab) when the |
| 62 | + static export can't execute, or as an alternative to the in-page WASM kernel. |
| 63 | + """ |
| 64 | + if not html_path.exists(): |
| 65 | + return |
| 66 | + html = html_path.read_text(encoding="utf-8") |
| 67 | + badge = ( |
| 68 | + f'<a href="{molab_url}" target="_top" rel="noopener" ' |
| 69 | + # right offset clears marimo's circular toolbar buttons in edit mode; |
| 70 | + # top offset is hand-tuned to vertically center against those buttons |
| 71 | + # (we can't group with marimo's UI, so this is a visual eyeball) |
| 72 | + f'style="position:fixed;top:16px;right:100px;z-index:9999;">' |
| 73 | + f'<img src="{_get_molab_badge()}" alt="Open in molab" />' |
| 74 | + f"</a>" |
| 75 | + ) |
| 76 | + new_html, n = re.subn(r"(<body[^>]*>)", r"\1" + badge, html, count=1) |
| 77 | + if n == 0: |
| 78 | + click.echo(f"⚠ Could not locate <body> in {html_path}, skipping molab badge") |
| 79 | + return |
| 80 | + html_path.write_text(new_html, encoding="utf-8") |
| 81 | + |
| 82 | + |
| 83 | +def build_marimo_notebook( |
| 84 | + source: Path, |
| 85 | + output_html: Path, |
| 86 | + content_path: Path, |
| 87 | + mode: MarimoExportMode = "wasm", |
| 88 | +): |
| 89 | + """Build a single marimo notebook to HTML and inject the molab badge. |
| 90 | +
|
| 91 | + Generic core for marimo builds — keep this notebook-agnostic so future |
| 92 | + callers (e.g. content-type builds in blog/tutorial) can reuse it. |
| 93 | +
|
| 94 | + Args: |
| 95 | + source: Path to the marimo .py file. |
| 96 | + output_html: Path to write the exported HTML to. |
| 97 | + content_path: Path of `source` relative to afterpython/, used to build |
| 98 | + the molab URL (which assumes the file lives under afterpython/ on |
| 99 | + the user's GitHub repo). |
| 100 | + mode: "wasm" (interactive, Pyodide) or "static" (pre-rendered). |
| 101 | + """ |
| 102 | + if not is_marimo_notebook(source): |
| 103 | + click.echo(f"{source} is not a marimo notebook, skip building") |
| 104 | + return |
| 105 | + |
| 106 | + click.echo(f"Building marimo notebook {source.name} (mode={mode})...") |
| 107 | + _export_marimo(source, output_html, mode) |
| 108 | + |
| 109 | + # WASM mode runs the notebook in-browser via Pyodide, so molab (a remote |
| 110 | + # runtime) is redundant. Skip the badge. |
| 111 | + if mode == "wasm": |
| 112 | + return |
| 113 | + |
| 114 | + add_molab_badge = os.getenv("AP_MOLAB_BADGE", "1") == "1" |
| 115 | + if not add_molab_badge: |
| 116 | + return |
| 117 | + |
| 118 | + metadata = read_metadata() |
| 119 | + github_url = ( |
| 120 | + metadata.urls.get("repository") if "repository" in metadata.urls else None |
| 121 | + ) |
| 122 | + if not github_url: |
| 123 | + click.echo( |
| 124 | + "⚠ Repository URL not found in [project.urls] in pyproject.toml, " |
| 125 | + "skipping molab badge" |
| 126 | + ) |
| 127 | + return |
| 128 | + |
| 129 | + molab_url = _create_molab_url(github_url, content_path) |
| 130 | + _inject_molab_badge(output_html, molab_url) |
| 131 | + |
| 132 | + |
| 133 | +def build_marimo_readme(mode: MarimoExportMode = "wasm"): |
| 134 | + """Build afterpython/README.py to _build/readme_py/readme_py.html. |
| 135 | +
|
| 136 | + Skips silently if README.py is absent or isn't a marimo notebook so users |
| 137 | + who keep only README.md aren't penalized. |
| 138 | + """ |
| 139 | + readme_path = ap.paths.afterpython_path / "README.py" |
| 140 | + if not readme_path.exists(): |
| 141 | + return |
| 142 | + output_html = ap.paths.build_path / "readme_py" / "readme_py.html" |
| 143 | + content_path = Path("README.py") |
| 144 | + build_marimo_notebook(readme_path, output_html, content_path, mode) |
0 commit comments