-
Notifications
You must be signed in to change notification settings - Fork 21
/
nbconvert.py
255 lines (201 loc) · 6.45 KB
/
nbconvert.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
import sys
import re
from subprocess import run
from textwrap import dedent
from ..core.helpers import console
from ..core.files import unexpanduser as ux, isDir, fileCopy, scanDir, initTree
__pdoc__ = {}
HELP = """
``` sh
nbconvert inputDir [outputDir]
```
Several modes:
Copy mode
---------
If outputDir is given and not equal to "-":
Converts all `.ipynb` files in `inputDir` to `.html` files in `outputDir`.
Copies all other files in `inputDir` to `outputDir`.
If `outputDir` does not exist, it will be created.
Makes sure that all links in the resulting HTML to one of the
original `.ipynb` files are transformed in links to the converted `.html` files.
In place mode
-------------
If outputDir is given and equal to "-":
Converts all `.ipynb` files in `inputDir` to `.html` files next to their originals.
Overwrites existing HTML names with the same name.
Makes sure that all links in the resulting HTML to one of the
original `.ipynb` files are transformed in links to the converted `.html` files.
Index mode
----------
Without outputDir
Generates an index.html file in inputDir with links
to all HTML files that can be recursively found inside the inputDir.
Command switches
``` sh
-h
--help
```
"""
HTML_EXT = ".html"
NB_EXT = ".ipynb"
INDEX = "index.html"
def task(*args):
inputDir = args[0]
if not isDir(inputDir):
console(f"Input directory does not exist: {inputDir}")
return 1
if len(args) == 1:
console("INDEX MODE")
makeIndex(inputDir)
else:
convertDir(inputDir, args[1])
def makeIndex(inputDir):
htmlStart = dedent(
"""
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
</head>
<style>
div {
padding-left: 3em;
}
</style>
<body>
"""
)
htmlEnd = dedent(
"""
</body>
</html>
"""
)
def doSubDir(path):
subInputDir = inputDir if path == "" else f"{inputDir}/{path}"
theseLinks = []
with scanDir(subInputDir) as dh:
for entry in dh:
name = entry.name
if name.startswith("."):
continue
subPath = name if path == "" else f"{path}/{name}"
if entry.is_dir():
subResult = doSubDir(subPath)
if len(subResult) > 0:
theseLinks.append((name, path, doSubDir(subPath)))
elif name.endswith(HTML_EXT) and name != INDEX:
theseLinks.append((name, path))
return sorted(theseLinks)
def formatDir(entry):
if len(entry) == 3:
(name, path, subEntries) = entry
subResults = "\n".join(formatDir(subEntry) for subEntry in subEntries)
return dedent(
f"""
<details>
<summary>{name}</summary>
<div>
{subResults}
</div>
</details>
"""
).strip()
else:
(name, path) = entry
url = name if path == "" else f"{path}/{name}"
return f"""<a href="{url}">{name.removesuffix(HTML_EXT)}</a><br>"""
console(f"Creating a table of contents for {ux(inputDir)}")
result = doSubDir("")
html = "\n".join(formatDir(d) for d in result)
html = f"{htmlStart}{html}{htmlEnd}"
filePath = INDEX if inputDir == "" else f"{inputDir}/{INDEX}"
with open(filePath, "w", encoding="utf8") as fh:
fh.write(html)
console(f"Created {ux(filePath)}")
def convertDir(inputDir, outputDir):
inPlace = outputDir == "-"
console("IN PLACE MODE" if inPlace else "COPY MODE")
if not inPlace:
initTree(outputDir, fresh=True)
convertedNotebooks = []
def escapeSpace(x):
return x.replace(" ", "\\ ")
def doSubDir(path):
subInputDir = inputDir if path == "" else f"{inputDir}/{path}"
if not inPlace:
subOutputDir = outputDir if path == "" else f"{outputDir}/{path}"
initTree(subOutputDir)
theseNotebooks = []
with scanDir(subInputDir) as dh:
for entry in dh:
name = entry.name
if name.startswith("."):
continue
subPath = name if path == "" else f"{path}/{name}"
if entry.is_dir():
doSubDir(subPath)
elif name.endswith(NB_EXT):
theseNotebooks.append(name)
else:
if not inPlace:
fileCopy(f"{subInputDir}/{name}", f"{subOutputDir}/{name}")
if len(theseNotebooks):
command = "jupyter nbconvert --to html"
inFiles = " ".join(
f"{subInputDir}/{escapeSpace(name)}" for name in theseNotebooks
)
destDir = subInputDir if inPlace else subOutputDir
commandLine = f"{command} --output-dir={destDir} {inFiles}"
run(commandLine, shell=True)
for thisNotebook in theseNotebooks:
convertedNotebooks.append(
(destDir, thisNotebook.replace(NB_EXT, ""))
)
doSubDir("")
convertedPat = ")|(?:".join(re.escape(c[1]) for c in convertedNotebooks)
LINK_RE = re.compile(
rf"""
\b
(
(?:
href|src
)
=
['"]
(?:
[^'"]*/
)?
(?:
{convertedPat}
)
)
(?:
{NB_EXT}
)
(
['"]
)
""",
re.X,
)
def processLinks(text):
return LINK_RE.sub(r"\1.html\2", text)
console("fixing links to converted notebooks:")
for (path, name) in convertedNotebooks:
pathName = f"{path}/{name}.html"
console(pathName)
with open(pathName, encoding="utf8") as fh:
text = fh.read()
text = processLinks(text)
with open(pathName, "w", encoding="utf8") as fh:
fh.write(text)
def main():
args = sys.argv[1:]
if "-h" in args or "--help" in args or len(args) not in {1, 2}:
console(HELP)
quit()
return task(*args)
__pdoc__["task"] = HELP
if __name__ == "__main__":
exit(main())