forked from sphinx-gallery/sphinx-gallery
/
notebook.py
380 lines (313 loc) · 12.9 KB
/
notebook.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
r"""Parser for Jupyter notebooks.
Class that holds the Jupyter notebook information
"""
# Author: Óscar Nájera
# License: 3-clause BSD
from collections import defaultdict
from functools import partial
from itertools import count
import argparse
import base64
import copy
import json
import mimetypes
import os
from pathlib import Path
import re
import sys
import textwrap
from sphinx.errors import ExtensionError
import sphinx.util
from .py_source_parser import split_code_and_text_blocks
logger = sphinx.util.logging.getLogger("sphinx-gallery")
def jupyter_notebook_skeleton():
"""Returns a dictionary with the elements of a Jupyter notebook."""
py_version = sys.version_info
notebook_skeleton = {
"cells": [],
"metadata": {
"kernelspec": {
"display_name": "Python " + str(py_version[0]),
"language": "python",
"name": "python" + str(py_version[0]),
},
"language_info": {
"codemirror_mode": {"name": "ipython", "version": py_version[0]},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython" + str(py_version[0]),
"version": "{}.{}.{}".format(*sys.version_info[:3]),
},
},
"nbformat": 4,
"nbformat_minor": 0,
}
return notebook_skeleton
def directive_fun(match, directive):
"""Helper to fill in directives."""
directive_to_alert = dict(note="info", warning="danger")
return '<div class="alert alert-{}"><h4>{}</h4><p>{}</p></div>'.format(
directive_to_alert[directive], directive.capitalize(), match.group(1).strip()
)
def convert_code_to_md(text):
"""Rewrite code blocks to use Markdown's preferred backtick notation.
Backtick notation preserves syntax highlighting.
Parameters
----------
text: str
A mostly converted string of markdown text. May contain zero, one,
or multiple code blocks in code-block format.
"""
code_regex = r"[ \t]*\.\. code-block::[ \t]*(\S*)\n[ \t]*\n([ \t]+)"
while True:
code_block = re.search(code_regex, text)
if not code_block:
break
indent = code_block.group(2)
start_index = code_block.span()[1] - len(indent)
# Find first non-empty, non-indented line
end = re.compile(rf"^(?!{re.escape(indent)})[ \t]*\S+", re.MULTILINE)
code_end_match = end.search(text, start_index)
end_index = code_end_match.start() if code_end_match else len(text)
contents = textwrap.dedent(text[start_index:end_index]).rstrip()
new_code = f"```{code_block.group(1)}\n{contents}\n```\n"
text = text[: code_block.span()[0]] + new_code + text[end_index:]
return text
def rst2md(text, gallery_conf, target_dir, heading_levels):
"""Converts reST from docstrings and text blocks to markdown for Jupyter notebooks.
Parameters
----------
text: str
reST input to be converted to MD
gallery_conf : dict
The sphinx-gallery configuration dictionary.
target_dir : str
Path that notebook is intended for. Used where relative paths
may be required.
heading_levels: dict
Mapping of heading style ``(over_char, under_char)`` to heading level.
Note that ``over_char`` is `None` when only underline is present.
"""
# Characters recommended for use with headings
# https://docutils.readthedocs.io/en/sphinx-docs/user/rst/quickstart.html#sections
adornment_characters = "=`:.'\"~^_*+#<>-"
headings = re.compile(
# Start of string or blank line
r"(?P<pre>\A|^[ \t]*\n)"
# Optional over characters, allowing leading space on heading text
r"(?:(?P<over>[{0}])(?P=over)*\n[ \t]*)?"
# The heading itself, with at least one non-white space character
r"(?P<heading>\S[^\n]*)\n"
# Under character, setting to same character if over present.
r"(?P<under>(?(over)(?P=over)|[{0}]))(?P=under)*$"
r"".format(adornment_characters),
flags=re.M,
)
text = re.sub(
headings,
lambda match: "{1}{0} {2}".format(
"#" * heading_levels[match.group("over", "under")],
*match.group("pre", "heading"),
),
text,
)
math_eq = re.compile(r"^\.\. math::((?:.+)?(?:\n+^ .+)*)", flags=re.M)
text = re.sub(
math_eq,
lambda match: r"\begin{{align}}{0}\end{{align}}".format(match.group(1).strip()),
text,
)
inline_math = re.compile(r":math:`(.+?)`", re.DOTALL)
text = re.sub(inline_math, r"$\1$", text)
directives = ("warning", "note")
for directive in directives:
directive_re = re.compile(
r"^\.\. %s::((?:.+)?(?:\n+^ .+)*)" % directive, flags=re.M
)
text = re.sub(directive_re, partial(directive_fun, directive=directive), text)
footnote_links = re.compile(r"^ *\.\. _.*:.*$\n", flags=re.M)
text = re.sub(footnote_links, "", text)
embedded_uris = re.compile(r"`([^`]*?)\s*<([^`]*)>`_")
text = re.sub(embedded_uris, r"[\1](\2)", text)
refs = re.compile(r":ref:`")
text = re.sub(refs, "`", text)
contents = re.compile(r"^\s*\.\. contents::.*$(\n +:\S+: *$)*\n", flags=re.M)
text = re.sub(contents, "", text)
images = re.compile(r"^\.\. image::(.*$)((?:\n +:\S+:.*$)*)\n", flags=re.M)
image_opts = re.compile(r"\n +:(\S+): +(.*)$", flags=re.M)
text = re.sub(
images,
lambda match: '<img src="{}"{}>\n'.format(
generate_image_src(match.group(1).strip(), gallery_conf, target_dir),
re.sub(image_opts, r' \1="\2"', match.group(2) or ""),
),
text,
)
text = convert_code_to_md(text)
return text
def generate_image_src(image_path, gallery_conf, target_dir):
"""Modify image path for notebook, according to "notebook_images" config.
URLs are unchanged.
If "notebook_images" config is a str, it is used as a prefix to image path, relative
to "src_dir". If "notebook_images" is `True`, image is embedded as URI. If
"notebook_images" is `False`, "file://" is prepended.
"""
if re.match(r"https?://", image_path):
return image_path
if not gallery_conf["notebook_images"]:
return "file://" + image_path.lstrip("/")
# If absolute path from source directory given
if image_path.startswith("/"):
# Path should now be relative to source dir, not target dir
target_dir = gallery_conf["src_dir"]
image_path = image_path.lstrip("/")
full_path = os.path.join(target_dir, image_path.replace("/", os.sep))
if isinstance(gallery_conf["notebook_images"], str):
# Use as prefix e.g. URL
prefix = gallery_conf["notebook_images"]
rel_path = os.path.relpath(full_path, gallery_conf["src_dir"])
return prefix + rel_path.replace(os.sep, "/")
else:
# True, but not string. Embed as data URI.
try:
with open(full_path, "rb") as image_file:
data = base64.b64encode(image_file.read())
except OSError:
raise ExtensionError(
f"Unable to open {full_path} to generate notebook data URI"
)
mime_type = mimetypes.guess_type(full_path)
return f"data:{mime_type[0]};base64,{data.decode('ascii')}"
def jupyter_notebook(script_blocks, gallery_conf, target_dir):
"""Generate a Jupyter notebook file cell-by-cell.
Parameters
----------
script_blocks : list
Script execution cells.
gallery_conf : dict
The sphinx-gallery configuration dictionary.
target_dir : str
Path that notebook is intended for. Used where relative paths
may be required.
"""
first_cell = gallery_conf["first_notebook_cell"]
last_cell = gallery_conf["last_notebook_cell"]
work_notebook = jupyter_notebook_skeleton()
if first_cell is not None:
add_code_cell(work_notebook, first_cell)
fill_notebook(work_notebook, script_blocks, gallery_conf, target_dir)
if last_cell is not None:
add_code_cell(work_notebook, last_cell)
return work_notebook
def add_code_cell(work_notebook, code):
"""Add a code cell to the notebook.
Parameters
----------
code : str
Cell content
"""
code_cell = {
"cell_type": "code",
"execution_count": None,
"metadata": {"collapsed": False},
"outputs": [],
"source": [code.strip()],
}
work_notebook["cells"].append(code_cell)
def add_markdown_cell(work_notebook, markdown):
"""Add a markdown cell to the notebook.
Parameters
----------
markdown : str
Markdown cell content.
"""
markdown_cell = {"cell_type": "markdown", "metadata": {}, "source": [markdown]}
work_notebook["cells"].append(markdown_cell)
def promote_jupyter_cell_magic(work_notebook, markdown):
"""Promote Jupyter cell magic in text blocks to code block in notebooks.
Parses a block of markdown text looking for code blocks starting with a
Jupyter cell magic (e.g. %%bash). Whenever one is found, the text before it
and the code (as a runnable code block) are added to work_notebook. Any
remaining text is returned.
Parameters
----------
markdown : str
Markdown cell content.
"""
# Regex detects all code blocks that use %% Jupyter cell magic
cell_magic_regex = r"\n?```\s*[a-z]*\n(%%(?:[\s\S]*?))\n?```\n?"
text_cell_start = 0
for magic_cell in re.finditer(cell_magic_regex, markdown):
# Extract the preceding text block, and add it if non-empty
text_block = markdown[text_cell_start : magic_cell.span()[0]]
if text_block and not text_block.isspace():
add_markdown_cell(work_notebook, text_block)
text_cell_start = magic_cell.span()[1]
code_block = magic_cell.group(1)
add_code_cell(work_notebook, code_block)
# Return remaining text (which equals markdown if no magic cells exist)
return markdown[text_cell_start:]
def fill_notebook(work_notebook, script_blocks, gallery_conf, target_dir):
"""Writes the Jupyter notebook cells.
If available, uses pypandoc to convert rst to markdown.
Parameters
----------
script_blocks : list
Each list element should be a tuple of (label, content, lineno).
"""
heading_level_counter = count(start=1)
heading_levels = defaultdict(lambda: next(heading_level_counter))
for blabel, bcontent, lineno in script_blocks:
if blabel == "code":
add_code_cell(work_notebook, bcontent)
else:
if gallery_conf["pypandoc"] is False:
markdown = rst2md(
bcontent + "\n", gallery_conf, target_dir, heading_levels
)
else:
import pypandoc
# pandoc automatically adds \n to the end
markdown = pypandoc.convert_text(
bcontent, to="md", format="rst", **gallery_conf["pypandoc"]
)
if gallery_conf["promote_jupyter_magic"]:
remaining = promote_jupyter_cell_magic(work_notebook, markdown)
if remaining and not remaining.isspace():
add_markdown_cell(work_notebook, remaining)
else:
add_markdown_cell(work_notebook, markdown)
def save_notebook(work_notebook, write_file):
"""Saves the Jupyter work_notebook to write_file."""
with open(write_file, "w") as out_nb:
json.dump(work_notebook, out_nb, indent=2)
###############################################################################
# Notebook shell utility
def python_to_jupyter_cli(args=None, namespace=None, sphinx_gallery_conf=None):
"""Exposes the jupyter notebook renderer to the command line.
Takes the same arguments as ArgumentParser.parse_args.
`sphinx_gallery_conf` functions same as in `conf.py`.
"""
from . import gen_gallery # To avoid circular import
parser = argparse.ArgumentParser(description="Sphinx-Gallery Notebook converter")
parser.add_argument(
"python_src_file",
nargs="+",
help="Input Python file script to convert. "
"Supports multiple files and shell wildcards"
" (e.g. *.py)",
)
args = parser.parse_args(args, namespace)
# handle `sphinx_gallery_conf`
gallery_conf = copy.deepcopy(gen_gallery.DEFAULT_GALLERY_CONF)
if sphinx_gallery_conf is not None:
gallery_conf.update(sphinx_gallery_conf)
# run script
for src_file in args.python_src_file:
file_conf, blocks = split_code_and_text_blocks(src_file)
print(f"Converting {src_file}")
target_dir = os.path.dirname(src_file)
example_nb = jupyter_notebook(blocks, copy.deepcopy(gallery_conf), target_dir)
save_notebook(example_nb, Path(src_file).with_suffix(".ipynb"))