Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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, 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;
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
Expand Down
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 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`.
- **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.
Expand Down
4 changes: 2 additions & 2 deletions notebooks/MorphoBricks_Preprocessing_Cellpose.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
3 changes: 3 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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"
Expand Down
69 changes: 65 additions & 4 deletions src/morphobricks_preprocessing/cellpose_install.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -73,13 +78,67 @@ 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.

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,
errors="replace",
bufsize=1,
) as pip:
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)


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
-------
Expand All @@ -98,7 +157,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 "
Expand All @@ -122,4 +181,6 @@ def install_cellpose(ticked: bool) -> str:
"cellpose_install_command",
"cellpose_ready",
"install_cellpose",
"install_changes",
"installed_distributions",
]
Loading
Loading