Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
fastai
GitHub Repository: fastai/fastbook
Path: blob/master/tools/clean.py
492 views
1
#!/usr/bin/env python
2
3
import nbformat
4
from nbdev.export import *
5
from nbdev.clean import *
6
from fastcore.all import *
7
8
_re_header = re.compile(r'^#+\s+\S+')
9
_re_clean = re.compile(r'^\s*#\s*clean\s*')
10
11
def is_header_cell(cell): return _re_header.search(cell['source']) is not None
12
def is_clean_cell(cell): return _re_clean.search(cell['source']) is not None
13
14
_re_questionnaire = re.compile(r'^#+\s+Questionnaire')
15
16
def get_stop_idx(cells):
17
i = 0
18
while i < len(cells) and _re_questionnaire.search(cells[i]['source']) is None: i+=1
19
return i
20
21
def clean_tags(cell):
22
if is_header_cell(cell): return cell
23
for attr in ["id", "caption", "alt", "width", "hide_input", "hide_output", "clean"]:
24
cell["source"] = re.sub(r'#\s*' + attr + r'.*?($|\n)', '', cell["source"])
25
return cell
26
27
def proc_nb(fname, dest):
28
nb = read_nb(fname)
29
i = get_stop_idx(nb['cells'])
30
nb['cells'] = [clean_tags(c) for j,c in enumerate(nb['cells']) if
31
c['cell_type']=='code' or is_header_cell(c) or is_clean_cell(c) or j >= i]
32
clean_nb(nb, clear_all=True)
33
with open(dest/fname.name, 'w') as f: nbformat.write(nb, f, version=4)
34
35
def proc_all(path='.', dest_path='clean'):
36
path,dest_path = Path(path),Path(dest_path)
37
fns = [f for f in path.iterdir() if f.suffix == '.ipynb' and not f.name.startswith('_')]
38
for fn in fns: proc_nb(fn, dest=dest_path)
39
40
if __name__=='__main__': proc_all()
41
42
43