forked from Iota-School/notebooks-for-all
-
Notifications
You must be signed in to change notification settings - Fork 1
/
dodo.py
438 lines (385 loc) · 13.7 KB
/
dodo.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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
from importlib.util import module_from_spec, spec_from_file_location
from pathlib import Path
from shutil import copyfile, copytree
from sys import executable
from doit import create_after, task_params
HERE = Path(__file__).parent
DOCS = Path("docs")
UTESTS = Path("user-tests")
TESTS = Path("tests")
EXPORTS = TESTS / "exports"
NBS = EXPORTS / "notebooks"
CONFIGS = EXPORTS / "configs"
HTML = EXPORTS / "html"
AUDITS = EXPORTS / "audits"
REPORTS = EXPORTS / "reports"
TEMPLATES = Path("nbconvert_a11y/templates/a11y")
def do(cmd, *args):
from shlex import split
from doit.cmd_base import CmdAction
return CmdAction(split(cmd) + list(args), shell=False)
def cp(x, y):
x, y = map(Path, (x, y))
if x.is_dir():
print(f"copy {x} to {y}")
copytree(x, y, dirs_exist_ok=True)
else:
Path.mkdir(y.parent, parents=True, exist_ok=True)
copyfile(x, y)
def task_styles():
def get_pygments(target, theme):
import pygments.formatters
target.write_text(
f"""body {{
background-color: var(--nb-background-color-{theme});
color-scheme: {theme};
}}\n"""
+ pygments.formatters.get_formatter_by_name(
"html", style=f"a11y-high-contrast-{theme}"
).get_style_defs()
)
for theme in ("light", "dark"):
name = f"{theme}-code"
target = (TEMPLATES / name).with_suffix(".css")
yield {
"name": f"{theme}-code",
"targets": [target],
"actions": [(get_pygments, (target, theme))],
"uptodate": [target.exists],
"clean": True,
}
@create_after("styles")
@task_params(
[
{"name": "notebooks", "default": [TESTS / "notebooks/lorenz.ipynb"], "type": list},
{"name": "configurations", "default": [TESTS / "configurations/default.py"], "type": list},
{"name": "target", "default": EXPORTS, "type": str},
]
)
def task_copy(notebooks, configurations, target):
"""Copy all of the notebooks we use for testing into a single directory that is exported with the documentation."""
NB = target / "notebooks"
CONFIGS = target / "configs"
notebooks = list(map(Path, notebooks))
configurations = list(map(Path, configurations))
styles = list(TEMPLATES.glob("*.css"))
scripts = list(TEMPLATES.glob("*.js"))
targets = [NB / x.name for x in notebooks]
def readme(target, ext, title):
body = f"""# {title}\n\n"""
for t in target.glob(f"*.{ext}"):
body += f"* [{t.name}]({t.relative_to(target)})\n"
(target / "README.md").write_text(body)
yield {
"name": "notebooks",
"clean": True,
"actions": [(cp, (x, NB / x.name)) for x in notebooks],
"targets": targets,
"uptodate": list(map(Path.exists, targets)),
}
yield {
"name": "styles",
"clean": True,
"task_dep": ["styles"],
"actions": [(cp, (x, HTML / x.name)) for x in styles],
"targets": [HTML / x.name for x in styles],
"uptodate": list(map(Path.exists, targets)),
}
yield {
"name": "scripts",
"clean": True,
"actions": [(cp, (x, HTML / x.name)) for x in scripts],
"targets": [HTML / x.name for x in scripts],
"uptodate": list(map(Path.exists, targets)),
}
targets = [CONFIGS / x.name for x in configurations]
yield {
"name": "configurations",
"clean": True,
"actions": [(cp, (x, CONFIGS / x.name)) for x in configurations],
"targets": [CONFIGS / x.name for x in configurations],
"uptodate": list(map(Path.exists, targets)),
}
yield {
"name": "readme-nb",
"actions": [(readme, (NB, "ipynb", "reference notebooks"))],
"file_dep": targets,
"clean": True,
"targets": [NB / "README.md"],
}
yield {
"name": "readme-config",
"actions": [(readme, (CONFIGS, "py", "configuration files"))],
"file_dep": targets,
"clean": True,
"targets": [CONFIGS / "README.md"],
}
# this is missing the file_deps and targets
# they can be computed
# for d in "user-tests resources".split():
# DIR = Path(d)
# files = [x for x in DIR.rglob("*") if x.is_file()]
# targets = [EXPORTS / x for x in files]
# print(EXPORTS / DIR)
# yield {
# "name": d,
# "actions": [(cp, (DIR, EXPORTS / DIR))],
# "clean": [f"""rm -rf {EXPORTS / DIR}"""],
# "file_dep": files,
# "targets": targets,
# }
# @task_params(
# [
# dict(name="notebooks", default=[TESTS / "notebooks/lorenz.ipynb"], type=list),
# dict(name="configuration", default="tests/configurations", type=str),
# dict(name="target", default="docs/exports", type=str),
# dict(name="audit", default=True, type=bool),
# ]
# )
# def task_export(notebooks, configuration, target, audit):
# target = Path(target)
# rel = []
# configs = []
# for c in Path(configuration).glob("*.py"):
# for nb in map(Path, notebooks):
# name = "-".join((nb.stem, c.stem))
# t = target / (name + ".html")
# rel.append(t)
# yield dict(
# name=f"export:{name}",
# actions=[
# f"jupyter nbconvert --config {c} --output {name} --output-dir {target} {nb}"
# ],
# file_dep=[nb, c],
# targets=[t],
# clean=True,
# )
# configs.append(
# dict(config=c, nb=nb, html=t, audit=t.parent / "data" / (t.name + ".json"))
# )
# if audit:
# from nbconvert_a11y.audit import main
# audits = [x["audit"] for x in configs]
# yield dict(
# name=f"audit",
# actions=[partial(main, id=rel, output_dir=Path("docs/exports/data"))],
# targets=audits,
# file_dep=[x["html"] for x in configs],
# clean=True,
# )
# INDEX = DOCS / "index.md"
# def get_violations(targets):
# import pandas
# from json import loads
# return (
# targets.apply(lambda x: pandas.Series(loads(x.read_text())))
# .stack()
# .apply(lambda x: len(x["nodes"]))
# .unstack()
# .fillna(0)
# .sum(1)
# .to_frame("nodes in violation")
# )
# def get_index():
# body = "# sample converted notebooks\n\n"
# import pandas
# df = pandas.DataFrame(configs)
# # config and nb are relative to the github repo
# # audit and html are relative to the docs
# names = df.applymap(lambda x: x.stem)
# violations = get_violations(df.audit)
# df = pandas.concat(
# [
# df[["config", "nb"]]
# .applymap(str)
# .applymap("https://github.com/iota-school/notebooks-for-all/blob/main/".__add__),
# df[["audit", "html"]]
# .applymap(lambda x: x.relative_to("docs"))
# .applymap(str)
# .applymap("/notebooks-for-all/".__add__),
# ]
# )
# df = ("[" + names.stack() + "](" + df.stack() + ")").unstack()
# df = df.set_index("config")[["nb", "html", "audit"]] # order the columns
# df = df.assign(violations=violations.values)
# body += df.to_markdown()
# INDEX.write_text(body)
# yield dict(name=f"index", file_dep=audits, targets=[INDEX], actions=[get_index], clean=True)
@create_after("copy")
@task_params(
[
{"name": "notebooks_dir", "default": NBS, "type": str},
{"name": "configs_dir", "default": CONFIGS, "type": str},
{"name": "target", "default": HTML, "type": str},
]
)
def task_convert(notebooks_dir, configs_dir, target):
"""Convert notebooks and configurations to their html outputs."""
target = Path(target)
def readme(target):
body = """# html versions\n\n"""
for t in target.glob("*.html"):
body += f"* [{t.name}]({t.relative_to(target)})\n"
(target / "README.md").write_text(body)
targets = []
for c in Path(configs_dir).glob("*.py"):
for nb in Path(notebooks_dir).glob("*.ipynb"):
name = "-".join((nb.stem, c.stem))
t = Path(target) / (name + ".html")
targets.append(t)
yield {
"name": str(name),
"actions": [
do(
f"{executable} -m jupyter nbconvert --config {c} --output {name} --output-dir {target} {nb}"
)
],
"file_dep": [nb, c],
"targets": [t],
"clean": True,
"basename": "convert",
}
yield {
"name": "readme",
"actions": [(readme, (target,))],
"file_dep": targets,
"targets": [target / "README.md"],
}
@create_after(executed="convert", creates=["audit"])
@task_params(
[
{"name": "html_dir", "default": HTML, "type": str},
{
"name": "target",
"default": AUDITS,
"type": str,
"help": "the subdirectory to place audits in",
},
]
)
def task_audit(html_dir, target):
"""Audit the files in the html directory."""
def readme(target):
body = """# audits\n\n"""
for t in target.glob("*.json"):
body += f"* [{t.name}]({t.relative_to(target)})\n"
(target / "README.md").write_text(body)
from nbconvert_a11y.audit import audit_one
targets = []
for x in Path(html_dir).rglob("*.html"):
print(x.name)
if x.name in {"Imaging_Sky_Background_Estimation-a11y.html"}:
continue
targets.append(Path(target) / x.with_suffix(".json").name)
yield {
"name": x.name,
"actions": [(audit_one, (x, targets[-1]))],
"file_dep": [x],
"targets": [targets[-1]],
"clean": True,
"basename": "audit",
}
yield {
"name": "readme",
"actions": [(readme, (target,))],
"file_dep": targets,
"targets": [target / "README.md"],
}
@create_after(executed="audit")
def task_report():
print((HERE / "tests/templates/report.py").exists())
TPL = HERE / "tests/templates/report.py"
report = module_from_spec(spec_from_file_location("test.templates.report", TPL))
report.__loader__.exec_module(report)
yield {
"name": "readme",
"actions": [report.write_experiments],
"clean": True,
"targets": [REPORTS / "experiment.md"],
}
yield {
"name": "nb",
"actions": [report.write_notebooks],
"clean": True,
"targets": [REPORTS / "notebooks.md"],
}
yield {
"name": "configs",
"actions": [report.write_configs],
"clean": True,
"targets": [REPORTS / "configs.md"],
}
# @create_after(executed="audit", creates=["docs"])
# @task_params(
# [
# dict(name="dir", default="docs/exports", type=str),
# dict(name="folder", default="audit", type=str, help="the subdirectory to place audits in")
# ]
# )
# def task_audit(dir, folder="audit"):
# from nbconvert_a11y.audit import audit_one
# for x in Path(dir).rglob("*.html"):
# a = x.parent / folder / x.name
# yield dict(
# name=str(x.relative_to(dir)),
# actions=[
# (audit_one, (x,))
# ],
# file_dep=[x],
# targets=[a],
# clean=True,
# basename="audit"
# )
# @task_params(
# [
# dict(name="notebooks", default=[TESTS / "notebooks/lorenz.ipynb"], type=list),
# dict(name="configurations", default=[TESTS / "notebooks/lorenz.ipynb"], type=list),
# dict(name="audit", default=True, type=bool),
# ]
# )
# def task_export(notebooks, audit):
# """export html versions of notebooks"""
# rel = []
# for format in ("html", "html5"):
# for notebook in map(Path, notebooks):
# target = notebook.with_suffix(notebook.suffix + f".{format}.html")
# output = DOCS / target
# if notebook.suffix in {".html"}:
# yield dict(
# name=f"html:{format}:{notebook}",
# actions=[(fix_html, (notebook, output))],
# targets=[output],
# file_dep=[notebook],
# )
# else:
# cmd = f"jupyter nbconvert --to={format} --output={target.name} --output-dir={output.parent} {notebook}"
# yield dict(
# name=f"html:{format}:{notebook}",
# actions=[cmd],
# targets=[output],
# file_dep=[notebook],
# )
# rel.append(output)
# rel_targets = [x.parent / "data" / ("axe-" + x.name + ".json") for x in rel]
# if audit:
# from nbconvert_a11y.audit import main
# yield dict(
# name=f"audit",
# actions=[partial(main, id=rel)],
# targets=rel_targets,
# file_dep=rel,
# )
# INDEX = DOCS / "index.md"
# body = "# sample converted notebooks\n\n"
# for id in rel:
# id = id.relative_to("docs")
# body += "* "
# body += f"[original](https://github.com/Iota-School/notebooks-for-all/blob/main/{id}) "
# body += f"[html](/notebooks-for-all/{id}) "
# body += str(id)
# body += "\n"
# yield dict(
# name=f"export_html:{INDEX}",
# targets=[INDEX],
# actions=[(lambda x: INDEX.write_text(x) and None, [body])],
# )