-
Notifications
You must be signed in to change notification settings - Fork 2
/
strip_solutions.py
94 lines (83 loc) · 2.55 KB
/
strip_solutions.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
import json
import argparse
from pathlib import Path
import os
from shutil import copytree, ignore_patterns
BASE_CELL = {
"cell_type": "code",
"execution_count": None,
"metadata": {},
"outputs": [],
}
EMPTY_CELL = BASE_CELL.copy()
EMPTY_CELL["source"] = ["# Insert your solution:\n"]
WIDGET_CELL = BASE_CELL.copy()
WIDGET_CELL["source"] = ["%matplotlib widget"]
parser = argparse.ArgumentParser(description="Remove solution cells from all notebooks")
parser.add_argument(
"destination", type=str, help="Destination folder for collecting outputs."
)
args = parser.parse_args()
def clean(filepath, destination, add_mpl_widget_cell=False):
with open(filepath, "r") as myfile:
data = myfile.read()
obj = json.loads(data)
out = []
if add_mpl_widget_cell:
out.append(WIDGET_CELL)
for cell in obj["cells"]:
if "tags" in cell["metadata"]:
if ("solution" in cell["metadata"]["tags"]) and (
"dmsc-school-keep" not in cell["metadata"]["tags"]
):
out.append(EMPTY_CELL)
elif (
("remove-cell" in cell["metadata"]["tags"])
and ("dmsc-school-keep" not in cell["metadata"]["tags"])
) or ("dmsc-school-remove" in cell["metadata"]["tags"]):
pass
else:
out.append(cell)
else:
out.append(cell)
obj["cells"] = out
outfile = os.path.join(destination, filepath)
with open(outfile, "w", encoding="utf-8") as f:
json.dump(obj, f, indent=1)
f.write("\n")
if __name__ == "__main__":
copytree(
".",
args.destination,
ignore=ignore_patterns(
".git*",
"*.pyc",
"__pycache__",
"*.ipynb_checkpoints",
"README.md",
"LICENSE",
"references.bib",
"*.html",
"*.yml",
"_static",
"article",
"clean_metadata.py",
"glossary.md",
"favicon.ico",
"intro.md",
"requirements.txt",
"strip_solutions.py",
"update_workbook.py",
),
dirs_exist_ok=True,
)
notebooks_with_figures = ("matplotlib", "3-mcstas", "4-reduction", "5-analysis")
for path in Path(".").rglob("*.ipynb"):
print(path)
clean(
filepath=path,
destination=args.destination,
add_mpl_widget_cell=any(
string in str(path) for string in notebooks_with_figures
),
)