Coverage for scripts/build_notebooks.py: 100%

87 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-22 12:55 +0000

1"""Build the tutorial notebooks from their percent-format sources (V6.6.5, #343). 

2 

3`notebooks/src/NN_name.py` is the source of truth: `# %%` starts a code cell, `# %% [markdown]` a markdown cell whose 

4lines lose their leading `# `. The notebook is written to `notebooks/NN_name.ipynb` with fixed cell ids and no 

5timestamps, so a rebuild only changes what changed. `--execute` runs each one with nbclient (from `notebooks/`, offline: 

6the notebooks read the bundled sample) and stores the outputs, which is what GitHub and Colab show. 

7 

8 python scripts/build_notebooks.py --execute # rebuild and run all four (about 4 minutes on a small PC) 

9 python scripts/build_notebooks.py --check # the .ipynb cells match their sources (no execution) 

10 python scripts/build_notebooks.py --check --execute # also run them in a temp dir and fail on any error (CI) 

11""" 

12 

13from __future__ import annotations 

14 

15import argparse 

16import shutil 

17import sys 

18import tempfile 

19import time 

20from pathlib import Path 

21 

22ROOT = Path(__file__).resolve().parents[1] 

23SOURCES = ROOT / "notebooks" / "src" 

24OUT = ROOT / "notebooks" 

25 

26 

27def parse_percent(text: str) -> list[tuple[str, str]]: 

28 """[(cell_type, source)] from a percent-format script.""" 

29 cells: list[tuple[str, list[str]]] = [] 

30 for line in text.splitlines(): 

31 if line.startswith("# %%"): 

32 cells.append(("markdown" if "[markdown]" in line else "code", [])) 

33 continue 

34 if not cells: 

35 continue 

36 kind, lines = cells[-1] 

37 if kind == "markdown": 

38 lines.append(line[2:] if line.startswith("# ") else line.lstrip("#")) 

39 else: 

40 lines.append(line) 

41 out = [] 

42 for kind, lines in cells: 

43 source = "\n".join(lines).strip("\n") 

44 if source: 

45 out.append((kind, source)) 

46 return out 

47 

48 

49def build_notebook(source_path: Path): 

50 import nbformat 

51 

52 notebook = nbformat.v4.new_notebook() 

53 notebook.metadata = { 

54 "kernelspec": {"display_name": "Python 3", "language": "python", "name": "python3"}, 

55 "language_info": {"name": "python"}, 

56 "colab": {"provenance": []}, 

57 } 

58 for index, (kind, source) in enumerate(parse_percent(source_path.read_text(encoding="utf-8"))): 

59 cell = nbformat.v4.new_markdown_cell(source) if kind == "markdown" else nbformat.v4.new_code_cell(source) 

60 cell["id"] = f"{source_path.stem}-{index:02d}" 

61 notebook.cells.append(cell) 

62 return notebook 

63 

64 

65def execute(notebook, workdir: Path, timeout: int = 900): 

66 from nbclient import NotebookClient 

67 

68 client = NotebookClient(notebook, timeout=timeout, kernel_name="python3", resources={"metadata": {"path": str(workdir)}}) 

69 client.execute() 

70 for cell in notebook.cells: 

71 cell.get("metadata", {}).pop("execution", None) 

72 return notebook 

73 

74 

75def cells_of(notebook) -> list[tuple[str, str]]: 

76 return [(cell["cell_type"], cell["source"]) for cell in notebook.cells] 

77 

78 

79def main(argv: list[str] | None = None) -> int: 

80 parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) 

81 parser.add_argument("--check", action="store_true", help="Compare the tracked .ipynb cells with their sources; write nothing") 

82 parser.add_argument("--execute", action="store_true", help="Run every notebook (with --check: in a temp dir, outputs discarded)") 

83 parser.add_argument("--only", default=None, help="Build one notebook by stem, e.g. 01_signal_evaluation") 

84 args = parser.parse_args(argv) 

85 import nbformat 

86 

87 sources = sorted(SOURCES.glob("*.py")) 

88 if args.only: 

89 sources = [path for path in sources if path.stem == args.only] 

90 problems: list[str] = [] 

91 for source in sources: 

92 target = OUT / f"{source.stem}.ipynb" 

93 built = build_notebook(source) 

94 if args.check: 

95 if not target.exists(): 

96 problems.append(f"{target.name} missing: run python scripts/build_notebooks.py --execute") 

97 elif cells_of(nbformat.read(target, as_version=4)) != cells_of(built): 

98 problems.append(f"{target.name} differs from {source.relative_to(ROOT)}: run python scripts/build_notebooks.py --execute") 

99 if args.execute: 

100 with tempfile.TemporaryDirectory() as scratch: 

101 began = time.perf_counter() 

102 try: 

103 execute(built, OUT if (OUT / "src").is_dir() else Path(scratch)) 

104 print(f"{source.stem}: ran in {time.perf_counter() - began:.0f} s") 

105 except Exception as error: 

106 problems.append(f"{source.stem}: {type(error).__name__}: {str(error)[-1500:]}") 

107 continue 

108 if args.execute: 

109 began = time.perf_counter() 

110 execute(built, OUT) 

111 print(f"{source.stem}: ran in {time.perf_counter() - began:.0f} s") 

112 nbformat.write(built, target) 

113 print(f"wrote {target.relative_to(ROOT)}") 

114 for leftover in OUT.glob("*.ipynb_checkpoints"): 

115 shutil.rmtree(leftover, ignore_errors=True) 

116 for problem in problems: 

117 print(problem, file=sys.stderr) 

118 return 1 if problems else 0 

119 

120 

121if __name__ == "__main__": 

122 raise SystemExit(main())