-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy path_custom_notebook.py
276 lines (205 loc) · 6.03 KB
/
_custom_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
import json
import argparse
import os
import re
from shutil import copyfile
def hide_cells(notebook):
"""
Finds the tag 'hide' in each cell and removes it
Returns dict without 'hide' tagged cells
"""
clean = []
for cell in notebook['cells']:
try:
if 'hide' in cell['metadata']['tags']:
pass
else:
clean.append(cell)
except KeyError:
clean.append(cell)
notebook['cells'] = clean
return notebook
def keep_cells(notebook):
"""
Finds the tag 'keep' in any cell and if it exists,
remove the ones that don't have it
Returns dict without 'hide' tagged cells
"""
has_keep = False
for cell in notebook['cells']:
try:
if 'keep' in cell['metadata']['tags']:
has_keep = True
break
except KeyError:
pass
if has_keep:
clean = []
for cell in notebook['cells']:
try:
if 'keep' in cell['metadata']['tags']:
clean.append(cell)
except KeyError:
pass
notebook['cells'] = clean
return notebook
def empty_cells(notebook):
"""
Finds the tag 'empty' in each cell and removes its content
Returns dict with empty cells
"""
clean = []
for cell in notebook['cells']:
try:
tags = cell['metadata']['tags']
if True in map(lambda x: x.lower().startswith('empty'), tags):
cell['source'] = []
clean.append(cell)
except KeyError:
clean.append(cell)
notebook['cells'] = clean
return notebook
def exercise_cells(notebook):
"""
Finds the tag 'exe' in each cell and applies HTML template
Returns dict with template cells
"""
clean = []
wraphead = ["<div class=\"alert alert-success\">\n",
]
wraptail = ["\n</div>",
]
for cell in notebook['cells']:
try:
tags = cell['metadata']['tags']
if True in [t.lower().startswith('ex') for t in tags]:
src = cell['source']
src = [re.sub(r"^#+? (.+)\n", r"<h3>\1</h3>\n", s) for s in src]
cell['source'] = wraphead + src + wraptail
except KeyError:
pass
clean.append(cell)
notebook['cells'] = clean
return notebook
def hide_code(notebook):
"""
Finds the tags '#!--' and '#--! in each cell and removes
the lines in between.
Returns dict
"""
for i, cell in enumerate(notebook['cells']):
istart = 0
istop = -1
for idx, line in enumerate(cell['source']):
if '#!--' in line:
istart = idx
if '#--!' in line:
istop = idx
notebook['cells'][i]['source'] = cell['source'][:istart] + cell['source'][istop+1:]
return notebook
def hide_toolbar(notebook):
"""
Finds the display toolbar tag and hides it
"""
if 'celltoolbar' in notebook['metadata']:
del(notebook['metadata']['celltoolbar'])
return notebook
def stripout(fname):
"""
Removes all output cells
"""
response = os.system("nbstripout {}".format(fname))
return
def process(fname,
outname,
poutput=True,
pkeep=True,
phide=True,
pexercise=True,
phidecode=True):
"""
Loads an 'ipynb' file as a dict and performs cleaning tasks
Writes cleaned version
"""
print(fname)
# if poutput:
# stripout(fname)
with open(fname, 'r') as f:
notebook_s = f.read()
notebook = json.loads(notebook_s, encoding='utf-8')
if pkeep:
notebook = keep_cells(notebook)
if phide:
notebook = hide_cells(notebook)
if pexercise:
notebook = exercise_cells(notebook)
if phidecode:
notebook = hide_code(notebook)
notebook = hide_toolbar(notebook)
with open(outname, 'w') as f:
_ = f.write(json.dumps(notebook))
return
def makedirs(name):
"""
"""
try:
os.mkdir(name)
except:
pass
return
def movefiles(names, dest):
"""
"""
for name in names:
copyfile(name.strip('\n'), dest+'/'+name.split("/")[-1].strip('\n'))
return
def processList(fname):
"""
Loads an 'txt' file with notebook filenames
and performs cleaning tasks on them
Writes cleaned version
"""
with open(fname, 'r') as f:
notebook_list = f.readlines()
student = 'notebooks'
# instructor = 'instructor'
makedirs(student)
# makedirs(instructor)
movefiles(notebook_list, student)
# movefiles(notebook_list, instructor)
cwd = os.getcwd()
os.chdir(os.path.join(cwd, student))
for name in notebook_list:
fname = name.split("/")[-1].strip('\n')
process(fname, fname)
# os.chdir(os.path.join(cwd, instructor))
# for name in notebook_list:
# fname = name.split("/")[-1].strip('\n')
# process(fname, fname,
# poutput=True,
# pkeep=False,
# phide=False,
# pexercise=True,
# phidecode=False)
return
def main(argv=None):
"""
Usage:
python custom_notebook.py --infile name.ipynb --outfile out.ipynb
"""
argp = argparse.ArgumentParser(description='Convert a set of notebooks')
argp.add_argument('--infile', nargs='?', type=str,
help='The .ipynb file')
argp.add_argument('--outfile', type=str,
help='Output filename.')
argp.add_argument('--listfile', type=str,
help='Text file with Notebook filenames')
args = argp.parse_args(argv)
if args.infile:
if not args.infile.endswith('.ipynb'):
raise FileNotFoundError("Could not find an ipynb file. Did you mean to use --listfile ??")
process(args.infile, args.outfile)
else:
processList(args.listfile)
if __name__ == '__main__':
main()