Skip to content

Commit 12eb7ac

Browse files
committed
Update script for TOC
1 parent 18dbddb commit 12eb7ac

File tree

1 file changed

+18
-7
lines changed

1 file changed

+18
-7
lines changed

tools/generate_contents.py

+18-7
Original file line numberDiff line numberDiff line change
@@ -1,49 +1,60 @@
11
import os
22
import re
33
from argparse import ArgumentParser
4+
from pathlib import Path
45

56
import nbformat
67

78
NOTEBOOK_DIR = os.path.join(os.path.dirname(__file__), '..', 'notebooks')
89

910
NBVERSION = 4
1011

11-
REG = re.compile(r'(\d\d)\.(\d\d)-(.*)\.ipynb')
12+
REG = re.compile(r'.*(\d\d)\.(\d\d)-(.*)\.ipynb')
1213

1314
NO_NUMBER = ['00']
1415

1516
TOC_STYLES = ['header_ulist', 'nested_list']
1617

1718

1819
def iter_notebooks(directory):
19-
return sorted(nb for nb in os.listdir(NOTEBOOK_DIR) if REG.match(nb))
20+
p = Path(directory)
21+
notebooks = p.glob('**/*.ipynb')
22+
notebooks = sorted(notebooks, key=str)
23+
notebooks = [nb for nb in notebooks if not '.ipynb_checkpoints' in str(nb)]
24+
return notebooks
2025

2126

2227
def is_title(cell):
2328
return cell.source.startswith('# ')
2429

2530

2631
def get_notebook_title(nb_file):
27-
nb = nbformat.read(os.path.join(NOTEBOOK_DIR, nb_file),
32+
nb = nbformat.read(nb_file,
2833
as_version=NBVERSION)
2934
for cell in nb.cells:
3035
if is_title(cell):
3136
return cell.source[1:].splitlines()[0].strip()
3237
else:
3338
# Apparently there was no heading, raise an error
34-
raise ValueError('No title found for {}.'.format(nb_file))
39+
raise ValueError(f'No title found for {nb_file}.')
3540

3641

3742
def gen_contents(directory=None, path_prefix=None,
3843
auto_number=False, toc_style=None):
3944

4045
current_chapter = -1
46+
root = Path(directory)
4147
for nb in iter_notebooks(directory):
4248
if path_prefix:
43-
nb_url = os.path.join(path_prefix, nb)
49+
nb_url = os.path.join(path_prefix, str(nb))
4450
else:
45-
nb_url = nb
46-
chapter, section, title = REG.match(nb).groups()
51+
nb_url = str(nb.relative_to(root))
52+
53+
matches = REG.match(str(nb))
54+
if matches:
55+
chapter, section, title = matches.groups()
56+
else:
57+
continue
4758

4859
# Generate auto chapter and section numbers even if
4960
# we do not end up using them

0 commit comments

Comments
 (0)