marimo-md-export 0.2.1__tar.gz → 0.4.3__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.
@@ -1,10 +1,10 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: marimo-md-export
3
- Version: 0.2.1
3
+ Version: 0.4.3
4
4
  Summary: A minimal solution for exporting marimo notebooks to markdown *with* rendered HTML outputs, designed for mkdocs/zensical sites.
5
5
  Keywords: marimo,markdown,documentation
6
- Author: jmarshrossney
7
- Author-email: jmarshrossney <17361029+jmarshrossney@users.noreply.github.com>
6
+ Author: Joe Marsh Rossney
7
+ Author-email: Joe Marsh Rossney <17361029+jmarshrossney@users.noreply.github.com>
8
8
  License-Expression: MIT
9
9
  License-File: LICENSE
10
10
  Classifier: Development Status :: 3 - Alpha
@@ -32,18 +32,16 @@ Description-Content-Type: text/markdown
32
32
  [![CI](https://github.com/jmarshrossney/marimo-md-export/actions/workflows/ci.yml/badge.svg)](https://github.com/jmarshrossney/marimo-md-export/actions/workflows/ci.yml)
33
33
  [![Docs](https://github.com/jmarshrossney/marimo-md-export/actions/workflows/docs.yml/badge.svg)](https://jmarshrossney.github.io/marimo-md-export)
34
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) and tables (as GFM or HTML).
35
+ A `uv` tool that wraps `marimo export`, extracts rendered outputs from the HTML export, and injects them into the markdown export.
36
+ The result is a self-contained markdown document with embedded figures (as base64 `<img>` tags), tables (as GFM or HTML), and other cell outputs.
38
37
 
39
38
  **[Full documentation](https://jmarshrossney.github.io/marimo-md-export)**
40
39
 
41
40
  ## Quick start
42
41
 
43
- Mark cells in your marimo `.py` notebook with `# @output: <label>`:
42
+ Write your marimo `.py` notebook — cell outputs are rendered by default:
44
43
 
45
44
  ```python
46
- # @output: my_figure
47
45
  fig, ax = plt.subplots()
48
46
  ax.plot(x, np.sin(x))
49
47
  fig
@@ -55,17 +53,10 @@ Then run:
55
53
  uvx marimo-md-export notebook.py output.md
56
54
  ```
57
55
 
58
- If you want the tool to be available globally you can "install" it with
59
-
60
- ```sh
61
- uv tool install marimo-md-export
62
- ```
63
-
64
56
  ## Integrating with documentation sites
65
57
 
66
- `marimo-md-export` is designed to produce markdown pages for static site generators like
67
- [mkdocs](https://www.mkdocs.org/) (Python) or
68
- [zensical](https://zensical.org/) (Rust). Both work identically for this purpose.
58
+ `marimo-md-export` is designed to produce markdown pages for static site generators like [mkdocs](https://www.mkdocs.org/) or [zensical](https://zensical.org/).
59
+ Both work identically for this purpose.
69
60
 
70
61
  **1. Add as a docs dependency:**
71
62
 
@@ -79,13 +70,11 @@ For example, this project uses the following [just](https://github.com/casey/jus
79
70
 
80
71
  ```just
81
72
  docs:
82
- marimo-md-export examples/notebook.py docs/example.md \
83
- --html-output docs/example-notebook.html
73
+ marimo-md-export examples/notebook.py docs/example.md
84
74
  zensical build
85
75
  ```
86
76
 
87
- This runs `marimo-md-export` to produce a self-contained markdown page (with any
88
- `# @output:` cells injected as figures/tables), then builds the site.
77
+ This runs `marimo-md-export` to produce a self-contained markdown page (with cell outputs injected), then builds the site.
89
78
 
90
79
  ## Development
91
80
 
@@ -6,18 +6,16 @@
6
6
  [![CI](https://github.com/jmarshrossney/marimo-md-export/actions/workflows/ci.yml/badge.svg)](https://github.com/jmarshrossney/marimo-md-export/actions/workflows/ci.yml)
7
7
  [![Docs](https://github.com/jmarshrossney/marimo-md-export/actions/workflows/docs.yml/badge.svg)](https://jmarshrossney.github.io/marimo-md-export)
8
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) and tables (as GFM or HTML).
9
+ A `uv` tool that wraps `marimo export`, extracts rendered outputs from the HTML export, and injects them into the markdown export.
10
+ The result is a self-contained markdown document with embedded figures (as base64 `<img>` tags), tables (as GFM or HTML), and other cell outputs.
12
11
 
13
12
  **[Full documentation](https://jmarshrossney.github.io/marimo-md-export)**
14
13
 
15
14
  ## Quick start
16
15
 
17
- Mark cells in your marimo `.py` notebook with `# @output: <label>`:
16
+ Write your marimo `.py` notebook — cell outputs are rendered by default:
18
17
 
19
18
  ```python
20
- # @output: my_figure
21
19
  fig, ax = plt.subplots()
22
20
  ax.plot(x, np.sin(x))
23
21
  fig
@@ -29,17 +27,10 @@ Then run:
29
27
  uvx marimo-md-export notebook.py output.md
30
28
  ```
31
29
 
32
- If you want the tool to be available globally you can "install" it with
33
-
34
- ```sh
35
- uv tool install marimo-md-export
36
- ```
37
-
38
30
  ## Integrating with documentation sites
39
31
 
40
- `marimo-md-export` is designed to produce markdown pages for static site generators like
41
- [mkdocs](https://www.mkdocs.org/) (Python) or
42
- [zensical](https://zensical.org/) (Rust). Both work identically for this purpose.
32
+ `marimo-md-export` is designed to produce markdown pages for static site generators like [mkdocs](https://www.mkdocs.org/) or [zensical](https://zensical.org/).
33
+ Both work identically for this purpose.
43
34
 
44
35
  **1. Add as a docs dependency:**
45
36
 
@@ -53,13 +44,11 @@ For example, this project uses the following [just](https://github.com/casey/jus
53
44
 
54
45
  ```just
55
46
  docs:
56
- marimo-md-export examples/notebook.py docs/example.md \
57
- --html-output docs/example-notebook.html
47
+ marimo-md-export examples/notebook.py docs/example.md
58
48
  zensical build
59
49
  ```
60
50
 
61
- This runs `marimo-md-export` to produce a self-contained markdown page (with any
62
- `# @output:` cells injected as figures/tables), then builds the site.
51
+ This runs `marimo-md-export` to produce a self-contained markdown page (with cell outputs injected), then builds the site.
63
52
 
64
53
  ## Development
65
54
 
@@ -4,10 +4,10 @@ build-backend = "uv_build"
4
4
 
5
5
  [project]
6
6
  name = "marimo-md-export"
7
- version = "0.2.1"
7
+ version = "0.4.3"
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
- { name = "jmarshrossney", email = "17361029+jmarshrossney@users.noreply.github.com" }
10
+ { name = "Joe Marsh Rossney", email = "17361029+jmarshrossney@users.noreply.github.com" }
11
11
  ]
12
12
  readme = "README.md"
13
13
  license = "MIT"
@@ -6,7 +6,7 @@ from rich.console import Console
6
6
  from .export import export_html, export_md, strip_header_from_frontmatter
7
7
  from .inject import inject_outputs
8
8
  from .parse_html import extract_outputs
9
- from .parse_md import collect_marked_cells
9
+ from .parse_md import collect_cells
10
10
 
11
11
  _err_console = Console(stderr=True)
12
12
 
@@ -50,11 +50,11 @@ def main(
50
50
  help="Run marimo export in an isolated uv environment. "
51
51
  "Without this flag, marimo's own sandbox prompt is suppressed.",
52
52
  ),
53
- timeout: int = typer.Option(
54
- 120,
53
+ timeout: int | None = typer.Option(
54
+ None,
55
55
  "--timeout",
56
56
  help="Maximum seconds to wait for each marimo export subprocess "
57
- "(set to 0 to disable).",
57
+ "(default: no timeout).",
58
58
  ),
59
59
  ) -> None:
60
60
  """Export a marimo notebook to markdown with rendered outputs injected.
@@ -75,20 +75,12 @@ def main(
75
75
  typer.echo(f"marimo export md failed:\n{exc}", err=True)
76
76
  raise typer.Exit(1)
77
77
 
78
- marked = collect_marked_cells(md)
79
- if not marked:
80
- _err_console.print(
81
- f"WARNING: no @output markers found in {notebook}. "
82
- "Did you forget to add '# @output: <label>' comments?",
83
- style="bold yellow",
84
- )
85
- raise typer.Exit(2)
78
+ cells = collect_cells(md)
86
79
 
87
80
  if verbose:
88
- typer.echo(
89
- f"Found {len(marked)} @output marker(s): "
90
- + ", ".join(c.label for c in marked)
91
- )
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")
92
84
  typer.echo(f"Exporting HTML: {notebook}")
93
85
 
94
86
  try:
@@ -103,10 +95,8 @@ def main(
103
95
  if verbose:
104
96
  typer.echo(f"Wrote {html_output}")
105
97
 
106
- target_hashes = {c.source_hash for c in marked}
107
- outputs = extract_outputs(html, target_hashes)
108
-
109
- result, warnings = inject_outputs(md, marked, outputs)
98
+ outputs = extract_outputs(html)
99
+ result, warnings = inject_outputs(md, cells, outputs)
110
100
 
111
101
  for warning in warnings:
112
102
  _err_console.print(f"WARNING: {warning}", style="bold yellow")
@@ -106,9 +106,12 @@ def export_html(
106
106
  f"marimo export html timed out after {timeout}s.\n"
107
107
  "Try passing --sandbox to run in an isolated environment."
108
108
  )
109
- if result.returncode != 0:
109
+ if result.returncode not in (0, 1):
110
110
  raise RuntimeError(f"marimo export html failed:\n{result.stderr}")
111
- return tmp.read_bytes()
111
+ html = tmp.read_bytes()
112
+ if result.returncode == 1 and not html:
113
+ raise RuntimeError(f"marimo export html failed:\n{result.stderr}")
114
+ return html
112
115
  finally:
113
116
  tmp.unlink(missing_ok=True)
114
117
 
@@ -134,9 +137,12 @@ def export_md(
134
137
  f"marimo export md timed out after {timeout}s.\n"
135
138
  "Try passing --sandbox to run in an isolated environment."
136
139
  )
137
- if result.returncode != 0:
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:
138
144
  raise RuntimeError(f"marimo export md failed:\n{result.stderr}")
139
- return tmp.read_text(encoding="utf-8")
145
+ return md
140
146
  finally:
141
147
  tmp.unlink(missing_ok=True)
142
148
 
@@ -1,6 +1,8 @@
1
+ import re
2
+
1
3
  from bs4 import BeautifulSoup
2
4
 
3
- from .models import ExtractedOutput, MarkedCell
5
+ from .models import Cell, ExtractedOutput
4
6
 
5
7
 
6
8
  def _table_to_gfm(html: str) -> str | None:
@@ -40,48 +42,65 @@ def _table_to_gfm(html: str) -> str | None:
40
42
  return "\n".join(lines)
41
43
 
42
44
 
45
+ def _escape_brackets(text: str) -> str:
46
+ return text.replace("[", "&#91;").replace("]", "&#93;")
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
+
43
58
  def _format_output(output: ExtractedOutput) -> str:
44
- comment = f"<!-- @output:{output.label} -->"
59
+ comment = f"<!-- @output:{output.cell_id} -->"
45
60
 
46
61
  parts = []
47
62
  if output.console_html:
48
- parts.append(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))
49
68
  if output.raw_html:
50
69
  if output.output_type == "table":
51
70
  gfm = _table_to_gfm(output.raw_html)
52
- parts.append(gfm if gfm is not None else output.raw_html)
71
+ parts.append(
72
+ gfm if gfm is not None else _escape_brackets_in_pre(output.raw_html)
73
+ )
53
74
  else:
54
- parts.append(output.raw_html)
75
+ parts.append(_escape_brackets_in_pre(output.raw_html))
55
76
 
56
77
  return comment + "\n\n" + "\n\n".join(parts)
57
78
 
58
79
 
59
80
  def inject_outputs(
60
81
  md: str,
61
- marked_cells: list[MarkedCell],
82
+ cells: list[Cell],
62
83
  outputs: dict[str, ExtractedOutput],
63
84
  ) -> tuple[str, list[str]]:
64
- """Inject rendered outputs into the markdown after each marked code block.
85
+ """Inject rendered outputs into the markdown after each code block.
65
86
 
66
- marked_cells should come from collect_marked_cells(md). outputs maps
67
- source_hash → ExtractedOutput. Labels are set from the corresponding
68
- MarkedCell during injection.
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.
69
90
 
70
91
  Returns (result_markdown, warnings) where warnings is a list of
71
- human-readable messages for outputs that had no matching rendered data.
92
+ human-readable messages.
72
93
  """
73
94
  result = md
74
95
  warnings: list[str] = []
75
- for cell in marked_cells:
96
+ for cell in cells:
97
+ if cell.suppressed:
98
+ continue
76
99
  matched = outputs.get(cell.source_hash)
77
100
  if matched is None:
78
- warnings.append(
79
- f"no output found for @output:{cell.label} "
80
- f"(hash {cell.source_hash[:8]})"
81
- )
101
+ # No renderable output — expected for import/setup cells
82
102
  continue
83
103
 
84
- matched.label = cell.label
85
104
  formatted = _format_output(matched)
86
105
  result = result.replace(
87
106
  cell.block_text, cell.block_text + "\n\n" + formatted, 1
@@ -2,14 +2,13 @@ from dataclasses import dataclass, field
2
2
 
3
3
 
4
4
  @dataclass
5
- class MarkedCell:
6
- """A fenced code block in the markdown that carries an @output marker."""
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
@@ -17,6 +16,8 @@ class ExtractedOutput:
17
16
  """The rendered output scraped from the HTML export for one cell."""
18
17
 
19
18
  raw_html: str
20
- output_type: str # "figure" | "table" | "text" | "unknown"
21
- label: 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,407 @@
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 ast
35
+ import json
36
+ import pprint
37
+ import re
38
+ from html import escape, unescape
39
+
40
+ from bs4 import BeautifulSoup
41
+
42
+ from .models import ExtractedOutput
43
+
44
+ _SESSION_CELLS_RE = re.compile(
45
+ r'"session"\s*:\s*\{"cells"\s*:\s*\[',
46
+ )
47
+
48
+ _decoder = json.JSONDecoder()
49
+
50
+
51
+ def _extract_session_cells_raw(html: bytes) -> str:
52
+ """Return the raw JSON string for session.cells from the HTML.
53
+
54
+ Uses json.JSONDecoder.raw_decode to correctly handle brackets inside
55
+ JSON string values.
56
+ """
57
+ text = html.decode("utf-8", errors="replace")
58
+ m = _SESSION_CELLS_RE.search(text)
59
+ if m is None:
60
+ return "[]"
61
+
62
+ start = m.end() - 1 # position of the opening '['
63
+ try:
64
+ _, end = _decoder.raw_decode(text, idx=start)
65
+ except json.JSONDecodeError:
66
+ return "[]"
67
+
68
+ return text[start:end]
69
+
70
+
71
+ def _table_html_from_marimo_table(marimo_table_html: str) -> str:
72
+ """Convert a <marimo-table> web component to a plain HTML <table>."""
73
+ soup = BeautifulSoup(marimo_table_html, "lxml")
74
+ elem = soup.find("marimo-table")
75
+ if elem is None:
76
+ return marimo_table_html
77
+
78
+ # Variable names follow HTML data-* attribute naming (hyphenated → snake_case)
79
+ data_data_attr = elem.get("data-data")
80
+ if not isinstance(data_data_attr, str):
81
+ return marimo_table_html
82
+ data_data = data_data_attr
83
+
84
+ field_types_raw_attr = elem.get("data-field-types")
85
+ if isinstance(field_types_raw_attr, str):
86
+ field_types_raw = field_types_raw_attr
87
+ else:
88
+ field_types_raw = "[]"
89
+
90
+ # data-data is a JSON-quoted string containing an array of row objects.
91
+ # It may contain literal NaN (not valid JSON). Replace only bare NaN
92
+ # tokens (not inside quoted string values) to avoid clobbering strings
93
+ # like "NaN handling".
94
+ try:
95
+ inner = json.loads(data_data) # unwrap outer JSON string
96
+ cleaned = re.sub(r'(?<!")\bNaN\b(?!")', "null", inner)
97
+ rows = json.loads(cleaned)
98
+ except (json.JSONDecodeError, AttributeError):
99
+ return marimo_table_html
100
+
101
+ try:
102
+ field_types = json.loads(field_types_raw)
103
+ columns = [ft[0] for ft in field_types]
104
+ except (json.JSONDecodeError, IndexError):
105
+ columns = list(rows[0].keys()) if rows else []
106
+
107
+ def _cell(v: object) -> str:
108
+ return "" if v is None else escape(str(v))
109
+
110
+ header = "".join(f"<th>{escape(str(col))}</th>" for col in columns)
111
+ body_rows = "".join(
112
+ "<tr>" + "".join(f"<td>{_cell(row.get(col))}</td>" for col in columns) + "</tr>"
113
+ for row in rows
114
+ )
115
+ return f"<table><thead><tr>{header}</tr></thead><tbody>{body_rows}</tbody></table>"
116
+
117
+
118
+ def _html_to_plain_text(html_str: str) -> str:
119
+ """Strip HTML markup from a string, leaving only plain text.
120
+
121
+ Used to clean Pygments-highlighted traceback output that marimo includes
122
+ in error-cell stderr entries.
123
+ """
124
+ text = unescape(html_str)
125
+ text = re.sub(r"<[^>]+>", "", text)
126
+ return unescape(text)
127
+
128
+
129
+ def _format_error(output: dict) -> str:
130
+ """Format an error output as plain text in a <pre> block.
131
+
132
+ Error outputs have: ename, evalue, traceback fields.
133
+ The traceback may be None when marimo truncates it.
134
+ """
135
+ ename = output.get("ename", "Error") or "Error"
136
+ evalue = output.get("evalue", "") or ""
137
+ traceback_lines = output.get("traceback") or []
138
+ traceback_text = "\n".join(traceback_lines)
139
+ if traceback_text.strip():
140
+ # Traceback lines may contain HTML markup from Pygments
141
+ traceback_text = _html_to_plain_text(traceback_text)
142
+ combined = f"{traceback_text}\n{ename}: {evalue}"
143
+ else:
144
+ combined = f"{ename}: {evalue}"
145
+ return f"<pre>{escape(combined)}</pre>"
146
+
147
+
148
+ _MARIMO_TYPE_RE = re.compile(r"^text/plain\+(\w+):(.*)$", re.DOTALL)
149
+
150
+
151
+ def _strip_marimo_type_prefixes(obj: object) -> object:
152
+ """Recursively strip marimo type prefixes from JSON values.
153
+
154
+ Marimo encodes typed values as ``"text/plain+float:1.0"`` in
155
+ ``application/json`` output. This helper converts them back to their
156
+ native Python types so the rendered JSON is clean.
157
+ """
158
+ if isinstance(obj, str):
159
+ m = _MARIMO_TYPE_RE.match(obj)
160
+ if m:
161
+ type_tag, raw = m.group(1), m.group(2)
162
+ if type_tag == "float":
163
+ try:
164
+ return float(raw)
165
+ except ValueError:
166
+ return raw
167
+ if type_tag == "int":
168
+ try:
169
+ return int(raw)
170
+ except ValueError:
171
+ return raw
172
+ if type_tag == "bool":
173
+ return raw.lower() == "true"
174
+ if type_tag in ("none", "NoneType"):
175
+ return None
176
+ return raw
177
+ return obj
178
+ if isinstance(obj, list):
179
+ return [_strip_marimo_type_prefixes(item) for item in obj]
180
+ if isinstance(obj, dict):
181
+ return {k: _strip_marimo_type_prefixes(v) for k, v in obj.items()}
182
+ return obj
183
+
184
+
185
+ def _classify_and_build(data: dict[str, str]) -> tuple[str, str] | None:
186
+ """
187
+ Given the output data dict (MIME → value), return (output_type, raw_html)
188
+ or None if there is nothing renderable.
189
+ """
190
+ # Figure: marimo mimebundle — try representations in priority order
191
+ bundle_raw = data.get("application/vnd.marimo+mimebundle")
192
+ if bundle_raw:
193
+ try:
194
+ bundle = json.loads(bundle_raw)
195
+ except json.JSONDecodeError:
196
+ bundle = {}
197
+ for mime_key in ("image/png", "image/svg+xml", "text/html", "text/plain"):
198
+ val = bundle.get(mime_key)
199
+ if val:
200
+ if mime_key.startswith("image/"):
201
+ return (
202
+ "figure",
203
+ f'<img src="{escape(val, quote=True)}" alt="{escape(mime_key.split("/")[1], quote=True)}">',
204
+ )
205
+ if mime_key == "text/html":
206
+ return "html", unescape(val)
207
+ if mime_key == "text/plain" and val.strip():
208
+ return "text", f"<pre>{escape(val)}</pre>"
209
+
210
+ # Standalone image MIME types
211
+ for mime_type in (
212
+ "image/png",
213
+ "image/jpeg",
214
+ "image/gif",
215
+ "image/svg+xml",
216
+ "image/tiff",
217
+ "image/avif",
218
+ "image/bmp",
219
+ "image/webp",
220
+ ):
221
+ img_val = data.get(mime_type)
222
+ if img_val:
223
+ fmt = mime_type.split("/")[1]
224
+ return (
225
+ "figure",
226
+ f'<img src="{escape(img_val, quote=True)}" alt="{escape(fmt, quote=True)}">',
227
+ )
228
+
229
+ # JSON output (dicts, lists, tuples)
230
+ json_val = data.get("application/json")
231
+ if json_val:
232
+ try:
233
+ parsed = json.loads(json_val)
234
+ cleaned = _strip_marimo_type_prefixes(parsed)
235
+ formatted = pprint.pformat(cleaned)
236
+ except (json.JSONDecodeError, TypeError):
237
+ formatted = json_val
238
+ return "json", f"<pre>{escape(formatted)}</pre>"
239
+
240
+ # LaTeX output — wrap in $$ delimiters for math rendering.
241
+ # NOTE: text/latex is a fallback MIME type and is not expected to appear
242
+ # in normal marimo usage. LaTeX in marimo is typically rendered inside
243
+ # mo.md() blocks, which produce text/markdown output (suppressed to avoid
244
+ # duplication with the markdown export). This handler exists for
245
+ # robustness in case a library emits standalone text/latex.
246
+ latex_val = data.get("text/latex", "")
247
+ if latex_val and latex_val.strip():
248
+ content = latex_val.strip()
249
+ if content.startswith("$$") and content.endswith("$$"):
250
+ return "latex", content
251
+ if (
252
+ content.startswith("$")
253
+ and content.endswith("$")
254
+ and not content.startswith("$$")
255
+ ):
256
+ return "latex", f"${content[1:-1]}$"
257
+ return "latex", f"$$\n{content}\n$$"
258
+
259
+ # CSV output — render as a plain text code block
260
+ csv_val = data.get("text/csv", "")
261
+ if csv_val and csv_val.strip():
262
+ return "csv", f"<pre><code>{escape(csv_val)}</code></pre>"
263
+
264
+ # HTML output (may be a marimo-table web component)
265
+ html_val = data.get("text/html")
266
+ if html_val:
267
+ decoded = unescape(html_val)
268
+ # Check for <pre> tag containing a Python string repr
269
+ pre_match = re.match(r"<pre[^>]*>(.*?)</pre>", decoded, re.DOTALL)
270
+ if pre_match:
271
+ content = pre_match.group(1)
272
+ if (
273
+ content.startswith(("'", '"'))
274
+ and content.endswith(("'", '"'))
275
+ and len(content) >= 2
276
+ ):
277
+ try:
278
+ content = ast.literal_eval(content)
279
+ except (ValueError, SyntaxError):
280
+ content = None
281
+ if content is not None:
282
+ return "text", f"<pre>{escape(content)}</pre>"
283
+ if "<marimo-table" in decoded:
284
+ table_html = _table_html_from_marimo_table(decoded)
285
+ return "table", table_html
286
+ # Generic HTML (e.g. styled dataframe rendered as <table>)
287
+ if "<table" in decoded:
288
+ return "table", decoded
289
+ return "html", decoded
290
+
291
+ plain = data.get("text/plain", "")
292
+ if plain and plain.strip():
293
+ if (
294
+ plain.startswith(("'", '"'))
295
+ and plain.endswith(("'", '"'))
296
+ and len(plain) >= 2
297
+ ):
298
+ try:
299
+ plain = ast.literal_eval(plain)
300
+ except (ValueError, SyntaxError):
301
+ pass
302
+ return "text", f"<pre>{escape(plain)}</pre>"
303
+
304
+ # Unsupported MIME types — leave a comment for debugging
305
+ unsupported = {
306
+ "application/vnd.vega.v5+json",
307
+ "application/vnd.vega.v6+json",
308
+ "application/vnd.vegalite.v5+json",
309
+ "application/vnd.vegalite.v6+json",
310
+ "application/vnd.jupyter.widget-view+json",
311
+ "text/markdown",
312
+ "text/password",
313
+ }
314
+ for mime_type in unsupported:
315
+ if mime_type in data:
316
+ return (
317
+ "unsupported",
318
+ f"<!-- unsupported output type: {escape(mime_type)} -->",
319
+ )
320
+
321
+ return None
322
+
323
+
324
+ def extract_outputs(html: bytes) -> dict[str, ExtractedOutput]:
325
+ """Extract rendered outputs from the marimo HTML export.
326
+
327
+ Returns a dict mapping source_hash → ExtractedOutput for each cell
328
+ that has a renderable output. The cell_id is populated from marimo's
329
+ internal cell identifier.
330
+
331
+ If a cell has multiple renderable outputs, all are collected and joined
332
+ (in MIME-type priority order). Console output (stdout and stderr) is
333
+ always captured independently.
334
+ """
335
+ cells_raw = _extract_session_cells_raw(html)
336
+ try:
337
+ cells = json.loads(cells_raw)
338
+ except json.JSONDecodeError:
339
+ return {}
340
+
341
+ results: dict[str, ExtractedOutput] = {}
342
+
343
+ for cell in cells:
344
+ code_hash = cell.get("code_hash")
345
+ cell_id = cell.get("id", "")
346
+
347
+ stdout = "".join(
348
+ c.get("text", "")
349
+ for c in cell.get("console", [])
350
+ if c.get("name") == "stdout"
351
+ )
352
+ console_html = f"<pre>{escape(stdout)}</pre>" if stdout.strip() else ""
353
+
354
+ # Stderr may contain Pygments-highlighted HTML; strip it to plain text
355
+ stderr = "".join(
356
+ c.get("text", "")
357
+ for c in cell.get("console", [])
358
+ if c.get("name") == "stderr"
359
+ )
360
+ stderr = _html_to_plain_text(stderr) if stderr.strip() else ""
361
+ stderr_html = (
362
+ f'<pre class="stderr">{escape(stderr)}</pre>' if stderr.strip() else ""
363
+ )
364
+
365
+ # Console media output (images printed to console)
366
+ media_parts = []
367
+ for c in cell.get("console", []):
368
+ if c.get("type") != "streamMedia":
369
+ continue
370
+ mimetype = c.get("mimetype", "")
371
+ data = c.get("data", "")
372
+ if mimetype.startswith("image/") and data:
373
+ fmt = mimetype.split("/")[1]
374
+ media_parts.append(
375
+ f'<img src="{escape(data, quote=True)}" alt="{escape(fmt, quote=True)}">'
376
+ )
377
+ media_html = "\n".join(media_parts)
378
+
379
+ output_parts: list[tuple[str, str]] = []
380
+ for output in cell.get("outputs", []):
381
+ if output.get("type") == "error":
382
+ error_html = _format_error(output)
383
+ if error_html:
384
+ output_parts.append(("error", error_html))
385
+ break
386
+ data = output.get("data", {})
387
+ classified = _classify_and_build(data)
388
+ if classified is None:
389
+ continue
390
+ output_parts.append(classified)
391
+
392
+ raw_html = "\n\n".join(html for _, html in output_parts) if output_parts else ""
393
+ output_type = output_parts[0][0] if output_parts else "unknown"
394
+
395
+ if not console_html and not stderr_html and not media_html and not raw_html:
396
+ continue
397
+
398
+ results[code_hash] = ExtractedOutput(
399
+ raw_html=raw_html,
400
+ output_type=output_type,
401
+ cell_id=cell_id,
402
+ console_html=console_html,
403
+ stderr_html=stderr_html,
404
+ media_html=media_html,
405
+ )
406
+
407
+ 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
@@ -1,188 +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
- _decoder = json.JSONDecoder()
35
-
36
-
37
- def _extract_session_cells_raw(html: bytes) -> str:
38
- """Return the raw JSON string for session.cells from the HTML.
39
-
40
- Uses json.JSONDecoder.raw_decode to correctly handle brackets inside
41
- JSON string values.
42
- """
43
- text = html.decode("utf-8", errors="replace")
44
- m = _SESSION_CELLS_RE.search(text)
45
- if m is None:
46
- return "[]"
47
-
48
- start = m.end() - 1 # position of the opening '['
49
- try:
50
- _, end = _decoder.raw_decode(text, idx=start)
51
- except json.JSONDecodeError:
52
- return "[]"
53
-
54
- return text[start:end]
55
-
56
-
57
- def _table_html_from_marimo_table(marimo_table_html: str) -> str:
58
- """Convert a <marimo-table> web component to a plain HTML <table>."""
59
- soup = BeautifulSoup(marimo_table_html, "lxml")
60
- elem = soup.find("marimo-table")
61
- if elem is None:
62
- return marimo_table_html
63
-
64
- # Variable names follow HTML data-* attribute naming (hyphenated → snake_case)
65
- data_data_attr = elem.get("data-data")
66
- if not isinstance(data_data_attr, str):
67
- return marimo_table_html
68
- data_data = data_data_attr
69
-
70
- field_types_raw_attr = elem.get("data-field-types")
71
- if isinstance(field_types_raw_attr, str):
72
- field_types_raw = field_types_raw_attr
73
- else:
74
- field_types_raw = "[]"
75
-
76
- # data-data is a JSON-quoted string containing an array of row objects.
77
- # It may contain literal NaN (not valid JSON). Replace only bare NaN
78
- # tokens (not inside quoted string values) to avoid clobbering strings
79
- # like "NaN handling".
80
- try:
81
- inner = json.loads(data_data) # unwrap outer JSON string
82
- cleaned = re.sub(r'(?<!")\bNaN\b(?!")', "null", inner)
83
- rows = json.loads(cleaned)
84
- except (json.JSONDecodeError, AttributeError):
85
- return marimo_table_html
86
-
87
- try:
88
- field_types = json.loads(field_types_raw)
89
- columns = [ft[0] for ft in field_types]
90
- except (json.JSONDecodeError, IndexError):
91
- columns = list(rows[0].keys()) if rows else []
92
-
93
- def _cell(v: object) -> str:
94
- return "" if v is None else escape(str(v))
95
-
96
- header = "".join(f"<th>{escape(str(col))}</th>" for col in columns)
97
- body_rows = "".join(
98
- "<tr>" + "".join(f"<td>{_cell(row.get(col))}</td>" for col in columns) + "</tr>"
99
- for row in rows
100
- )
101
- return f"<table><thead><tr>{header}</tr></thead><tbody>{body_rows}</tbody></table>"
102
-
103
-
104
- def _classify_and_build(data: dict[str, str]) -> tuple[str, str] | None:
105
- """
106
- Given the output data dict (MIME → value), return (output_type, raw_html)
107
- or None if there is nothing renderable.
108
- """
109
- # Figure: marimo mimebundle with image/png
110
- bundle_raw = data.get("application/vnd.marimo+mimebundle")
111
- if bundle_raw:
112
- try:
113
- bundle = json.loads(bundle_raw)
114
- except json.JSONDecodeError:
115
- bundle = {}
116
- src = bundle.get("image/png")
117
- if src:
118
- return "figure", f'<img src="{escape(src, quote=True)}" alt="figure">'
119
-
120
- # HTML output (may be a marimo-table web component)
121
- html_val = data.get("text/html")
122
- if html_val:
123
- decoded = unescape(html_val)
124
- if "<marimo-table" in decoded:
125
- table_html = _table_html_from_marimo_table(decoded)
126
- return "table", table_html
127
- # Generic HTML (e.g. styled dataframe rendered as <table>)
128
- if "<table" in decoded:
129
- return "table", decoded
130
- return "unknown", decoded
131
-
132
- plain = data.get("text/plain", "")
133
- if plain and plain.strip():
134
- return "text", f"<pre>{escape(plain)}</pre>"
135
-
136
- return None
137
-
138
-
139
- def extract_outputs(html: bytes, target_hashes: set[str]) -> dict[str, ExtractedOutput]:
140
- """Extract rendered outputs from the marimo HTML export.
141
-
142
- Returns a dict mapping source_hash → ExtractedOutput for each cell whose
143
- code_hash is in target_hashes and that has a renderable output.
144
-
145
- If a cell has multiple outputs, only the first renderable one is used
146
- (in MIME-type priority order: marimo mimebundle → text/html → text/plain).
147
- Console output (stdout) is always captured independently.
148
- """
149
- cells_raw = _extract_session_cells_raw(html)
150
- try:
151
- cells = json.loads(cells_raw)
152
- except json.JSONDecodeError:
153
- return {}
154
-
155
- results: dict[str, ExtractedOutput] = {}
156
-
157
- for cell in cells:
158
- code_hash = cell.get("code_hash")
159
- if code_hash not in target_hashes:
160
- continue
161
-
162
- stdout = "".join(
163
- c.get("text", "")
164
- for c in cell.get("console", [])
165
- if c.get("name") == "stdout"
166
- )
167
- console_html = f"<pre>{escape(stdout)}</pre>" if stdout.strip() else ""
168
-
169
- raw_html = ""
170
- output_type = "unknown"
171
- for output in cell.get("outputs", []):
172
- data = output.get("data", {})
173
- classified = _classify_and_build(data)
174
- if classified is None:
175
- continue
176
- output_type, raw_html = classified
177
- break # first renderable output per cell wins
178
-
179
- if not console_html and not raw_html:
180
- continue
181
-
182
- results[code_hash] = ExtractedOutput(
183
- raw_html=raw_html,
184
- output_type=output_type,
185
- console_html=console_html,
186
- )
187
-
188
- 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: set[str] = set()
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.add(label)
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