Repository navigation
Expand file tree
/
Copy pathgenerate_notebook.py
More file actions
136 lines (107 loc) · 3.91 KB
/
Copy pathgenerate_notebook.py
File metadata and controls
136 lines (107 loc) · 3.91 KB
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
"""
Generate a Jupyter notebook from a lesson's body content.
For each code block in the lesson:
1. Markdown cell with the surrounding explanation
2. Collapsible hint containing the code
3. Empty code cell for the user to type in
"""
import json
import os
import re
try:
import nbformat
from nbformat.v4 import new_notebook, new_markdown_cell, new_code_cell
except ImportError:
nbformat = None
def parse_body_to_blocks(body: str) -> list[dict]:
"""Parse a lesson body into alternating markdown and code blocks."""
blocks = []
code_pattern = re.compile(r'```python\n(.*?)```', re.DOTALL)
last_end = 0
for match in code_pattern.finditer(body):
start, end = match.span()
text_before = body[last_end:start].strip()
if text_before:
blocks.append({'type': 'markdown', 'text': text_before})
code = match.group(1).strip()
blocks.append({'type': 'code', 'code': code})
last_end = end
remaining = body[last_end:].strip()
if remaining:
blocks.append({'type': 'markdown', 'text': remaining})
return blocks
def generate_notebook(lesson_id: str, lesson_title: str, body: str,
exercises: list = None):
"""Generate a Jupyter notebook from lesson content."""
nb = new_notebook()
nb.metadata['kernelspec'] = {
'display_name': 'Python 3',
'language': 'python',
'name': 'python3'
}
nb.cells.append(new_markdown_cell(f"# {lesson_id} - {lesson_title}"))
blocks = parse_body_to_blocks(body)
for block in blocks:
if block['type'] == 'markdown':
nb.cells.append(new_markdown_cell(block['text']))
elif block['type'] == 'code':
hint_md = (
"<details>\n"
"<summary>Show code</summary>\n\n"
"```python\n"
f"{block['code']}\n"
"```\n"
"</details>"
)
nb.cells.append(new_markdown_cell(hint_md))
nb.cells.append(new_code_cell(""))
if exercises:
nb.cells.append(new_markdown_cell("---\n# Exercises"))
for i, ex in enumerate(exercises, 1):
ex_md = f"### Exercise {i}: {ex['title']}\n\n{ex['description']}"
nb.cells.append(new_markdown_cell(ex_md))
if ex.get('hint'):
hint_md = (
"<details>\n"
"<summary>Show hint</summary>\n\n"
f"{ex['hint']}\n"
"</details>"
)
nb.cells.append(new_markdown_cell(hint_md))
nb.cells.append(new_code_cell(""))
return nb
def generate_all():
"""Generate notebooks for all lessons."""
os.makedirs('notebooks', exist_ok=True)
with open('data/curriculum.json') as f:
curriculum = json.load(f)
total = 0
skipped = 0
for phase in curriculum['phases']:
phase_num = int(phase['id'].split('-')[1])
json_path = f'data/content/phase-{phase_num}.json'
try:
with open(json_path) as f:
content = json.load(f)
except FileNotFoundError:
continue
for module in phase['modules']:
for lesson in module['lessons']:
lid = lesson['id']
lesson_data = content.get(lid)
if not lesson_data or 'body' not in lesson_data:
skipped += 1
continue
nb = generate_notebook(
lid,
lesson['title'],
lesson_data['body'],
lesson_data.get('exercises', [])
)
out_path = f'notebooks/{lid}.ipynb'
with open(out_path, 'w') as f:
nbformat.write(nb, f)
total += 1
print(f"Generated {total} notebooks, skipped {skipped}")
if __name__ == '__main__':
generate_all()