Switch to unified view

a b/ndv/utils/notebook2script.py
1
2
import json, fire, re
3
from pathlib import Path
4
5
def is_export(cell):
6
    if cell['cell_type'] != 'code': return False
7
    src = cell['source']
8
    if len(src) == 0 or len(src[0]) < 7: return False
9
    return re.match(r'^\s*#\s*export\s*$', src[0], re.IGNORECASE) is not None
10
11
def notebook2script(fname):
12
    fname = Path(fname)
13
    fname_out = f'nb_{fname.stem.split("_")[0]}.py'
14
    main_dic = json.load(open(fname, 'r'))
15
    code_cells = [c for c in main_dic['cells'] if is_export(c)]
16
    module = f'''
17
#################################################
18
### THIS FILE WAS AUTOGENERATED! DO NOT EDIT! ###
19
#################################################
20
# file to edit: dev_nb/{fname.name}
21
'''
22
    for cell in code_cells: module += ''.join(cell['source'][1:]) + '\n\n'
23
    # remove trailing spaces
24
    module = re.sub(r' +$', '', module, flags=re.MULTILINE)
25
    open(fname.parent/'exp'/fname_out,'w').write(module[:-2])
26
    print(f"Converted {fname} to {fname_out}")
27
28
if __name__ == '__main__': fire.Fire(notebook2script)
29
30