marimo-md-export 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- marimo_md_export-0.1.0/LICENSE +21 -0
- marimo_md_export-0.1.0/PKG-INFO +61 -0
- marimo_md_export-0.1.0/README.md +38 -0
- marimo_md_export-0.1.0/pyproject.toml +50 -0
- marimo_md_export-0.1.0/src/marimo_md_export/__init__.py +5 -0
- marimo_md_export-0.1.0/src/marimo_md_export/__main__.py +4 -0
- marimo_md_export-0.1.0/src/marimo_md_export/cli.py +98 -0
- marimo_md_export-0.1.0/src/marimo_md_export/export.py +26 -0
- marimo_md_export-0.1.0/src/marimo_md_export/inject.py +88 -0
- marimo_md_export-0.1.0/src/marimo_md_export/models.py +22 -0
- marimo_md_export-0.1.0/src/marimo_md_export/parse_html.py +172 -0
- marimo_md_export-0.1.0/src/marimo_md_export/parse_md.py +44 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Joe Marsh Rossney
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: marimo-md-export
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: A minimal solution for exporting marimo notebooks to markdown *with* rendered HTML outputs, designed for mkdocs/zensical sites.
|
|
5
|
+
Keywords: marimo,markdown,documentation
|
|
6
|
+
Author: jmarshrossney
|
|
7
|
+
Author-email: jmarshrossney <17361029+jmarshrossney@users.noreply.github.com>
|
|
8
|
+
License-Expression: MIT
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Classifier: Development Status :: 3 - Alpha
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: Topic :: Documentation
|
|
13
|
+
Classifier: Topic :: Text Processing :: Markup :: Markdown
|
|
14
|
+
Requires-Dist: beautifulsoup4>=4.14.3
|
|
15
|
+
Requires-Dist: lxml>=6.1.0
|
|
16
|
+
Requires-Dist: marimo>=0.23.3
|
|
17
|
+
Requires-Dist: typer>=0.25.0
|
|
18
|
+
Requires-Python: >=3.14
|
|
19
|
+
Project-URL: Homepage, https://jmarshrossney.github.io/marimo-md-export
|
|
20
|
+
Project-URL: Repository, https://github.com/jmarshrossney/marimo-md-export
|
|
21
|
+
Project-URL: Documentation, https://jmarshrossney.github.io/marimo-md-export
|
|
22
|
+
Description-Content-Type: text/markdown
|
|
23
|
+
|
|
24
|
+
# marimo-md-export
|
|
25
|
+
|
|
26
|
+
A `uv` tool that wraps `marimo export`, extracts rendered outputs from the HTML export,
|
|
27
|
+
and injects them into the markdown export. The result is a self-contained markdown
|
|
28
|
+
document with embedded figures (as base64 `<img>` tags) and tables (as GFM or HTML).
|
|
29
|
+
|
|
30
|
+
**[Full documentation](https://jmarshrossney.github.io/marimo-md-export)**
|
|
31
|
+
|
|
32
|
+
## Quick start
|
|
33
|
+
|
|
34
|
+
Mark cells in your marimo `.py` notebook with `# @output: <label>`:
|
|
35
|
+
|
|
36
|
+
```python
|
|
37
|
+
# @output: my_figure
|
|
38
|
+
fig, ax = plt.subplots()
|
|
39
|
+
ax.plot(x, np.sin(x))
|
|
40
|
+
fig
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
Then run:
|
|
44
|
+
|
|
45
|
+
```sh
|
|
46
|
+
uvx marimo-md-export notebook.py output.md
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
## Installation
|
|
50
|
+
|
|
51
|
+
```sh
|
|
52
|
+
uv tool install marimo-md-export # or: pipx install marimo-md-export
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
## Development
|
|
56
|
+
|
|
57
|
+
```sh
|
|
58
|
+
uv sync
|
|
59
|
+
just test
|
|
60
|
+
just docs
|
|
61
|
+
```
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
# marimo-md-export
|
|
2
|
+
|
|
3
|
+
A `uv` tool that wraps `marimo export`, extracts rendered outputs from the HTML export,
|
|
4
|
+
and injects them into the markdown export. The result is a self-contained markdown
|
|
5
|
+
document with embedded figures (as base64 `<img>` tags) and tables (as GFM or HTML).
|
|
6
|
+
|
|
7
|
+
**[Full documentation](https://jmarshrossney.github.io/marimo-md-export)**
|
|
8
|
+
|
|
9
|
+
## Quick start
|
|
10
|
+
|
|
11
|
+
Mark cells in your marimo `.py` notebook with `# @output: <label>`:
|
|
12
|
+
|
|
13
|
+
```python
|
|
14
|
+
# @output: my_figure
|
|
15
|
+
fig, ax = plt.subplots()
|
|
16
|
+
ax.plot(x, np.sin(x))
|
|
17
|
+
fig
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
Then run:
|
|
21
|
+
|
|
22
|
+
```sh
|
|
23
|
+
uvx marimo-md-export notebook.py output.md
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
## Installation
|
|
27
|
+
|
|
28
|
+
```sh
|
|
29
|
+
uv tool install marimo-md-export # or: pipx install marimo-md-export
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
## Development
|
|
33
|
+
|
|
34
|
+
```sh
|
|
35
|
+
uv sync
|
|
36
|
+
just test
|
|
37
|
+
just docs
|
|
38
|
+
```
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["uv_build>=0.9.5,<0.10.0"]
|
|
3
|
+
build-backend = "uv_build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "marimo-md-export"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "A minimal solution for exporting marimo notebooks to markdown *with* rendered HTML outputs, designed for mkdocs/zensical sites."
|
|
9
|
+
authors = [
|
|
10
|
+
{ name = "jmarshrossney", email = "17361029+jmarshrossney@users.noreply.github.com" }
|
|
11
|
+
]
|
|
12
|
+
readme = "README.md"
|
|
13
|
+
license = "MIT"
|
|
14
|
+
license-files = ["LICENSE"]
|
|
15
|
+
requires-python = ">=3.14"
|
|
16
|
+
dependencies = [
|
|
17
|
+
"beautifulsoup4>=4.14.3",
|
|
18
|
+
"lxml>=6.1.0",
|
|
19
|
+
"marimo>=0.23.3",
|
|
20
|
+
"typer>=0.25.0",
|
|
21
|
+
]
|
|
22
|
+
keywords = ["marimo", "markdown", "documentation"]
|
|
23
|
+
classifiers = [
|
|
24
|
+
"Development Status :: 3 - Alpha",
|
|
25
|
+
"Intended Audience :: Developers",
|
|
26
|
+
"Topic :: Documentation",
|
|
27
|
+
"Topic :: Text Processing :: Markup :: Markdown",
|
|
28
|
+
]
|
|
29
|
+
|
|
30
|
+
[project.urls]
|
|
31
|
+
Homepage = "https://jmarshrossney.github.io/marimo-md-export"
|
|
32
|
+
Repository = "https://github.com/jmarshrossney/marimo-md-export"
|
|
33
|
+
Documentation = "https://jmarshrossney.github.io/marimo-md-export"
|
|
34
|
+
|
|
35
|
+
[project.scripts]
|
|
36
|
+
marimo-md-export = "marimo_md_export:main"
|
|
37
|
+
|
|
38
|
+
[dependency-groups]
|
|
39
|
+
dev = [
|
|
40
|
+
"pytest>=9.0.3",
|
|
41
|
+
"ruff>=0.15.12",
|
|
42
|
+
"rust-just>=1.50.0",
|
|
43
|
+
{include-group = "docs"},
|
|
44
|
+
]
|
|
45
|
+
docs = [
|
|
46
|
+
"matplotlib>=3.10.9",
|
|
47
|
+
"numpy>=2.4.4",
|
|
48
|
+
"pandas>=3.0.2",
|
|
49
|
+
"zensical>=0.0.37",
|
|
50
|
+
]
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
from pathlib import Path
|
|
2
|
+
|
|
3
|
+
import typer
|
|
4
|
+
|
|
5
|
+
from .export import export_html, export_md
|
|
6
|
+
from .inject import inject_outputs
|
|
7
|
+
from .parse_html import extract_outputs
|
|
8
|
+
from .parse_md import collect_marked_cells
|
|
9
|
+
|
|
10
|
+
app = typer.Typer(
|
|
11
|
+
help="Command-line tool for exporting marimo .py notebooks to markdown .md with rendered HTML.",
|
|
12
|
+
context_settings={"help_option_names": ["-h", "--help"]},
|
|
13
|
+
add_completion=False,
|
|
14
|
+
)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@app.command()
|
|
18
|
+
def main(
|
|
19
|
+
notebook: Path = typer.Argument(
|
|
20
|
+
...,
|
|
21
|
+
exists=True,
|
|
22
|
+
file_okay=True,
|
|
23
|
+
dir_okay=False,
|
|
24
|
+
readable=True,
|
|
25
|
+
help="Path to the marimo notebook (.py)",
|
|
26
|
+
),
|
|
27
|
+
output: Path = typer.Argument(
|
|
28
|
+
...,
|
|
29
|
+
writable=True,
|
|
30
|
+
help="Where to write the resulting markdown file",
|
|
31
|
+
),
|
|
32
|
+
html_output: Path = typer.Option(
|
|
33
|
+
None,
|
|
34
|
+
"--html-output",
|
|
35
|
+
writable=True,
|
|
36
|
+
help="If provided, also save the intermediate HTML export to this path",
|
|
37
|
+
),
|
|
38
|
+
marimo_args: str = typer.Option(
|
|
39
|
+
"",
|
|
40
|
+
"--marimo-args",
|
|
41
|
+
help="Extra arguments forwarded to marimo export (space-separated)",
|
|
42
|
+
),
|
|
43
|
+
verbose: bool = typer.Option(False, "--verbose", "-v"),
|
|
44
|
+
) -> None:
|
|
45
|
+
"""Export a marimo notebook to markdown with rendered outputs injected."""
|
|
46
|
+
extra = marimo_args.split() if marimo_args.strip() else []
|
|
47
|
+
|
|
48
|
+
if verbose:
|
|
49
|
+
typer.echo(f"Exporting markdown: {notebook}")
|
|
50
|
+
try:
|
|
51
|
+
md = export_md(notebook)
|
|
52
|
+
except RuntimeError as exc:
|
|
53
|
+
typer.echo(f"marimo export md failed:\n{exc}", err=True)
|
|
54
|
+
raise typer.Exit(1)
|
|
55
|
+
|
|
56
|
+
marked = collect_marked_cells(md)
|
|
57
|
+
if not marked:
|
|
58
|
+
typer.echo(
|
|
59
|
+
f"WARNING: no @output markers found in {notebook}. "
|
|
60
|
+
"Did you forget to add '# @output: <label>' comments?",
|
|
61
|
+
err=True,
|
|
62
|
+
)
|
|
63
|
+
raise typer.Exit(2)
|
|
64
|
+
|
|
65
|
+
if verbose:
|
|
66
|
+
typer.echo(
|
|
67
|
+
f"Found {len(marked)} @output marker(s): "
|
|
68
|
+
+ ", ".join(c.label for c in marked)
|
|
69
|
+
)
|
|
70
|
+
typer.echo(f"Exporting HTML: {notebook}")
|
|
71
|
+
|
|
72
|
+
try:
|
|
73
|
+
html = export_html(notebook, extra)
|
|
74
|
+
except RuntimeError as exc:
|
|
75
|
+
typer.echo(f"marimo export html failed:\n{exc}", err=True)
|
|
76
|
+
raise typer.Exit(1)
|
|
77
|
+
|
|
78
|
+
if html_output is not None:
|
|
79
|
+
html_output.parent.mkdir(parents=True, exist_ok=True)
|
|
80
|
+
html_output.write_bytes(html)
|
|
81
|
+
if verbose:
|
|
82
|
+
typer.echo(f"Wrote {html_output}")
|
|
83
|
+
|
|
84
|
+
target_hashes = {c.source_hash for c in marked}
|
|
85
|
+
outputs = extract_outputs(html, target_hashes)
|
|
86
|
+
|
|
87
|
+
# Attach labels to outputs
|
|
88
|
+
for cell in marked:
|
|
89
|
+
if cell.source_hash in outputs:
|
|
90
|
+
outputs[cell.source_hash].label = cell.label
|
|
91
|
+
|
|
92
|
+
result = inject_outputs(md, outputs)
|
|
93
|
+
|
|
94
|
+
output.parent.mkdir(parents=True, exist_ok=True)
|
|
95
|
+
output.write_text(result, encoding="utf-8")
|
|
96
|
+
|
|
97
|
+
if verbose:
|
|
98
|
+
typer.echo(f"Wrote {output}")
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
|
|
4
|
+
from marimo._cli.parse_args import parse_args
|
|
5
|
+
from marimo._server.export import export_as_md, run_app_then_export_as_html
|
|
6
|
+
from marimo._utils.marimo_path import MarimoPath
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def export_html(notebook: Path, extra_args: list[str] | None = None) -> bytes:
|
|
10
|
+
argv = list(extra_args or [])
|
|
11
|
+
result = asyncio.run(
|
|
12
|
+
run_app_then_export_as_html(
|
|
13
|
+
MarimoPath(notebook),
|
|
14
|
+
include_code=True,
|
|
15
|
+
cli_args=parse_args(tuple(argv)),
|
|
16
|
+
argv=argv,
|
|
17
|
+
)
|
|
18
|
+
)
|
|
19
|
+
if result.did_error:
|
|
20
|
+
raise RuntimeError("marimo HTML export reported errors")
|
|
21
|
+
return result.bytez
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def export_md(notebook: Path) -> str:
|
|
25
|
+
result = export_as_md(MarimoPath(notebook))
|
|
26
|
+
return result.text
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import sys
|
|
2
|
+
import warnings
|
|
3
|
+
|
|
4
|
+
from bs4 import BeautifulSoup
|
|
5
|
+
|
|
6
|
+
from .models import ExtractedOutput, MarkedCell
|
|
7
|
+
from .parse_md import collect_marked_cells
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def _table_to_gfm(html: str) -> str | None:
|
|
11
|
+
"""Convert a plain HTML <table> to GFM markdown, or return None on failure."""
|
|
12
|
+
soup = BeautifulSoup(html, "lxml")
|
|
13
|
+
table = soup.find("table")
|
|
14
|
+
if table is None:
|
|
15
|
+
return None
|
|
16
|
+
|
|
17
|
+
# Reject tables with merged cells — fall back to HTML
|
|
18
|
+
if table.find(attrs={"colspan": True}) or table.find(attrs={"rowspan": True}):
|
|
19
|
+
return None
|
|
20
|
+
|
|
21
|
+
rows: list[list[str]] = []
|
|
22
|
+
for tr in table.find_all("tr"):
|
|
23
|
+
cells = [td.get_text(strip=True) for td in tr.find_all(["th", "td"])]
|
|
24
|
+
rows.append(cells)
|
|
25
|
+
|
|
26
|
+
if not rows:
|
|
27
|
+
return None
|
|
28
|
+
|
|
29
|
+
header = rows[0]
|
|
30
|
+
body = rows[1:]
|
|
31
|
+
sep = ["---"] * len(header)
|
|
32
|
+
|
|
33
|
+
def _row(cells: list[str]) -> str:
|
|
34
|
+
return "| " + " | ".join(cells) + " |"
|
|
35
|
+
|
|
36
|
+
lines = [_row(header), _row(sep), *(_row(r) for r in body)]
|
|
37
|
+
return "\n".join(lines)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _format_output(output: ExtractedOutput) -> str:
|
|
41
|
+
comment = f"<!-- @output:{output.label} -->"
|
|
42
|
+
|
|
43
|
+
parts = []
|
|
44
|
+
if output.console_html:
|
|
45
|
+
parts.append(output.console_html)
|
|
46
|
+
if output.raw_html:
|
|
47
|
+
if output.output_type == "table":
|
|
48
|
+
gfm = _table_to_gfm(output.raw_html)
|
|
49
|
+
parts.append(gfm if gfm is not None else output.raw_html)
|
|
50
|
+
else:
|
|
51
|
+
parts.append(output.raw_html)
|
|
52
|
+
|
|
53
|
+
return comment + "\n\n" + "\n\n".join(parts)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def inject_outputs(
|
|
57
|
+
md: str,
|
|
58
|
+
outputs: dict[str, ExtractedOutput],
|
|
59
|
+
) -> str:
|
|
60
|
+
"""Inject rendered outputs into the markdown after each marked code block.
|
|
61
|
+
|
|
62
|
+
`outputs` maps source_hash → ExtractedOutput (label field will be updated
|
|
63
|
+
to the human-readable label from the @output marker).
|
|
64
|
+
"""
|
|
65
|
+
marked_cells: list[MarkedCell] = collect_marked_cells(md)
|
|
66
|
+
|
|
67
|
+
result = md
|
|
68
|
+
for cell in marked_cells:
|
|
69
|
+
matched = outputs.get(cell.source_hash)
|
|
70
|
+
if matched is None:
|
|
71
|
+
warnings.warn(
|
|
72
|
+
f"WARNING: no output found for @output:{cell.label} "
|
|
73
|
+
f"(hash {cell.source_hash[:8]})",
|
|
74
|
+
stacklevel=2,
|
|
75
|
+
)
|
|
76
|
+
print(
|
|
77
|
+
f"WARNING: no output found for @output:{cell.label}",
|
|
78
|
+
file=sys.stderr,
|
|
79
|
+
)
|
|
80
|
+
continue
|
|
81
|
+
|
|
82
|
+
matched.label = cell.label
|
|
83
|
+
formatted = _format_output(matched)
|
|
84
|
+
result = result.replace(
|
|
85
|
+
cell.block_text, cell.block_text + "\n\n" + formatted, 1
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
return result
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
from dataclasses import dataclass, field
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
@dataclass
|
|
5
|
+
class MarkedCell:
|
|
6
|
+
"""A fenced code block in the markdown that carries an @output marker."""
|
|
7
|
+
|
|
8
|
+
label: str
|
|
9
|
+
source: str
|
|
10
|
+
# MD5 hex digest of source.strip() — matches marimo's code_hash in HTML export
|
|
11
|
+
source_hash: str
|
|
12
|
+
block_text: str
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass
|
|
16
|
+
class ExtractedOutput:
|
|
17
|
+
"""The rendered output scraped from the HTML export for one cell."""
|
|
18
|
+
|
|
19
|
+
label: str
|
|
20
|
+
raw_html: str
|
|
21
|
+
output_type: str # "figure" | "table" | "text" | "unknown"
|
|
22
|
+
console_html: str = field(default="")
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
# Marimo HTML export structure (verified against marimo 0.23.3):
|
|
2
|
+
#
|
|
3
|
+
# The exported HTML is a SPA. Cell outputs are embedded as JSON inside a
|
|
4
|
+
# <script> tag that defines `window.__MARIMO_MOUNT_CONFIG__`. The relevant
|
|
5
|
+
# path is:
|
|
6
|
+
#
|
|
7
|
+
# __MARIMO_MOUNT_CONFIG__.session.cells[]
|
|
8
|
+
# .code_hash — MD5 hex digest of cell source (stripped)
|
|
9
|
+
# .outputs[]
|
|
10
|
+
# .type — "data"
|
|
11
|
+
# .data — dict of MIME type → value
|
|
12
|
+
#
|
|
13
|
+
# Supported MIME types:
|
|
14
|
+
# application/vnd.marimo+mimebundle — JSON string; "image/png" key → figure
|
|
15
|
+
# text/html — may contain <marimo-table> web component
|
|
16
|
+
# text/markdown — rendered markdown
|
|
17
|
+
# text/plain — plain text
|
|
18
|
+
#
|
|
19
|
+
# Tables are stored as <marimo-table data-data='...'> web components.
|
|
20
|
+
# `data-data` is a JSON-quoted string of row objects; NaN appears literally.
|
|
21
|
+
|
|
22
|
+
import json
|
|
23
|
+
import re
|
|
24
|
+
from html import escape, unescape
|
|
25
|
+
|
|
26
|
+
from bs4 import BeautifulSoup
|
|
27
|
+
|
|
28
|
+
from .models import ExtractedOutput
|
|
29
|
+
|
|
30
|
+
_SESSION_CELLS_RE = re.compile(
|
|
31
|
+
r'"session"\s*:\s*\{"cells"\s*:\s*(\[)',
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _extract_session_cells_raw(html: bytes) -> str:
|
|
36
|
+
"""Return the raw JSON string for session.cells from the HTML."""
|
|
37
|
+
text = html.decode("utf-8", errors="replace")
|
|
38
|
+
m = _SESSION_CELLS_RE.search(text)
|
|
39
|
+
if m is None:
|
|
40
|
+
return "[]"
|
|
41
|
+
|
|
42
|
+
start = m.start(1)
|
|
43
|
+
depth = 0
|
|
44
|
+
for i, ch in enumerate(text[start:], start=start):
|
|
45
|
+
if ch == "[":
|
|
46
|
+
depth += 1
|
|
47
|
+
elif ch == "]":
|
|
48
|
+
depth -= 1
|
|
49
|
+
if depth == 0:
|
|
50
|
+
return text[start : i + 1]
|
|
51
|
+
return "[]"
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _table_html_from_marimo_table(marimo_table_html: str) -> str:
|
|
55
|
+
"""Convert a <marimo-table> web component to a plain HTML <table>."""
|
|
56
|
+
soup = BeautifulSoup(marimo_table_html, "lxml")
|
|
57
|
+
elem = soup.find("marimo-table")
|
|
58
|
+
if elem is None:
|
|
59
|
+
return marimo_table_html
|
|
60
|
+
|
|
61
|
+
data_data = elem.get("data-data", "[]")
|
|
62
|
+
field_types_raw = elem.get("data-field-types", "[]")
|
|
63
|
+
|
|
64
|
+
# data-data is a JSON-quoted string containing an array of row objects.
|
|
65
|
+
# It may contain literal NaN (not valid JSON).
|
|
66
|
+
try:
|
|
67
|
+
inner = json.loads(data_data) # unwrap outer JSON string
|
|
68
|
+
cleaned = inner.replace("NaN", "null")
|
|
69
|
+
rows = json.loads(cleaned)
|
|
70
|
+
except json.JSONDecodeError, AttributeError:
|
|
71
|
+
return marimo_table_html
|
|
72
|
+
|
|
73
|
+
try:
|
|
74
|
+
field_types = json.loads(field_types_raw)
|
|
75
|
+
columns = [ft[0] for ft in field_types]
|
|
76
|
+
except json.JSONDecodeError, IndexError:
|
|
77
|
+
columns = list(rows[0].keys()) if rows else []
|
|
78
|
+
|
|
79
|
+
def _cell(v: object) -> str:
|
|
80
|
+
return "" if v is None else escape(str(v))
|
|
81
|
+
|
|
82
|
+
header = "".join(f"<th>{escape(str(col))}</th>" for col in columns)
|
|
83
|
+
body_rows = "".join(
|
|
84
|
+
"<tr>" + "".join(f"<td>{_cell(row.get(col))}</td>" for col in columns) + "</tr>"
|
|
85
|
+
for row in rows
|
|
86
|
+
)
|
|
87
|
+
return f"<table><thead><tr>{header}</tr></thead><tbody>{body_rows}</tbody></table>"
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _classify_and_build(data: dict[str, str]) -> tuple[str, str] | None:
|
|
91
|
+
"""
|
|
92
|
+
Given the output data dict (MIME → value), return (output_type, raw_html)
|
|
93
|
+
or None if there is nothing renderable.
|
|
94
|
+
"""
|
|
95
|
+
# Figure: marimo mimebundle with image/png
|
|
96
|
+
bundle_raw = data.get("application/vnd.marimo+mimebundle")
|
|
97
|
+
if bundle_raw:
|
|
98
|
+
try:
|
|
99
|
+
bundle = json.loads(bundle_raw)
|
|
100
|
+
except json.JSONDecodeError:
|
|
101
|
+
bundle = {}
|
|
102
|
+
src = bundle.get("image/png")
|
|
103
|
+
if src:
|
|
104
|
+
return "figure", f'<img src="{escape(src, quote=True)}" alt="figure">'
|
|
105
|
+
|
|
106
|
+
# HTML output (may be a marimo-table web component)
|
|
107
|
+
html_val = data.get("text/html")
|
|
108
|
+
if html_val:
|
|
109
|
+
decoded = unescape(html_val)
|
|
110
|
+
if "<marimo-table" in decoded:
|
|
111
|
+
table_html = _table_html_from_marimo_table(decoded)
|
|
112
|
+
return "table", table_html
|
|
113
|
+
# Generic HTML (e.g. styled dataframe rendered as <table>)
|
|
114
|
+
if "<table" in decoded:
|
|
115
|
+
return "table", decoded
|
|
116
|
+
return "unknown", decoded
|
|
117
|
+
|
|
118
|
+
plain = data.get("text/plain", "")
|
|
119
|
+
if plain and plain.strip():
|
|
120
|
+
return "text", f"<pre>{escape(plain)}</pre>"
|
|
121
|
+
|
|
122
|
+
return None
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def extract_outputs(html: bytes, target_hashes: set[str]) -> dict[str, ExtractedOutput]:
|
|
126
|
+
"""Extract rendered outputs from the marimo HTML export.
|
|
127
|
+
|
|
128
|
+
Returns a dict mapping source_hash → ExtractedOutput for each cell whose
|
|
129
|
+
code_hash is in target_hashes and that has a renderable output.
|
|
130
|
+
"""
|
|
131
|
+
cells_raw = _extract_session_cells_raw(html)
|
|
132
|
+
try:
|
|
133
|
+
cells = json.loads(cells_raw)
|
|
134
|
+
except json.JSONDecodeError:
|
|
135
|
+
return {}
|
|
136
|
+
|
|
137
|
+
results: dict[str, ExtractedOutput] = {}
|
|
138
|
+
|
|
139
|
+
for cell in cells:
|
|
140
|
+
code_hash = cell.get("code_hash")
|
|
141
|
+
if code_hash not in target_hashes:
|
|
142
|
+
continue
|
|
143
|
+
|
|
144
|
+
stdout = "".join(
|
|
145
|
+
c.get("text", "")
|
|
146
|
+
for c in cell.get("console", [])
|
|
147
|
+
if c.get("name") == "stdout"
|
|
148
|
+
)
|
|
149
|
+
console_html = f"<pre>{escape(stdout)}</pre>" if stdout.strip() else ""
|
|
150
|
+
|
|
151
|
+
raw_html = ""
|
|
152
|
+
output_type = "unknown"
|
|
153
|
+
for output in cell.get("outputs", []):
|
|
154
|
+
data = output.get("data", {})
|
|
155
|
+
classified = _classify_and_build(data)
|
|
156
|
+
if classified is None:
|
|
157
|
+
continue
|
|
158
|
+
output_type, raw_html = classified
|
|
159
|
+
break # take the first renderable output per cell
|
|
160
|
+
|
|
161
|
+
if not console_html and not raw_html:
|
|
162
|
+
continue
|
|
163
|
+
|
|
164
|
+
# label is filled in by inject.py after matching; use hash as placeholder
|
|
165
|
+
results[code_hash] = ExtractedOutput(
|
|
166
|
+
label=code_hash,
|
|
167
|
+
raw_html=raw_html,
|
|
168
|
+
output_type=output_type,
|
|
169
|
+
console_html=console_html,
|
|
170
|
+
)
|
|
171
|
+
|
|
172
|
+
return results
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import hashlib
|
|
2
|
+
import re
|
|
3
|
+
|
|
4
|
+
from .models import MarkedCell
|
|
5
|
+
|
|
6
|
+
# Matches fenced code blocks produced by `marimo export md`
|
|
7
|
+
_BLOCK_RE = re.compile(r"(```python \{\.marimo\}\n(.*?)```)", re.DOTALL)
|
|
8
|
+
_MARKER_RE = re.compile(r"#\s*@output:\s*(\S+)")
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def _md5(text: str) -> str:
|
|
12
|
+
return hashlib.md5(text.encode("utf-8"), usedforsecurity=False).hexdigest()
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def collect_marked_cells(md: str) -> list[MarkedCell]:
|
|
16
|
+
"""Return one MarkedCell for each fenced block that contains an @output marker."""
|
|
17
|
+
seen_labels: dict[str, int] = {}
|
|
18
|
+
results: list[MarkedCell] = []
|
|
19
|
+
|
|
20
|
+
for block_match in _BLOCK_RE.finditer(md):
|
|
21
|
+
block_text = block_match.group(1)
|
|
22
|
+
source = block_match.group(2)
|
|
23
|
+
|
|
24
|
+
marker = _MARKER_RE.search(source)
|
|
25
|
+
if marker is None:
|
|
26
|
+
continue
|
|
27
|
+
|
|
28
|
+
label = marker.group(1)
|
|
29
|
+
if label in seen_labels:
|
|
30
|
+
raise ValueError(
|
|
31
|
+
f"Duplicate @output label {label!r} — each label must be unique"
|
|
32
|
+
)
|
|
33
|
+
seen_labels[label] = 1
|
|
34
|
+
|
|
35
|
+
results.append(
|
|
36
|
+
MarkedCell(
|
|
37
|
+
label=label,
|
|
38
|
+
source=source,
|
|
39
|
+
source_hash=_md5(source.strip()),
|
|
40
|
+
block_text=block_text,
|
|
41
|
+
)
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
return results
|