forked from mbeyeler/opencv-machine-learning
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathadd_navigation.py
57 lines (43 loc) · 1.74 KB
/
add_navigation.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
import os
import itertools
from ipykernel import kernelspec as ks
import nbformat
from nbformat.v4.nbbase import new_markdown_cell
from generate_contents import NOTEBOOK_DIR, REG, iter_notebooks, get_notebook_title
def prev_this_next(it):
a, b, c = itertools.tee(it, 3)
next(c)
return zip(itertools.chain([None], a), b, itertools.chain(c, [None]))
PREV_TEMPLATE = "< [{title}]({url}) "
CONTENTS = "| [Contents](../README.md) |"
NEXT_TEMPLATE = " [{title}]({url}) >"
NAV_COMMENT = "<!--NAVIGATION-->\n"
def iter_navbars():
for prev_nb, nb, next_nb in prev_this_next(iter_notebooks()):
navbar = NAV_COMMENT
if prev_nb:
navbar += PREV_TEMPLATE.format(title=get_notebook_title(prev_nb),
url=prev_nb)
navbar += CONTENTS
if next_nb:
navbar += NEXT_TEMPLATE.format(title=get_notebook_title(next_nb),
url=next_nb)
yield os.path.join(NOTEBOOK_DIR, nb), navbar
def write_navbars():
for nb_name, navbar in iter_navbars():
nb = nbformat.read(nb_name, as_version=4)
nb_file = os.path.basename(nb_name)
is_comment = lambda cell: cell.source.startswith(NAV_COMMENT)
if is_comment(nb.cells[1]):
print("- amending navbar for {0}".format(nb_file))
nb.cells[1].source = navbar
else:
print("- inserting navbar for {0}".format(nb_file))
nb.cells.insert(1, new_markdown_cell(source=navbar))
if is_comment(nb.cells[-1]):
nb.cells[-1].source = navbar
else:
nb.cells.append(new_markdown_cell(source=navbar))
nbformat.write(nb, nb_name)
if __name__ == '__main__':
write_navbars()