|
1 | 1 | import os
|
2 | 2 | import re
|
3 | 3 | from argparse import ArgumentParser
|
| 4 | +from pathlib import Path |
4 | 5 |
|
5 | 6 | import nbformat
|
6 | 7 |
|
7 | 8 | NOTEBOOK_DIR = os.path.join(os.path.dirname(__file__), '..', 'notebooks')
|
8 | 9 |
|
9 | 10 | NBVERSION = 4
|
10 | 11 |
|
11 |
| -REG = re.compile(r'(\d\d)\.(\d\d)-(.*)\.ipynb') |
| 12 | +REG = re.compile(r'.*(\d\d)\.(\d\d)-(.*)\.ipynb') |
12 | 13 |
|
13 | 14 | NO_NUMBER = ['00']
|
14 | 15 |
|
15 | 16 | TOC_STYLES = ['header_ulist', 'nested_list']
|
16 | 17 |
|
17 | 18 |
|
18 | 19 | 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 |
20 | 25 |
|
21 | 26 |
|
22 | 27 | def is_title(cell):
|
23 | 28 | return cell.source.startswith('# ')
|
24 | 29 |
|
25 | 30 |
|
26 | 31 | def get_notebook_title(nb_file):
|
27 |
| - nb = nbformat.read(os.path.join(NOTEBOOK_DIR, nb_file), |
| 32 | + nb = nbformat.read(nb_file, |
28 | 33 | as_version=NBVERSION)
|
29 | 34 | for cell in nb.cells:
|
30 | 35 | if is_title(cell):
|
31 | 36 | return cell.source[1:].splitlines()[0].strip()
|
32 | 37 | else:
|
33 | 38 | # 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}.') |
35 | 40 |
|
36 | 41 |
|
37 | 42 | def gen_contents(directory=None, path_prefix=None,
|
38 | 43 | auto_number=False, toc_style=None):
|
39 | 44 |
|
40 | 45 | current_chapter = -1
|
| 46 | + root = Path(directory) |
41 | 47 | for nb in iter_notebooks(directory):
|
42 | 48 | if path_prefix:
|
43 |
| - nb_url = os.path.join(path_prefix, nb) |
| 49 | + nb_url = os.path.join(path_prefix, str(nb)) |
44 | 50 | 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 |
47 | 58 |
|
48 | 59 | # Generate auto chapter and section numbers even if
|
49 | 60 | # we do not end up using them
|
|
0 commit comments