marimo-md-export 0.2.0__tar.gz → 0.4.2__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.4.2/PKG-INFO +87 -0
- marimo_md_export-0.4.2/README.md +61 -0
- {marimo_md_export-0.2.0 → marimo_md_export-0.4.2}/pyproject.toml +4 -1
- {marimo_md_export-0.2.0 → marimo_md_export-0.4.2}/src/marimo_md_export/cli.py +16 -25
- {marimo_md_export-0.2.0 → marimo_md_export-0.4.2}/src/marimo_md_export/export.py +63 -13
- marimo_md_export-0.4.2/src/marimo_md_export/inject.py +109 -0
- {marimo_md_export-0.2.0 → marimo_md_export-0.4.2}/src/marimo_md_export/models.py +7 -6
- marimo_md_export-0.4.2/src/marimo_md_export/parse_html.py +381 -0
- marimo_md_export-0.4.2/src/marimo_md_export/parse_md.py +34 -0
- marimo_md_export-0.2.0/PKG-INFO +0 -60
- marimo_md_export-0.2.0/README.md +0 -37
- marimo_md_export-0.2.0/src/marimo_md_export/inject.py +0 -88
- marimo_md_export-0.2.0/src/marimo_md_export/parse_html.py +0 -181
- marimo_md_export-0.2.0/src/marimo_md_export/parse_md.py +0 -44
- {marimo_md_export-0.2.0 → marimo_md_export-0.4.2}/LICENSE +0 -0
- {marimo_md_export-0.2.0 → marimo_md_export-0.4.2}/src/marimo_md_export/__init__.py +0 -0
- {marimo_md_export-0.2.0 → marimo_md_export-0.4.2}/src/marimo_md_export/__main__.py +0 -0
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: marimo-md-export
|
|
3
|
+
Version: 0.4.2
|
|
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: Programming Language :: Python :: 3.12
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
15
|
+
Classifier: Topic :: Documentation
|
|
16
|
+
Classifier: Topic :: Text Processing :: Markup :: Markdown
|
|
17
|
+
Requires-Dist: beautifulsoup4>=4.14.3
|
|
18
|
+
Requires-Dist: lxml>=6.1.0
|
|
19
|
+
Requires-Dist: marimo>=0.23.3
|
|
20
|
+
Requires-Dist: typer>=0.25.0
|
|
21
|
+
Requires-Python: >=3.12
|
|
22
|
+
Project-URL: Homepage, https://jmarshrossney.github.io/marimo-md-export
|
|
23
|
+
Project-URL: Repository, https://github.com/jmarshrossney/marimo-md-export
|
|
24
|
+
Project-URL: Documentation, https://jmarshrossney.github.io/marimo-md-export
|
|
25
|
+
Description-Content-Type: text/markdown
|
|
26
|
+
|
|
27
|
+
# marimo-md-export
|
|
28
|
+
|
|
29
|
+
[](https://pypi.org/project/marimo-md-export/)
|
|
30
|
+
[](https://pypi.org/project/marimo-md-export/)
|
|
31
|
+
[](https://github.com/jmarshrossney/marimo-md-export/blob/main/LICENSE)
|
|
32
|
+
[](https://github.com/jmarshrossney/marimo-md-export/actions/workflows/ci.yml)
|
|
33
|
+
[](https://jmarshrossney.github.io/marimo-md-export)
|
|
34
|
+
|
|
35
|
+
A `uv` tool that wraps `marimo export`, extracts rendered outputs from the HTML export,
|
|
36
|
+
and injects them into the markdown export. The result is a self-contained markdown
|
|
37
|
+
document with embedded figures (as base64 `<img>` tags), tables (as GFM or HTML), and other cell outputs.
|
|
38
|
+
|
|
39
|
+
**[Full documentation](https://jmarshrossney.github.io/marimo-md-export)**
|
|
40
|
+
|
|
41
|
+
## Quick start
|
|
42
|
+
|
|
43
|
+
Write your marimo `.py` notebook — cell outputs are rendered by default:
|
|
44
|
+
|
|
45
|
+
```python
|
|
46
|
+
fig, ax = plt.subplots()
|
|
47
|
+
ax.plot(x, np.sin(x))
|
|
48
|
+
fig
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
Then run:
|
|
52
|
+
|
|
53
|
+
```sh
|
|
54
|
+
uvx marimo-md-export notebook.py output.md
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
## Integrating with documentation sites
|
|
58
|
+
|
|
59
|
+
`marimo-md-export` is designed to produce markdown pages for static site generators like
|
|
60
|
+
[mkdocs](https://www.mkdocs.org/) (Python) or
|
|
61
|
+
[zensical](https://zensical.org/) (Rust). Both work identically for this purpose.
|
|
62
|
+
|
|
63
|
+
**1. Add as a docs dependency:**
|
|
64
|
+
|
|
65
|
+
```sh
|
|
66
|
+
uv add --group docs marimo-md-export
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
**2. Add a build step** that converts your notebook(s) before building the site.
|
|
70
|
+
|
|
71
|
+
For example, this project uses the following [just](https://github.com/casey/just) command to build the docs:
|
|
72
|
+
|
|
73
|
+
```just
|
|
74
|
+
docs:
|
|
75
|
+
marimo-md-export examples/notebook.py docs/example.md
|
|
76
|
+
zensical build
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
This runs `marimo-md-export` to produce a self-contained markdown page (with cell
|
|
80
|
+
outputs injected), then builds the site.
|
|
81
|
+
|
|
82
|
+
## Development
|
|
83
|
+
|
|
84
|
+
```sh
|
|
85
|
+
uv sync # sync packages
|
|
86
|
+
just # run lint, typecheck, test, build docs
|
|
87
|
+
```
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
# marimo-md-export
|
|
2
|
+
|
|
3
|
+
[](https://pypi.org/project/marimo-md-export/)
|
|
4
|
+
[](https://pypi.org/project/marimo-md-export/)
|
|
5
|
+
[](https://github.com/jmarshrossney/marimo-md-export/blob/main/LICENSE)
|
|
6
|
+
[](https://github.com/jmarshrossney/marimo-md-export/actions/workflows/ci.yml)
|
|
7
|
+
[](https://jmarshrossney.github.io/marimo-md-export)
|
|
8
|
+
|
|
9
|
+
A `uv` tool that wraps `marimo export`, extracts rendered outputs from the HTML export,
|
|
10
|
+
and injects them into the markdown export. The result is a self-contained markdown
|
|
11
|
+
document with embedded figures (as base64 `<img>` tags), tables (as GFM or HTML), and other cell outputs.
|
|
12
|
+
|
|
13
|
+
**[Full documentation](https://jmarshrossney.github.io/marimo-md-export)**
|
|
14
|
+
|
|
15
|
+
## Quick start
|
|
16
|
+
|
|
17
|
+
Write your marimo `.py` notebook — cell outputs are rendered by default:
|
|
18
|
+
|
|
19
|
+
```python
|
|
20
|
+
fig, ax = plt.subplots()
|
|
21
|
+
ax.plot(x, np.sin(x))
|
|
22
|
+
fig
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
Then run:
|
|
26
|
+
|
|
27
|
+
```sh
|
|
28
|
+
uvx marimo-md-export notebook.py output.md
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
## Integrating with documentation sites
|
|
32
|
+
|
|
33
|
+
`marimo-md-export` is designed to produce markdown pages for static site generators like
|
|
34
|
+
[mkdocs](https://www.mkdocs.org/) (Python) or
|
|
35
|
+
[zensical](https://zensical.org/) (Rust). Both work identically for this purpose.
|
|
36
|
+
|
|
37
|
+
**1. Add as a docs dependency:**
|
|
38
|
+
|
|
39
|
+
```sh
|
|
40
|
+
uv add --group docs marimo-md-export
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
**2. Add a build step** that converts your notebook(s) before building the site.
|
|
44
|
+
|
|
45
|
+
For example, this project uses the following [just](https://github.com/casey/just) command to build the docs:
|
|
46
|
+
|
|
47
|
+
```just
|
|
48
|
+
docs:
|
|
49
|
+
marimo-md-export examples/notebook.py docs/example.md
|
|
50
|
+
zensical build
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
This runs `marimo-md-export` to produce a self-contained markdown page (with cell
|
|
54
|
+
outputs injected), then builds the site.
|
|
55
|
+
|
|
56
|
+
## Development
|
|
57
|
+
|
|
58
|
+
```sh
|
|
59
|
+
uv sync # sync packages
|
|
60
|
+
just # run lint, typecheck, test, build docs
|
|
61
|
+
```
|
|
@@ -4,7 +4,7 @@ build-backend = "uv_build"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "marimo-md-export"
|
|
7
|
-
version = "0.2
|
|
7
|
+
version = "0.4.2"
|
|
8
8
|
description = "A minimal solution for exporting marimo notebooks to markdown *with* rendered HTML outputs, designed for mkdocs/zensical sites."
|
|
9
9
|
authors = [
|
|
10
10
|
{ name = "jmarshrossney", email = "17361029+jmarshrossney@users.noreply.github.com" }
|
|
@@ -23,6 +23,9 @@ keywords = ["marimo", "markdown", "documentation"]
|
|
|
23
23
|
classifiers = [
|
|
24
24
|
"Development Status :: 3 - Alpha",
|
|
25
25
|
"Intended Audience :: Developers",
|
|
26
|
+
"Programming Language :: Python :: 3.12",
|
|
27
|
+
"Programming Language :: Python :: 3.13",
|
|
28
|
+
"Programming Language :: Python :: 3.14",
|
|
26
29
|
"Topic :: Documentation",
|
|
27
30
|
"Topic :: Text Processing :: Markup :: Markdown",
|
|
28
31
|
]
|
|
@@ -1,11 +1,14 @@
|
|
|
1
1
|
from pathlib import Path
|
|
2
2
|
|
|
3
3
|
import typer
|
|
4
|
+
from rich.console import Console
|
|
4
5
|
|
|
5
6
|
from .export import export_html, export_md, strip_header_from_frontmatter
|
|
6
7
|
from .inject import inject_outputs
|
|
7
8
|
from .parse_html import extract_outputs
|
|
8
|
-
from .parse_md import
|
|
9
|
+
from .parse_md import collect_cells
|
|
10
|
+
|
|
11
|
+
_err_console = Console(stderr=True)
|
|
9
12
|
|
|
10
13
|
app = typer.Typer(
|
|
11
14
|
help="Export a marimo (.py) notebook to markdown (.md) with rendered outputs embedded inline.",
|
|
@@ -47,11 +50,11 @@ def main(
|
|
|
47
50
|
help="Run marimo export in an isolated uv environment. "
|
|
48
51
|
"Without this flag, marimo's own sandbox prompt is suppressed.",
|
|
49
52
|
),
|
|
50
|
-
timeout: int = typer.Option(
|
|
51
|
-
|
|
53
|
+
timeout: int | None = typer.Option(
|
|
54
|
+
None,
|
|
52
55
|
"--timeout",
|
|
53
56
|
help="Maximum seconds to wait for each marimo export subprocess "
|
|
54
|
-
"(
|
|
57
|
+
"(default: no timeout).",
|
|
55
58
|
),
|
|
56
59
|
) -> None:
|
|
57
60
|
"""Export a marimo notebook to markdown with rendered outputs injected.
|
|
@@ -62,7 +65,7 @@ def main(
|
|
|
62
65
|
in an isolated uv environment.
|
|
63
66
|
"""
|
|
64
67
|
extra = marimo_args.split() if marimo_args.strip() else []
|
|
65
|
-
timeout_val = timeout or None
|
|
68
|
+
timeout_val: int | None = timeout or None
|
|
66
69
|
|
|
67
70
|
if verbose:
|
|
68
71
|
typer.echo(f"Exporting markdown: {notebook}")
|
|
@@ -72,20 +75,12 @@ def main(
|
|
|
72
75
|
typer.echo(f"marimo export md failed:\n{exc}", err=True)
|
|
73
76
|
raise typer.Exit(1)
|
|
74
77
|
|
|
75
|
-
|
|
76
|
-
if not marked:
|
|
77
|
-
typer.echo(
|
|
78
|
-
f"WARNING: no @output markers found in {notebook}. "
|
|
79
|
-
"Did you forget to add '# @output: <label>' comments?",
|
|
80
|
-
err=True,
|
|
81
|
-
)
|
|
82
|
-
raise typer.Exit(2)
|
|
78
|
+
cells = collect_cells(md)
|
|
83
79
|
|
|
84
80
|
if verbose:
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
)
|
|
81
|
+
n_active = sum(1 for c in cells if not c.suppressed)
|
|
82
|
+
n_suppressed = sum(1 for c in cells if c.suppressed)
|
|
83
|
+
typer.echo(f"Found {n_active} cell(s), {n_suppressed} suppressed")
|
|
89
84
|
typer.echo(f"Exporting HTML: {notebook}")
|
|
90
85
|
|
|
91
86
|
try:
|
|
@@ -100,15 +95,11 @@ def main(
|
|
|
100
95
|
if verbose:
|
|
101
96
|
typer.echo(f"Wrote {html_output}")
|
|
102
97
|
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
# Attach labels to outputs
|
|
107
|
-
for cell in marked:
|
|
108
|
-
if cell.source_hash in outputs:
|
|
109
|
-
outputs[cell.source_hash].label = cell.label
|
|
98
|
+
outputs = extract_outputs(html)
|
|
99
|
+
result, warnings = inject_outputs(md, cells, outputs)
|
|
110
100
|
|
|
111
|
-
|
|
101
|
+
for warning in warnings:
|
|
102
|
+
_err_console.print(f"WARNING: {warning}", style="bold yellow")
|
|
112
103
|
|
|
113
104
|
result = strip_header_from_frontmatter(result)
|
|
114
105
|
|
|
@@ -1,16 +1,50 @@
|
|
|
1
1
|
import os
|
|
2
|
-
import re
|
|
3
2
|
import subprocess
|
|
4
3
|
import sys
|
|
5
4
|
import tempfile
|
|
6
5
|
import threading
|
|
7
6
|
from pathlib import Path
|
|
8
7
|
|
|
9
|
-
|
|
8
|
+
|
|
9
|
+
def _strip_header_key(frontmatter: str) -> str | None:
|
|
10
|
+
"""Remove the 'header:' key (with its multiline value) from a YAML frontmatter block.
|
|
11
|
+
|
|
12
|
+
Returns None if the header key was not found. Handles YAML block scalars
|
|
13
|
+
(|-, |, >-, >) and plain multiline values (indented continuation lines).
|
|
14
|
+
"""
|
|
15
|
+
lines = frontmatter.split("\n")
|
|
16
|
+
result_lines: list[str] = []
|
|
17
|
+
i = 0
|
|
18
|
+
found = False
|
|
19
|
+
while i < len(lines):
|
|
20
|
+
line = lines[i]
|
|
21
|
+
stripped = line.lstrip()
|
|
22
|
+
if not stripped.startswith("header:"):
|
|
23
|
+
result_lines.append(line)
|
|
24
|
+
i += 1
|
|
25
|
+
continue
|
|
26
|
+
|
|
27
|
+
found = True
|
|
28
|
+
value_part = line[len("header:") :].strip()
|
|
29
|
+
# Detect block scalar indicators: |, |-, >, >-
|
|
30
|
+
is_block = value_part in ("|", "|-", ">", ">-")
|
|
31
|
+
if is_block:
|
|
32
|
+
# Skip indented continuation lines
|
|
33
|
+
i += 1
|
|
34
|
+
while i < len(lines) and lines[i].startswith((" ", "\t")):
|
|
35
|
+
i += 1
|
|
36
|
+
else:
|
|
37
|
+
# Plain value (possibly none after the colon)
|
|
38
|
+
i += 1
|
|
39
|
+
|
|
40
|
+
if not found:
|
|
41
|
+
return None
|
|
42
|
+
|
|
43
|
+
return "\n".join(result_lines)
|
|
10
44
|
|
|
11
45
|
|
|
12
46
|
def _run_with_visible_output(
|
|
13
|
-
cmd: list[str], *, env: dict[str, str], timeout:
|
|
47
|
+
cmd: list[str], *, env: dict[str, str], timeout: int | None
|
|
14
48
|
) -> subprocess.CompletedProcess[str]:
|
|
15
49
|
"""Run *cmd* with stdout inherited (visible) and stderr captured."""
|
|
16
50
|
stderr_lines: list[str] = []
|
|
@@ -42,7 +76,7 @@ def export_html(
|
|
|
42
76
|
notebook: Path,
|
|
43
77
|
extra_args: list[str] | None = None,
|
|
44
78
|
sandbox: bool = False,
|
|
45
|
-
timeout:
|
|
79
|
+
timeout: int | None = 120,
|
|
46
80
|
) -> bytes:
|
|
47
81
|
with tempfile.NamedTemporaryFile(suffix=".html", delete=False) as f:
|
|
48
82
|
tmp = Path(f.name)
|
|
@@ -72,9 +106,12 @@ def export_html(
|
|
|
72
106
|
f"marimo export html timed out after {timeout}s.\n"
|
|
73
107
|
"Try passing --sandbox to run in an isolated environment."
|
|
74
108
|
)
|
|
75
|
-
if result.returncode
|
|
109
|
+
if result.returncode not in (0, 1):
|
|
110
|
+
raise RuntimeError(f"marimo export html failed:\n{result.stderr}")
|
|
111
|
+
html = tmp.read_bytes()
|
|
112
|
+
if result.returncode == 1 and not html:
|
|
76
113
|
raise RuntimeError(f"marimo export html failed:\n{result.stderr}")
|
|
77
|
-
return
|
|
114
|
+
return html
|
|
78
115
|
finally:
|
|
79
116
|
tmp.unlink(missing_ok=True)
|
|
80
117
|
|
|
@@ -82,7 +119,7 @@ def export_html(
|
|
|
82
119
|
def export_md(
|
|
83
120
|
notebook: Path,
|
|
84
121
|
sandbox: bool = False,
|
|
85
|
-
timeout:
|
|
122
|
+
timeout: int | None = 120,
|
|
86
123
|
) -> str:
|
|
87
124
|
with tempfile.NamedTemporaryFile(suffix=".md", delete=False) as f:
|
|
88
125
|
tmp = Path(f.name)
|
|
@@ -100,15 +137,25 @@ def export_md(
|
|
|
100
137
|
f"marimo export md timed out after {timeout}s.\n"
|
|
101
138
|
"Try passing --sandbox to run in an isolated environment."
|
|
102
139
|
)
|
|
103
|
-
if result.returncode
|
|
140
|
+
if result.returncode not in (0, 1):
|
|
141
|
+
raise RuntimeError(f"marimo export md failed:\n{result.stderr}")
|
|
142
|
+
md = tmp.read_text(encoding="utf-8")
|
|
143
|
+
if result.returncode == 1 and not md:
|
|
104
144
|
raise RuntimeError(f"marimo export md failed:\n{result.stderr}")
|
|
105
|
-
return
|
|
145
|
+
return md
|
|
106
146
|
finally:
|
|
107
147
|
tmp.unlink(missing_ok=True)
|
|
108
148
|
|
|
109
149
|
|
|
110
150
|
def strip_header_from_frontmatter(md: str) -> str:
|
|
111
|
-
"""Remove the 'header:' key from YAML frontmatter if present.
|
|
151
|
+
"""Remove the 'header:' key from YAML frontmatter if present.
|
|
152
|
+
|
|
153
|
+
Parses the frontmatter line-by-line, removes the header key (including
|
|
154
|
+
any multiline block-scalar or indented continuation lines), then
|
|
155
|
+
reconstructs the frontmatter. If only a title key remains, it is
|
|
156
|
+
preserved cleanly. If the frontmatter is empty after removal, it is
|
|
157
|
+
dropped entirely.
|
|
158
|
+
"""
|
|
112
159
|
if not md.startswith("---"):
|
|
113
160
|
return md
|
|
114
161
|
|
|
@@ -123,11 +170,14 @@ def strip_header_from_frontmatter(md: str) -> str:
|
|
|
123
170
|
frontmatter = md[:after_close]
|
|
124
171
|
rest = md[after_close:]
|
|
125
172
|
|
|
126
|
-
stripped =
|
|
127
|
-
if stripped
|
|
173
|
+
stripped = _strip_header_key(frontmatter)
|
|
174
|
+
if stripped is None:
|
|
128
175
|
return md
|
|
129
176
|
|
|
130
|
-
|
|
177
|
+
inner_start = len("---\n")
|
|
178
|
+
inner_end = stripped.rfind("\n---")
|
|
179
|
+
inner = stripped[inner_start:inner_end]
|
|
180
|
+
|
|
131
181
|
if not inner.strip():
|
|
132
182
|
return rest.lstrip("\n")
|
|
133
183
|
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import re
|
|
2
|
+
|
|
3
|
+
from bs4 import BeautifulSoup
|
|
4
|
+
|
|
5
|
+
from .models import Cell, ExtractedOutput
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def _table_to_gfm(html: str) -> str | None:
|
|
9
|
+
"""Convert a plain HTML <table> to GFM markdown, or return None on failure."""
|
|
10
|
+
soup = BeautifulSoup(html, "lxml")
|
|
11
|
+
table = soup.find("table")
|
|
12
|
+
if table is None:
|
|
13
|
+
return None
|
|
14
|
+
|
|
15
|
+
# Reject tables with merged cells — fall back to HTML
|
|
16
|
+
if table.find(attrs={"colspan": True}) or table.find(attrs={"rowspan": True}):
|
|
17
|
+
return None
|
|
18
|
+
|
|
19
|
+
rows: list[list[str]] = []
|
|
20
|
+
for tr in table.find_all("tr"):
|
|
21
|
+
cells = [td.get_text(strip=True) for td in tr.find_all(["th", "td"])]
|
|
22
|
+
rows.append(cells)
|
|
23
|
+
|
|
24
|
+
if not rows:
|
|
25
|
+
return None
|
|
26
|
+
|
|
27
|
+
header = rows[0]
|
|
28
|
+
body = rows[1:]
|
|
29
|
+
|
|
30
|
+
# Reject tables with inconsistent row widths — fall back to HTML
|
|
31
|
+
ncols = len(header)
|
|
32
|
+
if any(len(row) != ncols for row in rows):
|
|
33
|
+
return None
|
|
34
|
+
|
|
35
|
+
sep = ["---"] * ncols
|
|
36
|
+
|
|
37
|
+
def _row(cells: list[str]) -> str:
|
|
38
|
+
escaped = [c.replace("|", "\\|") for c in cells]
|
|
39
|
+
return "| " + " | ".join(escaped) + " |"
|
|
40
|
+
|
|
41
|
+
lines = [_row(header), _row(sep), *(_row(r) for r in body)]
|
|
42
|
+
return "\n".join(lines)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _escape_brackets(text: str) -> str:
|
|
46
|
+
return text.replace("[", "[").replace("]", "]")
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _escape_brackets_in_pre(html: str) -> str:
|
|
50
|
+
return re.sub(
|
|
51
|
+
r"(<pre[^>]*>)(.*?)(</pre>)",
|
|
52
|
+
lambda m: m.group(1) + _escape_brackets(m.group(2)) + m.group(3),
|
|
53
|
+
html,
|
|
54
|
+
flags=re.DOTALL,
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _format_output(output: ExtractedOutput) -> str:
|
|
59
|
+
comment = f"<!-- @output:{output.cell_id} -->"
|
|
60
|
+
|
|
61
|
+
parts = []
|
|
62
|
+
if output.console_html:
|
|
63
|
+
parts.append(_escape_brackets_in_pre(output.console_html))
|
|
64
|
+
if output.stderr_html:
|
|
65
|
+
parts.append(_escape_brackets_in_pre(output.stderr_html))
|
|
66
|
+
if output.media_html:
|
|
67
|
+
parts.append(_escape_brackets_in_pre(output.media_html))
|
|
68
|
+
if output.raw_html:
|
|
69
|
+
if output.output_type == "table":
|
|
70
|
+
gfm = _table_to_gfm(output.raw_html)
|
|
71
|
+
parts.append(
|
|
72
|
+
gfm if gfm is not None else _escape_brackets_in_pre(output.raw_html)
|
|
73
|
+
)
|
|
74
|
+
else:
|
|
75
|
+
parts.append(_escape_brackets_in_pre(output.raw_html))
|
|
76
|
+
|
|
77
|
+
return comment + "\n\n" + "\n\n".join(parts)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def inject_outputs(
|
|
81
|
+
md: str,
|
|
82
|
+
cells: list[Cell],
|
|
83
|
+
outputs: dict[str, ExtractedOutput],
|
|
84
|
+
) -> tuple[str, list[str]]:
|
|
85
|
+
"""Inject rendered outputs into the markdown after each code block.
|
|
86
|
+
|
|
87
|
+
cells should come from collect_cells(md). outputs maps
|
|
88
|
+
source_hash → ExtractedOutput. Cell IDs from the HTML export are used
|
|
89
|
+
as labels in the output anchor comments.
|
|
90
|
+
|
|
91
|
+
Returns (result_markdown, warnings) where warnings is a list of
|
|
92
|
+
human-readable messages.
|
|
93
|
+
"""
|
|
94
|
+
result = md
|
|
95
|
+
warnings: list[str] = []
|
|
96
|
+
for cell in cells:
|
|
97
|
+
if cell.suppressed:
|
|
98
|
+
continue
|
|
99
|
+
matched = outputs.get(cell.source_hash)
|
|
100
|
+
if matched is None:
|
|
101
|
+
# No renderable output — expected for import/setup cells
|
|
102
|
+
continue
|
|
103
|
+
|
|
104
|
+
formatted = _format_output(matched)
|
|
105
|
+
result = result.replace(
|
|
106
|
+
cell.block_text, cell.block_text + "\n\n" + formatted, 1
|
|
107
|
+
)
|
|
108
|
+
|
|
109
|
+
return result, warnings
|
|
@@ -2,21 +2,22 @@ from dataclasses import dataclass, field
|
|
|
2
2
|
|
|
3
3
|
|
|
4
4
|
@dataclass
|
|
5
|
-
class
|
|
6
|
-
"""A fenced code block in the markdown
|
|
5
|
+
class Cell:
|
|
6
|
+
"""A fenced code block in the markdown export."""
|
|
7
7
|
|
|
8
|
-
label: str
|
|
9
8
|
source: str
|
|
10
|
-
# MD5 hex digest of source.strip() — matches marimo's code_hash in HTML export
|
|
11
9
|
source_hash: str
|
|
12
10
|
block_text: str
|
|
11
|
+
suppressed: bool = False
|
|
13
12
|
|
|
14
13
|
|
|
15
14
|
@dataclass
|
|
16
15
|
class ExtractedOutput:
|
|
17
16
|
"""The rendered output scraped from the HTML export for one cell."""
|
|
18
17
|
|
|
19
|
-
label: str
|
|
20
18
|
raw_html: str
|
|
21
|
-
output_type: str
|
|
19
|
+
output_type: str
|
|
20
|
+
cell_id: str = ""
|
|
22
21
|
console_html: str = field(default="")
|
|
22
|
+
stderr_html: str = field(default="")
|
|
23
|
+
media_html: str = field(default="")
|
|
@@ -0,0 +1,381 @@
|
|
|
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
|
+
# .id — marimo's internal cell identifier (e.g. "aaa", "bbb")
|
|
10
|
+
# .outputs[]
|
|
11
|
+
# .type — "data" or "error"
|
|
12
|
+
# .data — dict of MIME type → value (for type "data")
|
|
13
|
+
# .ename — exception class name (for type "error")
|
|
14
|
+
# .evalue — exception message (for type "error")
|
|
15
|
+
# .traceback — list of traceback lines (for type "error")
|
|
16
|
+
# .console[]
|
|
17
|
+
# .name — "stdout" or "stderr"
|
|
18
|
+
# .text — console text content
|
|
19
|
+
#
|
|
20
|
+
# Supported MIME types:
|
|
21
|
+
# application/vnd.marimo+mimebundle — JSON string; may contain image/png, image/svg+xml, text/html, text/plain
|
|
22
|
+
# image/* — standalone image outputs (png, jpeg, svg+xml, etc.)
|
|
23
|
+
# application/json — pretty-printed JSON (dicts, lists, etc.)
|
|
24
|
+
# text/latex — LaTeX math (wrapped in $$ delimiters)
|
|
25
|
+
# text/csv — CSV data (rendered as code block)
|
|
26
|
+
# text/html — may contain <marimo-table> web component
|
|
27
|
+
# text/markdown — rendered markdown (placeholder comment; already in MD export)
|
|
28
|
+
# text/plain — plain text
|
|
29
|
+
# Unsupported types (vega, jupyter widgets, etc.) produce a placeholder comment.
|
|
30
|
+
#
|
|
31
|
+
# Tables are stored as <marimo-table data-data='...'> web components.
|
|
32
|
+
# `data-data` is a JSON-quoted string of row objects; NaN appears literally.
|
|
33
|
+
|
|
34
|
+
import json
|
|
35
|
+
import re
|
|
36
|
+
from html import escape, unescape
|
|
37
|
+
|
|
38
|
+
from bs4 import BeautifulSoup
|
|
39
|
+
|
|
40
|
+
from .models import ExtractedOutput
|
|
41
|
+
|
|
42
|
+
_SESSION_CELLS_RE = re.compile(
|
|
43
|
+
r'"session"\s*:\s*\{"cells"\s*:\s*\[',
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
_decoder = json.JSONDecoder()
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _extract_session_cells_raw(html: bytes) -> str:
|
|
50
|
+
"""Return the raw JSON string for session.cells from the HTML.
|
|
51
|
+
|
|
52
|
+
Uses json.JSONDecoder.raw_decode to correctly handle brackets inside
|
|
53
|
+
JSON string values.
|
|
54
|
+
"""
|
|
55
|
+
text = html.decode("utf-8", errors="replace")
|
|
56
|
+
m = _SESSION_CELLS_RE.search(text)
|
|
57
|
+
if m is None:
|
|
58
|
+
return "[]"
|
|
59
|
+
|
|
60
|
+
start = m.end() - 1 # position of the opening '['
|
|
61
|
+
try:
|
|
62
|
+
_, end = _decoder.raw_decode(text, idx=start)
|
|
63
|
+
except json.JSONDecodeError:
|
|
64
|
+
return "[]"
|
|
65
|
+
|
|
66
|
+
return text[start:end]
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _table_html_from_marimo_table(marimo_table_html: str) -> str:
|
|
70
|
+
"""Convert a <marimo-table> web component to a plain HTML <table>."""
|
|
71
|
+
soup = BeautifulSoup(marimo_table_html, "lxml")
|
|
72
|
+
elem = soup.find("marimo-table")
|
|
73
|
+
if elem is None:
|
|
74
|
+
return marimo_table_html
|
|
75
|
+
|
|
76
|
+
# Variable names follow HTML data-* attribute naming (hyphenated → snake_case)
|
|
77
|
+
data_data_attr = elem.get("data-data")
|
|
78
|
+
if not isinstance(data_data_attr, str):
|
|
79
|
+
return marimo_table_html
|
|
80
|
+
data_data = data_data_attr
|
|
81
|
+
|
|
82
|
+
field_types_raw_attr = elem.get("data-field-types")
|
|
83
|
+
if isinstance(field_types_raw_attr, str):
|
|
84
|
+
field_types_raw = field_types_raw_attr
|
|
85
|
+
else:
|
|
86
|
+
field_types_raw = "[]"
|
|
87
|
+
|
|
88
|
+
# data-data is a JSON-quoted string containing an array of row objects.
|
|
89
|
+
# It may contain literal NaN (not valid JSON). Replace only bare NaN
|
|
90
|
+
# tokens (not inside quoted string values) to avoid clobbering strings
|
|
91
|
+
# like "NaN handling".
|
|
92
|
+
try:
|
|
93
|
+
inner = json.loads(data_data) # unwrap outer JSON string
|
|
94
|
+
cleaned = re.sub(r'(?<!")\bNaN\b(?!")', "null", inner)
|
|
95
|
+
rows = json.loads(cleaned)
|
|
96
|
+
except (json.JSONDecodeError, AttributeError):
|
|
97
|
+
return marimo_table_html
|
|
98
|
+
|
|
99
|
+
try:
|
|
100
|
+
field_types = json.loads(field_types_raw)
|
|
101
|
+
columns = [ft[0] for ft in field_types]
|
|
102
|
+
except (json.JSONDecodeError, IndexError):
|
|
103
|
+
columns = list(rows[0].keys()) if rows else []
|
|
104
|
+
|
|
105
|
+
def _cell(v: object) -> str:
|
|
106
|
+
return "" if v is None else escape(str(v))
|
|
107
|
+
|
|
108
|
+
header = "".join(f"<th>{escape(str(col))}</th>" for col in columns)
|
|
109
|
+
body_rows = "".join(
|
|
110
|
+
"<tr>" + "".join(f"<td>{_cell(row.get(col))}</td>" for col in columns) + "</tr>"
|
|
111
|
+
for row in rows
|
|
112
|
+
)
|
|
113
|
+
return f"<table><thead><tr>{header}</tr></thead><tbody>{body_rows}</tbody></table>"
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _html_to_plain_text(html_str: str) -> str:
|
|
117
|
+
"""Strip HTML markup from a string, leaving only plain text.
|
|
118
|
+
|
|
119
|
+
Used to clean Pygments-highlighted traceback output that marimo includes
|
|
120
|
+
in error-cell stderr entries.
|
|
121
|
+
"""
|
|
122
|
+
text = unescape(html_str)
|
|
123
|
+
text = re.sub(r"<[^>]+>", "", text)
|
|
124
|
+
return unescape(text)
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def _format_error(output: dict) -> str:
|
|
128
|
+
"""Format an error output as plain text in a <pre> block.
|
|
129
|
+
|
|
130
|
+
Error outputs have: ename, evalue, traceback fields.
|
|
131
|
+
The traceback may be None when marimo truncates it.
|
|
132
|
+
"""
|
|
133
|
+
ename = output.get("ename", "Error") or "Error"
|
|
134
|
+
evalue = output.get("evalue", "") or ""
|
|
135
|
+
traceback_lines = output.get("traceback") or []
|
|
136
|
+
traceback_text = "\n".join(traceback_lines)
|
|
137
|
+
if traceback_text.strip():
|
|
138
|
+
# Traceback lines may contain HTML markup from Pygments
|
|
139
|
+
traceback_text = _html_to_plain_text(traceback_text)
|
|
140
|
+
combined = f"{traceback_text}\n{ename}: {evalue}"
|
|
141
|
+
else:
|
|
142
|
+
combined = f"{ename}: {evalue}"
|
|
143
|
+
return f"<pre>{escape(combined)}</pre>"
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
_MARIMO_TYPE_RE = re.compile(r"^text/plain\+(\w+):(.*)$", re.DOTALL)
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _strip_marimo_type_prefixes(obj: object) -> object:
|
|
150
|
+
"""Recursively strip marimo type prefixes from JSON values.
|
|
151
|
+
|
|
152
|
+
Marimo encodes typed values as ``"text/plain+float:1.0"`` in
|
|
153
|
+
``application/json`` output. This helper converts them back to their
|
|
154
|
+
native Python types so the rendered JSON is clean.
|
|
155
|
+
"""
|
|
156
|
+
if isinstance(obj, str):
|
|
157
|
+
m = _MARIMO_TYPE_RE.match(obj)
|
|
158
|
+
if m:
|
|
159
|
+
type_tag, raw = m.group(1), m.group(2)
|
|
160
|
+
if type_tag == "float":
|
|
161
|
+
try:
|
|
162
|
+
return float(raw)
|
|
163
|
+
except ValueError:
|
|
164
|
+
return raw
|
|
165
|
+
if type_tag == "int":
|
|
166
|
+
try:
|
|
167
|
+
return int(raw)
|
|
168
|
+
except ValueError:
|
|
169
|
+
return raw
|
|
170
|
+
if type_tag == "bool":
|
|
171
|
+
return raw.lower() == "true"
|
|
172
|
+
if type_tag in ("none", "NoneType"):
|
|
173
|
+
return None
|
|
174
|
+
return raw
|
|
175
|
+
return obj
|
|
176
|
+
if isinstance(obj, list):
|
|
177
|
+
return [_strip_marimo_type_prefixes(item) for item in obj]
|
|
178
|
+
if isinstance(obj, dict):
|
|
179
|
+
return {k: _strip_marimo_type_prefixes(v) for k, v in obj.items()}
|
|
180
|
+
return obj
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def _classify_and_build(data: dict[str, str]) -> tuple[str, str] | None:
|
|
184
|
+
"""
|
|
185
|
+
Given the output data dict (MIME → value), return (output_type, raw_html)
|
|
186
|
+
or None if there is nothing renderable.
|
|
187
|
+
"""
|
|
188
|
+
# Figure: marimo mimebundle — try representations in priority order
|
|
189
|
+
bundle_raw = data.get("application/vnd.marimo+mimebundle")
|
|
190
|
+
if bundle_raw:
|
|
191
|
+
try:
|
|
192
|
+
bundle = json.loads(bundle_raw)
|
|
193
|
+
except json.JSONDecodeError:
|
|
194
|
+
bundle = {}
|
|
195
|
+
for mime_key in ("image/png", "image/svg+xml", "text/html", "text/plain"):
|
|
196
|
+
val = bundle.get(mime_key)
|
|
197
|
+
if val:
|
|
198
|
+
if mime_key.startswith("image/"):
|
|
199
|
+
return (
|
|
200
|
+
"figure",
|
|
201
|
+
f'<img src="{escape(val, quote=True)}" alt="{escape(mime_key.split("/")[1], quote=True)}">',
|
|
202
|
+
)
|
|
203
|
+
if mime_key == "text/html":
|
|
204
|
+
return "html", unescape(val)
|
|
205
|
+
if mime_key == "text/plain" and val.strip():
|
|
206
|
+
return "text", f"<pre>{escape(val)}</pre>"
|
|
207
|
+
|
|
208
|
+
# Standalone image MIME types
|
|
209
|
+
for mime_type in (
|
|
210
|
+
"image/png",
|
|
211
|
+
"image/jpeg",
|
|
212
|
+
"image/gif",
|
|
213
|
+
"image/svg+xml",
|
|
214
|
+
"image/tiff",
|
|
215
|
+
"image/avif",
|
|
216
|
+
"image/bmp",
|
|
217
|
+
"image/webp",
|
|
218
|
+
):
|
|
219
|
+
img_val = data.get(mime_type)
|
|
220
|
+
if img_val:
|
|
221
|
+
fmt = mime_type.split("/")[1]
|
|
222
|
+
return (
|
|
223
|
+
"figure",
|
|
224
|
+
f'<img src="{escape(img_val, quote=True)}" alt="{escape(fmt, quote=True)}">',
|
|
225
|
+
)
|
|
226
|
+
|
|
227
|
+
# JSON output (dicts, lists, tuples)
|
|
228
|
+
json_val = data.get("application/json")
|
|
229
|
+
if json_val:
|
|
230
|
+
try:
|
|
231
|
+
parsed = json.loads(json_val)
|
|
232
|
+
cleaned = _strip_marimo_type_prefixes(parsed)
|
|
233
|
+
formatted = json.dumps(cleaned, indent=2, ensure_ascii=False)
|
|
234
|
+
except (json.JSONDecodeError, TypeError):
|
|
235
|
+
formatted = json_val
|
|
236
|
+
return "json", f"<pre><code>{escape(formatted)}</code></pre>"
|
|
237
|
+
|
|
238
|
+
# LaTeX output — wrap in $$ delimiters for math rendering.
|
|
239
|
+
# NOTE: text/latex is a fallback MIME type and is not expected to appear
|
|
240
|
+
# in normal marimo usage. LaTeX in marimo is typically rendered inside
|
|
241
|
+
# mo.md() blocks, which produce text/markdown output (suppressed to avoid
|
|
242
|
+
# duplication with the markdown export). This handler exists for
|
|
243
|
+
# robustness in case a library emits standalone text/latex.
|
|
244
|
+
latex_val = data.get("text/latex", "")
|
|
245
|
+
if latex_val and latex_val.strip():
|
|
246
|
+
content = latex_val.strip()
|
|
247
|
+
if content.startswith("$$") and content.endswith("$$"):
|
|
248
|
+
return "latex", content
|
|
249
|
+
if (
|
|
250
|
+
content.startswith("$")
|
|
251
|
+
and content.endswith("$")
|
|
252
|
+
and not content.startswith("$$")
|
|
253
|
+
):
|
|
254
|
+
return "latex", f"${content[1:-1]}$"
|
|
255
|
+
return "latex", f"$$\n{content}\n$$"
|
|
256
|
+
|
|
257
|
+
# CSV output — render as a plain text code block
|
|
258
|
+
csv_val = data.get("text/csv", "")
|
|
259
|
+
if csv_val and csv_val.strip():
|
|
260
|
+
return "csv", f"<pre><code>{escape(csv_val)}</code></pre>"
|
|
261
|
+
|
|
262
|
+
# HTML output (may be a marimo-table web component)
|
|
263
|
+
html_val = data.get("text/html")
|
|
264
|
+
if html_val:
|
|
265
|
+
decoded = unescape(html_val)
|
|
266
|
+
if "<marimo-table" in decoded:
|
|
267
|
+
table_html = _table_html_from_marimo_table(decoded)
|
|
268
|
+
return "table", table_html
|
|
269
|
+
# Generic HTML (e.g. styled dataframe rendered as <table>)
|
|
270
|
+
if "<table" in decoded:
|
|
271
|
+
return "table", decoded
|
|
272
|
+
return "html", decoded
|
|
273
|
+
|
|
274
|
+
plain = data.get("text/plain", "")
|
|
275
|
+
if plain and plain.strip():
|
|
276
|
+
return "text", f"<pre>{escape(plain)}</pre>"
|
|
277
|
+
|
|
278
|
+
# Unsupported MIME types — leave a comment for debugging
|
|
279
|
+
unsupported = {
|
|
280
|
+
"application/vnd.vega.v5+json",
|
|
281
|
+
"application/vnd.vega.v6+json",
|
|
282
|
+
"application/vnd.vegalite.v5+json",
|
|
283
|
+
"application/vnd.vegalite.v6+json",
|
|
284
|
+
"application/vnd.jupyter.widget-view+json",
|
|
285
|
+
"text/markdown",
|
|
286
|
+
"text/password",
|
|
287
|
+
}
|
|
288
|
+
for mime_type in unsupported:
|
|
289
|
+
if mime_type in data:
|
|
290
|
+
return (
|
|
291
|
+
"unsupported",
|
|
292
|
+
f"<!-- unsupported output type: {escape(mime_type)} -->",
|
|
293
|
+
)
|
|
294
|
+
|
|
295
|
+
return None
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
def extract_outputs(html: bytes) -> dict[str, ExtractedOutput]:
|
|
299
|
+
"""Extract rendered outputs from the marimo HTML export.
|
|
300
|
+
|
|
301
|
+
Returns a dict mapping source_hash → ExtractedOutput for each cell
|
|
302
|
+
that has a renderable output. The cell_id is populated from marimo's
|
|
303
|
+
internal cell identifier.
|
|
304
|
+
|
|
305
|
+
If a cell has multiple renderable outputs, all are collected and joined
|
|
306
|
+
(in MIME-type priority order). Console output (stdout and stderr) is
|
|
307
|
+
always captured independently.
|
|
308
|
+
"""
|
|
309
|
+
cells_raw = _extract_session_cells_raw(html)
|
|
310
|
+
try:
|
|
311
|
+
cells = json.loads(cells_raw)
|
|
312
|
+
except json.JSONDecodeError:
|
|
313
|
+
return {}
|
|
314
|
+
|
|
315
|
+
results: dict[str, ExtractedOutput] = {}
|
|
316
|
+
|
|
317
|
+
for cell in cells:
|
|
318
|
+
code_hash = cell.get("code_hash")
|
|
319
|
+
cell_id = cell.get("id", "")
|
|
320
|
+
|
|
321
|
+
stdout = "".join(
|
|
322
|
+
c.get("text", "")
|
|
323
|
+
for c in cell.get("console", [])
|
|
324
|
+
if c.get("name") == "stdout"
|
|
325
|
+
)
|
|
326
|
+
console_html = f"<pre>{escape(stdout)}</pre>" if stdout.strip() else ""
|
|
327
|
+
|
|
328
|
+
# Stderr may contain Pygments-highlighted HTML; strip it to plain text
|
|
329
|
+
stderr = "".join(
|
|
330
|
+
c.get("text", "")
|
|
331
|
+
for c in cell.get("console", [])
|
|
332
|
+
if c.get("name") == "stderr"
|
|
333
|
+
)
|
|
334
|
+
stderr = _html_to_plain_text(stderr) if stderr.strip() else ""
|
|
335
|
+
stderr_html = (
|
|
336
|
+
f'<pre class="stderr">{escape(stderr)}</pre>' if stderr.strip() else ""
|
|
337
|
+
)
|
|
338
|
+
|
|
339
|
+
# Console media output (images printed to console)
|
|
340
|
+
media_parts = []
|
|
341
|
+
for c in cell.get("console", []):
|
|
342
|
+
if c.get("type") != "streamMedia":
|
|
343
|
+
continue
|
|
344
|
+
mimetype = c.get("mimetype", "")
|
|
345
|
+
data = c.get("data", "")
|
|
346
|
+
if mimetype.startswith("image/") and data:
|
|
347
|
+
fmt = mimetype.split("/")[1]
|
|
348
|
+
media_parts.append(
|
|
349
|
+
f'<img src="{escape(data, quote=True)}" alt="{escape(fmt, quote=True)}">'
|
|
350
|
+
)
|
|
351
|
+
media_html = "\n".join(media_parts)
|
|
352
|
+
|
|
353
|
+
output_parts: list[tuple[str, str]] = []
|
|
354
|
+
for output in cell.get("outputs", []):
|
|
355
|
+
if output.get("type") == "error":
|
|
356
|
+
error_html = _format_error(output)
|
|
357
|
+
if error_html:
|
|
358
|
+
output_parts.append(("error", error_html))
|
|
359
|
+
break
|
|
360
|
+
data = output.get("data", {})
|
|
361
|
+
classified = _classify_and_build(data)
|
|
362
|
+
if classified is None:
|
|
363
|
+
continue
|
|
364
|
+
output_parts.append(classified)
|
|
365
|
+
|
|
366
|
+
raw_html = "\n\n".join(html for _, html in output_parts) if output_parts else ""
|
|
367
|
+
output_type = output_parts[0][0] if output_parts else "unknown"
|
|
368
|
+
|
|
369
|
+
if not console_html and not stderr_html and not media_html and not raw_html:
|
|
370
|
+
continue
|
|
371
|
+
|
|
372
|
+
results[code_hash] = ExtractedOutput(
|
|
373
|
+
raw_html=raw_html,
|
|
374
|
+
output_type=output_type,
|
|
375
|
+
cell_id=cell_id,
|
|
376
|
+
console_html=console_html,
|
|
377
|
+
stderr_html=stderr_html,
|
|
378
|
+
media_html=media_html,
|
|
379
|
+
)
|
|
380
|
+
|
|
381
|
+
return results
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import hashlib
|
|
2
|
+
import re
|
|
3
|
+
|
|
4
|
+
from .models import Cell
|
|
5
|
+
|
|
6
|
+
# Matches fenced code blocks produced by `marimo export md`
|
|
7
|
+
_BLOCK_RE = re.compile(r"(```python \{\.marimo\}\n(.*?)```)", re.DOTALL)
|
|
8
|
+
_SUPPRESS_RE = re.compile(r"#\s*@suppress")
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def _md5(text: str) -> str:
|
|
12
|
+
return hashlib.md5(text.encode("utf-8"), usedforsecurity=False).hexdigest()
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def collect_cells(md: str) -> list[Cell]:
|
|
16
|
+
"""Return one Cell for each fenced code block in the markdown."""
|
|
17
|
+
results: list[Cell] = []
|
|
18
|
+
|
|
19
|
+
for block_match in _BLOCK_RE.finditer(md):
|
|
20
|
+
block_text = block_match.group(1)
|
|
21
|
+
source = block_match.group(2)
|
|
22
|
+
|
|
23
|
+
suppressed = _SUPPRESS_RE.search(source) is not None
|
|
24
|
+
|
|
25
|
+
results.append(
|
|
26
|
+
Cell(
|
|
27
|
+
source=source,
|
|
28
|
+
source_hash=_md5(source.strip()),
|
|
29
|
+
block_text=block_text,
|
|
30
|
+
suppressed=suppressed,
|
|
31
|
+
)
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
return results
|
marimo_md_export-0.2.0/PKG-INFO
DELETED
|
@@ -1,60 +0,0 @@
|
|
|
1
|
-
Metadata-Version: 2.4
|
|
2
|
-
Name: marimo-md-export
|
|
3
|
-
Version: 0.2.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.12
|
|
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 # sync packages
|
|
59
|
-
just # run lint, typecheck, test, build docs
|
|
60
|
-
```
|
marimo_md_export-0.2.0/README.md
DELETED
|
@@ -1,37 +0,0 @@
|
|
|
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 # sync packages
|
|
36
|
-
just # run lint, typecheck, test, build docs
|
|
37
|
-
```
|
|
@@ -1,88 +0,0 @@
|
|
|
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
|
|
@@ -1,181 +0,0 @@
|
|
|
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
|
-
# Variable names follow HTML data-* attribute naming (hyphenated → snake_case)
|
|
62
|
-
data_data_attr = elem.get("data-data")
|
|
63
|
-
if not isinstance(data_data_attr, str):
|
|
64
|
-
return marimo_table_html
|
|
65
|
-
data_data = data_data_attr
|
|
66
|
-
|
|
67
|
-
field_types_raw_attr = elem.get("data-field-types")
|
|
68
|
-
if isinstance(field_types_raw_attr, str):
|
|
69
|
-
field_types_raw = field_types_raw_attr
|
|
70
|
-
else:
|
|
71
|
-
field_types_raw = "[]"
|
|
72
|
-
|
|
73
|
-
# data-data is a JSON-quoted string containing an array of row objects.
|
|
74
|
-
# It may contain literal NaN (not valid JSON).
|
|
75
|
-
try:
|
|
76
|
-
inner = json.loads(data_data) # unwrap outer JSON string
|
|
77
|
-
cleaned = inner.replace("NaN", "null")
|
|
78
|
-
rows = json.loads(cleaned)
|
|
79
|
-
except (json.JSONDecodeError, AttributeError):
|
|
80
|
-
return marimo_table_html
|
|
81
|
-
|
|
82
|
-
try:
|
|
83
|
-
field_types = json.loads(field_types_raw)
|
|
84
|
-
columns = [ft[0] for ft in field_types]
|
|
85
|
-
except (json.JSONDecodeError, IndexError):
|
|
86
|
-
columns = list(rows[0].keys()) if rows else []
|
|
87
|
-
|
|
88
|
-
def _cell(v: object) -> str:
|
|
89
|
-
return "" if v is None else escape(str(v))
|
|
90
|
-
|
|
91
|
-
header = "".join(f"<th>{escape(str(col))}</th>" for col in columns)
|
|
92
|
-
body_rows = "".join(
|
|
93
|
-
"<tr>" + "".join(f"<td>{_cell(row.get(col))}</td>" for col in columns) + "</tr>"
|
|
94
|
-
for row in rows
|
|
95
|
-
)
|
|
96
|
-
return f"<table><thead><tr>{header}</tr></thead><tbody>{body_rows}</tbody></table>"
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
def _classify_and_build(data: dict[str, str]) -> tuple[str, str] | None:
|
|
100
|
-
"""
|
|
101
|
-
Given the output data dict (MIME → value), return (output_type, raw_html)
|
|
102
|
-
or None if there is nothing renderable.
|
|
103
|
-
"""
|
|
104
|
-
# Figure: marimo mimebundle with image/png
|
|
105
|
-
bundle_raw = data.get("application/vnd.marimo+mimebundle")
|
|
106
|
-
if bundle_raw:
|
|
107
|
-
try:
|
|
108
|
-
bundle = json.loads(bundle_raw)
|
|
109
|
-
except json.JSONDecodeError:
|
|
110
|
-
bundle = {}
|
|
111
|
-
src = bundle.get("image/png")
|
|
112
|
-
if src:
|
|
113
|
-
return "figure", f'<img src="{escape(src, quote=True)}" alt="figure">'
|
|
114
|
-
|
|
115
|
-
# HTML output (may be a marimo-table web component)
|
|
116
|
-
html_val = data.get("text/html")
|
|
117
|
-
if html_val:
|
|
118
|
-
decoded = unescape(html_val)
|
|
119
|
-
if "<marimo-table" in decoded:
|
|
120
|
-
table_html = _table_html_from_marimo_table(decoded)
|
|
121
|
-
return "table", table_html
|
|
122
|
-
# Generic HTML (e.g. styled dataframe rendered as <table>)
|
|
123
|
-
if "<table" in decoded:
|
|
124
|
-
return "table", decoded
|
|
125
|
-
return "unknown", decoded
|
|
126
|
-
|
|
127
|
-
plain = data.get("text/plain", "")
|
|
128
|
-
if plain and plain.strip():
|
|
129
|
-
return "text", f"<pre>{escape(plain)}</pre>"
|
|
130
|
-
|
|
131
|
-
return None
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
def extract_outputs(html: bytes, target_hashes: set[str]) -> dict[str, ExtractedOutput]:
|
|
135
|
-
"""Extract rendered outputs from the marimo HTML export.
|
|
136
|
-
|
|
137
|
-
Returns a dict mapping source_hash → ExtractedOutput for each cell whose
|
|
138
|
-
code_hash is in target_hashes and that has a renderable output.
|
|
139
|
-
"""
|
|
140
|
-
cells_raw = _extract_session_cells_raw(html)
|
|
141
|
-
try:
|
|
142
|
-
cells = json.loads(cells_raw)
|
|
143
|
-
except json.JSONDecodeError:
|
|
144
|
-
return {}
|
|
145
|
-
|
|
146
|
-
results: dict[str, ExtractedOutput] = {}
|
|
147
|
-
|
|
148
|
-
for cell in cells:
|
|
149
|
-
code_hash = cell.get("code_hash")
|
|
150
|
-
if code_hash not in target_hashes:
|
|
151
|
-
continue
|
|
152
|
-
|
|
153
|
-
stdout = "".join(
|
|
154
|
-
c.get("text", "")
|
|
155
|
-
for c in cell.get("console", [])
|
|
156
|
-
if c.get("name") == "stdout"
|
|
157
|
-
)
|
|
158
|
-
console_html = f"<pre>{escape(stdout)}</pre>" if stdout.strip() else ""
|
|
159
|
-
|
|
160
|
-
raw_html = ""
|
|
161
|
-
output_type = "unknown"
|
|
162
|
-
for output in cell.get("outputs", []):
|
|
163
|
-
data = output.get("data", {})
|
|
164
|
-
classified = _classify_and_build(data)
|
|
165
|
-
if classified is None:
|
|
166
|
-
continue
|
|
167
|
-
output_type, raw_html = classified
|
|
168
|
-
break # take the first renderable output per cell
|
|
169
|
-
|
|
170
|
-
if not console_html and not raw_html:
|
|
171
|
-
continue
|
|
172
|
-
|
|
173
|
-
# label is filled in by inject.py after matching; use hash as placeholder
|
|
174
|
-
results[code_hash] = ExtractedOutput(
|
|
175
|
-
label=code_hash,
|
|
176
|
-
raw_html=raw_html,
|
|
177
|
-
output_type=output_type,
|
|
178
|
-
console_html=console_html,
|
|
179
|
-
)
|
|
180
|
-
|
|
181
|
-
return results
|
|
@@ -1,44 +0,0 @@
|
|
|
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
|
|
File without changes
|
|
File without changes
|
|
File without changes
|