Skip to content

Commit 0c61d9c

Browse files
committed
Add header insertion support to tools/tutorial-cell-updater.py
1 parent 2442e42 commit 0c61d9c

2 files changed

Lines changed: 45 additions & 8 deletions

File tree

docs/tutorials/notebook-header.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
<!-- This cell is automatically updated by tools/tutorial-cell-updater.py -->
2+
<!-- The contents are initialized from tutorials/notebook-header.md -->
3+
4+
[<img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/>](https://colab.research.google.com/github/speechbrain/speechbrain/blob/develop/{tutorialpath})
5+
to execute or view/download this notebook on
6+
[GitHub](https://github.com/speechbrain/speechbrain/tree/develop/{tutorialpath})

tools/tutorial-cell-updater.py

Lines changed: 39 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,58 @@
11
#!/usr/bin/env python3
22

3-
import nbformat
43
import glob
5-
import logging
64
import json
5+
import logging
6+
77
logging.basicConfig(level=logging.INFO)
88

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+
934
def update_notebook(fname):
1035
logging.info(f"Updating {fname}")
1136

37+
tutorial_path = fname.replace("./", "")
38+
1239
with open(fname) as f:
1340
nb = json.load(f)
14-
41+
1542
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)
1950

2051
with open(fname, "w") as wf:
2152
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+
2355

2456
if __name__ == "__main__":
2557
for fname in glob.glob("./tutorials/**/*.ipynb", recursive=True):
2658
update_notebook(fname)
27-
break

0 commit comments

Comments
 (0)