-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathprepare-ipynb
executable file
·195 lines (141 loc) · 4.74 KB
/
prepare-ipynb
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
#! /usr/bin/env python3
from copy import deepcopy
from json import dump, load
class _SourceReplacer:
def __init__(self, cell):
self.cell = cell
def get(self):
cell = self.cell
if "inputs" in cell:
self.attr = "input"
return cell["inputs"]
if "input" in cell:
self.attr = "input"
return cell["input"]
if "source" in cell:
self.attr = "source"
return cell["source"]
print(cell)
raise ValueError("no inputs found")
def set(self, inputs):
if self.attr == "input" and "inputs" in self.cell:
del self.cell["inputs"]
self.cell[self.attr] = inputs
self.cell.pop("id", None)
class _CellsReplacer:
def __init__(self, ipynb):
self.ipynb = ipynb
self.has_worksheets = "worksheets" in ipynb
def get_cell_lists(self):
if self.has_worksheets:
return [ws["cells"] for ws in self.ipynb["worksheets"]]
else:
return [self.ipynb["cells"]]
def set_cell_lists(self, clists):
if self.has_worksheets:
for ws, cells in zip(self.ipynb["worksheets"], clists, strict=True):
ws["cells"] = cells
else:
cells, = clists
self.ipynb["cells"] = cells
def remove_marks(cell):
if cell["cell_type"] != "code":
return [cell]
sr = _SourceReplacer(cell)
inputs = sr.get()
new_inputs = []
for input_line in inputs:
if ("#clear" not in input_line
and "#beginclear" not in input_line
and "#endclear" not in input_line):
new_inputs.append(input_line)
sr.set(new_inputs)
return [cell]
def clear_output(cell):
if cell["cell_type"] != "code":
return [cell]
cell["outputs"] = []
cell.pop("prompt_number", None)
return [cell]
def process_input_lines(inputs):
made_changes = False
clearing = False
new_inputs = []
for input_line in inputs:
if "#clear" in input_line:
return [], True
elif "#beginclear" in input_line:
clearing = True
made_changes = True
new_inputs.append(input_line.replace("#beginclear", "..."))
elif "#endclear" in input_line:
clearing = False
elif not clearing:
new_inputs.append(input_line)
if clearing:
contents = "".join(inputs)
raise ValueError(f"unterminated #beginclear in cell with '{contents}'")
return new_inputs, made_changes
def clear_marked_inputs(cell):
if cell["cell_type"] != "code":
return [cell]
sr = _SourceReplacer(cell)
new_inputs, made_changes = process_input_lines(sr.get())
if made_changes:
sr.set(new_inputs)
return [cell]
def clear_and_collapse_marked_inputs(cell):
if cell["cell_type"] != "code":
return [cell]
old_cell = deepcopy(cell)
sr = _SourceReplacer(cell)
new_inputs, made_changes = process_input_lines(sr.get())
if made_changes:
sr.set(new_inputs)
if made_changes:
old_cell, = remove_marks(old_cell)
old_cell_md = old_cell.setdefault("metadata", {})
old_cell_jupy = old_cell_md.setdefault("jupyter", {})
old_cell_jupy["source_hidden"] = True
old_sr = _SourceReplacer(old_cell)
old_sr.set(["# expand this cell for solution\n"] + old_sr.get())
return [cell, old_cell]
else:
return [cell]
OP_FUNCS = {
"remove-marks": remove_marks,
"clear-output": clear_output,
"clear-marked-inputs": clear_marked_inputs,
"clear-and-collapse-marked-inputs": clear_and_collapse_marked_inputs,
}
def main():
from argparse import ArgumentParser
parser = ArgumentParser()
parser.add_argument(
"operations",
choices=tuple(OP_FUNCS.keys()),
nargs="+")
parser.add_argument("infile", metavar="INFILE.ipynb")
parser.add_argument("outfile", metavar="OUTFILE.ipynb")
args = parser.parse_args()
with open(args.infile, "rt", encoding="utf-8") as inf:
ipynb = load(inf)
cr = _CellsReplacer(ipynb)
new_clists = []
for clist in cr.get_cell_lists():
new_cells = []
for cell in clist:
result_cells = [cell]
for op in args.operations:
result_cells = [
rcell
for cell in result_cells
for rcell in OP_FUNCS[op](cell)
]
new_cells.extend(result_cells)
new_clists.append(new_cells)
cr.set_cell_lists(new_clists)
with open(args.outfile, "wt") as outf:
dump(ipynb, outf, indent=2, sort_keys=True)
if __name__ == "__main__":
main()