From bf2afe800178d873541f76497b0d6c61c43b4899 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 08:58:17 +0000 Subject: [PATCH 1/3] Cellpose cell 4: open the run once with its wait; show the install's progress (#574) Item 2, the silent Folders step: cell 4 opened the app's run twice before its widget was shown (once for the notice's refusal, once by Open the run), and each opening of a verify_content run reads every image whole for its content SHA-256. Cell 4 now shows the widget first (segmentation_step(notebook, show=display)), then opens the run once: 1 whole read per image instead of 2. run_inputs.open_checked is RunInputs.open (which now calls it, signature kept) telling a (phase, done, total, path) callback each phase of open_checks.OPEN_PHASES; the checks, their order, result and refusals are the same. notebook_open_progress.opening shows them with notebook_progress.Wait and its ticking thread (#567): the phase, n of N with the image, the elapsed time. Item 1, the slow, silent first install: the shared cell 1 does not install Cellpose (measured: 42 s first run in a fresh venv, 1.6 s second run); cell 4's own Install Cellpose step does. Its pip output went to the kernel's own output, invisible from a button. install_cellpose now streams pip's lines; the card shows what pip does now with a ticking time, then what it installed or changed (a failed install shows pip's last lines). The tick, the pinned release, the restart rule and the shared cells 1 to 3 are unchanged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WX6rdMV1r5jUPUR94kxV5a --- AGENTS.md | 9 +- CHANGELOG.md | 2 + .../MorphoBricks_Preprocessing_Cellpose.ipynb | 8 +- pyproject.toml | 3 + .../cellpose_install.py | 55 +++++- .../notebook_cellpose.py | 7 +- .../notebook_cellpose_app.py | 10 +- .../notebook_cellpose_form.py | 16 +- .../notebook_cellpose_install.py | 96 ++++++++++ .../notebook_open_progress.py | 70 ++++++++ .../notebook_preprocessing_cellpose.py | 111 ++++++++++-- src/morphobricks_preprocessing/open_checks.py | 68 ++++++++ src/morphobricks_preprocessing/run_inputs.py | 46 +++-- .../segmentation_cellpose_run.py | 16 +- tests/test_cellpose_folders_open.py | 165 ++++++++++++++++++ tests/test_notebook_cellpose_form.py | 2 +- tests/test_notebook_cellpose_republished.py | 7 +- tests/test_notebook_preprocessing_cellpose.py | 91 +++++++++- ...st_notebook_preprocessing_cellpose_file.py | 7 +- 19 files changed, 715 insertions(+), 74 deletions(-) create mode 100644 src/morphobricks_preprocessing/notebook_cellpose_install.py create mode 100644 src/morphobricks_preprocessing/notebook_open_progress.py create mode 100644 src/morphobricks_preprocessing/open_checks.py create mode 100644 tests/test_cellpose_folders_open.py diff --git a/AGENTS.md b/AGENTS.md index 39b56123..35112033 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -209,6 +209,8 @@ src/morphobricks_preprocessing/ preprocessing's discovery and pairing; RunInputs.open raises UnrecordedFilesError for them (PP-8b, contract §9.1) run_inputs_text.py the texts RunInputs refuses a run with (moved from run_inputs.py in PP-12) + open_checks.py OPEN_PHASES, counted: the phases of opening a run told to a progress callback + (run_inputs.open_checked: RunInputs.open with checking=; #574) (pure) run_inputs_stopped.py stopped_run_refusal: the one reader of discovery_report.json for the bricks; RunInputs.open raises RunStoppedError (RUN_FOLDER_STOPPED, the stopped run's error issues as the report records them) or @@ -309,8 +311,11 @@ src/morphobricks_preprocessing/ notebook, #441), the same CellposeNotebook forms the Cellpose cells mount notebook_preprocessing_cellpose.py segmentation_step(app): cell 4 of notebooks/MorphoBricks_Preprocessing_Cellpose.ipynb (#441), segmentation_app - on the Preprocessing app's finished run; cellpose_install.py installs - Cellpose 4.2.1.1 only on the user's tick (restart when numpy/opencv changed); + on the Preprocessing app's finished run, shown (show=display) before the run + is opened once; cellpose_install.py installs Cellpose 4.2.1.1 only on the + user's tick (restart when numpy/opencv changed), pip's lines streamed; + notebook_cellpose_install.py what pip does now, then what it installed; + notebook_open_progress.py opening: the wait of opening a run (#574); notebook_mask_register.py register_step(app, segmentation): cell 5, a declaration to tick per mask type, then the app's own check, Masks answer, save, run and Describe the masks diff --git a/CHANGELOG.md b/CHANGELOG.md index 841cf7f1..d5b01a3c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,8 @@ v0.5.1: no run before v0.5.1 is read.) ## Unreleased +- **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 now calls `segmentation_step(notebook, show=display)`: the widget is shown first, 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. `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. 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`. - **`piece_counts` counts the pieces of masks of objects by runs (#69).** It sorted every pixel (`np.unique(..., return_inverse=True)`, most of its time) and labelled each label again in its bounding box, so labels spread over the plane read it once each. Each row is now cut into runs of one label and runs of one label in neighbouring rows that touch (8-connected, from `masks.binary.STRUCTURE`) are joined with `scipy.sparse.csgraph.connected_components` (new pure module `mask_pieces`; `mask_scan.piece_counts` is the same function, imported). On pixel-scale masks (noise, checkerboards) runs are almost pixels and that graph needs several times the memory of the sort, so above `RUNS_PER_PIXEL_LIMIT` = 0.25 runs per pixel the former route is taken, unchanged. The results are byte-identical either way (labels in the mask's pixel type, counts `int64`): a property test compares both routes, forced and as chosen, with the former function, kept in the test as the reference, on random masks of every label pixel type (touching labels, holes, single pixels, edges, corners, no background, empty) and on the benchmark masks; every digest of `tools/benchmark_kernels.py --group masks` is unchanged, including its new pixel-scale cases (`benchmark_inputs.pixel_mask`). On the benchmark machine `piece_counts` of the 4096 px cells mask went from 2.1 to 2.3 s to 0.07 to 0.10 s and one position's scan from 4.9 to 5.1 s to 0.9 to 1.0 s; the pixel-scale masks take the time and memory they took before (`docs/benchmarks.md`). Outside the former results: a mask with a side of length 0 now has no labels, where the former function failed inside SciPy; a mask that is not 2D is refused with a `ValueError` saying so (it was a SciPy `RuntimeError`, or no labels when it was all background). **The mask scan refuses a mask plane of no pixels** (`mask_without_pixels`, naming the mask): before, SciPy's failure in `piece_counts` was its only guard, and with no labels such a plane would have counted as an image and as a plane of at most one label in its mask type's kind. `pair_counts` and the repeated pair work of #69 are not changed. `tests/test_mask_pieces.py`, `tests/test_mask_scan.py`. - **The run shows its own folder and header check, and that check is no longer quadratic (owner Colab test of v0.9.0, 25 November 2026).** On a large mixed-layout experiment, *Run* showed "Preparing: checking the folders and the image headers again · 0:00 elapsed" for 10-15 minutes before the first image: the run checks every header again (bound to its fingerprint) with no progress reported, and the elapsed time was redrawn only on a progress report. The run now reports that check through `RunMode(checking=...)` (preflight's `(phase, done, total, path)`, operational only like `workers`; `run_experiment`'s parameters are unchanged), and the notebook shows each phase and each header of how many ("Preparing: reading the image headers again · 120 of 24,000"), with the elapsed time redrawn every second by `Wait.ticking()` while the run works. While it goes, the notebook says that a cell run meanwhile waits for it, and how to interrupt it. Two steps of the check were O(n²): each image's staging key took `MetadataReport.dtype` (a pass over every header) and the mask-name screen compared each image's name with every other one (`mask_names._mask_owner` now looks up the prefixes of the name). The outputs are byte for byte the same (`plane_histograms.csv`, `experiment_design.csv`, `image_qc.csv` of a 4,800-image three- and two-channel tree); the check before the first image took 30.0 s → 10.3 s for 12,000 images and 72-75 s → 24-27 s for 24,000 on local disk (`tests/test_run_checking_progress.py`). In a `verify_content` run (the notebook's default, and any run on a fresh output folder) the run then reads every image whole for its content SHA-256 before the first pixel is read: on Google Drive that pass, not the header check, is what took minutes (owner: about 200 images, 10-15 minutes). It is now reported too, as the phase `contents` (`run.phases.CONTENTS`, "Preparing: reading each image whole for its content SHA-256 · 12 of 200"); what is read and verified is unchanged. diff --git a/notebooks/MorphoBricks_Preprocessing_Cellpose.ipynb b/notebooks/MorphoBricks_Preprocessing_Cellpose.ipynb index 225e65a9..416af96d 100644 --- a/notebooks/MorphoBricks_Preprocessing_Cellpose.ipynb +++ b/notebooks/MorphoBricks_Preprocessing_Cellpose.ipynb @@ -617,11 +617,11 @@ "\n", "Segments the run that cell 3's app just finished, in the masks folder that run uses (the masks folder the app checked, else the one the run recorded). The step says which run and masks folder it took. With no finished run in the app (no run yet, or a run that stopped), it says so and names cell 3; to segment an earlier finished run instead, type its output folder and a masks folder in step 1 (**Folders**) and press **Open the run**. A run whose images changed since it ran is refused, with the reason.\n", "\n", - "**The first time:** Cellpose 4.2.1.1 and PyTorch are not installed by cell 1. Tick **Install Cellpose 4.2.1.1 (with PyTorch) now** and press **Install Cellpose 4.2.1.1** (a download of a few gigabytes). If the installation changes `numpy` or `opencv` while the runtime already has them loaded, the step says to restart the runtime (Colab: Runtime > Restart session); then run cells 1, 3 and 4 again: nothing more is installed.\n", + "**The first time:** Cellpose 4.2.1.1 and PyTorch are not installed by cell 1. Tick **Install Cellpose 4.2.1.1 (with PyTorch) now** and press **Install Cellpose 4.2.1.1** (a download of a few gigabytes where PyTorch is not installed yet; on Google Colab PyTorch is usually installed already, so much less is downloaded). The card says what pip is doing, with the time since it started, and then what it installed. If the installation changes `numpy` or `opencv` while the runtime already has them loaded, the step says to restart the runtime (Colab: Runtime > Restart session); then run cells 1, 3 and 4 again: nothing more is installed.\n", "\n", "Then four steps, one on screen at a time, like the preprocessing app: move with **Next** and **Back** or click a step in the strip at the top; your answers are kept.\n", "\n", - "1. **Folders**: the run and the masks folder. The masks folder is checked here: it may not be the run's output folder or the experiment folder, nor inside or around either. Once the run is open, its images are shown with the preprocessing image viewer (channels named by their IDs).\n", + "1. **Folders**: the run and the masks folder. The masks folder is checked here: it may not be the run's output folder or the experiment folder, nor inside or around either. Opening the run checks every image against the run again (a run that checked the image contents reads each image whole, which takes minutes for large images on Google Drive): a line says which check, how many images of how many, and the time since it started. Once the run is open, its images are shown with the preprocessing image viewer (channels named by their IDs).\n", "2. **Output and channels**: the **output**, explained next to the choice (Cell mask, Nuclei mask or **Both**: two mask types, both channels required, each its own batch), then the channels **by channel ID** or **By number** (counted from 1, only when every image has the same channels in the same order).\n", "3. **Model and preview**: the model, the device and the settings (each with a one-line help). **Preview** loads the model the first time (built-in weights are downloaded from **Hugging Face** only if you tick the download box, with one progress bar; a GPU that is not available is refused, never replaced by the CPU), then segments the image chosen; nothing is written. Choose another image and press **Preview** again: the model is reused, and loaded again only if you change the model, its file or the device. With **Both**, a box below lets the nuclei use a model and settings of their own.\n", "4. **Segment**: the whole experiment (existing masks are never overwritten unless you tick it). One line at the end says what comes next: cell 5.\n", @@ -658,8 +658,8 @@ "\n", "from morphobricks_preprocessing.notebook_preprocessing_cellpose import segmentation_step\n", "\n", - "segmentation = segmentation_step(notebook)\n", - "display(segmentation)" + "# Shown first, then the run is opened: the wait of its checks is on screen (#574).\n", + "segmentation = segmentation_step(notebook, show=display)" ] }, { diff --git a/pyproject.toml b/pyproject.toml index 00e113d2..6278d510 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -156,6 +156,7 @@ baseline = "tools/code_rules_baseline.json" "morphobricks_preprocessing.name_issues" = "pure" "morphobricks_preprocessing.run.phases" = "pure" "morphobricks_preprocessing.ome_header" = "io" +"morphobricks_preprocessing.open_checks" = "pure" "morphobricks_preprocessing.tiff_colour" = "io" "morphobricks_preprocessing.tiff_axes" = "io" "morphobricks_preprocessing.rgb_override" = "pure" @@ -237,6 +238,8 @@ baseline = "tools/code_rules_baseline.json" "morphobricks_preprocessing.notebook_folder" = "ui" "morphobricks_preprocessing.notebook_folder_previews" = "ui" "morphobricks_preprocessing.notebook_options" = "ui" +"morphobricks_preprocessing.notebook_cellpose_install" = "ui" +"morphobricks_preprocessing.notebook_open_progress" = "ui" "morphobricks_preprocessing.notebook_plots" = "ui" "morphobricks_preprocessing.notebook_channel_identity" = "ui" "morphobricks_preprocessing.notebook_render" = "ui" diff --git a/src/morphobricks_preprocessing/cellpose_install.py b/src/morphobricks_preprocessing/cellpose_install.py index 89629f57..2a3b6cd3 100644 --- a/src/morphobricks_preprocessing/cellpose_install.py +++ b/src/morphobricks_preprocessing/cellpose_install.py @@ -7,15 +7,20 @@ installation (the consent, as for the model download and DINOv3). It keeps the rules of the Cellpose notebook's install cell: the release pinned, never DINOv3, and a restart asked for when ``pip`` changed a package the running kernel already loaded (:data:`LOADED_BY_KERNEL`), -never a guess that the old copy still works. Nothing here imports Cellpose or torch. +never a guess that the old copy still works. ``pip``'s lines are passed on as it prints them +(``output``), so the notebook shows its progress (owner Colab test, #574), and +:func:`installed_distributions` / :func:`install_changes` say what it installed. Nothing here +imports Cellpose or torch. """ from __future__ import annotations import importlib +import importlib.metadata +import re import subprocess import sys -from collections.abc import Mapping +from collections.abc import Callable, Mapping from . import segmentation_cellpose_model as model from .segmentation_cellpose_model import CELLPOSE_VERSION @@ -73,13 +78,53 @@ def _changed(before: Mapping[str, str | None]) -> list[str]: ] -def install_cellpose(ticked: bool) -> str: +def installed_distributions() -> dict[str, str]: + """Return the version of every installed distribution, by its normalized name (PEP 503).""" + found = {} + for dist in importlib.metadata.distributions(): + name = dist.metadata["Name"] + if name: + found[re.sub(r"[-_.]+", "-", name).lower()] = dist.version + return found + + +def install_changes(before: Mapping[str, str], after: Mapping[str, str]) -> list[str]: + """Return what an installation added or changed: ``name version`` (``was old``), sorted.""" + return [ + f"{name} {version}" + (f" (was {before[name]})" if name in before else "") + for name, version in sorted(after.items()) + if before.get(name) != version + ] + + +def _pip(command: list[str], output: Callable[[str], object]) -> None: + """Run ``pip``, telling ``output`` each line it prints (also its errors), as it prints it. + + Raises + ------ + subprocess.CalledProcessError + When ``pip`` fails. + """ + with subprocess.Popen( + command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, bufsize=1 + ) as pip: + for line in pip.stdout: + output(line.rstrip()) + if pip.returncode: + raise subprocess.CalledProcessError(pip.returncode, command) + + +def install_cellpose(ticked: bool, output: Callable[[str], object] = print) -> str: """Install the pinned Cellpose release when it is not installed, if ``ticked``. Parameters ---------- ticked Whether the user ticked the installation (their consent to the download). + output + Told each line ``pip`` prints, as it prints it (the notebook shows its progress from + them, owner Colab test #574); by default printed, where a widget's callback would + otherwise lose them. Returns ------- @@ -98,7 +143,7 @@ def install_cellpose(ticked: bool) -> str: raise SegmentationError(NOT_TICKED.format(version=CELLPOSE_VERSION)) before = {name: model.installed_version(name) for name in LOADED_BY_KERNEL} try: - subprocess.run(cellpose_install_command(), check=True) + _pip(cellpose_install_command(), output) except (subprocess.CalledProcessError, OSError) as exc: raise SegmentationError( f"Cellpose {CELLPOSE_VERSION} could not be installed ({exc}). Check the installation " @@ -122,4 +167,6 @@ def install_cellpose(ticked: bool) -> str: "cellpose_install_command", "cellpose_ready", "install_cellpose", + "install_changes", + "installed_distributions", ] diff --git a/src/morphobricks_preprocessing/notebook_cellpose.py b/src/morphobricks_preprocessing/notebook_cellpose.py index d9a8c452..d094ce83 100644 --- a/src/morphobricks_preprocessing/notebook_cellpose.py +++ b/src/morphobricks_preprocessing/notebook_cellpose.py @@ -34,6 +34,7 @@ from .notebook_progress import progress_html from .notebook_stop import CellStop from .notebook_style import STYLE_CSS, table, tiles +from .open_checks import Checking, quiet from .run_inputs import Fov, RunInputs from .segmentation_cellpose_run import ( channel_layouts, @@ -164,8 +165,8 @@ def model_for(self, output: str) -> tuple[cp.LoadedModel, cp.Settings]: return self.loaded, self.settings @stops - def open(self, run_folder: str, masks_folder: str) -> None: - """Open the run and say what it holds (cell 3). + def open(self, run_folder: str, masks_folder: str, *, checking: Checking = quiet) -> None: + """Open the run and say what it holds (cell 3); ``checking`` is told how its checks go. What an earlier open chose is dropped first: a refused open leaves no run, channels or model to segment with, so nothing is written to the folders of the run before. @@ -175,7 +176,7 @@ def open(self, run_folder: str, masks_folder: str) -> None: self.drop_choice() if not masks_folder.strip(): raise SegmentationError("Give the masks folder (outside the experiment and the run).") - inputs, pinned = open_pinned(run_folder) + inputs, pinned = open_pinned(run_folder, checking=checking) # The physical folder, fixed now: a relative path never follows a later change of the # kernel's working directory (review aq, B1). masks_root = Path(masks_folder.strip()).expanduser().resolve() diff --git a/src/morphobricks_preprocessing/notebook_cellpose_app.py b/src/morphobricks_preprocessing/notebook_cellpose_app.py index 648fad9c..a003a911 100644 --- a/src/morphobricks_preprocessing/notebook_cellpose_app.py +++ b/src/morphobricks_preprocessing/notebook_cellpose_app.py @@ -138,6 +138,7 @@ def segmentation_app( app: object = None, on_masks_written: Callable[[cp.BatchResult], object] | None = None, register_with: str | None = None, + open_now: bool = True, ) -> SegmentationApp: """Return the whole Cellpose segmentation as one widget. @@ -158,13 +159,16 @@ def segmentation_app( Where the notebook registers the masks itself (the combined notebook's cell 5); the line shown once the masks are written then names it (:func:`.segmentation_cellpose_run.next_step_line`). None: the declaration by hand. + open_now + False leaves the run to be opened by the caller (``segmentation.workflow.forms + ["open"].submit()``), once the widget is on screen to show the wait. Returns ------- SegmentationApp The steps of :data:`PAGES` in a stepper; ``.workflow`` is the - :class:`.CellposeNotebook` behind them. Given both folders, the run is opened at once - (its result, or its refusal, is shown under **Open the run**). + :class:`.CellposeNotebook` behind them. Given both folders and ``open_now``, the run is + opened at once (its result, or its refusal, is shown under **Open the run**). """ found = app_folders(app) if app is not None else ("", "") if isinstance(run_folder, RunInputs): @@ -180,6 +184,6 @@ def segmentation_app( segmentation = SegmentationApp(workflow) opener = workflow.forms["open"] opener.fields["run_folder"].value, opener.fields["masks_folder"].value = run, masks - if run and masks: + if run and masks and open_now: opener.submit() return segmentation diff --git a/src/morphobricks_preprocessing/notebook_cellpose_form.py b/src/morphobricks_preprocessing/notebook_cellpose_form.py index 771abc56..0343626a 100644 --- a/src/morphobricks_preprocessing/notebook_cellpose_form.py +++ b/src/morphobricks_preprocessing/notebook_cellpose_form.py @@ -45,6 +45,7 @@ from .notebook_cellpose_guard import check_current, check_folders, take_over from .notebook_cellpose_summary import summary_html, summary_widget, used from .notebook_cellpose_view import run_entries, run_viewer +from .notebook_open_progress import opening from .notebook_stepper import field_rows __all__ = [ @@ -161,6 +162,7 @@ def __init__(self) -> None: self._summary: widgets.HTML | None = None self.on_change: list[Callable[[], object]] = [] # called after every step's button self.viewer = run_viewer(lambda: self.inputs) + self.opening = widgets.HTML() # the wait of Open the run (owner Colab test, #574) take_over(self) # the forms of an earlier workflow in this kernel stop working def _keep(self, name: str, form: StepForm) -> StepForm: @@ -229,15 +231,17 @@ def open_form(self) -> StepForm: lambda: self._open_and_show(ui.clean_path(run.value), ui.clean_path(masks.value)), {"run_folder": run, "masks_folder": masks}, ) - form.body.children = [*form.body.children, self.viewer.widget] + form.body.children = [*form.body.children, self.opening, self.viewer.widget] return self._keep("open", form) def _open_and_show(self, run_folder: str, masks_folder: str) -> None: - """Open the run, then show its images (or none, when it was refused).""" - try: - self.open(run_folder, masks_folder) - finally: - self.viewer.set_entries(run_entries(self.inputs)) + """Open the run, then show its images (or none, when it was refused), with the wait.""" + with opening(self.opening) as checking: + try: + self.open(run_folder, masks_folder, checking=checking) + finally: + checking("viewer", 0, 0, "") + self.viewer.set_entries(run_entries(self.inputs)) def channels_form(self) -> StepForm: """Show the form of cell 4: the output and the mask type(s); the channels come after it. diff --git a/src/morphobricks_preprocessing/notebook_cellpose_install.py b/src/morphobricks_preprocessing/notebook_cellpose_install.py new file mode 100644 index 00000000..cd59fa67 --- /dev/null +++ b/src/morphobricks_preprocessing/notebook_cellpose_install.py @@ -0,0 +1,96 @@ +"""The progress and the result of installing Cellpose in the combined notebook's cell 4. + +The owner's Colab test of 26 November 2026 (issue #574) found the first installation slow and +silent: ``pip`` printed to the kernel's own output, which a widget's button does not show. +:class:`PipProgress` turns each line ``pip`` prints (:func:`.cellpose_install.install_cellpose` +``output``) into the wait of #567 (:class:`.notebook_progress.Wait`): what pip is doing now, +with an elapsed time that ticks; :func:`installed_html` then says what was installed. Nothing +here runs ``pip`` or decides anything. +""" + +from __future__ import annotations + +import html +import re +from collections import deque +from collections.abc import Iterable + +from . import notebook_style as ui +from .notebook_progress import Wait + +INSTALLING = "Installing Cellpose {version} (with PyTorch)" +"""The wait's label (``{version}``: the pinned release); what pip does now follows it.""" +PIP_STEPS = ( + ("Collecting ", "finding {rest}"), + ("Downloading ", "downloading {rest}"), + ("Building wheel", "building {rest}"), + ("Installing collected packages", "installing the packages (this can take minutes)"), +) +"""The lines of ``pip`` that name a new step of the installation, and what the wait says.""" +KEPT_LINES = 20 +"""How many of pip's last lines a failed installation shows.""" + + +def pip_step(line: str) -> str | None: + """Return what the wait says for one line ``pip`` printed, or None for a line it ignores.""" + text = line.strip() + for start, said in PIP_STEPS: + if text.startswith(start): + rest = text[len(start) :].strip(" :") + return said.format(rest=re.split(r" \(?from ", rest)[0]) + return None + + +class PipProgress: + """Show each step ``pip`` reports in a :class:`.notebook_progress.Wait`; keep its last lines. + + Parameters + ---------- + wait + The started wait. + label + Its label (:data:`INSTALLING`, formatted). + """ + + def __init__(self, wait: Wait, label: str) -> None: + self.wait, self.label = wait, label + self.lines: deque[str] = deque(maxlen=KEPT_LINES) + + def line(self, text: str) -> None: + """Take one line of pip's output: kept, and shown when it names a new step.""" + self.lines.append(text) + step = pip_step(text) + if step: + self.wait.phase(f"{self.label}: {step}") + + +def installed_html(version: str, took: str, changes: Iterable[str]) -> str: + """Return the green card saying Cellpose is installed, how long it took and what changed.""" + changes = list(changes) + listed = ", ".join(changes) if changes else "nothing new (it was all there already)" + return ui.status( + "ok", + f"Cellpose {version} is installed ({took})", + [f"pip installed or changed: {html.escape(listed)}."], + raw=True, + ) + + +def failed_lines(lines: Iterable[str]) -> list[str]: + """Return pip's last lines for a failed installation's card (HTML), or none.""" + lines = [line for line in lines if line.strip()] + if not lines: + return [] + text = html.escape("\n".join(lines)) + return [f"pip's last lines:
{text}
"] + + +__all__ = [ + "INSTALLING", + "KEPT_LINES", + "PIP_STEPS", + "PipProgress", + "failed_lines", + "installed_html", + "pip_step", +] diff --git a/src/morphobricks_preprocessing/notebook_open_progress.py b/src/morphobricks_preprocessing/notebook_open_progress.py new file mode 100644 index 00000000..3aa341f9 --- /dev/null +++ b/src/morphobricks_preprocessing/notebook_open_progress.py @@ -0,0 +1,70 @@ +"""The wait shown while the Cellpose step **Folders** opens a run (owner Colab test, 26 Nov 2026). + +Opening a run checks every image against the manifest (:mod:`.open_checks`); on Google Drive, +with a run that verified content, every image is read whole for its SHA-256, which took about +4 minutes on 200 images with nothing on screen (issue #574). :func:`opening` shows that wait +with the run's own progress line (:class:`.notebook_progress.Wait`, #567): the phase, "n of N" +with the image being read, and an elapsed time that ticks in a thread while nothing is +reported. Nothing here reads a file or decides anything. +""" + +from __future__ import annotations + +import html +from collections.abc import Iterator +from contextlib import contextmanager + +import ipywidgets as widgets + +from .notebook_progress import Wait +from .open_checks import Checking + +OPENING = { + "run": "Opening the run: reading its manifest, table and description", + "images": "Checking that each image is the one the run read (size and date)", + "contents": "Reading each image whole for its content SHA-256", + "masks": "Checking that each mask is the one the run read (size and date)", + "unrecorded": "Listing the folders for images added since the run", + "viewer": "Reading the first image for the viewer", +} +"""What the wait says in each phase (:data:`.open_checks.OPEN_PHASES`, then ``viewer``).""" +COUNTED = ("images", "contents", "masks") +"""The phases shown as done of total, each with its file.""" +TOOK = "Opened and checked in {took}." +"""The line left once the wait ends (``{took}``: ``m:ss``), refused or not.""" + + +@contextmanager +def opening(target: widgets.HTML) -> Iterator[Checking]: + """Show the wait of opening a run in ``target`` while the block runs. + + Parameters + ---------- + target + The HTML widget the line is drawn in; it is left saying how long it took. + + Yields + ------ + Checking + The ``checking(phase, done, total, path)`` to pass to the opening + (:func:`.segmentation_cellpose_run.open_run`): each phase of :data:`OPENING` is + named, the counted ones as done of total with the file read now. + """ + wait = Wait(target) + wait.start(OPENING["run"]) + + def checking(phase: str, done: int, total: int, path: str) -> None: + label = OPENING[phase] + if wait.label != label: + wait.phase(label, total if phase in COUNTED else 0) + if phase in COUNTED: + wait.step(done, total, path) + + try: + with wait.ticking(): + yield checking + finally: + target.value = f"
{html.escape(TOOK.format(took=wait.took()))}
" + + +__all__ = ["COUNTED", "OPENING", "TOOK", "opening"] diff --git a/src/morphobricks_preprocessing/notebook_preprocessing_cellpose.py b/src/morphobricks_preprocessing/notebook_preprocessing_cellpose.py index 2ef1cf85..2a3e72be 100644 --- a/src/morphobricks_preprocessing/notebook_preprocessing_cellpose.py +++ b/src/morphobricks_preprocessing/notebook_preprocessing_cellpose.py @@ -29,10 +29,20 @@ from . import notebook_style as ui from . import segmentation_cellpose as cp -from .cellpose_install import cellpose_install_command, cellpose_ready, install_cellpose +from .cellpose_install import ( + cellpose_install_command, + cellpose_ready, + install_cellpose, + install_changes, + installed_distributions, +) from .notebook_cellpose_app import SegmentationApp, app_folders, segmentation_app from .notebook_cellpose_form import CellposeNotebook +from .notebook_cellpose_install import INSTALLING, PipProgress, failed_lines, installed_html +from .notebook_open_progress import opening +from .notebook_progress import Wait from .notebook_render import blocked_line +from .open_checks import Checking, quiet from .run_inputs import RunInputsError from .segmentation_cellpose_run import open_run @@ -87,22 +97,50 @@ class SegmentationStep(widgets.VBox): def __init__( self, app: object, on_masks_written: Callable[[cp.BatchResult], object] | None ) -> None: - """Read the app's run and masks folder, then mount or offer the installation.""" + """Read the app's run and masks folder, then mount or offer the installation. + + Nothing is opened yet: :meth:`check` opens the run, once this widget can show it. + """ super().__init__(layout=widgets.Layout(width="99%")) self.app, self._on_masks_written = app, on_masks_written self.run_folder, self.masks_folder = app_folders(app) - self.refused = _refusal(self.run_folder) + self.refused = "" self.segmentation: SegmentationApp | None = None self.rechecked_run: Path | None = None self.registered_manifest: str | None = None self.notice = widgets.HTML(self._notice()) + self.opening = widgets.HTML() # the wait of the run's checks without the component + self.installed = widgets.HTML() # what the installation installed, once it did self.install_box = widgets.VBox() - self.children = [widgets.HTML(ui.STYLE_CSS), self.notice, self.install_box] + self.children = [ + widgets.HTML(ui.STYLE_CSS), + self.notice, + self.opening, + self.installed, + self.install_box, + ] if cellpose_ready(): - self._mount() + self._mount(open_now=False) else: self.install_box.children = [self._install_card()] + def check(self) -> None: + """Open the app's run once, showing the wait, and say when it cannot be segmented. + + With the component and both folders, **Open the run** opens it (its wait under the + button); otherwise it is opened here only for its refusal (its wait under the notice). + Opened once, not twice (owner Colab test, #574): every image of a ``verify_content`` + run is read whole for its SHA-256 at each opening. + """ + if not self.run_folder: + return + if self.segmentation is not None and self.masks_folder: + self._open_in_form() + return + with opening(self.opening) as checking: + self.refused = _refusal(self.run_folder, checking) + self.notice.value = self._notice() + @property def workflow(self) -> CellposeNotebook | None: """The segmentation's state (its masks folder and results), or None before it shows.""" @@ -127,14 +165,25 @@ def _run_card(self) -> str: raw=True, ) - def _mount(self) -> None: - """Mount the segmentation component on the app's run (opened when both folders are).""" + def _mount(self, open_now: bool = True) -> None: + """Mount the segmentation component on the app's run; ``open_now``: open it there.""" self.segmentation = segmentation_app( - app=self.app, on_masks_written=self._on_masks_written, register_with=REGISTER_WITH + app=self.app, + on_masks_written=self._on_masks_written, + register_with=REGISTER_WITH, + open_now=False, ) - self.install_box.children = [self.segmentation] + self.install_box.children = [self.segmentation] # on screen before the wait + if open_now: + self._open_in_form() + + def _open_in_form(self) -> None: + """Open the run by **Open the run** when both folders are known; keep its refusal.""" opener = self.segmentation.workflow.forms["open"] - if self.run_folder and self.masks_folder and opener.stopped is not None: + if not (self.run_folder and self.masks_folder): + return + opener.submit() + if opener.stopped is not None: # A refused masks folder is said under Open the run; the run itself is not refused. if not self.refused and not self.segmentation.workflow.folders_refused: self.refused = opener.refusal @@ -175,23 +224,36 @@ def _update_install_button(self) -> None: self.install_blocker.value = blocked_line([] if ticked else ["tick the installation"]) def install(self) -> bool: - """Install Cellpose (the tick is the consent) and mount the component; False if refused.""" - self.install_status.value = ui.working(f"Installing Cellpose {cp.CELLPOSE_VERSION}…") + """Install Cellpose (the tick is the consent) and mount the component; False if refused. + + The wait says what pip does now, with a ticking time; then a card says what pip + installed or changed, above the component (owner Colab test, #574). + """ + label = INSTALLING.format(version=cp.CELLPOSE_VERSION) + wait = Wait(self.install_status) + wait.start(f"{label}: starting pip") + shown, before = PipProgress(wait, label), installed_distributions() try: - install_cellpose(self.install_tick.value) + with wait.ticking(): + version = install_cellpose(self.install_tick.value, shown.line) except cp.SegmentationError as exc: - self.install_status.value = ui.status("error", "Cellpose is not installed", [str(exc)]) + lines = [html.escape(str(exc)), *failed_lines(shown.lines)] + self.install_status.value = ui.status( + "error", "Cellpose is not installed", lines, raw=True + ) return False + changes = install_changes(before, installed_distributions()) + self.installed.value = installed_html(version, wait.took(), changes) self._mount() return True -def _refusal(run_folder: str) -> str: +def _refusal(run_folder: str, checking: Checking = quiet) -> str: """Return why the run in ``run_folder`` cannot be opened, or "" (also for no run).""" if not run_folder: return "" try: - open_run(run_folder) + open_run(run_folder, checking=checking) except (RunInputsError, cp.SegmentationError) as exc: return str(exc) return "" @@ -203,9 +265,12 @@ def _refused_card(reason: str) -> str: def segmentation_step( - app: object, *, on_masks_written: Callable[[cp.BatchResult], object] | None = None + app: object, + *, + on_masks_written: Callable[[cp.BatchResult], object] | None = None, + show: Callable[[SegmentationStep], object] | None = None, ) -> SegmentationStep: - """Return cell 4's widget: the Cellpose segmentation of the run of the Preprocessing app. + """Return cell 4's widget, its run opened: the Cellpose segmentation of the app's run. Parameters ---------- @@ -214,8 +279,16 @@ def segmentation_step( masks folder rule give the folders (:func:`.notebook_cellpose_app.app_folders`). on_masks_written Passed to :func:`.notebook_cellpose_app.segmentation_app`. + show + Called with the widget before the run is opened (cell 4: IPython's ``display``), so + that the wait of its checks is on screen (owner Colab test, #574); None: the widget + is returned opened, for the caller to show. """ - return SegmentationStep(app, on_masks_written) + step = SegmentationStep(app, on_masks_written) + if show is not None: + show(step) + step.check() + return step __all__ = ["NO_RUN", "REGISTER_WITH", "RUN_REFUSED", "SegmentationStep", "segmentation_step"] diff --git a/src/morphobricks_preprocessing/open_checks.py b/src/morphobricks_preprocessing/open_checks.py new file mode 100644 index 00000000..f9cbcbdb --- /dev/null +++ b/src/morphobricks_preprocessing/open_checks.py @@ -0,0 +1,68 @@ +"""The phases of opening a run, told to a progress callback (owner Colab test, 26 Nov 2026). + +Opening a run (:func:`.run_inputs.open_checked`, :meth:`.run_inputs.RunInputs.open`) checks +every image and mask against the manifest before anything is used: on Google Drive, with a +``verify_content`` run of 200 images of 10-50 MB each, that took minutes with nothing on +screen (the Cellpose step **Folders**, issue #574). A caller that shows it passes +``checking(phase, done, total, path)``, the signature of the run's own checks +(:class:`.run.modes.RunMode` ``checking``, #567), told each phase of :data:`OPEN_PHASES`. +It changes nothing: the same files are checked, in the same order, with the same result. +Nothing here reads a file. +""" + +from __future__ import annotations + +from collections.abc import Callable, Iterable, Iterator +from operator import attrgetter +from typing import TypeVar + +Checking = Callable[[str, int, int, str], None] +"""``checking(phase, done, total, path)``: a phase of :data:`OPEN_PHASES`, ``done`` of +``total`` items (0 of 0 for a phase that is not counted) and the item now checked.""" + +OPEN_PHASES = ("run", "images", "contents", "masks", "unrecorded") +"""In order: the manifest, table and description; each image's fingerprint (size and +modification time); each image's content SHA-256 (``verify_content`` runs only: every image +read whole); each mask's fingerprint; the folders listed for files added since the run.""" + +RELATIVE = attrgetter("relative_path") +"""The relative path of an image's manifest entry, as a progress line shows it.""" + +T = TypeVar("T") + + +def quiet(phase: str, done: int, total: int, path: str) -> None: + """Tell nothing: the ``checking`` of a caller that shows no progress.""" + + +def counted( + checking: Checking, phase: str, items: Iterable[T], path: Callable[[T], str] +) -> Iterator[T]: + """Yield ``items`` in order, telling ``checking`` before each one and once at the end. + + Parameters + ---------- + checking + The progress callback. + phase + The phase of :data:`OPEN_PHASES` these items are checked in. + items + What is checked, one after another. + path + The item's relative path, as shown. + + Yields + ------ + T + Each item, after ``checking(phase, done, total, path(item))``; then + ``checking(phase, total, total, "")``. + """ + items = list(items) + total = len(items) + for done, item in enumerate(items): + checking(phase, done, total, path(item)) + yield item + checking(phase, total, total, "") + + +__all__ = ["OPEN_PHASES", "RELATIVE", "Checking", "counted", "quiet"] diff --git a/src/morphobricks_preprocessing/run_inputs.py b/src/morphobricks_preprocessing/run_inputs.py index 4d2a42e7..53dc76ae 100644 --- a/src/morphobricks_preprocessing/run_inputs.py +++ b/src/morphobricks_preprocessing/run_inputs.py @@ -67,6 +67,7 @@ from .mask_conversion import ConversionInputs from .mask_record import shared_mask_text from .masks import FOLDER +from .open_checks import RELATIVE, Checking, counted, quiet from .plane_channels import read_xyc_plane from .planes import DEFAULT_MEMORY_LIMIT from .recorded_sizes import RecordedSize @@ -262,17 +263,7 @@ def open( ``RUN_FOLDER_REPORT_UNREADABLE``: the folder holds no manifest and its report cannot be read, or is of another report version; it names the file. """ - output = Path(output_folder).resolve() - # One generation of the outputs (contract §9): read again if a run published - # meanwhile. - inputs = read_stable(output, lambda: cls._read(output, experiment_root, masks_root)) - if inputs is None: - raise RunInputsError( - f"Another run kept publishing new results in {output} while they were being " - "opened. Open the run again once it has finished." - ) - inputs._check_files() - return inputs + return open_checked(output_folder, experiment_root, masks_root) @classmethod def _read( @@ -388,15 +379,18 @@ def histograms(self) -> tuple[PlaneRecord, ...]: """Return the table's rows, as read when the run was opened.""" return self.records - def _check_files(self) -> None: + def _check_files(self, checking: Checking = quiet) -> None: """Refuse changed or gone files, masks without axes or shared, unrecorded files.""" - changed = [e.relative_path for e in self.manifest.files if not self._unchanged(e)] + images = counted(checking, "images", self.manifest.files, RELATIVE) + changed = [e.relative_path for e in images if not self._unchanged(e)] if not changed and self.manifest.settings.verify_content: - changed = content_changed(self.manifest.files, self.experiment_root) + entries = counted(checking, "contents", self.manifest.files, RELATIVE) + changed = content_changed(entries, self.experiment_root) if changed: raise RunInputsError(_changed_text(changed)) recorded = (self.manifest.masks or {}).get("files", ()) - changed = [m["path"] for m in recorded if not self._mask_unchanged(m)] + masks = counted(checking, "masks", recorded, lambda m: m["path"]) + changed = [m["path"] for m in masks if not self._mask_unchanged(m)] if changed: raise RunInputsError(_changed_text(changed, "mask")) without_axes = [m["path"] for m in recorded if not m.get("axes") or not m.get("roles")] @@ -405,6 +399,7 @@ def _check_files(self) -> None: shared = shared_mask_text(recorded) if shared: raise RunInputsError(shared) + checking("unrecorded", 0, 0, "") try: unrecorded = unrecorded_files( self.manifest, self.experiment_root, self.masks_root, self.output_folder @@ -460,6 +455,27 @@ def _mask_unchanged(self, recorded: Mapping) -> bool: return False +def open_checked( + output_folder: str | os.PathLike, + experiment_root: str | os.PathLike | None = None, + masks_root: str | os.PathLike | None = None, + *, + checking: Checking = quiet, +) -> RunInputs: + """Open a run as :meth:`RunInputs.open` does, telling ``checking`` (:mod:`.open_checks`).""" + output = Path(output_folder).resolve() + checking("run", 0, 0, "") + # One generation of the outputs (contract §9): read again if a run published meanwhile. + inputs = read_stable(output, lambda: RunInputs._read(output, experiment_root, masks_root)) + if inputs is None: + raise RunInputsError( + f"Another run kept publishing new results in {output} while they were being " + "opened. Open the run again once it has finished." + ) + inputs._check_files(checking) + return inputs + + def _manifest(output: Path) -> tuple[RunManifest, str]: """Read an output folder's manifest and the SHA-256 of the bytes it was parsed from. diff --git a/src/morphobricks_preprocessing/segmentation_cellpose_run.py b/src/morphobricks_preprocessing/segmentation_cellpose_run.py index ec136649..19d38de3 100644 --- a/src/morphobricks_preprocessing/segmentation_cellpose_run.py +++ b/src/morphobricks_preprocessing/segmentation_cellpose_run.py @@ -11,7 +11,8 @@ from ._io import file_sha256 from .manifest import MANIFEST_FILENAME -from .run_inputs import RunInputs +from .open_checks import Checking, quiet +from .run_inputs import RunInputs, open_checked from .segmentation_cellpose_model import CELLPOSE_VERSION from .segmentation_record import SegmentationError, check_mask_type @@ -38,9 +39,12 @@ """The refusal of a preview, a batch or a record whose run manifest is no longer the opened one.""" -def open_run(run_folder: str) -> RunInputs: +def open_run(run_folder: str, *, checking: Checking = quiet) -> RunInputs: """Open the run in ``run_folder`` (preprocessing's own checks; refusals are unchanged). + ``checking`` is told each phase of the checks (:func:`.run_inputs.open_checked`); it + changes nothing they check or decide. + Raises ------ SegmentationError @@ -50,11 +54,11 @@ def open_run(run_folder: str) -> RunInputs: """ if not run_folder.strip(): raise SegmentationError("Give the run's output folder (the one holding run_manifest.json).") - return RunInputs.open(Path(run_folder.strip())) + return open_checked(Path(run_folder.strip()), checking=checking) -def open_pinned(run_folder: str) -> tuple[RunInputs, str | None]: - """Open the run (:func:`open_run`) and return it with the SHA-256 of its manifest. +def open_pinned(run_folder: str, *, checking: Checking = quiet) -> tuple[RunInputs, str | None]: + """Open the run (:func:`open_run`, with ``checking``) and return it with its manifest SHA-256. The SHA-256 is the snapshot's (:attr:`.run_inputs.RunInputs.manifest_sha256`: of the bytes the manifest was parsed from, review ar B2); a run published again before this returns is @@ -69,7 +73,7 @@ def open_pinned(run_folder: str) -> tuple[RunInputs, str | None]: RunInputsError For a run that cannot be opened. """ - inputs = open_run(run_folder) + inputs = open_run(run_folder, checking=checking) check_manifest(inputs, inputs.manifest_sha256) return inputs, inputs.manifest_sha256 diff --git a/tests/test_cellpose_folders_open.py b/tests/test_cellpose_folders_open.py new file mode 100644 index 00000000..1ebbb5fc --- /dev/null +++ b/tests/test_cellpose_folders_open.py @@ -0,0 +1,165 @@ +"""The Cellpose step Folders opens the run once, on screen, with its wait (issue #574, item 2). + +Owner's Colab test of v0.9.0 (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, once by **Open the run**), and each +opening of a ``verify_content`` run reads every image whole for its content SHA-256. It now +shows the widget first, opens the run once, and names each phase with "n of N" and the time. +The checks are the same: :func:`.run_inputs.open_checked` refuses and returns what +:meth:`.RunInputs.open` does. +""" + +import os +from collections import Counter +from pathlib import Path + +import numpy as np +import pytest + +from cellpose_stub import install +from test_notebook_preprocessing_cellpose import ran_app + +widgets = pytest.importorskip("ipywidgets") + +from morphobricks_preprocessing import _io, notebook_progress, source_content # noqa: E402 +from morphobricks_preprocessing.notebook_open_progress import OPENING, opening # noqa: E402 +from morphobricks_preprocessing.notebook_preprocessing_cellpose import ( # noqa: E402 + RUN_REFUSED, + segmentation_step, +) +from morphobricks_preprocessing.open_checks import OPEN_PHASES # noqa: E402 +from morphobricks_preprocessing.run_inputs import ( # noqa: E402 + RunInputs, + RunInputsError, + open_checked, +) + +pytestmark = pytest.mark.usefixtures("legacy_grid") + + +def count_whole_reads(monkeypatch, root, seen=None): + """Count, per image of ``root``, the whole reads for a content SHA-256 (``file_sha256``). + + ``seen`` (a list) gets, at each read, what ``seen_now()`` returns, if given as a pair. + """ + reads, real = Counter(), _io.file_sha256 + root = Path(root).resolve() + + def counting(path): + where = Path(path).resolve() + if where.is_relative_to(root): + reads[where.relative_to(root).as_posix()] += 1 + if seen is not None: + seen[0].append(seen[1]()) + return real(path) + + monkeypatch.setattr(source_content, "file_sha256", counting) + return reads + + +@pytest.fixture +def app(tmp_path, monkeypatch): + nb = ran_app(tmp_path, with_masks=True) # the app's masks folder: cell 4 opens the run + install(monkeypatch, tmp_path) + assert nb.result.written + return nb + + +def test_cell_4_reads_each_image_whole_once_not_twice(app, tmp_path, monkeypatch): + reads = count_whole_reads(monkeypatch, tmp_path / "exp") + step = segmentation_step(app) + assert step.refused == "" and step.workflow.inputs is not None + images = [f.relative_path for f in step.workflow.inputs.fovs()] + assert len(images) == 4 + assert reads == Counter({image: 1 for image in images}) # was 2 each before #574 + + +def test_cell_4_is_shown_before_any_image_is_read(app, tmp_path, monkeypatch): + reads = count_whole_reads(monkeypatch, tmp_path / "exp") + shown = [] + step = segmentation_step(app, show=lambda widget: shown.append((widget, sum(reads.values())))) + assert shown == [(step, 0)] + assert sum(reads.values()) == 4 + + +def test_the_wait_names_the_phase_counts_the_images_and_ticks(app, tmp_path, monkeypatch): + holder, lines = [], [] + reads = count_whole_reads( + monkeypatch, tmp_path / "exp", (lines, lambda: holder[0].workflow.opening.value) + ) + monkeypatch.setattr(notebook_progress, "MIN_INTERVAL", 0.0) # every step drawn + ticking, original = [], notebook_progress.Wait.ticking + + def spy(self, *args, **kwargs): + ticking.append(self.target) + return original(self, *args, **kwargs) + + monkeypatch.setattr(notebook_progress.Wait, "ticking", spy) + step = segmentation_step(app, show=holder.append) + assert sum(reads.values()) == 4 and len(lines) == 4 + for done, line in enumerate(lines): + assert OPENING["contents"] in line + assert f"{done} of 4" in line and "elapsed" in line + # The read image is named (escaped as HTML): the four images in path order. + names = [f.relative_path for f in step.workflow.inputs.fovs()] + assert [next(n for n in names if n in line) for line in lines] == names + assert ticking == [step.workflow.opening] # the timer thread of #567 redraws the line + assert step.workflow.opening.value.endswith("") and "Opened and checked in" in ( + step.workflow.opening.value + ) + + +def test_open_checked_tells_every_phase_in_order_and_opens_what_open_opens(app): + out = app.result.output_folder + told = [] + checked = open_checked(out, checking=lambda *call: told.append(call)) + plain = RunInputs.open(out) + assert checked.fovs() == plain.fovs() + assert checked.manifest_sha256 == plain.manifest_sha256 + assert checked.masks_root == plain.masks_root + assert [r.plane_id for r in checked.records] == [r.plane_id for r in plain.records] + for ours, theirs in zip(checked.records, plain.records, strict=True): + for a, b in zip(ours.histograms, theirs.histograms, strict=True): + assert np.array_equal(a.counts, b.counts) + phases = list(dict.fromkeys(phase for phase, *_ in told)) + assert phases == list(OPEN_PHASES) + for phase in ("images", "contents"): + calls = [c for c in told if c[0] == phase] + assert [c[1:3] for c in calls] == [(i, 4) for i in range(5)] # before each, then 4 of 4 + assert calls[-1][3] == "" + + +def test_a_changed_image_is_refused_the_same_way_with_or_without_the_wait(app, tmp_path): + out = app.result.output_folder + image = sorted((tmp_path / "exp").rglob("*.tif"))[0] + before = image.stat() + data = bytearray(image.read_bytes()) + data[-1] ^= 0xFF # same size, same modification time: only the content SHA-256 sees it + image.write_bytes(bytes(data)) + os.utime(image, ns=(before.st_atime_ns, before.st_mtime_ns)) + with pytest.raises(RunInputsError) as plain: + RunInputs.open(out) + with pytest.raises(RunInputsError) as checked: + open_checked(out, checking=lambda *call: None) + assert str(checked.value) == str(plain.value) + step = segmentation_step(app) + assert step.refused == str(plain.value) + assert RUN_REFUSED.split(".")[0] in step.notice.value.replace("'", "'") + + +def test_the_step_without_a_masks_folder_shows_its_own_wait(tmp_path, monkeypatch): + nb = ran_app(tmp_path) # no masks folder: the run is opened for its refusal only + install(monkeypatch, tmp_path) + reads = count_whole_reads(monkeypatch, tmp_path / "exp") + step = segmentation_step(nb) + assert step.refused == "" and sum(reads.values()) == 4 + assert "Opened and checked in" in step.opening.value + + +def test_opening_leaves_the_time_it_took_even_when_refused(): + target = widgets.HTML() + with pytest.raises(RuntimeError), opening(target) as checking: + checking("images", 0, 2, "a.tif") + assert OPENING["images"] in target.value and "0 of 2" in target.value + raise RuntimeError("refused") + assert "Opened and checked in 0:00" in target.value diff --git a/tests/test_notebook_cellpose_form.py b/tests/test_notebook_cellpose_form.py index 1d0e84a9..7a9f81eb 100644 --- a/tests/test_notebook_cellpose_form.py +++ b/tests/test_notebook_cellpose_form.py @@ -109,7 +109,7 @@ def test_every_field_reaches_the_workflow_as_given(monkeypatch): steps = ("open", "choose_channels", "set_settings", "load", "preview", "run") for name in steps: monkeypatch.setattr( - CellposeNotebook, name, lambda self, *a, name=name: calls.append((name, a)) + CellposeNotebook, name, lambda self, *a, name=name, **_: calls.append((name, a)) ) forms = shown_forms().forms values = { diff --git a/tests/test_notebook_cellpose_republished.py b/tests/test_notebook_cellpose_republished.py index 00852c14..ed2f1b95 100644 --- a/tests/test_notebook_cellpose_republished.py +++ b/tests/test_notebook_cellpose_republished.py @@ -20,7 +20,7 @@ from morphobricks_preprocessing import segmentation_cellpose as cp from morphobricks_preprocessing import segmentation_cellpose_run as run_module from morphobricks_preprocessing.manifest import MANIFEST_FILENAME -from morphobricks_preprocessing.run_inputs import RunInputs +from morphobricks_preprocessing.run_inputs import RunInputs, open_checked from morphobricks_preprocessing.segmentation_record import read_record, record_path from test_notebook_cellpose import BATCH, CHANNELS, MODEL, OPEN, PREVIEW, run_cell, source @@ -143,14 +143,15 @@ def progress(done, total, image): def test_a_run_published_while_it_is_opened_is_refused(monkeypatch, tmp_path): install(monkeypatch, tmp_path) run, ns = two_channel_run(tmp_path / "run"), {} - real = RunInputs.open + real = open_checked def open_then_publish(*args, **kwargs): inputs = real(*args, **kwargs) republish(run.out, check=False) # after the snapshot was read return inputs - monkeypatch.setattr(RunInputs, "open", open_then_publish) + # The notebook opens the run through open_checked (RunInputs.open with its wait, #574). + monkeypatch.setattr(run_module, "open_checked", open_then_publish) exec(compile(source(OPEN), "", "exec"), ns) opener = ns["workflow"].forms["open"] opener.fields["run_folder"].value = str(run.out) diff --git a/tests/test_notebook_preprocessing_cellpose.py b/tests/test_notebook_preprocessing_cellpose.py index c0a40ada..a5f0b115 100644 --- a/tests/test_notebook_preprocessing_cellpose.py +++ b/tests/test_notebook_preprocessing_cellpose.py @@ -22,13 +22,21 @@ pytest.importorskip("ipywidgets") pytest.importorskip("matplotlib") -from morphobricks_preprocessing import cellpose_install # noqa: E402 +from morphobricks_preprocessing import ( # noqa: E402 + cellpose_install, + notebook_preprocessing_cellpose, +) from morphobricks_preprocessing import segmentation_cellpose_model as model # noqa: E402 from morphobricks_preprocessing.axes import AxisMapping # noqa: E402 +from morphobricks_preprocessing.cellpose_install import ( # noqa: E402 + install_changes, + installed_distributions, +) from morphobricks_preprocessing.description_file import DESCRIPTION_FILENAME # noqa: E402 from morphobricks_preprocessing.manifest import MANIFEST_FILENAME # noqa: E402 from morphobricks_preprocessing.mask_scan import MASK_REPORT_FILENAME # noqa: E402 from morphobricks_preprocessing.notebook_cellpose_app import app_folders # noqa: E402 +from morphobricks_preprocessing.notebook_cellpose_install import pip_step # noqa: E402 from morphobricks_preprocessing.notebook_mask_register import ( # noqa: E402 AXES_AGAIN, NO_MASKS, @@ -158,7 +166,7 @@ def test_the_line_after_the_batch_in_cell_4_names_cell_5_and_no_form_is_left(tmp @pytest.fixture def pip(monkeypatch, stub): """Cellpose not installed; ``pip`` installs it (and may change numpy) when it runs.""" - state = SimpleNamespace(commands=[], numpy=None) + state = SimpleNamespace(commands=[], numpy=None, lines=PIP_LINES, returncode=0, seen=[]) stub.version = None real = model.installed_version @@ -169,15 +177,39 @@ def version(name): return state.numpy[1 if state.commands else 0] return real(name) - def run(command, check): - state.commands.append(command) - stub.version = "4.2.1.1" + class Pip: + """pip as ``cellpose_install`` runs it: its lines as it prints them, then its status.""" + + def __init__(self, command, **options): + assert options["stderr"] is subprocess.STDOUT and options["text"] + state.commands.append(command) + self.stdout, self.returncode = iter(state.lines), None + + def __enter__(self): + return self + + def __exit__(self, *exc): + self.returncode = state.returncode + if not state.returncode: + stub.version = "4.2.1.1" monkeypatch.setattr(model, "installed_version", version) - monkeypatch.setattr(cellpose_install.subprocess, "run", run) + monkeypatch.setattr(cellpose_install.subprocess, "Popen", Pip) + monkeypatch.setattr(cellpose_install.subprocess, "run", None) # never the silent run return state +PIP_LINES = [ + "Collecting cellpose==4.2.1.1\n", + " Downloading cellpose-4.2.1.1-py3-none-any.whl.metadata (24 kB)\n", + "Requirement already satisfied: torch>=1.6 in /usr/lib/python3/site-packages (2.9.0)\n", + "Downloading opencv_python_headless-5.1.0.95-cp37-abi3-manylinux_2_28_x86_64.whl (63.7 MB)\n", + "Installing collected packages: cellpose\n", + "Successfully installed cellpose-4.2.1.1\n", +] +"""What pip prints for the installation on Colab, where PyTorch is already there (shortened).""" + + def test_cellpose_is_installed_only_when_ticked_then_the_component_appears(tmp_path, pip): step = segmentation_step(ran_app(tmp_path)) assert step.segmentation is None and step.install_button.disabled @@ -201,6 +233,53 @@ def test_an_install_that_changes_a_loaded_numpy_asks_for_a_restart(tmp_path, pip assert "run cells 1 to 3 again" in step.install_status.value +def test_the_install_shows_what_pip_does_then_what_it_installed(tmp_path, pip, monkeypatch): + # Owner's Colab test (#574): the first installation was slow and showed nothing useful. + snapshots = iter([{"torch": "2.9.0"}, {"torch": "2.9.0", "cellpose": "4.2.1.1"}]) + monkeypatch.setattr( + notebook_preprocessing_cellpose, "installed_distributions", lambda: next(snapshots) + ) + step = segmentation_step(ran_app(tmp_path)) + shown = [] + step.install_status.observe(lambda change: shown.append(change["new"]), names="value") + step.install_tick.value = True + assert step.install() + said = "".join(shown) + for step_said in ( + "Installing Cellpose 4.2.1.1 (with PyTorch): starting pip", + "Installing Cellpose 4.2.1.1 (with PyTorch): finding cellpose==4.2.1.1", + "downloading opencv_python_headless-5.1.0.95-cp37-abi3-manylinux_2_28_x86_64.whl (63.7 MB)", + "installing the packages (this can take minutes)", + ): + assert step_said in said, step_said + assert "elapsed" in said + assert "Cellpose 4.2.1.1 is installed (0:0" in step.installed.value + assert "pip installed or changed: cellpose 4.2.1.1." in step.installed.value + assert step.installed in step.children and step.segmentation is not None + + +def test_a_failed_install_shows_pips_last_lines(tmp_path, pip): + pip.lines, pip.returncode = ["Collecting cellpose==4.2.1.1", "ERROR: No matching dist"], 1 + step = segmentation_step(ran_app(tmp_path)) + step.install_tick.value = True + assert not step.install() and step.segmentation is None + status = step.install_status.value + assert "Cellpose is not installed" in status and "could not be installed" in status + assert "pip's last lines" in status and "ERROR: No matching dist" in status + assert step.installed.value == "" + + +def test_pip_steps_and_the_list_of_changes(): + assert pip_step("Collecting fastremap (from cellpose==4.2.1.1)") == "finding fastremap" + assert pip_step("Requirement already satisfied: numpy in /usr (2.0.2)") is None + before = {"numpy": "2.0.2", "torch": "2.9.0"} + after = {"numpy": "2.3.0", "torch": "2.9.0", "fill-voids": "2.1.2"} + assert install_changes(before, after) == ["fill-voids 2.1.2", "numpy 2.3.0 (was 2.0.2)"] + assert install_changes(after, after) == [] + names = installed_distributions() + assert names["morphobricks-preprocessing"] and "pytest" in names + + def test_preprocessing_alone_never_imports_cellpose_or_torch(): code = ( "import sys\n" diff --git a/tests/test_notebook_preprocessing_cellpose_file.py b/tests/test_notebook_preprocessing_cellpose_file.py index 5cc5b6fc..c2bad217 100644 --- a/tests/test_notebook_preprocessing_cellpose_file.py +++ b/tests/test_notebook_preprocessing_cellpose_file.py @@ -91,9 +91,12 @@ def test_preprocessing_never_installs_cellpose_and_cells_4_and_5_are_thin(): for role in SHARED: text = OWN_LINES.sub("", code[role]) # notebook_name names this notebook assert "cellpose" not in text.lower() and "torch" not in text - for role, call in ((SEGMENT, "segmentation_step(notebook)"), (REGISTER, "register_step(")): + # Cell 4 shows its widget itself before it opens the run, so that the wait is seen (#574). + shown = ((SEGMENT, "segmentation = segmentation_step(notebook, show=display)"), + (REGISTER, "display(")) # fmt: skip + for role, last in shown: text = code[role] - assert call in text and text.rstrip().splitlines()[-1].startswith("display(") + assert text.rstrip().splitlines()[-1].startswith(last) assert len(text.splitlines()) < 25 for other in ("pip", "subprocess", "import cellpose", "import torch", "RELEASE_REF"): assert other not in text From 8ddd4351d149d913e7ea72d52e05fdc0d2a80666 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 10:54:11 +0000 Subject: [PATCH 2/3] Address #575 review: kill pip on interrupt; keep cell 4 as pinned - _pip kills and waits for pip when the reading stops (an interrupt included), as subprocess.run did; undecodable output is replaced. - Cell 4 is back to the pinned release's call. In a kernel, segmentation_step displays the widget first itself and the cell's display(segmentation) then adds nothing, so the cell works with both the pinned code (3af7891) and this code. - An error that is not a refusal while cell 4 opens the run leaves the cell again (StepForm.submit(reraise=True)); a button's stays under it. - The opening's line says "Stopped after m:ss." when an exception went through it. - Restore the register_step( check of cell 5 in the notebook file test. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WX6rdMV1r5jUPUR94kxV5a --- AGENTS.md | 2 +- CHANGELOG.md | 4 +- .../MorphoBricks_Preprocessing_Cellpose.ipynb | 4 +- .../cellpose_install.py | 20 ++++- .../notebook_cellpose_form.py | 12 ++- .../notebook_open_progress.py | 14 ++- .../notebook_preprocessing_cellpose.py | 49 +++++++++-- tests/test_cellpose_folders_open.py | 85 ++++++++++++++++++- tests/test_notebook_preprocessing_cellpose.py | 27 ++++++ ...st_notebook_preprocessing_cellpose_file.py | 8 +- 10 files changed, 196 insertions(+), 29 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 35112033..5f2c6a8d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -311,7 +311,7 @@ src/morphobricks_preprocessing/ notebook, #441), the same CellposeNotebook forms the Cellpose cells mount notebook_preprocessing_cellpose.py segmentation_step(app): cell 4 of notebooks/MorphoBricks_Preprocessing_Cellpose.ipynb (#441), segmentation_app - on the Preprocessing app's finished run, shown (show=display) before the run + on the Preprocessing app's finished run, displayed by itself (in a kernel) before the run is opened once; cellpose_install.py installs Cellpose 4.2.1.1 only on the user's tick (restart when numpy/opencv changed), pip's lines streamed; notebook_cellpose_install.py what pip does now, then what it installed; diff --git a/CHANGELOG.md b/CHANGELOG.md index d5b01a3c..79821284 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,8 +8,8 @@ v0.5.1: no run before v0.5.1 is read.) ## Unreleased -- **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 now calls `segmentation_step(notebook, show=display)`: the widget is shown first, 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. `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. The tick, the pinned release, the restart rule and the shared cells 1 to 3 are unchanged. +- **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). 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`. - **`piece_counts` counts the pieces of masks of objects by runs (#69).** It sorted every pixel (`np.unique(..., return_inverse=True)`, most of its time) and labelled each label again in its bounding box, so labels spread over the plane read it once each. Each row is now cut into runs of one label and runs of one label in neighbouring rows that touch (8-connected, from `masks.binary.STRUCTURE`) are joined with `scipy.sparse.csgraph.connected_components` (new pure module `mask_pieces`; `mask_scan.piece_counts` is the same function, imported). On pixel-scale masks (noise, checkerboards) runs are almost pixels and that graph needs several times the memory of the sort, so above `RUNS_PER_PIXEL_LIMIT` = 0.25 runs per pixel the former route is taken, unchanged. The results are byte-identical either way (labels in the mask's pixel type, counts `int64`): a property test compares both routes, forced and as chosen, with the former function, kept in the test as the reference, on random masks of every label pixel type (touching labels, holes, single pixels, edges, corners, no background, empty) and on the benchmark masks; every digest of `tools/benchmark_kernels.py --group masks` is unchanged, including its new pixel-scale cases (`benchmark_inputs.pixel_mask`). On the benchmark machine `piece_counts` of the 4096 px cells mask went from 2.1 to 2.3 s to 0.07 to 0.10 s and one position's scan from 4.9 to 5.1 s to 0.9 to 1.0 s; the pixel-scale masks take the time and memory they took before (`docs/benchmarks.md`). Outside the former results: a mask with a side of length 0 now has no labels, where the former function failed inside SciPy; a mask that is not 2D is refused with a `ValueError` saying so (it was a SciPy `RuntimeError`, or no labels when it was all background). **The mask scan refuses a mask plane of no pixels** (`mask_without_pixels`, naming the mask): before, SciPy's failure in `piece_counts` was its only guard, and with no labels such a plane would have counted as an image and as a plane of at most one label in its mask type's kind. `pair_counts` and the repeated pair work of #69 are not changed. `tests/test_mask_pieces.py`, `tests/test_mask_scan.py`. - **The run shows its own folder and header check, and that check is no longer quadratic (owner Colab test of v0.9.0, 25 November 2026).** On a large mixed-layout experiment, *Run* showed "Preparing: checking the folders and the image headers again · 0:00 elapsed" for 10-15 minutes before the first image: the run checks every header again (bound to its fingerprint) with no progress reported, and the elapsed time was redrawn only on a progress report. The run now reports that check through `RunMode(checking=...)` (preflight's `(phase, done, total, path)`, operational only like `workers`; `run_experiment`'s parameters are unchanged), and the notebook shows each phase and each header of how many ("Preparing: reading the image headers again · 120 of 24,000"), with the elapsed time redrawn every second by `Wait.ticking()` while the run works. While it goes, the notebook says that a cell run meanwhile waits for it, and how to interrupt it. Two steps of the check were O(n²): each image's staging key took `MetadataReport.dtype` (a pass over every header) and the mask-name screen compared each image's name with every other one (`mask_names._mask_owner` now looks up the prefixes of the name). The outputs are byte for byte the same (`plane_histograms.csv`, `experiment_design.csv`, `image_qc.csv` of a 4,800-image three- and two-channel tree); the check before the first image took 30.0 s → 10.3 s for 12,000 images and 72-75 s → 24-27 s for 24,000 on local disk (`tests/test_run_checking_progress.py`). In a `verify_content` run (the notebook's default, and any run on a fresh output folder) the run then reads every image whole for its content SHA-256 before the first pixel is read: on Google Drive that pass, not the header check, is what took minutes (owner: about 200 images, 10-15 minutes). It is now reported too, as the phase `contents` (`run.phases.CONTENTS`, "Preparing: reading each image whole for its content SHA-256 · 12 of 200"); what is read and verified is unchanged. diff --git a/notebooks/MorphoBricks_Preprocessing_Cellpose.ipynb b/notebooks/MorphoBricks_Preprocessing_Cellpose.ipynb index 416af96d..3ad2799a 100644 --- a/notebooks/MorphoBricks_Preprocessing_Cellpose.ipynb +++ b/notebooks/MorphoBricks_Preprocessing_Cellpose.ipynb @@ -658,8 +658,8 @@ "\n", "from morphobricks_preprocessing.notebook_preprocessing_cellpose import segmentation_step\n", "\n", - "# Shown first, then the run is opened: the wait of its checks is on screen (#574).\n", - "segmentation = segmentation_step(notebook, show=display)" + "segmentation = segmentation_step(notebook)\n", + "display(segmentation)" ] }, { diff --git a/src/morphobricks_preprocessing/cellpose_install.py b/src/morphobricks_preprocessing/cellpose_install.py index 2a3b6cd3..9b548ddb 100644 --- a/src/morphobricks_preprocessing/cellpose_install.py +++ b/src/morphobricks_preprocessing/cellpose_install.py @@ -100,16 +100,30 @@ def install_changes(before: Mapping[str, str], after: Mapping[str, str]) -> list def _pip(command: list[str], output: Callable[[str], object]) -> None: """Run ``pip``, telling ``output`` each line it prints (also its errors), as it prints it. + Like ``subprocess.run``, pip is killed (and waited for) when anything stops the reading, + an interrupt included: it never goes on installing behind a stopped cell. A byte that is + not text is replaced, so that a decoding error cannot stop the reading either. + Raises ------ subprocess.CalledProcessError When ``pip`` fails. """ with subprocess.Popen( - command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, bufsize=1 + command, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + text=True, + errors="replace", + bufsize=1, ) as pip: - for line in pip.stdout: - output(line.rstrip()) + try: + for line in pip.stdout: + output(line.rstrip()) + except BaseException: + pip.kill() + pip.wait() + raise if pip.returncode: raise subprocess.CalledProcessError(pip.returncode, command) diff --git a/src/morphobricks_preprocessing/notebook_cellpose_form.py b/src/morphobricks_preprocessing/notebook_cellpose_form.py index 0343626a..161dce62 100644 --- a/src/morphobricks_preprocessing/notebook_cellpose_form.py +++ b/src/morphobricks_preprocessing/notebook_cellpose_form.py @@ -121,14 +121,17 @@ def refusal(self) -> str: """The message of the last refusal, or ``""``.""" return "" if self.stopped is None else str(self.stopped) - def submit(self) -> None: + def submit(self, *, reraise: bool = False) -> None: """Run the step with the fields as they are now; show a refusal, unchanged, in a card. - Any other error is left to the output area, which shows it with its traceback. + Any other error is left to the output area, which shows it with its traceback (in a + kernel it goes no further: a button's error has nowhere else to go). ``reraise``: it + is also raised again, for a cell that submits the form itself (cell 4, #574). """ self.stopped = None self.output.clear_output() self.button.disabled = True + unexpected: BaseException | None = None try: with self.output: try: @@ -138,9 +141,14 @@ def submit(self) -> None: self.stopped = exc card = _card("error", STOPPED, (_verbatim(str(exc)),), raw=True) self.workflow._show(card) + except BaseException as exc: + unexpected = exc + raise finally: self.button.disabled = False self.workflow._after_step() + if reraise and unexpected is not None: + raise unexpected class CellposeNotebook(CellposeWorkflow): diff --git a/src/morphobricks_preprocessing/notebook_open_progress.py b/src/morphobricks_preprocessing/notebook_open_progress.py index 3aa341f9..f3a53b3b 100644 --- a/src/morphobricks_preprocessing/notebook_open_progress.py +++ b/src/morphobricks_preprocessing/notebook_open_progress.py @@ -31,7 +31,9 @@ COUNTED = ("images", "contents", "masks") """The phases shown as done of total, each with its file.""" TOOK = "Opened and checked in {took}." -"""The line left once the wait ends (``{took}``: ``m:ss``), refused or not.""" +"""The line left once the opening ends, opened or refused (``{took}``: ``m:ss``).""" +STOPPED_AFTER = "Stopped after {took}." +"""The line left when an error or an interrupt went through the opening.""" @contextmanager @@ -41,7 +43,8 @@ def opening(target: widgets.HTML) -> Iterator[Checking]: Parameters ---------- target - The HTML widget the line is drawn in; it is left saying how long it took. + The HTML widget the line is drawn in; it is left saying how long it took + (:data:`TOOK`), or, when an exception went through the block, :data:`STOPPED_AFTER`. Yields ------ @@ -60,11 +63,14 @@ def checking(phase: str, done: int, total: int, path: str) -> None: if phase in COUNTED: wait.step(done, total, path) + line = STOPPED_AFTER try: with wait.ticking(): yield checking + line = TOOK finally: - target.value = f"
{html.escape(TOOK.format(took=wait.took()))}
" + text = html.escape(line.format(took=wait.took())) + target.value = f"
{text}
" -__all__ = ["COUNTED", "OPENING", "TOOK", "opening"] +__all__ = ["COUNTED", "OPENING", "STOPPED_AFTER", "TOOK", "opening"] diff --git a/src/morphobricks_preprocessing/notebook_preprocessing_cellpose.py b/src/morphobricks_preprocessing/notebook_preprocessing_cellpose.py index 2a3e72be..e503ec39 100644 --- a/src/morphobricks_preprocessing/notebook_preprocessing_cellpose.py +++ b/src/morphobricks_preprocessing/notebook_preprocessing_cellpose.py @@ -26,6 +26,8 @@ from pathlib import Path import ipywidgets as widgets +from IPython import get_ipython +from IPython.display import display from . import notebook_style as ui from . import segmentation_cellpose as cp @@ -108,6 +110,7 @@ def __init__( self.segmentation: SegmentationApp | None = None self.rechecked_run: Path | None = None self.registered_manifest: str | None = None + self.skip_next_display = False # shown by segmentation_step: the cell's display adds none self.notice = widgets.HTML(self._notice()) self.opening = widgets.HTML() # the wait of the run's checks without the component self.installed = widgets.HTML() # what the installation installed, once it did @@ -135,12 +138,19 @@ def check(self) -> None: if not self.run_folder: return if self.segmentation is not None and self.masks_folder: - self._open_in_form() + self._open_in_form(reraise=True) return with opening(self.opening) as checking: self.refused = _refusal(self.run_folder, checking) self.notice.value = self._notice() + def _ipython_display_(self) -> None: + """Display the widget, unless :func:`segmentation_step` just did (then once nothing).""" + if self.skip_next_display: + self.skip_next_display = False + return + display(self._repr_mimebundle_(), raw=True) + @property def workflow(self) -> CellposeNotebook | None: """The segmentation's state (its masks folder and results), or None before it shows.""" @@ -177,12 +187,16 @@ def _mount(self, open_now: bool = True) -> None: if open_now: self._open_in_form() - def _open_in_form(self) -> None: - """Open the run by **Open the run** when both folders are known; keep its refusal.""" + def _open_in_form(self, reraise: bool = False) -> None: + """Open the run by **Open the run** when both folders are known; keep its refusal. + + ``reraise``: an error that is not a refusal goes out of the cell (:meth:`check`), as + it did before the opening moved into the form; a button's shows it under the button. + """ opener = self.segmentation.workflow.forms["open"] if not (self.run_folder and self.masks_folder): return - opener.submit() + opener.submit(reraise=reraise) if opener.stopped is not None: # A refused masks folder is said under Open the run; the run itself is not refused. if not self.refused and not self.segmentation.workflow.folders_refused: @@ -264,11 +278,26 @@ def _refused_card(reason: str) -> str: return ui.status("error", "The run cannot be segmented", [RUN_REFUSED, reason]) +def _shown_first(step: SegmentationStep) -> None: + """Display ``step`` now, in a notebook; the cell's own ``display(step)`` then adds nothing.""" + display(step) + step.skip_next_display = True + + +def _default_show() -> Callable[[SegmentationStep], object] | None: + """Return how cell 4 shows its widget first: :func:`_shown_first` in a kernel, else None.""" + return _shown_first if get_ipython() is not None else None + + +_DEFAULT = object() +"""``show`` not given: :func:`_default_show`.""" + + def segmentation_step( app: object, *, on_masks_written: Callable[[cp.BatchResult], object] | None = None, - show: Callable[[SegmentationStep], object] | None = None, + show: Callable[[SegmentationStep], object] | None | object = _DEFAULT, ) -> SegmentationStep: """Return cell 4's widget, its run opened: the Cellpose segmentation of the app's run. @@ -280,11 +309,15 @@ def segmentation_step( on_masks_written Passed to :func:`.notebook_cellpose_app.segmentation_app`. show - Called with the widget before the run is opened (cell 4: IPython's ``display``), so - that the wait of its checks is on screen (owner Colab test, #574); None: the widget - is returned opened, for the caller to show. + Called with the widget before the run is opened, so that the wait of its checks is on + screen (owner Colab test, #574); None: the widget is returned opened, for the caller + to show. By default, in a notebook, the widget is displayed first, and the cell's + ``display(segmentation)`` that follows shows nothing more: cell 4 is the same for the + release it pins and for this code. Outside a notebook: None. """ step = SegmentationStep(app, on_masks_written) + if show is _DEFAULT: + show = _default_show() if show is not None: show(step) step.check() diff --git a/tests/test_cellpose_folders_open.py b/tests/test_cellpose_folders_open.py index 1ebbb5fc..e8cd8d2f 100644 --- a/tests/test_cellpose_folders_open.py +++ b/tests/test_cellpose_folders_open.py @@ -21,7 +21,13 @@ widgets = pytest.importorskip("ipywidgets") +from ipywidgets.widgets import widget_output # noqa: E402 + from morphobricks_preprocessing import _io, notebook_progress, source_content # noqa: E402 +from morphobricks_preprocessing import ( # noqa: E402 + notebook_preprocessing_cellpose as step_module, +) +from morphobricks_preprocessing import segmentation_cellpose_run as run_module # noqa: E402 from morphobricks_preprocessing.notebook_open_progress import OPENING, opening # noqa: E402 from morphobricks_preprocessing.notebook_preprocessing_cellpose import ( # noqa: E402 RUN_REFUSED, @@ -156,10 +162,85 @@ def test_the_step_without_a_masks_folder_shows_its_own_wait(tmp_path, monkeypatc assert "Opened and checked in" in step.opening.value -def test_opening_leaves_the_time_it_took_even_when_refused(): +def test_opening_says_stopped_when_an_exception_goes_through_it(): target = widgets.HTML() with pytest.raises(RuntimeError), opening(target) as checking: checking("images", 0, 2, "a.tif") assert OPENING["images"] in target.value and "0 of 2" in target.value raise RuntimeError("refused") - assert "Opened and checked in 0:00" in target.value + assert "Stopped after 0:00." in target.value and "Opened" not in target.value + with opening(target) as checking: + checking("images", 2, 2, "a.tif") + assert "Opened and checked in 0:00." in target.value + + +def test_in_a_notebook_the_step_shows_itself_first_and_the_cells_display_adds_nothing( + app, tmp_path, monkeypatch +): + # Cell 4 stays the pinned release's (segmentation_step(notebook); display(segmentation)), + # and still shows the widget before the run is opened (#574 review). + reads = count_whole_reads(monkeypatch, tmp_path / "exp") + shown, published = [], [] + monkeypatch.setattr(step_module, "get_ipython", lambda: object()) + + def display(obj, raw=False): + if raw: + published.append(obj) + else: + shown.append((obj, sum(reads.values()))) + obj._ipython_display_() # what IPython's display does with such an object + + monkeypatch.setattr(step_module, "display", display) + step = segmentation_step(app) + assert [(obj, count) for obj, count in shown] == [(step, 0)] + bundle = step._repr_mimebundle_() + assert published == [bundle] and step.skip_next_display # shown once, before any read + step._ipython_display_() # the cell's display(segmentation): nothing more + assert published == [bundle] and not step.skip_next_display + step._ipython_display_() # a later display shows it as any widget + assert published == [bundle, bundle] + + +def test_outside_a_notebook_the_step_shows_nothing_itself(app, monkeypatch): + monkeypatch.setattr(step_module, "display", lambda *a, **k: pytest.fail("displayed")) + assert segmentation_step(app).skip_next_display is False + + +class Kernel: + """Enough of IPython for ``widgets.Output``: it shows a traceback and swallows the error.""" + + kernel = None + + def __init__(self): + self.tracebacks = [] + + def showtraceback(self, exc_info, tb_offset=None): + self.tracebacks.append(exc_info[0]) + + +def test_an_unexpected_error_while_cell_4_opens_the_run_leaves_the_cell(app, monkeypatch): + kernel = Kernel() + monkeypatch.setattr(widget_output, "get_ipython", lambda: kernel) + + def broken(*args, **kwargs): + raise OSError("Drive disconnected") + + monkeypatch.setattr(run_module, "open_checked", broken) + with pytest.raises(OSError, match="Drive disconnected"): + segmentation_step(app) + assert kernel.tracebacks == [OSError] # also shown under Open the run + + +def test_a_refusal_or_a_buttons_error_stays_in_the_form(app, monkeypatch): + kernel = Kernel() + monkeypatch.setattr(widget_output, "get_ipython", lambda: kernel) + step = segmentation_step(app) + opener = step.workflow.forms["open"] + monkeypatch.setattr(run_module, "open_checked", lambda *a, **k: 1 / 0) + opener.submit() # the button: shown under it, nowhere else to go + assert kernel.tracebacks == [ZeroDivisionError] + opener.fields["run_folder"].value = str(app.result.output_folder) + "_missing" + monkeypatch.undo() + monkeypatch.setattr(widget_output, "get_ipython", lambda: kernel) + opener.submit(reraise=True) # a refusal is shown, never raised + assert opener.stopped is not None and kernel.tracebacks == [ZeroDivisionError] diff --git a/tests/test_notebook_preprocessing_cellpose.py b/tests/test_notebook_preprocessing_cellpose.py index a5f0b115..2fd6f6f2 100644 --- a/tests/test_notebook_preprocessing_cellpose.py +++ b/tests/test_notebook_preprocessing_cellpose.py @@ -269,6 +269,33 @@ def test_a_failed_install_shows_pips_last_lines(tmp_path, pip): assert step.installed.value == "" +def test_an_interrupted_install_kills_pip(monkeypatch): + # #574 review: subprocess.run killed pip on any exception; the streaming loop must too. + started = [] + + class Recorded(subprocess.Popen): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + started.append(self) + + def interrupt(line): + raise KeyboardInterrupt + + monkeypatch.setattr(cellpose_install.subprocess, "Popen", Recorded) + child = "import time; print('Collecting cellpose', flush=True); time.sleep(120)" + with pytest.raises(KeyboardInterrupt): + cellpose_install._pip([sys.executable, "-c", child], interrupt) + (pip,) = started + assert pip.returncode is not None and pip.returncode != 0 # killed, and waited for + + +def test_pip_output_that_is_not_text_is_replaced_not_fatal(): + lines = [] + child = "import sys; sys.stdout.buffer.write(b'Downloading caf\\xe9 (1 MB)\\n')" + cellpose_install._pip([sys.executable, "-c", child], lines.append) + assert lines == ["Downloading caf\ufffd (1 MB)"] + + def test_pip_steps_and_the_list_of_changes(): assert pip_step("Collecting fastremap (from cellpose==4.2.1.1)") == "finding fastremap" assert pip_step("Requirement already satisfied: numpy in /usr (2.0.2)") is None diff --git a/tests/test_notebook_preprocessing_cellpose_file.py b/tests/test_notebook_preprocessing_cellpose_file.py index c2bad217..3bc120c5 100644 --- a/tests/test_notebook_preprocessing_cellpose_file.py +++ b/tests/test_notebook_preprocessing_cellpose_file.py @@ -91,12 +91,10 @@ def test_preprocessing_never_installs_cellpose_and_cells_4_and_5_are_thin(): for role in SHARED: text = OWN_LINES.sub("", code[role]) # notebook_name names this notebook assert "cellpose" not in text.lower() and "torch" not in text - # Cell 4 shows its widget itself before it opens the run, so that the wait is seen (#574). - shown = ((SEGMENT, "segmentation = segmentation_step(notebook, show=display)"), - (REGISTER, "display(")) # fmt: skip - for role, last in shown: + # Cell 4 is the pinned release's: segmentation_step shows its widget first itself (#574). + for role, call in ((SEGMENT, "segmentation_step(notebook)"), (REGISTER, "register_step(")): text = code[role] - assert text.rstrip().splitlines()[-1].startswith(last) + assert call in text and text.rstrip().splitlines()[-1].startswith("display(") assert len(text.splitlines()) < 25 for other in ("pip", "subprocess", "import cellpose", "import torch", "RELEASE_REF"): assert other not in text From 85a4b06b66d4ce9a246506bb5107abbc08033b9c Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 11:17:09 +0000 Subject: [PATCH 3/3] Display cell 4's step with ipywidgets 7 too (#575 re-review) SegmentationStep._ipython_display_ drew the widget with _repr_mimebundle_, which ipywidgets 7.7 (Colab) does not have: the first display raised AttributeError, which IPython swallows, so the widget never appeared. It now uses the parent's _ipython_display_ when there is one (ipywidgets 7) and _repr_mimebundle_ otherwise (8). Tests cover both branches; the cell-4 tests also pass under ipywidgets 7.7.5. The docstring says the skip is consumed by the next display of that same step only. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WX6rdMV1r5jUPUR94kxV5a --- CHANGELOG.md | 2 +- .../notebook_preprocessing_cellpose.py | 17 ++++-- tests/test_cellpose_folders_open.py | 52 +++++++++++++++---- 3 files changed, 56 insertions(+), 15 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 79821284..1b3114bd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,7 +8,7 @@ v0.5.1: no run before v0.5.1 is read.) ## Unreleased -- **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). 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 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`. - **`piece_counts` counts the pieces of masks of objects by runs (#69).** It sorted every pixel (`np.unique(..., return_inverse=True)`, most of its time) and labelled each label again in its bounding box, so labels spread over the plane read it once each. Each row is now cut into runs of one label and runs of one label in neighbouring rows that touch (8-connected, from `masks.binary.STRUCTURE`) are joined with `scipy.sparse.csgraph.connected_components` (new pure module `mask_pieces`; `mask_scan.piece_counts` is the same function, imported). On pixel-scale masks (noise, checkerboards) runs are almost pixels and that graph needs several times the memory of the sort, so above `RUNS_PER_PIXEL_LIMIT` = 0.25 runs per pixel the former route is taken, unchanged. The results are byte-identical either way (labels in the mask's pixel type, counts `int64`): a property test compares both routes, forced and as chosen, with the former function, kept in the test as the reference, on random masks of every label pixel type (touching labels, holes, single pixels, edges, corners, no background, empty) and on the benchmark masks; every digest of `tools/benchmark_kernels.py --group masks` is unchanged, including its new pixel-scale cases (`benchmark_inputs.pixel_mask`). On the benchmark machine `piece_counts` of the 4096 px cells mask went from 2.1 to 2.3 s to 0.07 to 0.10 s and one position's scan from 4.9 to 5.1 s to 0.9 to 1.0 s; the pixel-scale masks take the time and memory they took before (`docs/benchmarks.md`). Outside the former results: a mask with a side of length 0 now has no labels, where the former function failed inside SciPy; a mask that is not 2D is refused with a `ValueError` saying so (it was a SciPy `RuntimeError`, or no labels when it was all background). **The mask scan refuses a mask plane of no pixels** (`mask_without_pixels`, naming the mask): before, SciPy's failure in `piece_counts` was its only guard, and with no labels such a plane would have counted as an image and as a plane of at most one label in its mask type's kind. `pair_counts` and the repeated pair work of #69 are not changed. `tests/test_mask_pieces.py`, `tests/test_mask_scan.py`. diff --git a/src/morphobricks_preprocessing/notebook_preprocessing_cellpose.py b/src/morphobricks_preprocessing/notebook_preprocessing_cellpose.py index e503ec39..398c4fbe 100644 --- a/src/morphobricks_preprocessing/notebook_preprocessing_cellpose.py +++ b/src/morphobricks_preprocessing/notebook_preprocessing_cellpose.py @@ -110,7 +110,8 @@ def __init__( self.segmentation: SegmentationApp | None = None self.rechecked_run: Path | None = None self.registered_manifest: str | None = None - self.skip_next_display = False # shown by segmentation_step: the cell's display adds none + # Shown by segmentation_step: the next display of this step (the cell's) adds nothing. + self.skip_next_display = False self.notice = widgets.HTML(self._notice()) self.opening = widgets.HTML() # the wait of the run's checks without the component self.installed = widgets.HTML() # what the installation installed, once it did @@ -144,11 +145,21 @@ def check(self) -> None: self.refused = _refusal(self.run_folder, checking) self.notice.value = self._notice() - def _ipython_display_(self) -> None: - """Display the widget, unless :func:`segmentation_step` just did (then once nothing).""" + def _ipython_display_(self, **kwargs: object) -> None: + """Display the widget, unless :func:`segmentation_step` just did (then once nothing). + + :attr:`skip_next_display` is consumed by the next display of this same step only (the + cell's ``display(segmentation)``); every later display shows it. ipywidgets 7 (Colab) + displays a widget by ``Widget._ipython_display_``, ipywidgets 8 by + ``_repr_mimebundle_`` (7 has none): whichever the installed version has. + """ if self.skip_next_display: self.skip_next_display = False return + shown_by_widget = getattr(super(), "_ipython_display_", None) + if shown_by_widget is not None: + shown_by_widget(**kwargs) + return display(self._repr_mimebundle_(), raw=True) @property diff --git a/tests/test_cellpose_folders_open.py b/tests/test_cellpose_folders_open.py index e8cd8d2f..b73e85ab 100644 --- a/tests/test_cellpose_folders_open.py +++ b/tests/test_cellpose_folders_open.py @@ -180,25 +180,55 @@ def test_in_a_notebook_the_step_shows_itself_first_and_the_cells_display_adds_no # Cell 4 stays the pinned release's (segmentation_step(notebook); display(segmentation)), # and still shows the widget before the run is opened (#574 review). reads = count_whole_reads(monkeypatch, tmp_path / "exp") - shown, published = [], [] + shown, drawn = [], [] monkeypatch.setattr(step_module, "get_ipython", lambda: object()) + # How the widget itself is drawn (ipywidgets 7 or 8) is the next two tests'. + monkeypatch.setattr( + widgets.Widget, "_ipython_display_", lambda self, **k: drawn.append(self), raising=False + ) def display(obj, raw=False): - if raw: - published.append(obj) - else: - shown.append((obj, sum(reads.values()))) - obj._ipython_display_() # what IPython's display does with such an object + assert not raw + shown.append((obj, sum(reads.values()))) + obj._ipython_display_() # what IPython's display does with such an object monkeypatch.setattr(step_module, "display", display) step = segmentation_step(app) - assert [(obj, count) for obj, count in shown] == [(step, 0)] - bundle = step._repr_mimebundle_() - assert published == [bundle] and step.skip_next_display # shown once, before any read + assert shown == [(step, 0)] + assert drawn == [step] and step.skip_next_display # drawn once, before any read step._ipython_display_() # the cell's display(segmentation): nothing more - assert published == [bundle] and not step.skip_next_display + assert drawn == [step] and not step.skip_next_display step._ipython_display_() # a later display shows it as any widget - assert published == [bundle, bundle] + assert drawn == [step, step] + + +def test_with_ipywidgets_7_the_step_is_displayed_by_the_widgets_own_display(app, monkeypatch): + # ipywidgets 7.7 (Colab) has Widget._ipython_display_ and no _repr_mimebundle_ (#575). + calls = [] + monkeypatch.setattr(step_module, "display", lambda *a, **k: pytest.fail("raw display")) + monkeypatch.delattr(widgets.Widget, "_repr_mimebundle_", raising=False) + monkeypatch.setattr( + widgets.Widget, "_ipython_display_", lambda self, **k: calls.append(self), raising=False + ) + step = segmentation_step(app) + step.skip_next_display = True # as segmentation_step leaves it in a kernel + step._ipython_display_() + assert calls == [] + step._ipython_display_() + assert calls == [step] + + +def test_with_ipywidgets_8_the_step_is_displayed_by_its_mimebundle(app, monkeypatch): + if not hasattr(widgets.Widget, "_repr_mimebundle_"): + pytest.skip("ipywidgets 7: a widget has no _repr_mimebundle_ (the test above is its)") + published = [] + monkeypatch.setattr(step_module, "display", lambda obj, raw=False: published.append(obj)) + for parent in widgets.Widget.__mro__: + if "_ipython_display_" in vars(parent): + monkeypatch.delattr(parent, "_ipython_display_") + step = segmentation_step(app) + step._ipython_display_() + assert published == [step._repr_mimebundle_()] def test_outside_a_notebook_the_step_shows_nothing_itself(app, monkeypatch):