-
Notifications
You must be signed in to change notification settings - Fork 15
/
__init__.py
242 lines (199 loc) · 7.98 KB
/
__init__.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
"""A sphinx extension for including notebook files from outside sphinx source root.
Usage:
- Install the package.
- Add 'nbsphinx_link' to extensions in Sphinx config 'conf.py'
- Add a file with the '.nblink' extension where you want them included.
The .nblink file is a JSON file with the following structure:
{
"path": "relative/path/to/notebook"
}
Optionally the "extra-media" key can be added, if your notebook includes
any media, i.e. images. The value needs to be an array of strings,
which are paths to the media files or directories.
Further keys might be added in the future.
"""
import json
import os
import shutil
from docutils import io, nodes, utils
from docutils.utils.error_reporting import SafeString, ErrorString
import docutils # noqa: F401
from nbsphinx import NotebookParser, NotebookError, _ipynbversion
import nbformat
from sphinx.util.logging import getLogger
from ._version import __version__
def register_dependency(file_path, document):
"""
Registers files as dependency, so sphinx rebuilds the docs
when they changed.
Parameters
----------
file_path : str
[description]
document: docutils.nodes.document
Parsed document instance.
"""
document.settings.record_dependencies.add(file_path)
document.settings.env.note_dependency(file_path)
def copy_file(src, dest, document):
"""
Copies a singe file from ``src`` to ``dest``.
Parameters
----------
src : str
Path to the source file.
dest : str
Path to the destination file or directory.
document: docutils.nodes.document
Parsed document instance.
"""
logger = getLogger(__name__)
try:
shutil.copy(src, dest)
register_dependency(src, document)
except (OSError) as e:
logger.warning(
"The the file {} couldn't be copied. "
"Error:\n {}".format(src, e)
)
def copy_and_register_files(src, dest, document):
"""
Copies a directory or file from the path ``src`` to ``dest``
and registers all files as dependency,
so sphinx rebuilds the docs when they changed.
Parameters
----------
src : str
Path to the source directory or file
dest : str
Path to the destination directory or file
document: docutils.nodes.document
Parsed document instance.
"""
if os.path.isdir(src):
for root, _, filenames in os.walk(src):
dst_root = os.path.join(dest, os.path.relpath(root, src))
if filenames and not os.path.exists(dst_root):
os.makedirs(dst_root)
for filename in filenames:
src_path = os.path.abspath(os.path.join(root, filename))
copy_file(src_path, dst_root, document)
else:
copy_file(src, dest, document)
def collect_extra_media(extra_media, source_file, nb_path, document):
"""
Collects extra media defined in the .nblink file, with the key
'extra-media'. The extra media (i.e. images) need to be copied
in order for nbsphinx to properly render the notebooks, since
nbsphinx assumes that the files are relative to the .nblink.
Parameters
----------
extra_media : list
Paths to directories and/or files with extra media.
source_file : str
Path to the .nblink file.
nb_path : str
Path to the notebook defined in the .nblink file , with the key 'path'.
document: docutils.nodes.document
Parsed document instance.
"""
any_dirs = False
logger = getLogger(__name__)
source_dir = os.path.dirname(source_file)
if not isinstance(extra_media, list):
logger.warning(
'The "extra-media", defined in {} needs to be a list of paths. '
'The current value is:\n{}'.format(source_file, extra_media)
)
for extract_media_path in extra_media:
if os.path.isabs(extract_media_path):
src_path = extract_media_path
else:
extract_media_relpath = os.path.join(
source_dir, extract_media_path
)
src_path = os.path.normpath(
os.path.join(source_dir, extract_media_relpath)
)
dest_path = utils.relative_path(nb_path, src_path)
dest_path = os.path.normpath(os.path.join(source_dir, dest_path))
if os.path.exists(src_path):
any_dirs = any_dirs or os.path.isdir(src_path)
copy_and_register_files(src_path, dest_path, document)
else:
logger.warning(
'The path "{}", defined in {} "extra-media", '
'isn\'t a valid path.'.format(
extract_media_path, source_file
)
)
if any_dirs:
document.settings.env.note_reread()
class LinkedNotebookParser(NotebookParser):
"""A parser for .nblink files.
The parser will replace the link file with the output from
nbsphinx on the linked notebook. It will also add the linked
file as a dependency, so that sphinx will take it into account
when figuring out whether it should be rebuilt.
The .nblink file is a JSON file with the following structure:
{
"path": "relative/path/to/notebook"
}
Optionally the "extra-media" key can be added, if your notebook includes
any media, i.e. images. The value needs to be an array of strings,
which are paths to the media files or directories.
Further keys might be added in the future.
"""
supported = 'linked_jupyter_notebook',
def parse(self, inputstring, document):
"""Parse the nblink file.
Adds the linked file as a dependency, read the file, and
pass the content to the nbshpinx.NotebookParser.
"""
link = json.loads(inputstring)
env = document.settings.env
source_dir = os.path.dirname(env.doc2path(env.docname))
abs_path = os.path.normpath(os.path.join(source_dir, link['path']))
path = utils.relative_path(None, abs_path)
path = nodes.reprunicode(path)
extra_media = link.get('extra-media', None)
if extra_media:
source_file = env.doc2path(env.docname)
collect_extra_media(extra_media, source_file, path, document)
register_dependency(path, document)
target_root = env.config.nbsphinx_link_target_root
target = utils.relative_path(target_root, abs_path)
target = nodes.reprunicode(target).replace(os.path.sep, '/')
env.metadata[env.docname]['nbsphinx-link-target'] = target
# Copy parser from nbsphinx for our cutom format
try:
formats = env.config.nbsphinx_custom_formats
except AttributeError:
pass
else:
formats.setdefault(
'.nblink',
lambda s: nbformat.reads(s, as_version=_ipynbversion))
try:
include_file = io.FileInput(source_path=path, encoding='utf8')
except UnicodeEncodeError as error:
raise NotebookError(u'Problems with linked notebook "%s" path:\n'
'Cannot encode input file path "%s" '
'(wrong locale?).' %
(env.docname, SafeString(path)))
except IOError as error:
raise NotebookError(u'Problems with linked notebook "%s" path:\n%s.' %
(env.docname, ErrorString(error)))
try:
rawtext = include_file.read()
except UnicodeError as error:
raise NotebookError(u'Problem with linked notebook "%s":\n%s' %
(env.docname, ErrorString(error)))
return super(LinkedNotebookParser, self).parse(rawtext, document)
def setup(app):
"""Initialize Sphinx extension."""
app.setup_extension('nbsphinx')
app.add_source_suffix('.nblink', 'linked_jupyter_notebook')
app.add_source_parser(LinkedNotebookParser)
app.add_config_value('nbsphinx_link_target_root', None, rebuild='env')
return {'version': __version__, 'parallel_read_safe': True}