Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
jantic
GitHub Repository: jantic/deoldify
Path: blob/master/fastai/gen_doc/convert2html.py
781 views
1
import os.path, re, nbformat, jupyter_contrib_nbextensions
2
from nbconvert.preprocessors import Preprocessor
3
from nbconvert import HTMLExporter
4
from traitlets.config import Config
5
from pathlib import Path
6
7
__all__ = ['read_nb', 'convert_nb', 'convert_all']
8
9
exporter = HTMLExporter(Config())
10
exporter.exclude_input_prompt=True
11
exporter.exclude_output_prompt=True
12
#Loads the template to deal with hidden cells.
13
exporter.template_file = 'jekyll.tpl'
14
path = Path(__file__).parent
15
exporter.template_path.append(str(path))
16
17
def read_nb(fname):
18
"Read the notebook in `fname`."
19
with open(fname,'r') as f: return nbformat.reads(f.read(), as_version=4)
20
21
def convert_nb(fname, dest_path='.'):
22
"Convert a notebook `fname` to html file in `dest_path`."
23
from .gen_notebooks import remove_undoc_cells, remove_code_cell_jupyter_widget_state_elem
24
nb = read_nb(fname)
25
nb['cells'] = remove_undoc_cells(nb['cells'])
26
nb['cells'] = remove_code_cell_jupyter_widget_state_elem(nb['cells'])
27
fname = Path(fname).absolute()
28
dest_name = fname.with_suffix('.html').name
29
meta = nb['metadata']
30
meta_jekyll = meta['jekyll'] if 'jekyll' in meta else {'title': fname.with_suffix('').name}
31
meta_jekyll['nb_path'] = f'{fname.parent.name}/{fname.name}'
32
with open(f'{dest_path}/{dest_name}','w') as f:
33
f.write(exporter.from_notebook_node(nb, resources=meta_jekyll)[0])
34
35
def convert_all(folder, dest_path='.', force_all=False):
36
"Convert modified notebooks in `folder` to html pages in `dest_path`."
37
path = Path(folder)
38
39
changed_cnt = 0
40
for fname in path.glob("*.ipynb"):
41
# only rebuild modified files
42
fname_out = Path(dest_path)/fname.with_suffix('.html').name
43
if not force_all and fname_out.exists():
44
in_mod = os.path.getmtime(fname)
45
out_mod = os.path.getmtime(fname_out)
46
if in_mod < out_mod: continue
47
48
print(f"converting: {fname} => {fname_out}")
49
changed_cnt += 1
50
convert_nb(fname, dest_path=dest_path)
51
if not changed_cnt: print("No notebooks were modified")
52
53