Path: blob/master/internal/add_try_except_in_probml_utils_line.py
1191 views
import pytest1from glob import glob2import nbformat34# Load notebooks5notebooks1 = glob("notebooks/book1/*/*.ipynb")6notebooks2 = glob("notebooks/book2/*/*.ipynb")7notebooks = notebooks1 + notebooks28910def get_try_except_probml_utils_line(line):11f"""12check if import probml_utils is in given line: {line}13if present, then return {line} wrapped with try...except14"""15line = line.rstrip()16if not line.startswith(" ") and "probml_utils" in line and "import" in line:17try_except_line = (18f"try:\n {line}\nexcept ModuleNotFoundError:\n %pip install git+https://github.com/probml/probml-utils.git\n {line}"19)20return try_except_line21return 0222324# Parameterize notebooks25@pytest.mark.parametrize("notebook", notebooks)26def add_try_except_for_probml_util(notebook):27nb = nbformat.read(notebook, as_version=4)28for cell in nb.cells:29lines = cell["source"].split("\n")30for line_no, line in enumerate(lines):31updated_line = get_try_except_probml_utils_line(line)32if updated_line:33lines[line_no] = updated_line34break35cell["source"] = "\n".join(lines)36nbformat.write(nb, notebook)373839if __name__ == "__main__":40for notebook in notebooks:41add_try_except_for_probml_util(notebook)424344