diff --git a/CHANGELOG.md b/CHANGELOG.md index 1b3114bd..fcb20792 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ v0.5.1: no run before v0.5.1 is read.) ## Unreleased +- **Register the masks (cell 5) says in its own cell when its folder check fails, and never crashes on the next press (owner's Colab test of v0.9.0).** When the app's folder check that **Register the masks** makes with the masks folder failed (an `OSError` such as a Google Drive that stopped answering, or a coded refusal), cell 5 said to confirm the axes again in cell 3 (there was no check to confirm), the reason was drawn only in cell 3, and the check had cleared the app's run: every later press and cell 5 run again raised `AttributeError` (`app.preflight` is None in `_app_run`) out of the click handler, with the axes line left on screen. Cell 5 now shows `CHECK_FAILED` with cell 3's reason, whatever the press (nothing is declared, saved or run, as before), and continues once cell 3's check is made again. An unexpected error during a press is shown in cell 5 (`STOPPED`) and still raised. What is checked, declared and written is unchanged. Tests: `tests/test_notebook_preprocessing_cellpose.py`. - **Cellpose step Folders: the run is opened once, on screen, with its wait (#574, item 2; owner's Colab test of 26 November 2026).** "Step 1 of 4 · Folders" showed nothing for about 4 minutes on ~200 images of 10-50 MB on Google Drive. Cell 4 opened the app's run twice before its widget was shown: once for the notice's refusal (`_refusal`) and once by **Open the run**, and each opening of a `verify_content` run reads every image whole for its content SHA-256 (`RunInputs._check_files` → `content_changed`): 2 whole reads per image, plus the viewer's first image. Cell 4 is unchanged (the pinned release's `segmentation = segmentation_step(notebook)` / `display(segmentation)`): in a notebook `segmentation_step` now displays its widget first itself (`show=` overrides it, None outside a kernel) and the cell's `display(segmentation)` then adds nothing (`SegmentationStep._ipython_display_`, once; it draws the widget with ipywidgets 7's `Widget._ipython_display_` when there is one, as on Colab, else with ipywidgets 8's `_repr_mimebundle_`). Then `SegmentationStep.check()` opens the run once (by **Open the run** when Cellpose is installed and the masks folder known, else for the refusal only): 1 whole read per image. The checks are unchanged: `run_inputs.open_checked(..., checking=)` is `RunInputs.open` (now a call of it, signature kept) telling a callback each phase of `open_checks.OPEN_PHASES` (manifest, image fingerprints, content SHA-256, mask fingerprints, the folders listed for unrecorded files), the `(phase, done, total, path)` of `RunMode(checking=)` (#567); same files, same order, same result and refusals (tests compare both). `notebook_open_progress.opening` shows it with `notebook_progress.Wait` and its ticking thread: the phase, "n of N" with the image read, the elapsed time, then "Opened and checked in m:ss". `segmentation_app(open_now=False)` leaves the opening to the caller. An error that is not a refusal while cell 4 opens the run still leaves the cell, as before (`StepForm.submit(reraise=True)`; a button's stays under it); after an error or an interrupt the line says "Stopped after m:ss." `tests/test_cellpose_folders_open.py` counts the whole reads per image (1, was 2), that the widget is shown before any read, the wait's lines and the identical result and refusal. - **Cellpose installation: what pip does now, then what it installed (#574, item 1).** Measured in a fresh Python 3.12 venv with real pip (no cache): the shared cell 1 installs preprocessing, normalization (both cloned and built from Git), imagecodecs (27.7 MB), ipywidgets and matplotlib (with numpy and scipy when missing): 42 s the first time, 1.6 s the second (nothing installed); it does not install Cellpose. Cell 4's own **Install Cellpose** step installs `cellpose==4.2.1.1`: 3.2 GB of downloads without PyTorch (torch 2.15 with its CUDA libraries, 3 GB of it), 5-8 s with PyTorch already installed, as on Colab (cellpose, opencv-python-headless 63.7 MB and five small packages). Its `pip` printed to the kernel's output, which a button callback does not show: `cellpose_install.install_cellpose(ticked, output=)` now streams pip's lines (`subprocess.Popen`), and the card shows "Installing Cellpose 4.2.1.1 (with PyTorch): finding/downloading/installing …" with the ticking elapsed time (`notebook_cellpose_install.PipProgress`), then a green card above the component: how long it took and every package pip installed or changed (`installed_distributions`, `install_changes`); a failed install shows pip's last 20 lines. As with `subprocess.run`, pip is killed and waited for when anything stops the reading (an interrupt included), and output that is not UTF-8 is replaced rather than stopping it. The tick, the pinned release, the restart rule and the shared cells 1 to 3 are unchanged. - **The run's masks counter ends at N of N (follow-up of #567).** The mask header check reported "done of N" before each mask and nothing after the last, so the run's wait stopped at "N-1 of N" (preflight's closing `("masks", 1, 1, "")` is a placeholder the wait ignores unless the total is 1). The check now also reports `(total, total, "")` after the last mask; what is read and recorded is unchanged. A stray docstring in `notebook_progress` (the one of `PREPARING` sat after `COUNTED_PHASES`) is back under `PREPARING`. Tests: `tests/test_run_checking_progress.py`, `tests/test_notebook_progress.py`. diff --git a/src/morphobricks_preprocessing/notebook_mask_register.py b/src/morphobricks_preprocessing/notebook_mask_register.py index ccf0a8e2..53d79ba8 100644 --- a/src/morphobricks_preprocessing/notebook_mask_register.py +++ b/src/morphobricks_preprocessing/notebook_mask_register.py @@ -91,6 +91,16 @@ "step Axes, confirm the recorded axes, then press Register the masks again. Nothing was " "declared." ) +CHECK_FAILED = ( + "The folder check of cell 3 with the masks folder did not finish: {reason} Nothing was " + "declared and the run folder is unchanged. Fix what it names, press Check folder (Scan the " + "folders) in cell 3, step Images, confirm the axes, then press Register the masks again." +) +STOPPED = ( + "Register the masks stopped on an unexpected problem ({problem}). The run records the " + "masks only once this step says The masks are registered; cell 3 shows what it saved. " + "Press Register the masks again." +) NOT_SAVED = ( "Check and save did not save the description: open cell 3, step Check and save, answer " "what it lists, then press Register the masks again here." @@ -149,8 +159,9 @@ def _app_run(app: object, rechecked: bool) -> tuple[str, str]: it runs again; the run is then the output folder the app's own rule gives now. """ run, masks = app_folders(app) - if not run and rechecked and getattr(app, "result", None) is None: - run = os.fspath(app._output_path(Path(app.preflight.discovery.root))) + pre = getattr(app, "preflight", None) + if not run and rechecked and getattr(app, "result", None) is None and pre is not None: + run = os.fspath(app._output_path(Path(pre.discovery.root))) return run, masks @@ -167,6 +178,8 @@ def refusal(app: object, segmentation: object, *, rechecked: bool = False) -> st inputs, masks = workflow.inputs, Path(workflow.masks_root).resolve() segmented = Path(inputs.output_folder).resolve() rechecked = rechecked or getattr(segmentation, "rechecked_run", None) == segmented + if rechecked and getattr(app, "preflight", None) is None: # cell 5's folder check failed + return CHECK_FAILED.format(reason=_plain(app.folder_status.value)) app_run, app_masks = _app_run(app, rechecked) if not app_run or Path(app_run).resolve() != segmented: held = app_run or "no finished run" @@ -307,6 +320,14 @@ def register(self) -> bool: """Declare the ticked masks through the app, save, run and describe; True when done.""" if self.button.disabled: return False + try: + return self._register() + except BaseException as exc: # a click handler's error is never shown in this cell + self._stop(STOPPED.format(problem=f"{type(exc).__name__}: {exc}")) + raise + + def _register(self) -> bool: + """Do the work of :meth:`register` once its button is enabled.""" why = refusal(self.app, self.segmentation) if why: return self._stop(why) @@ -319,11 +340,13 @@ def register(self) -> bool: or any(t not in found.types for t in self.ticks) # checked before cell 4 wrote ): app.masks_folder.value = os.fspath(masks) - app.check_folder() # the app's Scan the folders, now with the masks folder + pre = app.check_folder() # the app's Scan the folders, now with the masks folder # Kept on cell 4's step, not this widget: cell 5 run again continues from here. self.segmentation.rechecked_run = Path( self.segmentation.workflow.inputs.output_folder ).resolve() + if pre is None: # its reason is drawn in cell 3: say it here, not the axes + return self._stop(CHECK_FAILED.format(reason=_plain(app.folder_status.value))) if app.confirmed_mapping is None: return self._stop(AXES_AGAIN) why = _other_experiment(app, self.segmentation.workflow.inputs) diff --git a/tests/test_notebook_preprocessing_cellpose.py b/tests/test_notebook_preprocessing_cellpose.py index 2fd6f6f2..e656e1a0 100644 --- a/tests/test_notebook_preprocessing_cellpose.py +++ b/tests/test_notebook_preprocessing_cellpose.py @@ -40,6 +40,7 @@ from morphobricks_preprocessing.notebook_mask_register import ( # noqa: E402 AXES_AGAIN, NO_MASKS, + STOPPED, register_step, toml_section, ) @@ -535,3 +536,59 @@ def test_cell_5_run_again_after_it_registered_the_masks_is_not_refused(tmp_path, assert registration.register(), registration.status.value again = register_step(nb, registration.segmentation) assert list(again.ticks) == ["Cells"], again.status.value + + +def pressed_with_a_failed_check(tmp_path, monkeypatch, error): + """Return the app, cell 5 and the run after a press whose folder check raised ``error``.""" + from morphobricks_preprocessing import notebook_folder + + nb = ran_app(tmp_path) + out = nb.result.output_folder + step = segmentation_step(nb) + segment(step, tmp_path / "masks") + registration = register_step(nb, step) + registration.ticks["Cells"].value = True + real = notebook_folder.preflight + + def failing(*args, **kwargs): + raise error + + monkeypatch.setattr(notebook_folder, "preflight", failing) + before = snapshot(out) + return nb, registration, out, before, real + + +def test_a_failed_folder_check_says_so_in_cell_5_not_the_axes(tmp_path, stub, monkeypatch): + # Before, cell 5 said to confirm the axes again (there was no check to confirm), the + # reason was drawn only in cell 3, and every later press raised AttributeError out of the + # click handler with the axes line left on screen. + from morphobricks_preprocessing import notebook_folder + + nb, registration, out, before, real = pressed_with_a_failed_check( + tmp_path, monkeypatch, OSError("Drive stopped answering") + ) + assert not registration.register() + status = registration.status.value + assert "did not finish" in status and "Drive stopped answering" in status + assert AXES_AGAIN.split(":")[0] not in status + assert snapshot(out) == before # nothing declared, saved or run + assert not registration.register() # pressed again: the same refusal, no exception + assert "did not finish" in registration.status.value + again = register_step(nb, registration.segmentation) # cell 5 run again + assert "did not finish" in again.status.value + monkeypatch.setattr(notebook_folder, "preflight", real) # Drive answers again + nb.check_button.click() # cell 3's check, as the refusal says; the axes, then Register + nb.quick_confirm.click() + assert registration.register(), registration.status.value + assert RunInputs.open(out).mask_types() == ("Cells",) + + +def test_an_unexpected_error_during_register_is_shown_in_cell_5(tmp_path, stub, monkeypatch): + _nb, registration, out, before, _real = pressed_with_a_failed_check( + tmp_path, monkeypatch, RuntimeError("unexpected") + ) + with pytest.raises(RuntimeError): + registration.register() + assert STOPPED.split("(")[0] in registration.status.value + assert "RuntimeError: unexpected" in registration.status.value + assert snapshot(out) == before