diff --git a/autohands/build_util.py b/autohands/build_util.py index 46eee114..83f07d52 100644 --- a/autohands/build_util.py +++ b/autohands/build_util.py @@ -1,3 +1,4 @@ +import ast import datetime import logging import os @@ -131,7 +132,6 @@ def tail(stream) -> str: return "\n".join(parts) - # The SIGABRT below leaves the child dying of a core-dumping signal. Nothing # here wants a core: the stack has already been written to stderr, and a # multi-GB core per timed-out script would fill a runner's disk over a mega-run. @@ -293,15 +293,39 @@ def py_to_notebook(filename: Path): COLAB_SETUP_MARKDOWN = """__Google Colab Setup__ -This cell sets up the environment when the notebook is run on Google Colab: it installs the -required PyAuto packages, clones the workspace (configuration files and example datasets) and -points the configuration at it. If you are running the notebook elsewhere (e.g. locally via -your own installation) it does nothing, and you can run it safely. +Run this cell to install {name} and download the files needed for this notebook on Google Colab. +If you’re running locally or in HTML, it leaves your installation unchanged.""" + +def _colab_setup_config(): + """Read project names and entry points from the adopter-owned workspace config.""" + import yaml + + path = BUILD_PATH / "config" / "workspaces.yaml" + return (yaml.safe_load(path.read_text()) or {})["colab_setup"] + + +_COLAB_SETUP = _colab_setup_config() +_COLAB_INTRO_NOTEBOOKS = { + project: config["intro_url"] for project, config in _COLAB_SETUP.items() +} + + +def _colab_setup_markdown(notebook_path, project): + """Introduce setup once; later examples link to their project's introduction.""" + path = Path(notebook_path) + config = _COLAB_SETUP[project] + introductory = path.stem == "start_here" or any( + path.match(pattern) for pattern in config["intro_patterns"] + ) + if introductory: + return COLAB_SETUP_MARKDOWN.format(name=config["name"]) + return ( + "__Google Colab Setup__\n\nSet up Google Colab as in " + f"[the introductory notebook]({_COLAB_INTRO_NOTEBOOKS[project]})." + ) -Colab tip: model-fits run much faster on a GPU — enable one via "Runtime" -> "Change runtime -type" -> "Hardware accelerator" before running the notebook.""" -COLAB_SETUP_CODE = '''try: +COLAB_SETUP_CODE = """try: import google.colab except ImportError: from {package} import setup_colab as _setup_colab @@ -315,19 +339,81 @@ def py_to_notebook(filename: Path): ) _setup_colab = importlib.import_module("autonerves.setup_colab") -_setup_colab.setup("{project}")''' +_setup_colab.setup("{project}")""" + + +def _compact_setup_cell(cell): + """Use Colab's form view and Jupyter's collapsed input without hiding outputs.""" + source = "".join(cell["source"]) + title = '# @title Set up Google Colab { display-mode: "form" }\n' + if not source.startswith(title): + cell["source"] = (title + source).splitlines(keepends=True) + metadata = cell.setdefault("metadata", {}) + metadata["cellView"] = "form" + metadata.setdefault("jupyter", {})["source_hidden"] = True + + +def _expand_setup_cell(cell, project): + """Recognize the maintained import/call or legacy bootstrap, never arbitrary code. + + Return a fresh bootstrap and optional science-code tail. Unknown custom setup + is left untouched rather than changing its meaning or hiding science code. + """ + source = "".join(cell.get("source", [])) + try: + nodes = ast.parse(source).body + except SyntaxError: + return None + if len(nodes) < 2: + return None + first, second = nodes[:2] + if first.end_lineno >= second.lineno or ( + len(nodes) > 2 and second.end_lineno >= nodes[2].lineno + ): + return None + package = COLAB_PROJECTS[project] + if ( + isinstance(first, ast.ImportFrom) + and first.module == package + and len(first.names) == 1 + ): + imported = first.names[0] + if imported.name != "setup_colab": + return None + alias = imported.asname or imported.name + else: + legacy = ast.parse( + COLAB_SETUP_CODE.format(package=package, project=project) + ).body[0] + if ast.dump(first) != ast.dump(legacy): + return None + alias = "_setup_colab" + if not isinstance(second, ast.Expr) or not isinstance(second.value, ast.Call): + return None + call = second.value + if not ( + isinstance(call.func, ast.Attribute) + and isinstance(call.func.value, ast.Name) + and call.func.value.id == alias + and call.func.attr in {"setup", *(f"for_{p}" for p in COLAB_PROJECTS)} + ): + return None + # Preserve the original call, including CPU/GPU options and inline comments. + lines = source.splitlines(keepends=True) + call_source = "".join(lines[second.lineno - 1 : second.end_lineno]) + bootstrap = COLAB_SETUP_CODE.format(package=package, project=project) + bootstrap = bootstrap.rsplit("_setup_colab.setup(", 1)[0].replace( + "_setup_colab", alias + ) + tail = "".join(lines[second.end_lineno :]) + return bootstrap + call_source, tail if tail.strip() else "" def inject_colab_setup(notebook_path, project: str): """ - Prepend the standard Google Colab setup cell pair (markdown explainer + - code cell) to a generated notebook containing code, so runnable notebooks - can bootstrap themselves on Colab. Prose-only notebooks need no setup. - - The cells are inserted after the notebook's leading markdown cell (the - script's intro docstring) so the title stays on top. Notebooks whose - source already calls ``setup_colab`` (hand-written setup sections) are - left untouched. Returns True if cells were injected. + Insert or normalize a compact, self-contained setup cell. Preserve supported + handwritten setup options and keep subsequent science code visible. Unknown + custom setup is left untouched. Return True only when the notebook changes. """ import json @@ -349,14 +435,65 @@ def inject_colab_setup(notebook_path, project: str): ): return False - for cell in cells: - if "setup_colab" in "".join(cell.get("source", [])): + original = json.dumps(notebook, sort_keys=True) + setup_markdown = _colab_setup_markdown(notebook_path, project) + "\n" + for index, cell in enumerate(cells): + if cell["cell_type"] != "code": + continue + expanded = _expand_setup_cell(cell, project) + if expanded is None: + if "setup_colab" in "".join(cell.get("source", [])): + return False + continue + setup, tail = expanded + cell["source"] = setup.splitlines(keepends=True) + _compact_setup_cell(cell) + if tail: + # Never collapse unrelated science code along with the setup. + cells.insert( + index + 1, + { + "cell_type": "code", + "metadata": {}, + "execution_count": None, + "outputs": [], + "source": tail.splitlines(keepends=True), + }, + ) + # A source introduction may include the setup heading in its last section. + previous = cells[index - 1] if index else None + if ( + previous + and previous["cell_type"] == "markdown" + and "__Google Colab Setup__" in "".join(previous["source"]) + ): + text = "".join(previous["source"]) + text = re.sub( + r"__Google Colab Setup__.*?(?=\n(?:__[^\n]+__|#{1,6} |[^\n]+\n[=-]{3,}\s*(?:\n|$))|\Z)", + setup_markdown, + text, + flags=re.S, + ) + previous["source"] = text.splitlines(keepends=True) + else: + cells.insert( + index, + { + "cell_type": "markdown", + "metadata": {}, + "source": setup_markdown.splitlines(keepends=True), + }, + ) + if json.dumps(notebook, sort_keys=True) == original: return False + with open(notebook_path, "w") as f: + json.dump(notebook, f, indent=1) + return True markdown_cell = { "cell_type": "markdown", "metadata": {}, - "source": COLAB_SETUP_MARKDOWN.splitlines(keepends=True), + "source": setup_markdown.splitlines(keepends=True), } code_cell = { "cell_type": "code", @@ -368,6 +505,7 @@ def inject_colab_setup(notebook_path, project: str): ).splitlines(keepends=True), } + _compact_setup_cell(code_cell) insert_at = 1 if cells and cells[0]["cell_type"] == "markdown" else 0 cells[insert_at:insert_at] = [markdown_cell, code_cell] @@ -1068,7 +1206,6 @@ def execute_notebook(f, report=None, env=None, write_back=True, ) - def execute_notebooks_in_folder( directory, no_run_list, diff --git a/autohands/config/workspaces.yaml b/autohands/config/workspaces.yaml index c3b61a93..b5f14e70 100644 --- a/autohands/config/workspaces.yaml +++ b/autohands/config/workspaces.yaml @@ -35,6 +35,34 @@ slow_skip_default: - autofit_workspace_test - autolens_workspace_test +# Colab setup copy and canonical introductions. Root/topic start_here notebooks +# are introductory too; intro_patterns adds each project's other entry points. +colab_setup: + autofit: + name: PyAutoFit + intro_url: https://github.com/PyAutoLabs/autofit_workspace/blob/main/notebooks/overview/overview_1_the_basics.ipynb + intro_patterns: [overview_1_the_basics.ipynb] + autogalaxy: + name: PyAutoGalaxy + intro_url: https://github.com/PyAutoLabs/autogalaxy_workspace/blob/main/start_here.ipynb + intro_patterns: [] + autolens: + name: PyAutoLens + intro_url: https://github.com/PyAutoLabs/autolens_workspace/blob/main/start_here.ipynb + intro_patterns: [cosmos_web_ring_colab.ipynb] + howtofit: + name: PyAutoFit + intro_url: https://github.com/PyAutoLabs/HowToFit/blob/main/notebooks/chapter_1_introduction/tutorial_1_models.ipynb + intro_patterns: [chapter_1_introduction/tutorial_1_*.ipynb] + howtogalaxy: + name: PyAutoGalaxy + intro_url: https://github.com/PyAutoLabs/HowToGalaxy/blob/main/notebooks/chapter_1_introduction/tutorial_1_grids_and_galaxies.ipynb + intro_patterns: [chapter_1_introduction/tutorial_1_*.ipynb] + howtolens: + name: PyAutoLens + intro_url: https://github.com/PyAutoLabs/HowToLens/blob/main/notebooks/chapter_1_introduction/tutorial_1_grids_and_galaxies.ipynb + intro_patterns: [chapter_1_introduction/tutorial_1_*.ipynb] + # colab_gemini: Colab Gemini instructions (PyAutoHands#324). Per project, the # repository its notebooks live in (the "/" prefix the assistant's # colab/contexts.yaml globs match) and the assistant owning that mapping. diff --git a/tests/test_inject_colab_setup.py b/tests/test_inject_colab_setup.py index 6fc55e7c..68e8422c 100644 --- a/tests/test_inject_colab_setup.py +++ b/tests/test_inject_colab_setup.py @@ -64,15 +64,19 @@ def test_injects_at_top_when_no_leading_markdown(tmp_path): assert '_setup_colab.setup("autofit")' in "".join(cells[1]["source"]) -def test_skips_notebook_with_hand_written_setup(tmp_path): +def test_expands_notebook_with_hand_written_setup(tmp_path): original = [ markdown_cell("Title"), code_cell("from autolens import setup_colab\nsetup_colab.for_autolens()"), ] nb_path = make_notebook(tmp_path / "start_here.ipynb", original) - assert build_util.inject_colab_setup(nb_path, "autolens") is False - assert json.loads(nb_path.read_text())["cells"] == original + assert build_util.inject_colab_setup(nb_path, "autolens") is True + cells = json.loads(nb_path.read_text())["cells"] + assert '"pip", "install", "autonerves", "--no-deps"' in "".join(cells[2]["source"]) + assert "setup_colab.for_autolens()" in "".join(cells[2]["source"]) + assert cells[2]["metadata"]["cellView"] == "form" + assert "locally or in HTML" in "".join(cells[1]["source"]) @pytest.mark.parametrize( @@ -146,6 +150,24 @@ def test_unknown_project_raises(tmp_path): build_util.inject_colab_setup(nb_path, "euclid") +@pytest.mark.parametrize("heading", ["## Science", "__science__", "Science\n======="]) +def test_keeps_following_markdown_sections(tmp_path, heading): + following = heading + "\n\nKeep this scientific explanation.\n" + path = make_notebook( + tmp_path / "start_here.ipynb", + [ + markdown_cell( + "Title\n\n__Google Colab Setup__\n\nOld setup.\n\n" + following + ), + code_cell("from autolens import setup_colab\nsetup_colab.for_autolens()"), + ], + ) + build_util.inject_colab_setup(path, "autolens") + text = "".join(json.loads(path.read_text())["cells"][0]["source"]) + assert following in text + assert "Old setup." not in text + + def test_output_is_valid_notebook_json(tmp_path): nb_path = make_notebook( tmp_path / "example.ipynb", [markdown_cell("Title"), code_cell("x = 1")] @@ -160,3 +182,125 @@ def test_output_is_valid_notebook_json(tmp_path): code = notebook["cells"][2] assert code["outputs"] == [] assert code["execution_count"] is None + + +@pytest.mark.parametrize("project", build_util.COLAB_PROJECTS) +def test_intro_and_advanced_copy(tmp_path, project): + intro = ( + tmp_path / build_util._COLAB_INTRO_NOTEBOOKS[project].split("/blob/main/")[1] + ) + intro.parent.mkdir(parents=True, exist_ok=True) + make_notebook(intro, [code_cell("x = 1")]) + build_util.inject_colab_setup(intro, project) + cells = json.loads(intro.read_text())["cells"] + assert "locally or in HTML" in "".join(cells[0]["source"]) + assert cells[1]["metadata"]["jupyter"]["source_hidden"] is True + advanced = make_notebook(tmp_path / "advanced.ipynb", [code_cell("x = 1")]) + build_util.inject_colab_setup(advanced, project) + text = "".join(json.loads(advanced.read_text())["cells"][0]["source"]) + assert "as in [the introductory notebook]" in text + assert "locally" not in text + + +@pytest.mark.parametrize("legacy", [True, False]) +def test_existing_options_preserved_and_science_visible(tmp_path, legacy): + if legacy: + source = build_util.COLAB_SETUP_CODE.format( + project="autolens", package="autolens" + ) + source = source.replace( + 'setup("autolens")', 'setup("autolens", raise_error_if_not_gpu=False)' + ) + else: + source = "from autolens import setup_colab\nsetup_colab.for_autolens(raise_error_if_not_gpu=False)" + source += "\nresult = 42\nprint(result)\n" + path = make_notebook( + tmp_path / "start_here.ipynb", + [ + markdown_cell( + "Title\n\n__Google Colab Setup__\n\nOld lengthy explanation." + ), + code_cell(source), + ], + ) + assert build_util.inject_colab_setup(path, "autolens") + cells = json.loads(path.read_text())["cells"] + assert "Title" in "".join(cells[0]["source"]) + assert "Old lengthy" not in "".join(cells[0]["source"]) + assert "raise_error_if_not_gpu=False" in "".join(cells[1]["source"]) + assert "result = 42" not in "".join(cells[1]["source"]) + assert "result = 42" in "".join(cells[2]["source"]) + assert "cellView" not in cells[2]["metadata"] + once = path.read_bytes() + assert not build_util.inject_colab_setup(path, "autolens") + assert path.read_bytes() == once + + +@pytest.mark.parametrize( + "source", + [ + "custom_setup_colab()\nscience()", + "from autolens import setup_colab; setup_colab.for_autolens(); science()", + ], +) +def test_unknown_custom_setup_is_not_hidden_or_rewritten(tmp_path, source): + path = make_notebook(tmp_path / "custom.ipynb", [code_cell(source)]) + original = path.read_bytes() + assert not build_util.inject_colab_setup(path, "autolens") + assert path.read_bytes() == original + + +@pytest.mark.parametrize("colab", [True, False]) +@pytest.mark.parametrize("gpu_required", [True, False]) +def test_bootstrap_runs_before_library_import_and_preserves_options( + tmp_path, monkeypatch, colab, gpu_required +): + import builtins + import importlib + import subprocess + from types import SimpleNamespace + + events = [] + setup = SimpleNamespace( + for_autolens=lambda **kwargs: events.append(("setup", kwargs)) + ) + original_import = builtins.__import__ + + def guarded_import(name, *args, **kwargs): + if name == "google.colab": + if not colab: + raise ImportError("not Colab") + return SimpleNamespace() + if name == "autolens": + if colab: + pytest.fail("Fresh Colab must bootstrap before importing autolens") + return SimpleNamespace(setup_colab=setup) + return original_import(name, *args, **kwargs) + + monkeypatch.setattr(builtins, "__import__", guarded_import) + monkeypatch.setattr( + subprocess, "check_call", lambda command: events.append(("install", command)) + ) + original_import_module = importlib.import_module + + def import_module(name, *args): + if name == "autonerves.setup_colab": + assert events[0][0] == "install" + return setup + return original_import_module(name, *args) + + monkeypatch.setattr(importlib, "import_module", import_module) + path = make_notebook( + tmp_path / "start_here.ipynb", + [ + code_cell( + "from autolens import setup_colab\n" + f"setup_colab.for_autolens(raise_error_if_not_gpu={gpu_required})" + ) + ], + ) + build_util.inject_colab_setup(path, "autolens") + cells = json.loads(path.read_text())["cells"] + exec("".join(cells[1]["source"]), {}) + assert events[-1] == ("setup", {"raise_error_if_not_gpu": gpu_required}) + assert len(events) == (2 if colab else 1)