forked from curiousily/Getting-Things-Done-with-Pytorch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathipynb2lmd.py
244 lines (187 loc) · 7.11 KB
/
ipynb2lmd.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
# This scripts is created by Luigi Ballabio: https://github.com/lballabio/ipynb2lmd
import io
import json
import os
import re
import sys
def join(lines):
return "".join(lines)
def in_prompt(prompt_number):
return "In [%d]: " % prompt_number
def out_prompt(prompt_number):
return "Out[%d]: " % prompt_number
def add_prompt(lines, prompt):
"add the prompt on the first line, indent all other lines accordingly"
indentation = " " * len(prompt)
return [prompt + lines[0]] + [indentation + l for l in lines[1:]]
def indent(lines):
"add indentation required for code samples in Markdown"
return [" " + l for l in lines]
def code(lines):
return join(indent(lines))
formulas = re.compile(r"(\$\$?)([^\$]+)(\$\$?)")
def replace_formulas(text):
"In Leanpub Markdown, formulas are delimited by {$$}...{/$$}"
return formulas.sub(r"{$$}\2{/$$}", text)
def text(lines):
return replace_formulas(join(lines))
def convert_markdown(cell, out):
content = text(cell["source"])
if content.startswith("#"):
# a heading
out.write(u"\n")
out.write(content)
out.write(u"\n\n")
def convert_raw(cell, out):
out.write(join(cell["source"]))
out.write(u"\n\n")
def convert_code(cell, out, base_name, output_dir):
prompt_number = cell["execution_count"]
if cell["source"]:
out.write(code(add_prompt(cell["source"], in_prompt(prompt_number))))
out.write(u"\n")
last_output_type = None
for output in cell["outputs"]:
output_type = output["output_type"]
if output_type == "execute_result":
convert_result(
output, out, prompt_number, continued=(output_type == last_output_type)
)
elif output_type == "stream":
convert_stream(
output, out, prompt_number, continued=(output_type == last_output_type)
)
elif output_type == "error":
convert_error(output, out, prompt_number)
elif output_type == "display_data":
if last_output_type in ["execute_result", "stream"]:
out.write(u"\n\n")
convert_image(output, out, base_name, output_dir, prompt_number)
else:
raise Exception("unknown output type: %s" % output_type)
last_output_type = output_type
if last_output_type in ["execute_result", "stream"] and not (
"data" in output and "text/html" in output["data"]
):
out.write(u"\n\n")
out.write(u"\n")
def convert_result(output, out, prompt_number, continued=False):
out.write(u" \n")
if "data" in output and "text/html" in output["data"]:
if not continued:
out.write(code(add_prompt([u""], out_prompt(prompt_number))))
out.write(u"\n")
convert_html(join(output["data"]["text/html"]), out)
else:
prompt = out_prompt(prompt_number)
if continued:
# we don't want the prompt, but we need to indent as if it
# was there.
prompt = " " * len(prompt)
out.write(code(add_prompt(output["data"]["text/plain"], prompt)))
def convert_stream(output, out, prompt_number, continued=False):
out.write(u" \n")
prompt = out_prompt(prompt_number)
if continued:
# we don't want the prompt, but we need to indent as if it
# was there.
prompt = " " * len(prompt)
out.write(code(add_prompt(output["text"], prompt)))
table_html = re.compile(r"<table.*?>(.*)</table>", re.DOTALL)
def convert_html(html, out):
match = table_html.search(html)
if match:
convert_table(match.group(1), out)
else:
raise Exception("Unknown html: %s" % html)
row_html = re.compile(r"<tr.*?>(.*?)</tr>", re.DOTALL)
cell_html = re.compile(r"<t[dh].*?>(.*?)</t[dh]>", re.DOTALL)
def convert_table(table, out):
data = []
rows = row_html.findall(table)
for r in rows:
data.append([x.strip() for x in cell_html.findall(r)])
widths = [max(len(d[i]) for d in data) for i in range(len(data[0]))]
format = "|" + "|".join([" %%%ds " % w for w in widths]) + "|\n"
total_width = len(format % tuple("" for e in widths))
if total_width <= 60:
width = "narrow"
elif total_width >= 80:
width = "wide"
else:
width = "default"
out.write(u'\n{width="%s"}\n' % width)
out.write(format % tuple(data[0]))
out.write("|" + "|".join([u"-" * (w + 2) for w in widths]) + "|\n")
for d in data[1:]:
out.write(format % tuple(d))
out.write(u"\n\n")
terminal_codes = re.compile(r".\[[01](;\d\d)?m")
def convert_error(output, out, prompt_number):
def unescape_terminal_codes(line):
return terminal_codes.sub("", line)
out.write(u" \n")
# There are embedded \n in the lines...
lines = [l + "\n" for line in output["traceback"] for l in line.split("\n")]
# ...and control codes for the terminal
out.write(
code(
add_prompt(
[unescape_terminal_codes(l) for l in lines], out_prompt(prompt_number)
)
)
)
out.write(u"\n\n")
def convert_image(output, out, base_name, output_dir, prompt_number):
ext = extension(output)
images_dir = os.path.join(output_dir, "images")
if not os.path.exists(images_dir):
os.mkdir(images_dir)
image_name = "%s-%d.%s" % (base_name.replace(" ", "_"), prompt_number, ext)
image_path = os.path.join(images_dir, image_name)
with open(image_path, "w") as image:
image.write(output["data"]["image/%s" % ext].decode("base64"))
out.write(u"\n")
out.write(u"" % image_name)
out.write(u"\n\n")
def extension(output):
candidates = set(output["data"].keys()) - {"text/plain"}
# whatever key remains should be the extension
if len(candidates) > 1:
raise Exception("multiple extensions found: %s" % candidates)
candidate = str(candidates.pop())
if not candidate.startswith("image/"):
raise Exception("not an image type: %s" % candidate)
return candidate[6:]
def convert(path, output_dir):
_, filename = os.path.split(path)
base_name, _ = os.path.splitext(filename)
base_name = base_name.lower()
md_name = base_name + ".md"
with open(path) as f:
data = json.load(f)
cells = data["cells"]
with io.open(os.path.join(output_dir, md_name), "w") as out:
for cell in cells:
cell_type = cell["cell_type"]
if cell_type == "markdown":
convert_markdown(cell, out)
elif cell_type == "code":
convert_code(cell, out, base_name, output_dir)
elif cell_type == "raw":
convert_raw(cell, out)
else:
raise Exception("unknown cell type: %s" % cell_type)
if __name__ == "__main__":
if len(sys.argv) != 3:
print(
"""
Usage: %s notebook.ipynb output_dir
The file notebook.md will be created in output_dir; if the
notebook contains images, they will be extracted and stored
in the output_dir/images folder.
"""
% sys.argv[0]
)
sys.exit(1)
convert(os.path.abspath(sys.argv[1]), sys.argv[2])