|
1 | 1 | #!/usr/bin/env python3 |
2 | 2 |
|
3 | | -import nbformat |
4 | 3 | import glob |
5 | | -import logging |
6 | 4 | import json |
| 5 | +import logging |
| 6 | + |
7 | 7 | logging.basicConfig(level=logging.INFO) |
8 | 8 |
|
| 9 | +with open("tutorials/notebook-header.md", "r", encoding="utf-8") as header_file: |
| 10 | + header_contents = header_file.read() |
| 11 | + |
| 12 | + |
| 13 | +def find_first_cell_with_tag(cell_list, tag_to_find): |
| 14 | + for cell in cell_list: |
| 15 | + tags = cell.get("metadata", {}).get("tags", {}) |
| 16 | + if tag_to_find in tags: |
| 17 | + return cell |
| 18 | + |
| 19 | + return None |
| 20 | + |
| 21 | + |
| 22 | +def update_header(header_cell, path): |
| 23 | + header_cell.update( |
| 24 | + { |
| 25 | + "cell_type": "markdown", |
| 26 | + "metadata": {"id": "sb_auto_header", "tags": ["sb_auto_header"]}, |
| 27 | + "source": header_contents.replace( |
| 28 | + "{tutorialpath}", path |
| 29 | + ).splitlines(True), |
| 30 | + } |
| 31 | + ) |
| 32 | + |
| 33 | + |
9 | 34 | def update_notebook(fname): |
10 | 35 | logging.info(f"Updating {fname}") |
11 | 36 |
|
| 37 | + tutorial_path = fname.replace("./", "") |
| 38 | + |
12 | 39 | with open(fname) as f: |
13 | 40 | nb = json.load(f) |
14 | | - |
| 41 | + |
15 | 42 | cells = nb["cells"] |
16 | | - |
17 | | - for cell in cells: |
18 | | - print(list(cell.keys())) |
| 43 | + header_cell = find_first_cell_with_tag(cells, "sb_auto_header") |
| 44 | + if header_cell is None: |
| 45 | + logging.info("Header not found; creating") |
| 46 | + cells.insert(0, {}) |
| 47 | + header_cell = cells[0] |
| 48 | + |
| 49 | + update_header(header_cell, tutorial_path) |
19 | 50 |
|
20 | 51 | with open(fname, "w") as wf: |
21 | 52 | json.dump(nb, wf, indent=1, ensure_ascii=False) |
22 | | - print(file=wf) # print final newline that jupyter adds apparently |
| 53 | + print(file=wf) # print final newline that jupyter adds apparently |
| 54 | + |
23 | 55 |
|
24 | 56 | if __name__ == "__main__": |
25 | 57 | for fname in glob.glob("./tutorials/**/*.ipynb", recursive=True): |
26 | 58 | update_notebook(fname) |
27 | | - break |
|
0 commit comments