Debian Codegraph @

myst_nb/core/nb_to_tokens.py

raw symbols SCIP
1 """Module for parsing notebooks to Markdown-it tokens."""
2
3 from __future__ import annotations
4
5 from typing import Any
6
7 from markdown_it.main import MarkdownIt
8 from markdown_it.rules_core import StateCore
9 from markdown_it.token import Token
10 from nbformat import NotebookNode
11
12 from myst_nb.core.loggers import LoggerType
13
14
15 def nb_node_to_dict(node: NotebookNode) -> dict[str, Any]:
16 """Recursively convert a notebook node to a dict."""
17 return _nb_node_to_dict(node)
18
19
20 def _nb_node_to_dict(item: Any) -> Any:
21 """Recursively convert any notebook nodes to dict."""
22 if isinstance(item, NotebookNode):
23 return {k: _nb_node_to_dict(v) for k, v in item.items()}
24 return item
25
26
27 def notebook_to_tokens(
28 notebook: NotebookNode,
29 mdit_parser: MarkdownIt,
30 mdit_env: dict[str, Any],
31 logger: LoggerType,
32 ) -> list[Token]:
33 # disable front-matter, since this is taken from the notebook
34 mdit_parser.disable("front_matter", ignoreInvalid=True)
35 # this stores global state, such as reference definitions
36
37 # Parse block tokens only first, leaving inline parsing to a second phase
38 # (required to collect all reference definitions, before assessing references).
39 block_tokens = [Token("nb_initialise", "", 0, map=[0, 0])]
40 for cell_index, nb_cell in enumerate(notebook.cells):
41 # skip empty cells
42 if len(nb_cell["source"].strip()) == 0:
43 continue
44
45 # skip cells tagged for removal
46 tags = nb_cell.metadata.get("tags", [])
47 if ("remove_cell" in tags) or ("remove-cell" in tags):
48 continue
49
50 # generate tokens
51 tokens: list[Token]
52 if nb_cell["cell_type"] == "markdown":
53 # https://nbformat.readthedocs.io/en/5.1.3/format_description.html#markdown-cells
54 # TODO if cell has tag output-caption, then use as caption for next/preceding cell?
55 tokens = [
56 Token(
57 "nb_cell_markdown_open",
58 "",
59 1,
60 hidden=True,
61 meta={
62 "index": cell_index,
63 "metadata": nb_node_to_dict(nb_cell["metadata"]),
64 },
65 map=[0, len(nb_cell["source"].splitlines()) - 1],
66 ),
67 ]
68 with mdit_parser.reset_rules():
69 # enable only rules up to block
70 rules = mdit_parser.core.ruler.get_active_rules()
71 mdit_parser.core.ruler.enableOnly(rules[: rules.index("inline")])
72 tokens.extend(mdit_parser.parse(nb_cell["source"], mdit_env))
73 tokens.append(
74 Token(
75 "nb_cell_markdown_close",
76 "",
77 -1,
78 hidden=True,
79 ),
80 )
81 elif nb_cell["cell_type"] == "raw":
82 # https://nbformat.readthedocs.io/en/5.1.3/format_description.html#raw-nbconvert-cells
83 tokens = [
84 Token(
85 "nb_cell_raw",
86 "code",
87 0,
88 content=nb_cell["source"],
89 meta={
90 "index": cell_index,
91 "metadata": nb_node_to_dict(nb_cell["metadata"]),
92 },
93 map=[0, 0],
94 )
95 ]
96 elif nb_cell["cell_type"] == "code":
97 # https://nbformat.readthedocs.io/en/5.1.3/format_description.html#code-cells
98 # we don't copy the outputs here, since this would
99 # greatly increase the memory consumption,
100 # instead they will referenced by the cell index
101 tokens = [
102 Token(
103 "nb_cell_code",
104 "code",
105 0,
106 content=nb_cell["source"],
107 meta={
108 "index": cell_index,
109 "metadata": nb_node_to_dict(nb_cell["metadata"]),
110 },
111 map=[0, 0],
112 )
113 ]
114 else:
115 pass # TODO create warning
116
117 # update token's source lines, using either a source_map (index -> line),
118 # set when converting to a notebook, or a pseudo base of the cell index
119 smap = notebook.metadata.get("source_map", None)
120 start_line = smap[cell_index] if smap else (cell_index + 1) * 10000
121 start_line += 1 # use base 1 rather than 0
122 for token in tokens:
123 if token.map:
124 token.map = [start_line + token.map[0], start_line + token.map[1]]
125 # also update the source lines for duplicate references
126 for dup_ref in mdit_env.get("duplicate_refs", []):
127 if "fixed" not in dup_ref:
128 dup_ref["map"] = [
129 start_line + dup_ref["map"][0],
130 start_line + dup_ref["map"][1],
131 ]
132 dup_ref["fixed"] = True
133
134 # add tokens to list
135 block_tokens.extend(tokens)
136
137 block_tokens.append(Token("nb_finalise", "", 0, map=[0, 0]))
138
139 # Now all definitions have been gathered, run the inline parsing phase
140 state = StateCore("", mdit_parser, mdit_env, block_tokens)
141 with mdit_parser.reset_rules():
142 rules = mdit_parser.core.ruler.get_active_rules()
143 mdit_parser.core.ruler.enableOnly(rules[rules.index("inline") :])
144 mdit_parser.core.process(state)
145
146 return state.tokens