-
Notifications
You must be signed in to change notification settings - Fork 5
/
cli.py
executable file
·57 lines (45 loc) · 1.56 KB
/
cli.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
#!/usr/bin/env python
import pathlib
import zipfile
import click
import yaml
from nbconvert.exporters import NotebookExporter
from nbconvert.preprocessors import ClearOutputPreprocessor
def get_materials() -> dict:
with open("course.yml", "r", encoding="utf8") as f:
course = yaml.safe_load(f)
materials = {
lesson["slug"]: lesson.get("materials", []) for lesson in course["plan"]
}
return materials
def clear_notebook(path: pathlib.Path) -> bytes:
exporter = NotebookExporter()
exporter.register_preprocessor(ClearOutputPreprocessor(), enabled=True)
output = exporter.from_filename(str(path))
return output[0]
@click.group()
def cli():
pass
@cli.command()
@click.argument("slug")
def export(slug: str) -> None:
"""Export all material folders for a lesson as a single zip file.
Clears the output of ipynb jupyter notebook files.
"""
materials = get_materials()
dirs = [
"lessons" / pathlib.Path(material["lesson"]) for material in materials[slug]
]
with zipfile.ZipFile(f"{slug}.zip", "w") as zip:
for dir in dirs:
for file in dir.glob("**/*"):
click.echo(f" {file}")
if not file.is_file():
continue
if file.suffix == ".ipynb":
content = clear_notebook(file)
zip.writestr(str(file.relative_to(dir.parent)), content)
else:
zip.write(file, arcname=file.relative_to(dir.parent))
if __name__ == "__main__":
cli()