From 22439276fc2a474f09c1a061333972040f952574 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 07:59:23 +0000 Subject: [PATCH 01/10] Cellpose Preview: show only this Preview's result, cleared before each run The owner's Colab test of v0.9.0 (26 November 2026): some nuclei results of the first Preview stayed on screen after later Previews. The result (card and figures) was displayed into the step's output area and its clearing was left to the frontend; a Preview that failed (Cellpose, or the model's load) also kept the earlier result in `previewed`, and the Segment step's line still compared with it. The result now lives in one box of widgets (`CellposeWorkflow.preview_box`, the figures as PNG pictures), emptied (and its widgets closed) when Preview is pressed, before the model is loaded; when the channels or the output change; and when a Preview fails. While Cellpose runs, the box says "Running on the preview image...". A Preview still writes and records nothing. Regression tests: tests/test_notebook_cellpose_preview_stale.py. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WX6rdMV1r5jUPUR94kxV5a --- CHANGELOG.md | 1 + .../notebook_cellpose.py | 52 ++++-- .../notebook_cellpose_form.py | 19 ++- .../notebook_cellpose_preview.py | 20 +++ tests/test_notebook_cellpose_preview_stale.py | 158 ++++++++++++++++++ 5 files changed, 238 insertions(+), 12 deletions(-) create mode 100644 tests/test_notebook_cellpose_preview_stale.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 072997e2..c7ab0576 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ v0.5.1: no run before v0.5.1 is read.) ## Unreleased +- **Cellpose Preview shows only its own result (owner's Colab test of v0.9.0, 26 November 2026).** Some nuclei results of the first Preview stayed on screen after later ones. The result (the card and the figures) was displayed into the step's output area, and its clearing was left to the frontend; a Preview that failed (Cellpose, or the model's load) also kept the earlier result in `previewed` and the Segment step's line still compared with it. The result is now held by one box of widgets (`CellposeWorkflow.preview_box`, the figures as PNG pictures), emptied when Preview is pressed (before the model is loaded), when the channels or output change, and when a Preview fails. While Cellpose runs, the box says "Running on the preview image…". Nothing is written or recorded by a Preview, as before. `tests/test_notebook_cellpose_preview_stale.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. - **Earlier work that does not record its experiment folder no longer leaves the stepper at a dead end (owner's Colab test of v0.9.0 at ca3b3c6).** An output folder holding only saved answers (here an older version's `morphobricks.draft.json`) showed *"The experiment folder it is of is not recorded … Enter the experiment folder and click Check folder"*: the stepper has no *Check folder* button (its check, *Looks right: read all image headers*, stays disabled until **Scan the folders**), and entering the folder showed the same message again, with no scan and no picture. Now the experiment folder entered is scanned at once on the stepper (folder walk and one picture; nothing is written), the message names the stepper's own buttons, and the check, on the user's click, reads the saved answers as always. Saved answers written by another version of the software (`DraftFileError` `unknown_version`, `unknown_key` or `spec_commit_mismatch`; the owner's file is format 3, `unknown_version`) are not earlier work (`EarlierWork.old_answers`): one line says they are not used and the file is left as it is, and the experiment folder entered is scanned and shown as above (an early **Scan the folders** click, before the typed folder reached the kernel, is made good when it arrives). The same scan follows a record and a run that name different folders. Each message names the buttons of the layout shown (the stacked pages say **Check folder**). Tests: `tests/test_notebook_restore.py`. - **A saved repeat order is never replaced by an abandoned *Yes* (review of #546 at e40f1ad).** On a reopened per-repeat draft, picking *Yes*, filling its row with rep1's order and going back to *No, per repeat folder* showed rep1's order in every repeat row, under "Pre-answered from your saved tags", and one Submit published it for every unit. A row's own saved tags now rank above a broader choice of the session (`channel_scope.seed`: the row's choice, its saved tags, a broader choice, the header names), and the "Pre-answered" note goes at the first change of the answer or of a row. Tests: `tests/test_notebook_channel_guide_reopen.py`, `tests/test_channel_scope.py`. diff --git a/src/morphobricks_preprocessing/notebook_cellpose.py b/src/morphobricks_preprocessing/notebook_cellpose.py index d9a8c452..2f80bcfa 100644 --- a/src/morphobricks_preprocessing/notebook_cellpose.py +++ b/src/morphobricks_preprocessing/notebook_cellpose.py @@ -30,10 +30,10 @@ _card, ) from .notebook_cellpose_download import quiet_cellpose -from .notebook_cellpose_preview import MaskResult, preview_figures +from .notebook_cellpose_preview import MaskResult, preview_images from .notebook_progress import progress_html from .notebook_stop import CellStop -from .notebook_style import STYLE_CSS, table, tiles +from .notebook_style import STYLE_CSS, status, table, tiles from .run_inputs import Fov, RunInputs from .segmentation_cellpose_run import ( channel_layouts, @@ -117,6 +117,7 @@ def __init__(self) -> None: self.result: cp.BatchResult | None = None self.results: dict[str, cp.BatchResult] = {} self.previewed: list[MaskResult] = [] + self.preview_box = widgets.VBox() # the last Preview's result, and nothing else self.shown: list[str] = [] self.on_masks_written: Callable[[cp.BatchResult], object] | None = None self.register_with: str | None = None @@ -147,6 +148,20 @@ def drop_choice(self) -> None: """Forget the channels, the mask types and every loaded model (the choice changed).""" self.picker = self.loaded = self.nuclei_loaded = self.nuclei_settings = None self.mask_types = {} + self.clear_preview() # a preview of other channels says nothing of the next ones + + def clear_preview(self) -> None: + """Take the last Preview's result off the screen and out of :attr:`previewed`.""" + self.previewed = [] + shown, self.preview_box.children = self.preview_box.children, () + for widget in shown: # their pictures leave the kernel too + widget.close() + + def _mount_preview(self) -> None: + """Show :attr:`preview_box` in the cell that previews (a form shows it on its page).""" + if not self.shown: + display(widgets.HTML(STYLE_CSS)) + display(self.preview_box) def model_for(self, output: str) -> tuple[cp.LoadedModel, cp.Settings]: """Return the model and the settings that segment the masks of ``output``. @@ -382,8 +397,21 @@ def _load_model( def preview(self, image: str = "") -> None: """Segment one image and show it with the outlines; nothing is written (cell 6). - For Both, the image is segmented twice, the cells and the nuclei, each shown. + For Both, the image is segmented twice, the cells and the nuclei, each shown. Every + result of an earlier Preview is taken off the screen first (:meth:`clear_preview`), and + a Preview that fails shows none: what is shown is always this Preview's result. While + Cellpose runs, one line says which model runs. """ + self.clear_preview() + self._mount_preview() + try: + self._preview(image) + except BaseException: # a refusal, any error or an interrupt: no result is shown + self.clear_preview() + raise + + def _preview(self, image: str) -> None: + """Segment ``image`` and put this Preview's result in :attr:`preview_box`.""" self._need("model") targets = self.picker.current_targets() fovs = self.inputs.fovs() @@ -395,24 +423,26 @@ def preview(self, image: str = "") -> None: ) fov = by_path[image.strip()] if image.strip() else (self.first_without_mask() or fovs[0]) check_manifest(self.inputs, self.run_manifest_sha256) # the run opened, still + models = [self.model_for(target.output) for target in targets] + names = " and ".join(dict.fromkeys(loaded.name for loaded, _ in models)) + running = status("info", f"Running {names} on the preview image…") + self.preview_box.children = (widgets.HTML(f"
{running}
"),) results, lines = [], [] - for target in targets: - loaded, settings = self.model_for(target.output) + for target, (loaded, settings) in zip(targets, models, strict=True): stack = target.plan.read(fov) labels, flows = cp.evaluate(loaded, settings, stack) named = tuple(zip(target.channel_ids, target.roles, strict=True)) result = MaskResult(OUTPUT_NAMES[target.output], stack, named, labels, flows) results.append(result) lines.append(f"{result.name}: {result.objects} objects; diameter {_diameter(settings)}") - self._show( - _card("info", f"Preview of {fov.relative_path} (nothing is written)", tuple(lines)) - ) + card = _card("info", f"Preview of {fov.relative_path} (nothing is written)", tuple(lines)) try: - figures = preview_figures(results) + pictures = preview_images(results) except ValueError as exc: raise SegmentationError(str(exc)) from exc - for figure in figures: - display(figure) + self.shown.append(card.value) + self.clear_preview() # the line of the model running + self.preview_box.children = (card, *pictures) self.previewed = results def first_without_mask(self) -> Fov | None: diff --git a/src/morphobricks_preprocessing/notebook_cellpose_form.py b/src/morphobricks_preprocessing/notebook_cellpose_form.py index 771abc56..e9bdb37b 100644 --- a/src/morphobricks_preprocessing/notebook_cellpose_form.py +++ b/src/morphobricks_preprocessing/notebook_cellpose_form.py @@ -400,11 +400,28 @@ def preview_form(self) -> StepForm: cards, "Preview", "eye", - lambda: self._with_form_settings(lambda: self._preview_and_note(image.value or "")), + lambda: self._preview_from_form(image.value or ""), {"preview_image": image}, ) + # Under the button's output (the model's loading), the last Preview's result only. + form.body.children = [*form.body.children, self.preview_box] return self._keep("preview", form) + def _mount_preview(self) -> None: + """Show the preview's box in the cell, unless the Preview form already holds it.""" + if "preview" not in self.forms: + super()._mount_preview() + + def _preview_from_form(self, image: str) -> None: + """Press of **Preview**: take the last result off first, then load if needed and preview. + + Cleared before the model is checked or loaded, so a refused or failed load leaves no + earlier result on screen, nor the Segment step's line saying what it used. + """ + self.clear_preview() + self._previewed_with = None + self._with_form_settings(lambda: self._preview_and_note(image)) + def segment_form(self) -> StepForm: """Show the form of cell 7: overwrite (off by default) and the button that segments.""" overwrite = widgets.Checkbox(value=False, description="Replace masks that already exist") diff --git a/src/morphobricks_preprocessing/notebook_cellpose_preview.py b/src/morphobricks_preprocessing/notebook_cellpose_preview.py index 2aa7c8a5..0c18d881 100644 --- a/src/morphobricks_preprocessing/notebook_cellpose_preview.py +++ b/src/morphobricks_preprocessing/notebook_cellpose_preview.py @@ -9,13 +9,20 @@ A preview holds a list of :class:`MaskResult`: one now, a cell mask or a nuclei mask; the *Both* output (#440) adds a second result and the figures follow, with no change here. + +The figures are shown as PNG pictures in widgets (:func:`preview_images`), never displayed into +an output area: the preview's box then holds the last Preview's result only, in every frontend +(owner, 26 November 2026: in Colab, nuclei figures of the first Preview stayed on screen after +later ones). """ from __future__ import annotations import importlib +import io from dataclasses import dataclass +import ipywidgets as widgets import numpy as np from matplotlib.figure import Figure @@ -90,3 +97,16 @@ def segmentation_figure(result: MaskResult) -> Figure: def preview_figures(results: list[MaskResult]) -> list[Figure]: """Return the preview's figures: the channels, then Cellpose's panels, for each result.""" return [figure for r in results for figure in (channel_figure(r), segmentation_figure(r))] + + +def figure_image(figure: Figure) -> widgets.Image: + """Return ``figure`` as a PNG picture widget, at most 99% of its box wide..""" + buffer = io.BytesIO() + figure.savefig(buffer, format="png", bbox_inches="tight") + layout = widgets.Layout(max_width="99%", height="auto") + return widgets.Image(value=buffer.getvalue(), format="png", layout=layout) + + +def preview_images(results: list[MaskResult]) -> list[widgets.Image]: + """Return the figures of :func:`preview_figures` as picture widgets, in the same order.""" + return [figure_image(figure) for figure in preview_figures(results)] diff --git a/tests/test_notebook_cellpose_preview_stale.py b/tests/test_notebook_cellpose_preview_stale.py new file mode 100644 index 00000000..fd99b877 --- /dev/null +++ b/tests/test_notebook_cellpose_preview_stale.py @@ -0,0 +1,158 @@ +"""Every Preview shows its own result only: nothing of an earlier Preview stays (owner, 26 Nov). + +The owner's Colab report: some nuclei results of the first Preview were not cleared after +pressing Preview several times. The result was displayed into the step's output area, and +its clearing was left to the frontend; a Preview that failed (the model, or its load) also +left the earlier result in ``previewed`` and the Segment step's line saying what "the last +Preview" used. The result is now held by one box of widgets (``workflow.preview_box``), +emptied before each Preview starts, before the model is loaded, and when the channels change; +a failed Preview leaves it empty. These cases drive ``segmentation_app`` headless with the +stand-in Cellpose (``tests/cellpose_stub.py``) on a run whose every image has DNA and TUB. +""" + +import ipywidgets as widgets +import pytest + +from cellpose_stub import install, two_channel_run +from morphobricks_preprocessing.notebook_cellpose_app import segmentation_app +from morphobricks_preprocessing.segmentation_record import record_path + + +@pytest.fixture +def stub(monkeypatch, tmp_path): + return install(monkeypatch, tmp_path) + + +@pytest.fixture +def run(tmp_path): + return two_channel_run(tmp_path / "run") + + +def walk(widget): + yield widget + for child in getattr(widget, "children", ()): + yield from walk(child) + + +def texts(widget): + return " ".join(str(w.value) for w in walk(widget) if isinstance(w, widgets.HTML)) + + +def pictures(widget): + return [w for w in walk(widget) if isinstance(w, widgets.Image)] + + +def choose(app, output): + form = app.workflow.forms["channels"] + form.fields["output"].value = output + form.button.click() + assert form.refusal == "", form.refusal + picker = app.workflow.picker + picker.cell.value = "TUB" + if output == "both": + picker.nuclear.value = "DNA" + + +def both_previewed(run): + """An app whose Preview showed the cells and the nuclei of Both once.""" + app = segmentation_app(run.out, run.masks) + choose(app, "both") + app.workflow.forms["model"].fields["device"].value = "cpu" + press_preview(app) + assert [r.name for r in app.workflow.previewed] == ["Cell mask", "Nuclei mask"] + assert "Segment will use what the last Preview used" in app.workflow._summary.value + return app + + +def press_preview(app): + form = app.workflow.forms["preview"] + form.submit() + assert form.refusal == "", form.refusal + return form + + +def snapshot(folder): + if not folder.exists(): + return None + return sorted((str(p.relative_to(folder)), p.stat().st_mtime_ns) for p in folder.rglob("*")) + + +def test_the_preview_page_holds_the_last_previews_result_only(run, stub): + app = both_previewed(run) + workflow = app.workflow + assert "Nuclei mask" in texts(workflow.preview_box) + page = app.stepper.pages[2] # Model and preview + assert sum(w is workflow.preview_box for w in walk(page)) == 1 + assert len(pictures(page)) == 4 # channels and Cellpose's panels, for cells and nuclei + workflow.forms["model"].fields["diameter"].value = "17" + press_preview(app) + shown = texts(workflow.preview_box) + assert shown.count("Preview of") == 1 and shown.count("Nuclei mask") == 1 + assert "diameter 17" in shown and len(pictures(page)) == 4 + + +def test_a_preview_of_cells_only_shows_no_nuclei_of_the_preview_of_both(run, stub): + app = both_previewed(run) + workflow = app.workflow + choose(app, "cells") # the output changed: the Both preview goes at once + assert workflow.previewed == [] + assert workflow.preview_box.children == () + press_preview(app) + assert [r.name for r in workflow.previewed] == ["Cell mask"] + assert "Nuclei" not in texts(workflow.preview_box) + assert len(pictures(workflow.preview_box)) == 2 + assert "Nuclei" not in texts(app.stepper.pages[2]) + + +def test_a_preview_whose_model_fails_leaves_no_earlier_result(run, stub): + app = both_previewed(run) + workflow = app.workflow + + def fail_nuclei(stack): + if stack.shape[0] == 1: + raise RuntimeError("out of memory") + + stub.fail = fail_nuclei + with pytest.raises(RuntimeError, match="out of memory"): # the output area shows it + workflow.forms["preview"].submit() + assert workflow.previewed == [] + assert "not previewed yet" in workflow._summary.value + assert workflow.preview_box.children == () + + +def test_a_preview_whose_model_does_not_load_leaves_no_earlier_result(run, stub): + app = both_previewed(run) + workflow = app.workflow + workflow.forms["model"].fields["device"].value = "cuda" # no GPU: the load is refused + form = workflow.forms["preview"] + form.submit() + assert form.refusal and workflow.loaded is None + assert workflow.previewed == [] + assert "not previewed yet" in workflow._summary.value + assert workflow.preview_box.children == () + + +def test_a_line_names_the_model_while_cellpose_runs_on_the_preview_image(run, stub): + app = segmentation_app(run.out, run.masks) + choose(app, "both") + model = app.workflow.forms["model"].fields + model["device"].value = "cpu" + model["separate_nuclei"].value, model["nuclei_model"].value = True, "cpsam" + seen = [] + stub.fail = lambda stack: seen.append(texts(app.workflow.preview_box)) + press_preview(app) + assert seen and all("on the preview image" in line for line in seen) + assert all("cpsam_v2 and cpsam" in line for line in seen) + assert "on the preview image" not in texts(app.workflow.preview_box) # replaced by the result + + +def test_previews_write_nothing(run, stub): + before = snapshot(run.masks) + app = both_previewed(run) + app.workflow.forms["model"].fields["diameter"].value = "17" + press_preview(app) + choose(app, "cells") + press_preview(app) + assert snapshot(run.masks) == before + assert app.workflow.results == {} and app.workflow.result is None + assert all(not record_path(run.masks, t).exists() for t in ("Cells", "Nuclei")) From 7c6a4c9761747f51d313f1634e2908b02e13f7c4 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 10:49:49 +0000 Subject: [PATCH 02/10] Cellpose: weights download on first use, pinned and checked; hide one torch warning (#574) Item 3 (owner decision, 26 November 2026): choosing the model and pressing Preview or Segment (or Load the model) is the consent to download its weights. The weights-download and DINOv3 ticks are removed from the model form. The brick downloads only the chosen model's file from the Hugging Face repository at a pinned commit, keeps it only with its pinned size and SHA-256 (a cached copy is checked too), and hands Cellpose the absolute path. A failed or blocked download is a refusal naming the model and the URL; no other model is used. The notebook shows a "Downloading weights..." line with progress. DINOv3 is installed at its pinned commit on a DINOv3 model's first load when none is installed; another commit is refused, not replaced. The record adds weights_repository, weights_revision, dinov3_source and dinov3_installed. Item 5: evaluate runs model.eval inside sparse_warning_hidden(), which filters only torch's "Sparse invariant checks are implicitly disabled" UserWarning from the torch or cellpose modules, in catch_warnings. normalization, eval_arguments and inference_parameters move to segmentation_cellpose_eval (re-exported) for the 600-line rule. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WX6rdMV1r5jUPUR94kxV5a --- AGENTS.md | 10 +- CHANGELOG.md | 2 + docs/contract.md | 26 +- docs/plan.md | 16 ++ docs/testing/cellpose-stepper-human-test.md | 13 +- docs/user_guide.md | 33 ++- notebooks/MorphoBricks_Cellpose.ipynb | 12 +- .../MorphoBricks_Preprocessing_Cellpose.ipynb | 4 +- pyproject.toml | 2 + .../notebook_cellpose.py | 83 +++--- .../notebook_cellpose_download.py | 151 ++++++----- .../notebook_cellpose_fields.py | 30 +-- .../notebook_cellpose_form.py | 22 +- .../segmentation_cellpose.py | 128 +++------- .../segmentation_cellpose_eval.py | 130 ++++++++++ .../segmentation_cellpose_model.py | 197 +++++++++----- .../segmentation_cellpose_weights.py | 241 ++++++++++++++++++ tests/cellpose_stub.py | 80 +++++- tests/test_notebook_cellpose.py | 34 ++- tests/test_notebook_cellpose_both.py | 4 +- tests/test_notebook_cellpose_form.py | 62 +++-- tests/test_notebook_cellpose_stepper.py | 86 +++---- tests/test_segmentation_cellpose.py | 58 +++-- tests/test_segmentation_cellpose_record.py | 14 +- tests/test_segmentation_cellpose_weights.py | 200 +++++++++++++++ 25 files changed, 1208 insertions(+), 430 deletions(-) create mode 100644 src/morphobricks_preprocessing/segmentation_cellpose_eval.py create mode 100644 src/morphobricks_preprocessing/segmentation_cellpose_weights.py create mode 100644 tests/test_segmentation_cellpose_weights.py diff --git a/AGENTS.md b/AGENTS.md index 39b56123..bb6546b3 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -291,8 +291,14 @@ src/morphobricks_preprocessing/ channel_by_number (a channel number only when every image has the same channel IDs at the same C positions, translated once to the ID; #440); segmentation_cellpose_model.py choose_model (a built-in name or an existing file, - before loading), load_model (the weights file and device verified after loading, no - download without allow_download, SHA-256 recorded, DINOv3 at a pinned commit); + before loading), load_model (the weights file and device verified after loading, + SHA-256 recorded, DINOv3 installed at a pinned commit on a cpdino model's first + load: ensure_dinov3); segmentation_cellpose_weights.py fetch_weights: the chosen + built-in model's file only, from a pinned Hugging Face revision, checked against + its pinned SHA-256 (a cached copy too), a failed download a refusal (owner, + #574: choosing the model and loading it is the consent; no tick); + segmentation_cellpose_eval.py eval_arguments, inference_parameters (what + model.eval is given and what the batch records); notebook_cellpose.py CellposeWorkflow, ChannelPicker, CellStop: the widgets behind notebooks/MorphoBricks_Cellpose.ipynb notebook_stop.py CellStop (one line, no traceback), defined once: cells 2-8 diff --git a/CHANGELOG.md b/CHANGELOG.md index 841cf7f1..29f408d4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,8 @@ v0.5.1: no run before v0.5.1 is read.) ## Unreleased +- **Cellpose: no download ticks; the chosen model's weights download on first use, pinned and checked (v0.9.1, #574 item 3; owner decision of 26 November 2026).** Choosing the model and pressing **Preview** or **Segment** (or **Load the model** in the Cellpose notebook) is now the consent to download its weights: the "Allow the weights download from Hugging Face" and "Install DINOv3 now" ticks are removed from the model form (both notebooks share it). Cellpose no longer downloads anything itself: the new `segmentation_cellpose_weights.fetch_weights` downloads only the chosen model's file from `mouseland/cellpose-sam` at the pinned commit `WEIGHTS_REVISION` (`7c61431b5fbb`, not Cellpose's moving `main`, and with TLS verification, which Cellpose's own download turns off), through a temporary file kept only with the pinned size and SHA-256 (`PINNED_WEIGHTS`, as Hugging Face lists them at that commit), then hands Cellpose the absolute path. A copy already in Cellpose's model folder is hashed and must match the pin; one that differs is refused, not used and not replaced. A failed or blocked download, or bytes that do not match, is a refusal naming the model and the URL; nothing partial is kept and no other model is used. The notebook shows a "Downloading weights…" line with the megabytes received, a bar and the elapsed time (`notebook_cellpose_download.DownloadLine`), then how long it took; Cellpose's `tqdm` bar is no longer patched (`BAR_LABEL` and `notebook_bar` are removed). DINOv3, the code of the `cpdino` networks (their weights are all in the Cellpose file), is installed at its pinned commit on a `cpdino` model's first load when no DINOv3 is installed (`ensure_dinov3`, before Cellpose is imported); a DINOv3 of another commit is refused, not replaced. The check that Cellpose imported DINOv3 now looks at `cellpose.vit` (Cellpose 4.2.1.1 defines `CPDINO` whether or not DINOv3 imports, so the former `hasattr(models, "CPDINO")` check could not fail). The record's `parameters` add `weights_repository`, `weights_revision`, `dinov3_source` and `dinov3_installed`; `weights_source` is the pinned URL. **API change:** `load_model(model, device, *, progress=None)` (no `allow_download`), `CellposeWorkflow.load` and `load_nuclei` take `(model, custom_model_file, device)`, `LoadedModel` gains `repository`, `revision` and `dinov3_installed`. `normalization`, `eval_arguments` and `inference_parameters` moved, unchanged apart from the new fields, to `segmentation_cellpose_eval` (re-exported by `segmentation_cellpose`) to keep the file under the 600-line rule. `tests/test_segmentation_cellpose_weights.py`; nothing is downloaded in the tests. +- **Cellpose: torch's "Sparse invariant checks are implicitly disabled" warning is hidden while Cellpose runs (v0.9.1, #574 item 5).** Cellpose's `dynamics.py` builds a sparse tensor and torch warns each session. `segmentation_cellpose.evaluate` now runs `model.eval` inside `segmentation_cellpose_model.sparse_warning_hidden()`, which filters only that `UserWarning`, by its message's start (`SPARSE_WARNING`), from the `torch` or `cellpose` modules, inside `warnings.catch_warnings()` (no global filter; every other warning is shown). The checks it is about only validate sparse tensors and do not change results, so nothing is recorded. `tests/test_segmentation_cellpose_weights.py`. - **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/docs/contract.md b/docs/contract.md index db613c21..c4ab3a64 100644 --- a/docs/contract.md +++ b/docs/contract.md @@ -1399,7 +1399,16 @@ Cellpose's own `model.device` is not evidence (it only repeats the device it was nothing beyond the network's tensors is verified. The device is the placement of the network's tensors; Cellpose's own post-processing is not covered by it: Cellpose may move the flow-threshold quality step to the CPU when GPU memory is short, and always computes the masks from the flows on the CPU on `mps`; that is Cellpose's -behaviour, **not refused**, and the batch records it as a note. Uncached weights are downloaded only on an explicit request; more than +behaviour, **not refused**, and the batch records it as a note. Built-in weights are never +downloaded by Cellpose: choosing a built-in model and loading it is the consent to download that +model's file (owner, #574), which `segmentation_cellpose_weights` fetches from +`mouseland/cellpose-sam` at a pinned commit (`WEIGHTS_REVISION`) and accepts only with its +pinned size and SHA-256 (`PINNED_WEIGHTS`); a copy already in Cellpose's model folder must match +too, else it is refused and left as it is. A failed or blocked download is a refusal naming the +model and the URL; nothing partial is kept and no other model is used. Cellpose is then given +the file's absolute path. While `model.eval` runs, torch's `UserWarning` starting "Sparse +invariant checks are implicitly disabled" from the `torch` or `cellpose` modules is filtered +(`warnings.catch_warnings`, never a global filter); it does not affect results. More than three channels are refused (Cellpose reads the first three by position); a blank diameter is the model's native scale, never an estimate and never 0, and a diameter that gives fewer than one flow iteration (`int(200 / rescale)` is 0) is refused, never raised to 1. The batch's `model` holds the model @@ -1407,12 +1416,15 @@ name, the weights file name (or the custom file's path) and its SHA-256, and its every effective setting (diameter in pixels or null with its meaning, thresholds, the **full** normalisation dictionary given to Cellpose (its defaults read from its module at call time, with the user's values applied) and the flow iterations `niter` (`int(200 / rescale)`, passed -explicitly), batch and tile size, `channel_axis` 0, device type, versions, `weights_downloaded` -and `weights_source` (the Hugging Face URL Cellpose uses; null for a model file), the device -`notes` and, for a DINOv3 model, the DINOv3 commit). The batch ID is the record's -`new_batch_id()`. The DINOv3 package is installed with `--no-deps` at a pinned commit, the head -of its default branch on 22 November 2026, which is **not verified against `cpdino`**; Cellpose -imports it only when first imported, so the runtime is restarted after installing it. +explicitly), batch and tile size, `channel_axis` 0, device type, versions, `weights_downloaded`, +`weights_source` (the pinned URL, `.../resolve//`), `weights_repository` and +`weights_revision` (all three null for a model file), the device `notes` and, for a DINOv3 +model, `dinov3_commit`, `dinov3_source` and `dinov3_installed`). The batch ID is the record's +`new_batch_id()`. The DINOv3 package (the code of the `cpdino` networks) is installed on the +first load of a `cpdino` model when none is installed, with `--no-deps` at a pinned commit, the +head of its default branch on 22 November 2026, which is **not verified against `cpdino`**; a +DINOv3 of another commit is refused, not replaced. Cellpose imports it only when first imported +(`cellpose.vit`), so a DINOv3 installed after that needs a restart, and the load says so. Two-dimensional images only. **A mask the batch publishes is never left without its record entry**: each mask's SHA-256 and the record write (the batch so far, the same batch ID growing) happen in `write_mask`'s `on_published`, **under the type's write lock**, before the next image diff --git a/docs/plan.md b/docs/plan.md index fdf624eb..567efaa3 100644 --- a/docs/plan.md +++ b/docs/plan.md @@ -1715,3 +1715,19 @@ Raised during review; to be decided before the milestones that need them: work records; mask headers and projection markers are read as always; *Start fresh* writes and deletes nothing; a finished run is one `RunInputs.open` opens (review of #547) (`notebook_restore`, contract §9.2). +86. Does the Cellpose step need the user's tick to download a model's weights, and to install + DINOv3? *Decided (owner, 26 November 2026, v0.9.1, #574):* no. Choosing the model, then + pressing **Preview** or **Segment** (or **Load the model** in the Cellpose notebook), is the + consent to download that model's weights; the "Allow the weights download from Hugging + Face" and "Install DINOv3 now" ticks are removed. Only the chosen model's file is + downloaded, on first use, with a visible "Downloading weights…" line; the record + names the weights exactly; another model is never used instead and a failed download is a + refusal. *Encoding choices of this brick:* the file is downloaded from + `mouseland/cellpose-sam` at a pinned commit (`WEIGHTS_REVISION`, not Cellpose's moving + `main`) and kept only with its pinned size and SHA-256 (`PINNED_WEIGHTS`, the hashes Hugging + Face lists at that commit); a copy already on disk must match too, else it is refused and + left in place; the record adds `weights_repository` and `weights_revision` beside + `weights_source`, `weights_downloaded` and the model's `sha256`. DINOv3 (the code of the + `cpdino` networks, no weights of its own) is installed at its pinned commit only when none + is installed; a DINOv3 of another commit is refused, not replaced + (`segmentation_cellpose_weights`, `segmentation_cellpose_model.ensure_dinov3`). diff --git a/docs/testing/cellpose-stepper-human-test.md b/docs/testing/cellpose-stepper-human-test.md index b79a552e..661c9db2 100644 --- a/docs/testing/cellpose-stepper-human-test.md +++ b/docs/testing/cellpose-stepper-human-test.md @@ -50,11 +50,14 @@ note anything that looks wrong next to it. - [ ] There is no **Load the model** button. Each setting (diameter, flow threshold, cell probability threshold, batch size) has a one-line help beside it saying which way to move it. -- [ ] Leave the device on `cuda`. If the model's weights are not on this runtime yet, press - **Preview** without the download tick: it refuses and says to allow the download. -- [ ] Tick **Allow the weights download** and press **Preview**: the download shows as **one** - progress bar (no stream of log lines), then a green *Model ... loaded on cuda* card and the - preview figures for the image in the dropdown. +- [ ] There is no **Allow the weights download** tick and no **Install DINOv3 now** tick. +- [ ] Leave the device on `cuda`. With the model's weights not on this runtime yet, press + **Preview**: a line **Downloading cpsam_v2 weights…** shows the megabytes received of the + total (no stream of log lines), then *done in m:ss*, then a green *Model ... loaded on + cuda* card (it names the repository and revision) and the preview figures for the image + in the dropdown. +- [ ] Press **Preview** again after a runtime restart: nothing downloads; the card says the + weights on this computer match the pinned file. - [ ] Choose another image and press **Preview**: no loading card appears this time (the model is reused); the preview is of the new image. - [ ] Change the diameter and press **Preview**: still no reload; the new diameter is used. diff --git a/docs/user_guide.md b/docs/user_guide.md index 9aa3b28c..723a7457 100644 --- a/docs/user_guide.md +++ b/docs/user_guide.md @@ -296,9 +296,24 @@ banner then says "commit unknown" and that the override is on). Then: channels, so more are refused. - **Model.** `cpsam_v2` (default), `cpsam`, `cpdino`, `cpdino-vitb` or a model file of your own. A name or file that does not exist is refused: Cellpose itself would silently use - `cpsam_v2`. The weights of a built-in model are downloaded from Hugging Face on first use, - only if you tick the download box. `cpdino` models also need DINOv3, installed at a pinned - commit (the head of its default branch on 22 November 2026, not verified against `cpdino`; installed without its dependencies) only if you tick its box. Restart the runtime after installing it, then run the cells again. + `cpsam_v2`. +- **Weights download (owner, #574).** Choosing a built-in model and pressing **Preview** or + **Segment** (or **Load the model** in the Cellpose notebook) is your consent to download that + model's weights; there is no box to tick. The first time, only that model's file is + downloaded, from Hugging Face (`mouseland/cellpose-sam` at the pinned revision + `7c61431b5fbb`, never the moving `main` branch), with a line such as **Downloading cpsam_v2 + weights…** (megabytes, a bar, the time). The file must have its pinned size and SHA-256 + before it is used; a copy already on this computer (in Cellpose's model folder) is checked + too, and one that differs is refused, not used and not replaced: delete it and press the + button again. A failed or blocked download stops with a message naming the model and the + URL; nothing partial is kept, and no other model is ever used instead. +- **DINOv3 (`cpdino` models).** DINOv3 is the code of the `cpdino` networks (their weights are + all in the Cellpose file). When no DINOv3 is installed, the first load of a `cpdino` model + installs it, without its dependencies, at a pinned commit (the head of its default branch on + 22 November 2026, not verified against `cpdino`). A DINOv3 of another commit is not + replaced: the load is refused with the command to run. If Cellpose was already loaded in + this runtime (another model loaded first), the load asks you to restart the runtime and run + the cells again; nothing is downloaded again. - **Device.** The model form says, before anything loads, whether a GPU was found and which. You choose `cuda`, `mps` or `cpu`. A GPU that is not available is refused, never replaced by the CPU, and after loading every parameter and buffer of the network must be on @@ -310,9 +325,13 @@ banner then says "commit unknown" and that the override is on). Then: decrease if merged), the flow threshold (0.4; increase to keep more objects, decrease if they are badly shaped), the cell probability threshold (0; decrease to find more and larger objects, increase for fewer) and the batch size (8; lower it if the GPU runs out of memory). -- **Download display.** While a model loads, a weights download shows as one progress bar and - Cellpose's log lines are not printed; its warnings are shown in one card. What is loaded is - unchanged: the same file, no download without the tick, no substitution, no device fallback. +- **Download display.** While a model loads, a weights download shows as one line with its + progress, then how long it took; Cellpose's log lines are not printed and its warnings are + shown in one card. Cellpose never downloads anything itself: it is given the checked file. +- **One torch warning is hidden.** While Cellpose runs, torch's *UserWarning: Sparse invariant + checks are implicitly disabled…* (from Cellpose's `dynamics.py`) is not shown. Only that + warning, from torch or Cellpose, only during the call; it is about validating sparse tensors + and does not change any result. Every other warning is shown. - **Diameter** is in pixels. Blank means the model's own native scale (Cellpose 4.2.1.1 does not estimate a diameter); 0 is refused. - **Normalisation** is always Cellpose's own, per image (each channel to its 1st to 99th @@ -323,7 +342,7 @@ banner then says "commit unknown" and that the override is on). Then: - **Result.** One mask per image at `///.tif` (2D, `int32`, 0 is background, the image's width and height), never over an existing mask unless you tick overwrite, and `//segmentation_record.json` with the model's - file name and SHA-256, every setting (the full normalisation and the flow iterations included), whether the weights were downloaded now and from where, the channels, the device and each image as written, + file name and SHA-256, every setting (the full normalisation and the flow iterations included), where the weights come from (`weights_repository`, `weights_revision`, `weights_source`) and whether they were downloaded now (`weights_downloaded`), for a `cpdino` model the DINOv3 commit and source and whether it was installed now, the channels, the device and each image as written, skipped or failed. The final table lists every image, with the error of a failed one. - **The masks folder is checked when the run is opened.** **Open the run** refuses a masks folder that is the run's output folder or the experiment folder, or inside or around either, diff --git a/notebooks/MorphoBricks_Cellpose.ipynb b/notebooks/MorphoBricks_Cellpose.ipynb index 50f1a715..34763abb 100644 --- a/notebooks/MorphoBricks_Cellpose.ipynb +++ b/notebooks/MorphoBricks_Cellpose.ipynb @@ -25,11 +25,11 @@ "- **2D images only for now.** An image with more than one Z plane or time point fails with a message that says so; it is never reduced to one plane.\n", "- **Channels by ID.** You choose channels by their ID (for example `DNA`, `ACTIN`): a cell channel, a nuclear channel or both, and the output, a cell mask (cell channel, then the nuclear one if chosen) or a nuclei mask (nuclear channel only). In a run where some images have a channel that others lack, only the channels every image has can be used; the notebook shows the refusal as it is. Cellpose reads at most three channels and drops the rest by position, so more than three are refused.\n", "- **Models:** `cpsam_v2` (default), `cpsam`, `cpdino`, `cpdino-vitb`, or a model file of your own. A name or file Cellpose cannot find is **refused**; Cellpose itself would silently use `cpsam_v2` instead.\n", - "- **Downloads:** built-in weights are downloaded from Hugging Face (mouseland/cellpose-sam) on first use. Nothing downloads unless you tick the download box in the form of cell 5. The `cpdino` models also need DINOv3 (installed only if you tick its box, at a pinned commit; see cell 5, which also says that the runtime must be restarted after that).\n", + "- **Downloads:** choosing a built-in model and pressing **Load the model** is your consent to download that model's weights, the first time only: just that one file, from Hugging Face (mouseland/cellpose-sam, at the pinned revision `7c61431b5fbb`), with a progress line, checked against its pinned SHA-256. Weights already on this computer are checked against it too. A failed or blocked download stops with a message naming the model and where it comes from; no other model is ever used instead. The `cpdino` models also need DINOv3, installed the first time at a pinned commit (see cell 5, which says when the runtime must be restarted).\n", "- **Device:** you choose `cuda`, `mps` or `cpu`. A GPU that is not available is **refused**; it never falls back to the CPU, and the notebook checks that every weight of the network sits on the device you chose (that is the network's placement only). Cellpose's own post-processing is not covered by that check: it may move its flow-threshold quality step to the CPU when GPU memory is short, and always computes the masks from the flows on the CPU on `mps`. That is Cellpose's own behaviour, it is **not refused**, and it is written to the record as a note.\n", "- **Diameter:** in pixels. **Blank means the model's own native scale** (Cellpose 4.2.1.1 does not estimate a diameter). Zero is refused.\n", "- **Normalisation** is always Cellpose's own, per image (each channel to its 1st-99th percentile); it is not a choice: images are never sent to Cellpose unnormalised.\n", - "- Every setting that ran (the full normalisation and the flow iterations included), the model's file name and its SHA-256, and whether the weights were downloaded in this session and from where, are written to the record.\n", + "- Every setting that ran (the full normalisation and the flow iterations included), the model's file name and its SHA-256, where the weights come from (the repository, its revision and the URL) and whether they were downloaded in this session, are written to the record.\n", "\n", "### How to run\n", "\n", @@ -440,11 +440,11 @@ "\n", "## **5. Choose the model and the settings, then load the model**\n", "\n", - "Choose the model (or give a model file of your own), the device and the settings in the form, then press **Load the model**. Built-in weights are downloaded from **Hugging Face** on first use, and only if you tick the download box; the download shows one progress bar, and Cellpose's log lines are not printed (its warnings are shown in one card). When the form appears it says whether a GPU was found here, and which, before anything loads. The device is never chosen for you: a GPU that is not available is refused, not replaced by the CPU. The notebook loads the model, then checks that the weights file is the one you asked for and that the network's weights are on the device you asked for. It shows the file's SHA-256, which is written to the record. The diameter, the flow and cell probability thresholds and the batch size are in **Cellpose settings**, each with a one-line help saying which way to move it (the defaults are Cellpose's). The diameter is in pixels; blank is the model's native scale. Normalisation is not a setting: it is always Cellpose's own, per image (each channel to its 1st-99th percentile).\n", + "Choose the model (or give a model file of your own), the device and the settings in the form, then press **Load the model**. The first time a built-in model is loaded, its weights are downloaded from **Hugging Face** (mouseland/cellpose-sam at revision `7c61431b5fbb`): choosing the model and pressing **Load the model** is the consent, there is no box to tick. Only that model's file is downloaded, with a line such as **Downloading cpsam_v2 weights…** (megabytes, a bar and the time), and it is checked against its pinned SHA-256 before it is used; a copy already here is checked too, and one that differs is refused, not replaced. A failed or blocked download is refused with the model and the source named; no other model is used. Cellpose's log lines are not printed (its warnings are shown in one card). When the form appears it says whether a GPU was found here, and which, before anything loads. The device is never chosen for you: a GPU that is not available is refused, not replaced by the CPU. The notebook loads the model, then checks that the weights file is the one you asked for and that the network's weights are on the device you asked for. It shows the file's SHA-256, which is written to the record. The diameter, the flow and cell probability thresholds and the batch size are in **Cellpose settings**, each with a one-line help saying which way to move it (the defaults are Cellpose's). The diameter is in pixels; blank is the model's native scale. Normalisation is not a setting: it is always Cellpose's own, per image (each channel to its 1st-99th percentile).\n", "\n", - "**The check covers every parameter and buffer of the network** (not Cellpose's own `device` attribute, which only repeats what it was given). Cellpose's post-processing is outside this check: it may move its flow-threshold quality step to the CPU when GPU memory is short, and always computes the masks from the flows on the CPU on `mps`. That is Cellpose's behaviour, not refused; the record carries it as a note, together with the full normalisation, the flow iterations, and whether the weights were downloaded now and from where.\n", + "**The check covers every parameter and buffer of the network** (not Cellpose's own `device` attribute, which only repeats what it was given). Cellpose's post-processing is outside this check: it may move its flow-threshold quality step to the CPU when GPU memory is short, and always computes the masks from the flows on the CPU on `mps`. That is Cellpose's behaviour, not refused; the record carries it as a note, together with the full normalisation, the flow iterations, and where the weights come from (repository, revision, URL) and whether they were downloaded now.\n", "\n", - "**The `cpdino` models need DINOv3, and a restart.** Ticking the install box and pressing **Load the model** installs DINOv3 with `--no-deps` (so it cannot change your PyTorch) at commit `6876159a11b4`, **the head of its default branch on 22 November 2026, not verified against `cpdino`**. Cellpose imports DINOv3 only when it is first imported, so after installing DINOv3 **restart the runtime** (Colab: Runtime > Restart session), run cells 1 to 4 again and load a `cpdino` model; loading before the restart is refused with that instruction." + "**The `cpdino` models need DINOv3, and sometimes a restart.** DINOv3 is the code of their network (their weights are all in the Cellpose file). When none is installed, loading a `cpdino` model installs it first, with `--no-deps` (so it cannot change your PyTorch) at commit `6876159a11b4`, **the head of its default branch on 22 November 2026, not verified against `cpdino`**. A DINOv3 of another commit is yours and is not replaced: the load is refused with the command to run. Cellpose imports DINOv3 only when it is first imported, so if Cellpose was already loaded in this runtime (another model loaded before), **restart the runtime** (Colab: Runtime > Restart session), run cells 1 to 4 again and load the `cpdino` model; loading before the restart is refused with that instruction, and nothing is downloaded again." ] }, { @@ -568,7 +568,7 @@ "\n", "## **Versions and citation**\n", "\n", - "**Versions.** This notebook runs **Cellpose 4.2.1.1** (pinned in cell 1, which also pins the MorphoBricks preprocessing commit and prints both versions when it says **Ready**). Each batch in `//segmentation_record.json` stores the tool and its exact version (`tool`, `tool_version`; again as `cellpose_version` in the batch's `parameters`), the model's name, weights file and SHA-256, the DINOv3 commit for a `cpdino` model (`dinov3_commit`), whether the weights were downloaded and from where, the device and every setting that ran. The preprocessing version is not in that record: cell 1 prints it, and the run's own `run_manifest.json` records the preprocessing that made the run.\n", + "**Versions.** This notebook runs **Cellpose 4.2.1.1** (pinned in cell 1, which also pins the MorphoBricks preprocessing commit and prints both versions when it says **Ready**). Each batch in `//segmentation_record.json` stores the tool and its exact version (`tool`, `tool_version`; again as `cellpose_version` in the batch's `parameters`), the model's name, weights file and SHA-256, the DINOv3 commit for a `cpdino` model (`dinov3_commit`), where the weights come from (`weights_repository`, `weights_revision`, `weights_source`) and whether they were downloaded (`weights_downloaded`), the device and every setting that ran. The preprocessing version is not in that record: cell 1 prints it, and the run's own `run_manifest.json` records the preprocessing that made the run.\n", "\n", "**Citation.** As Cellpose's own README (release 4.2.1.1) asks:\n", "\n", diff --git a/notebooks/MorphoBricks_Preprocessing_Cellpose.ipynb b/notebooks/MorphoBricks_Preprocessing_Cellpose.ipynb index 225e65a9..3a892a4c 100644 --- a/notebooks/MorphoBricks_Preprocessing_Cellpose.ipynb +++ b/notebooks/MorphoBricks_Preprocessing_Cellpose.ipynb @@ -34,7 +34,7 @@ "4. **Segment with Cellpose** installs Cellpose (with PyTorch) the first time, only when you tick it, then segments the run of cell 3.\n", "5. **Register the masks** declares the new masks, runs again and describes them.\n", "\n", - "Cells 1 to 3 are exactly those of the MorphoBricks preprocessing notebook. Cellpose, PyTorch and the model weights are downloaded only in cell 4, and only when you tick their boxes." + "Cells 1 to 3 are exactly those of the MorphoBricks preprocessing notebook. Cellpose, PyTorch and the model weights are downloaded only in cell 4: Cellpose and PyTorch when you tick their box, a model's weights the first time you press **Preview** or **Segment** with it." ] }, { @@ -623,7 +623,7 @@ "\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", "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", + "3. **Model and preview**: the model, the device and the settings (each with a one-line help). **Preview** loads the model the first time (choosing the model and pressing **Preview** or **Segment** is the consent to download its weights: only that model's file, from **Hugging Face** at a pinned revision, with a line such as **Downloading cpsam_v2 weights…**, checked against its pinned SHA-256; a failed download is refused, never replaced by another model; a `cpdino` model also installs DINOv3 at a pinned commit; 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", "\n", "Cells and nuclei are never paired by label number: MorphoRelate relates them later, by geometry. Cellpose's own normalization is always on. **Open the run** fixes the run and the masks folder as they are then: if the run is published again (cell 3 or cell 5 runs it again) or a relative masks folder would now point elsewhere (the working directory changed), Preview and Segment refuse until you press **Open the run** again." diff --git a/pyproject.toml b/pyproject.toml index 00e113d2..139cd43a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -392,9 +392,11 @@ baseline = "tools/code_rules_baseline.json" "morphobricks_preprocessing.cellpose_install" = "io" "morphobricks_preprocessing.segmentation_cellpose" = "io" "morphobricks_preprocessing.segmentation_cellpose_commit" = "io" +"morphobricks_preprocessing.segmentation_cellpose_eval" = "io" "morphobricks_preprocessing.segmentation_cellpose_model" = "io" "morphobricks_preprocessing.segmentation_cellpose_run" = "io" "morphobricks_preprocessing.segmentation_cellpose_settings" = "pure" +"morphobricks_preprocessing.segmentation_cellpose_weights" = "io" "morphobricks_preprocessing.segmentation_handoff" = "io" "morphobricks_preprocessing.segmentation_record" = "io" "morphobricks_preprocessing.lock_file" = "io" diff --git a/src/morphobricks_preprocessing/notebook_cellpose.py b/src/morphobricks_preprocessing/notebook_cellpose.py index d9a8c452..fc688b83 100644 --- a/src/morphobricks_preprocessing/notebook_cellpose.py +++ b/src/morphobricks_preprocessing/notebook_cellpose.py @@ -29,7 +29,7 @@ MaskTarget, _card, ) -from .notebook_cellpose_download import quiet_cellpose +from .notebook_cellpose_download import DownloadLine, quiet_cellpose from .notebook_cellpose_preview import MaskResult, preview_figures from .notebook_progress import progress_html from .notebook_stop import CellStop @@ -273,33 +273,21 @@ def set_nuclei_settings( self.nuclei_settings = _settings(diameter, flow_threshold, cellprob_threshold, batch_size) @stops - def load( - self, - model: str, - custom_model_file: str, - device: str, - download_weights: bool, - install_dino: bool, - ) -> None: - """Say what loading does, then load the verified model (cell 5).""" + def load(self, model: str, custom_model_file: str, device: str) -> None: + """Say what loading does, then load the verified model (cell 5). + + Loading a built-in model is the consent to download its weights when they are not on + this computer (and DINOv3 for a ``cpdino`` model; owner, #574): there is no tick. + """ self._need("channels") self.picker.current_targets() if self.settings is None: raise SegmentationError("Set the settings first: press Load the model.") self.loaded = None - self.loaded = self._load_model( - model, custom_model_file, device, download_weights, install_dino, self.settings - ) + self.loaded = self._load_model(model, custom_model_file, device, self.settings) @stops - def load_nuclei( - self, - model: str, - custom_model_file: str, - device: str, - download_weights: bool, - install_dino: bool, - ) -> None: + def load_nuclei(self, model: str, custom_model_file: str, device: str) -> None: """Load a separate model for the nuclei of the output Both (cell 5's Advanced).""" self._need_both() if self.nuclei_settings is None: @@ -309,7 +297,7 @@ def load_nuclei( ) self.nuclei_loaded = None self.nuclei_loaded = self._load_model( - model, custom_model_file, device, download_weights, install_dino, self.nuclei_settings + model, custom_model_file, device, self.nuclei_settings ) def _need_both(self) -> None: @@ -327,36 +315,35 @@ def same_model_for_nuclei(self) -> None: self.nuclei_loaded = self.nuclei_settings = None def _load_model( - self, - model: str, - custom_model_file: str, - device: str, - download_weights: bool, - install_dino: bool, - settings: cp.Settings, + self, model: str, custom_model_file: str, device: str, settings: cp.Settings ) -> cp.LoadedModel: - """Load the model chosen, verified, and show what was loaded.""" + """Load the model chosen, verified, and show what was loaded (and any download).""" chosen = custom_model_file.strip() or model - if install_dino and chosen in cp.DINO_MODELS: - self._show(_card("info", "Installing DINOv3", (" ".join(cp.dinov3_install_command()),))) - cp.install_dinov3() self._show( _card( "info", f"Loading {chosen} on {device}", ( - "Built-in weights are downloaded from Hugging Face on first use; they are " - "downloaded only if the download box is ticked, with one progress bar.", + "Built-in weights not yet on this computer are downloaded now, from " + f"Hugging Face ({cp.WEIGHTS_REPOSITORY} at revision " + f"{cp.WEIGHTS_REVISION[:12]}), and checked against their pinned SHA-256; " + "weights already here are checked too. Only this model's weights are " + "downloaded, and no other model is ever used instead.", "On a GPU Cellpose may move its flow-threshold quality step to the CPU " "when GPU memory is short, and always computes the masks on the CPU on " "mps. That is Cellpose's own behaviour; it is recorded as a note.", ), ) ) - with quiet_cellpose() as said: # one tqdm.auto bar; what is loaded is unchanged + line = DownloadLine(self._show) # shown only if something downloads + with quiet_cellpose() as said: + ok = False try: - loaded = cp.load_model(chosen, device, allow_download=download_weights) + with line.wait.ticking(): + loaded = cp.load_model(chosen, device, progress=line) + ok = True finally: + line.finish(ok) if said: self._show(_card("warn", "Cellpose said, while loading", tuple(said))) self._show( @@ -367,11 +354,7 @@ def _load_model( f"Weights file: {loaded.file}", f"SHA-256: {loaded.sha256}", f"Network {loaded.backbone}, tile size {loaded.tile_size}", - ( - f"Weights downloaded now from {loaded.source}" - if loaded.downloaded - else "Weights were already on this computer (nothing downloaded)" - ), + *_weights_lines(loaded), "Diameter: " + _diameter(settings), ), ) @@ -544,3 +527,19 @@ def _diameter(settings: cp.Settings) -> str: def _named(exc: BaseException) -> str: """Return an error as ``Type: message``.""" return f"{type(exc).__name__}: {exc}" + + +def _weights_lines(loaded: cp.LoadedModel) -> tuple[str, ...]: + """Return where the loaded weights came from, for the card that says what was loaded.""" + if loaded.source is None: + return ("A model file of your own (nothing downloaded)",) + where = f"{loaded.repository} at revision {loaded.revision}" + lines = [ + f"Weights downloaded now from {loaded.source} ({where}); SHA-256 matches the pinned one" + if loaded.downloaded + else f"Weights were already on this computer and match the pinned file of {where} " + "(nothing downloaded)" + ] + if loaded.dinov3_installed: + lines.append(f"DINOv3 installed now at commit {loaded.dinov3_commit}") + return tuple(lines) diff --git a/src/morphobricks_preprocessing/notebook_cellpose_download.py b/src/morphobricks_preprocessing/notebook_cellpose_download.py index a8532fe2..6fcbe785 100644 --- a/src/morphobricks_preprocessing/notebook_cellpose_download.py +++ b/src/morphobricks_preprocessing/notebook_cellpose_download.py @@ -1,46 +1,46 @@ -"""What the notebook shows while Cellpose loads a model: one progress bar, no log noise. - -Cellpose 4.2.1.1 downloads built-in weights with ``cellpose.utils.download_url_to_file``, which -draws a plain-text ``tqdm`` bar (in a notebook, a new line of text at each update), and logs -each step at INFO through the ``cellpose`` loggers. While a model loads, -:func:`quiet_cellpose` only changes how that is **shown**: - -- the bar is ``tqdm.auto``'s (one widget bar in a notebook), same total, unit and updates; -- the ``cellpose`` loggers' INFO lines are dropped and their warnings are collected, to be - shown in one card afterwards (never lost). - -Nothing about **what** is loaded changes: the same URL, file and bytes, and the checks of -:func:`.segmentation_cellpose_model.load_model` (no download without the user's tick, no model -substitution, no device fallback) run unchanged. Everything is put back when the load ends, -also when it fails. Cellpose is imported here only when the pinned release is installed (the -load imports it right after anyway); otherwise nothing is patched and the load refuses as -before. +"""What the notebook shows while a model loads: the download's progress, no Cellpose log noise. + +Owner decision (issue #574): choosing a model and pressing **Preview** or **Segment** (or +**Load the model**) is the consent to download that model's weights, so there is no tick to +allow it; the download is shown instead. :class:`DownloadLine` is the ``progress`` given to +:func:`.segmentation_cellpose_model.load_model`: the first time it is told something it +appears, as one line "Downloading weights…" with the megabytes received of the total, +a bar and the elapsed time (:class:`.notebook_progress.Wait`), or "Installing DINOv3…" for a +``cpdino`` model; it says at the end how long it took, or that it stopped. A model already on +this computer shows nothing. + +Cellpose itself never downloads here: the model is handed to it as the absolute path of the +checked file (:mod:`.segmentation_cellpose_weights`). While it loads, :func:`quiet_cellpose` +drops the ``cellpose`` loggers' INFO lines and collects their warnings, to be shown in one card +afterwards (never lost). Everything is put back when the load ends, also when it fails. """ from __future__ import annotations -import importlib import logging -import sys -from collections.abc import Iterator +import time +from collections.abc import Callable, Iterator from contextlib import contextmanager -from types import ModuleType -from . import segmentation_cellpose_model as model_module +import ipywidgets as widgets + +from .notebook_progress import Wait +from .notebook_style import status LOGGER = "cellpose" """The parent of every Cellpose logger (``cellpose.models``, ``cellpose.core``, ...).""" -BAR_LABEL = "Downloading the weights" CPDINO_IMPORT = "Could not import CPDINO" """How Cellpose 4.2.1.1's ``cellpose.models`` starts the warning it logs at import when DINOv3 is not importable; the warning goes on to recommend ``pip install git+.../dinov3`` unpinned.""" CPDINO_NOTE = ( - "Cellpose could not import DINOv3. Only the cpdino models need it: for those, tick " - "Install DINOv3 now (it installs the pinned commit), then restart the runtime. The other " - "models do not use it." + "Cellpose could not import DINOv3. Only the cpdino models need it: choosing one and pressing " + "the button installs the pinned commit, and the runtime then needs a restart if Cellpose was " + "already imported. The other models do not use it." ) -"""What is shown instead: the notebook's pinned installation (``install_dinov3``), never an +"""What is shown instead: the notebook's pinned installation (``ensure_dinov3``), never an unpinned one.""" +MEGABYTE = 1 << 20 +"""The unit the download's line counts in (MB, as 2**20 bytes).""" class _Collect(logging.Handler): @@ -53,40 +53,13 @@ def __init__(self) -> None: def emit(self, record: logging.LogRecord) -> None: text = record.getMessage() if text.startswith(CPDINO_IMPORT): - text = CPDINO_NOTE # never an unpinned install: the notebook's own tick instead + text = CPDINO_NOTE # never an unpinned install: the notebook's own instead self.lines.append(f"{record.levelname.title()}: {text}") -def _cellpose_utils() -> ModuleType | None: - """Return ``cellpose.utils`` of the pinned release, or None (nothing is then patched).""" - loaded = sys.modules.get("cellpose.utils") - if loaded is not None: - return loaded - if model_module.installed_version("cellpose") != model_module.CELLPOSE_VERSION: - return None - try: - return importlib.import_module("cellpose.utils") - except ImportError: - return None - - -def _auto_bar() -> type | None: - """Return ``tqdm.auto.tqdm`` (Cellpose depends on tqdm), or None where it does not import.""" - try: - return importlib.import_module("tqdm.auto").tqdm - except (ImportError, AttributeError): - return None - - -def notebook_bar(*args: object, **kwargs: object) -> object: - """Return ``tqdm.auto``'s bar with Cellpose's own arguments and a plain label.""" - kwargs.setdefault("desc", BAR_LABEL) - return _auto_bar()(*args, **kwargs) - - @contextmanager def quiet_cellpose() -> Iterator[list[str]]: - """Show Cellpose's download as one ``tqdm.auto`` bar and collect its warnings. + """Drop Cellpose's INFO lines and collect its warnings while a model loads. Yields ------ @@ -95,21 +68,67 @@ def quiet_cellpose() -> Iterator[list[str]]: """ logger = logging.getLogger(LOGGER) handler, propagate = _Collect(), logger.propagate - logger.addHandler(handler) # first: importing Cellpose below may already log + logger.addHandler(handler) # before the load imports Cellpose: importing it may log logger.propagate = False - utils, original = None, None try: - utils = _cellpose_utils() - if utils is not None and _auto_bar() is not None: # else Cellpose's own bar stays - original = getattr(utils, "tqdm", None) - if original is not None: - utils.tqdm = notebook_bar yield handler.lines finally: - if original is not None: - utils.tqdm = original logger.removeHandler(handler) logger.propagate = propagate -__all__ = ["BAR_LABEL", "CPDINO_IMPORT", "CPDINO_NOTE", "LOGGER", "notebook_bar", "quiet_cellpose"] +class DownloadLine: + """The ``progress(label, done, total)`` of a load, drawn as one wait line once called. + + Parameters + ---------- + show + Called once with :attr:`widget`, the first time there is something to show. + clock + Returns the time in seconds (monotonic), for the wait; replaced in tests. + + Attributes + ---------- + widget + The line (HTML). + labels + Every label shown, in order (``"Downloading cpsam_v2 weights…"``, ...). + """ + + def __init__( + self, show: Callable[[widgets.Widget], object], clock: Callable[[], float] = time.monotonic + ) -> None: + self.widget = widgets.HTML() + self.wait = Wait(self.widget, clock=clock) + self.labels: list[str] = [] + self._show = show + + def __call__(self, label: str, done: int, total: int) -> None: + """Show ``done`` of ``total`` bytes under ``label`` (a new label starts a new line).""" + first = not self.labels + if first or self.labels[-1] != label: + self.labels.append(label) + self.wait.start(label, total // MEGABYTE) + self.wait.step(done // MEGABYTE, total // MEGABYTE, "MB") + if first: # drawn first, so that what is shown says what is happening + self._show(self.widget) + + def finish(self, ok: bool) -> None: + """Replace the line by how long it took, or by where it stopped (if it was shown).""" + if not self.labels: + return + label = self.labels[-1].rstrip("…") + if ok: + self.widget.value = status("ok", f"{label}: done in {self.wait.took()}") + else: + self.widget.value = status("error", f"{label}: stopped after {self.wait.took()}") + + +__all__ = [ + "CPDINO_IMPORT", + "CPDINO_NOTE", + "LOGGER", + "MEGABYTE", + "DownloadLine", + "quiet_cellpose", +] diff --git a/src/morphobricks_preprocessing/notebook_cellpose_fields.py b/src/morphobricks_preprocessing/notebook_cellpose_fields.py index 6ffe2b76..27d3a519 100644 --- a/src/morphobricks_preprocessing/notebook_cellpose_fields.py +++ b/src/morphobricks_preprocessing/notebook_cellpose_fields.py @@ -1,14 +1,14 @@ """The fields of the Cellpose notebook's forms: paths with **Browse…**, the model and settings. Split from :mod:`.notebook_cellpose_form` to keep each file small; built from the Preprocessing -app's helpers in :mod:`.notebook_style`. The defaults are those of the former Colab form: -the weights download and the DINOv3 installation off, the device ``cuda`` (an unavailable GPU -is refused, never replaced by the CPU), the model ``cpsam_v2`` and a blank diameter. +app's helpers in :mod:`.notebook_style`. The defaults are those of the former Colab form: the +device ``cuda`` (an unavailable GPU is refused, never replaced by the CPU), the model +``cpsam_v2`` and a blank diameter. There is no tick for the weights download or for DINOv3: +choosing the model and pressing the button that loads it is the consent (owner, #574). The output Both (#440) segments the cells and the nuclei with **one model and one set of settings** by default. In the box **Output Both: the nuclei**, a tick gives the nuclei a model -and settings of their own (:data:`NUCLEI_FIELDS`); the device and the download and install -ticks stay shared. +and settings of their own (:data:`NUCLEI_FIELDS`); the device stays shared. """ from __future__ import annotations @@ -249,10 +249,6 @@ def model_fields() -> dict[str, widgets.Widget]: description="Device", style=STYLE, ), - "download_weights": widgets.Checkbox( - value=False, description="Allow the weights download from Hugging Face" - ), - "install_dinov3": widgets.Checkbox(value=False, description="Install DINOv3 now"), **{name: main[name] for name in NUCLEI_FIELDS[2:]}, SEPARATE_NUCLEI: widgets.Checkbox( value=False, description="Output Both: a different model or settings for the nuclei" @@ -290,8 +286,7 @@ def shown(change: dict) -> None: full_help( "Both writes the cells and the nuclei. By default the nuclei use the " "model and the settings above. Tick to give the nuclei their own model and " - "settings (for example a smaller diameter); the device and the download and " - "install ticks are shared." + "settings (for example a smaller diameter); the device is shared." ), fields[SEPARATE_NUCLEI], own, @@ -307,7 +302,7 @@ def show_nuclei_box(box: widgets.Widget, fields: dict[str, widgets.Widget], both def model_cards(fields: dict[str, widgets.Widget], status: widgets.HTML) -> list[widgets.Widget]: - """Return cell 5's cards: the model, device and downloads; the settings; the nuclei's box. + """Return cell 5's cards: the model and device; the settings; the nuclei's box. ``status`` shows, under a model file, how to paste its path where no dialog opens. The nuclei's box is the last card, hidden until the output is Both (:func:`show_nuclei_box`). @@ -330,12 +325,13 @@ def model_cards(fields: dict[str, widgets.Widget], status: widgets.HTML) -> list "The device is never chosen for you: a GPU that is not available is " "refused, not replaced by the CPU." ), - fields["download_weights"], - fields["install_dinov3"], ui.help_text( - "Built-in weights are downloaded from Hugging Face on first use, only with " - "the download ticked. The cpdino models need DINOv3: tick to install it, then " - "restart the runtime and run the notebook again from its first cell." + "The first time a built-in model is used, only its weights are downloaded " + "from Hugging Face (a pinned revision), with a progress line, and checked " + "against their pinned SHA-256: choosing the model and pressing the button " + "is the consent. A failed download stops; no other model is used. The " + "cpdino models also install DINOv3 (a pinned commit) the first time; if " + "Cellpose was already loaded, you are asked to restart the runtime." ), ], ), diff --git a/src/morphobricks_preprocessing/notebook_cellpose_form.py b/src/morphobricks_preprocessing/notebook_cellpose_form.py index 771abc56..782dff50 100644 --- a/src/morphobricks_preprocessing/notebook_cellpose_form.py +++ b/src/morphobricks_preprocessing/notebook_cellpose_form.py @@ -10,9 +10,11 @@ ``clean_path``); a refusal that stopped the cell (:class:`.CellStop`) is shown with the same message, verbatim, in a red card. -The defaults are those of the former form: overwrite, the weights download and the DINOv3 -installation are off, the device is ``cuda`` (an unavailable GPU is refused, never replaced by -the CPU), the model ``cpsam_v2`` and a blank diameter (the model's native scale). +The defaults are those of the former form: overwrite is off, the device is ``cuda`` (an +unavailable GPU is refused, never replaced by the CPU), the model ``cpsam_v2`` and a blank +diameter (the model's native scale). There is no tick for the weights download or the DINOv3 +installation: choosing the model and pressing the button that loads it is the consent (owner, +#574). """ from __future__ import annotations @@ -332,21 +334,11 @@ def _load_from(self, fields: dict[str, widgets.Widget]) -> None: self._nuclei_failed = False value = {name: field.value for name, field in fields.items()} self._set_form_settings(fields) - self.load( - value["model"], - value["custom_model_file"], - value["device"], - value["download_weights"], - value["install_dinov3"], - ) + self.load(value["model"], value["custom_model_file"], value["device"]) if value[SEPARATE_NUCLEI]: try: self.load_nuclei( - value["nuclei_model"], - value["nuclei_custom_model_file"], - value["device"], - value["download_weights"], - value["install_dinov3"], + value["nuclei_model"], value["nuclei_custom_model_file"], value["device"] ) except BaseException: # a refusal, any error or an interrupt: neither stays loaded self.loaded = self.nuclei_loaded = None diff --git a/src/morphobricks_preprocessing/segmentation_cellpose.py b/src/morphobricks_preprocessing/segmentation_cellpose.py index ba442bc3..353d3a6a 100644 --- a/src/morphobricks_preprocessing/segmentation_cellpose.py +++ b/src/morphobricks_preprocessing/segmentation_cellpose.py @@ -8,8 +8,10 @@ Loading a model (:func:`load_model`, in :mod:`.segmentation_cellpose_model`, re-exported here) refuses what Cellpose 4.2.1.1 would do silently: substitute ``cpsam_v2`` for a model it cannot -find, fall back from the GPU to the CPU, and download uncached weights. This module adds the -rest of what an audit of the Cellpose hand-off asked for: +find and fall back from the GPU to the CPU; built-in weights are downloaded on first use from a +pinned revision and checked against their pinned SHA-256 +(:mod:`.segmentation_cellpose_weights`), never by Cellpose. This module adds the rest of what +an audit of the Cellpose hand-off asked for: - **Channels by ID.** The channels are resolved by canonical ID (:func:`.segmentation_handoff.resolve_segmentation`) and passed as a ``(C, Y, X)`` stack with @@ -24,8 +26,10 @@ (:func:`inference_parameters`), every image into the batch with its outcome, written, skipped or failed with the error (:func:`run_batch`); nothing is dropped. Each mask's hash and record entry are written under the type's write lock; a failure there rolls the mask back. The full - normalisation, the flow iterations, and whether built-in weights were downloaded (and from - where) are in it. + normalisation, the flow iterations, and the built-in weights' source (repository, revision + and URL) and whether they were downloaded are in it. +- **One torch warning hidden** while Cellpose runs (:func:`evaluate`, + :func:`.segmentation_cellpose_model.sparse_warning_hidden`); it does not change any result. Mask paths, pairing, the mask-type rules, writing, the folder rules and the record are the hand-off's own (:mod:`.segmentation_handoff`, :mod:`.segmentation_record`); nothing is repeated. @@ -48,6 +52,16 @@ is_recorded, replaced_earlier_mask, ) +from .segmentation_cellpose_eval import ( + MAX_SIZE_FRACTION, + MIN_SIZE, + NATIVE_SCALE, + NORMALIZE_PERCENTILE, + TILE_OVERLAP, + eval_arguments, + inference_parameters, + normalization, +) from .segmentation_cellpose_model import ( BUILTIN_MODELS, CELLPOSE_VERSION, @@ -55,7 +69,9 @@ DEVICE_NOTE, DINO_MODELS, DINOV3_COMMIT, + DINOV3_LABEL, DINOV3_URL, + SPARSE_WARNING, LoadedModel, ModelChoice, check_device, @@ -68,6 +84,7 @@ installed_dinov3_commit, installed_version, load_model, + sparse_warning_hidden, weights_file, ) from .segmentation_cellpose_run import ( @@ -99,6 +116,7 @@ output_inputs, rescale_factor, ) +from .segmentation_cellpose_weights import WEIGHTS_REPOSITORY, WEIGHTS_REVISION, weights_url from .segmentation_handoff import ( SegmentationPlan, images_to_segment, @@ -119,6 +137,17 @@ ) __all__ = [ + "DEVICE_NOTE", + "MAX_SIZE_FRACTION", + "MIN_SIZE", + "NATIVE_SCALE", + "NORMALIZE_PERCENTILE", + "TILE_OVERLAP", + "eval_arguments", + "flow_iterations", + "inference_parameters", + "normalization", + "rescale_factor", "MAX_CHANNELS", "channel_coverage", "check_channel_count", @@ -129,6 +158,7 @@ "CELLPOSE_VERSION", "DEFAULT_MODEL", "DINOV3_COMMIT", + "DINOV3_LABEL", "DINOV3_URL", "DINO_MODELS", "BOTH_NEEDS", @@ -141,6 +171,9 @@ "NUCLEAR_ROLE", "NUCLEI_OUTPUT", "OUTPUT_MASK_TYPES", + "SPARSE_WARNING", + "WEIGHTS_REPOSITORY", + "WEIGHTS_REVISION", "LoadedModel", "ModelChoice", "Settings", @@ -159,16 +192,10 @@ "installed_version", "load_model", "weights_file", + "weights_url", ] TOOL = "cellpose" -TILE_OVERLAP, MIN_SIZE, MAX_SIZE_FRACTION = 0.1, 15, 0.4 -"""Cellpose's own defaults, passed explicitly so that the record holds the effective values.""" -NORMALIZE_PERCENTILE = [1.0, 99.0] -NATIVE_SCALE = ( - "native scale of the model: Cellpose 4.2.1.1 does not estimate the diameter, so a blank " - "diameter means the model's own scale" -) IMAGE_SKIPPED = "a mask of this type is already there; not replaced (overwrite is off)" IMAGE_UNRECORDED = ( "exists without provenance (not made by a recorded batch); not replaced (overwrite is off)" @@ -183,49 +210,6 @@ # --- one image -------------------------------------------------------------------------------- -def normalization(settings: Settings) -> dict[str, Any]: - """Return the full normalisation given to Cellpose: its defaults now, with the user's values. - - The defaults (``tile_norm_blocksize``, ``sharpen_radius``, ``invert``, ``lowhigh``, ...) come - from Cellpose's module global at call time, copied; ``normalize`` (always on: a setting - that is not True is refused) and the percentiles are then set. Nothing is left to Cellpose's - defaults, so the record holds all. - """ - if settings.normalize is not True: # Settings refuses it; never reach Cellpose without it - raise SegmentationError(NORMALIZE_REFUSAL) - return { - **default_normalization(), - "normalize": True, - "percentile": list(NORMALIZE_PERCENTILE), - } - - -def eval_arguments(loaded: LoadedModel, settings: Settings) -> dict[str, Any]: - """Return every argument given to ``model.eval``, the effective inference settings. - - ``channel_axis`` is 0: the stack from :meth:`.segmentation_handoff.SegmentationPlan.read` - is ``(C, Y, X)`` in the order of the requested channel IDs. The tile size, the full - normalisation, the flow iterations and the other values Cellpose would default are given - explicitly, so what is recorded is what ran. - """ - return { - "batch_size": settings.batch_size, - "resample": True, - "channel_axis": 0, - "normalize": normalization(settings), - "diameter": settings.diameter, - "flow_threshold": settings.flow_threshold, - "cellprob_threshold": settings.cellprob_threshold, - "do_3D": False, - "min_size": MIN_SIZE, - "max_size_fraction": MAX_SIZE_FRACTION, - "niter": flow_iterations(settings), - "augment": False, - "tile_overlap": TILE_OVERLAP, - "bsize": loaded.tile_size, - } - - def segment_image(loaded: LoadedModel, settings: Settings, stack: np.ndarray) -> np.ndarray: """Segment one ``(C, Y, X)`` stack (the chosen channels, in the order chosen). @@ -247,49 +231,21 @@ def evaluate(loaded: LoadedModel, settings: Settings, stack: np.ndarray) -> tupl """Return the labels of :func:`segment_image` and Cellpose's flows (``flows[0]`` is RGB). The flows are for the preview (``cellpose.plot.show_segmentation``); the batch keeps only - the labels. None when Cellpose returned no flows. + the labels. None when Cellpose returned no flows. While Cellpose runs, torch's warning that + begins :data:`SPARSE_WARNING` is hidden, and only it (:func:`sparse_warning_hidden`). """ array = np.asarray(stack) if array.ndim != 3: raise SegmentationError(f"The stack is {array.ndim}D; Cellpose gets (C, Y, X).") check_channel_count([f"channel {i}" for i in range(array.shape[0])]) - out = loaded.model.eval(array, **eval_arguments(loaded, settings)) + with sparse_warning_hidden(): + out = loaded.model.eval(array, **eval_arguments(loaded, settings)) labels = np.asarray(out[0] if isinstance(out, tuple) else out) if labels.ndim != 2: raise SegmentationError(f"Cellpose returned {labels.ndim}D labels; a mask is 2D (Y, X).") return labels, (out[1] if isinstance(out, tuple) and len(out) > 1 else None) -def inference_parameters( - loaded: LoadedModel, settings: Settings, channel_ids: Sequence[str] -) -> dict[str, Any]: - """Return the parameters of a batch for the record: every effective setting, plain JSON. - - The diameter is in pixels, or null with the statement that it is the model's native - scale; ``rescale`` is the factor Cellpose derives from it (30 / diameter, or 1). The - normalisation is the full dictionary given to Cellpose and ``niter`` the flow iterations - it derives from the rescale. ``weights_downloaded`` and ``weights_source`` say whether this - session downloaded the built-in weights and from where; ``notes`` holds Cellpose's device - behaviour (:data:`.segmentation_cellpose_model.DEVICE_NOTE`) for a GPU run. - """ - arguments = eval_arguments(loaded, settings) - notes = [DEVICE_NOTE] if loaded.device != "cpu" else [] - return { - **arguments, - "diameter_unit": "pixels" if settings.diameter is not None else NATIVE_SCALE, - "rescale": rescale_factor(settings), - "channel_ids_order": list(channel_ids), - "device_type": loaded.device, - "backbone": loaded.backbone, - "use_bfloat16": True, - "cellpose_version": CELLPOSE_VERSION, - "dinov3_commit": loaded.dinov3_commit, - "weights_downloaded": loaded.downloaded, - "weights_source": loaded.source, - "notes": notes, - } - - # --- the batch -------------------------------------------------------------------------------- diff --git a/src/morphobricks_preprocessing/segmentation_cellpose_eval.py b/src/morphobricks_preprocessing/segmentation_cellpose_eval.py new file mode 100644 index 00000000..624982d1 --- /dev/null +++ b/src/morphobricks_preprocessing/segmentation_cellpose_eval.py @@ -0,0 +1,130 @@ +"""The arguments Cellpose's ``eval`` is given, and the parameters a batch records. + +Split from :mod:`.segmentation_cellpose` (which re-exports these names) to keep each file +small. Every value Cellpose would default is given explicitly, so what is recorded is what ran: +the full normalisation (Cellpose's defaults read at call time, with the user's values), the +flow iterations, the tile size; and, for the record, where the weights came from (the pinned +repository, revision and URL, :mod:`.segmentation_cellpose_weights`) and whether they, or +DINOv3, were fetched in this session. +""" + +from __future__ import annotations + +from collections.abc import Sequence +from typing import Any + +from .segmentation_cellpose_model import ( + CELLPOSE_VERSION, + DEVICE_NOTE, + DINOV3_URL, + LoadedModel, + default_normalization, +) +from .segmentation_cellpose_settings import ( + NORMALIZE_REFUSAL, + Settings, + flow_iterations, + rescale_factor, +) +from .segmentation_record import SegmentationError + +TILE_OVERLAP, MIN_SIZE, MAX_SIZE_FRACTION = 0.1, 15, 0.4 +"""Cellpose's own defaults, passed explicitly so that the record holds the effective values.""" +NORMALIZE_PERCENTILE = [1.0, 99.0] +NATIVE_SCALE = ( + "native scale of the model: Cellpose 4.2.1.1 does not estimate the diameter, so a blank " + "diameter means the model's own scale" +) + + +def normalization(settings: Settings) -> dict[str, Any]: + """Return the full normalisation given to Cellpose: its defaults now, with the user's values. + + The defaults (``tile_norm_blocksize``, ``sharpen_radius``, ``invert``, ``lowhigh``, ...) come + from Cellpose's module global at call time, copied; ``normalize`` (always on: a setting + that is not True is refused) and the percentiles are then set. Nothing is left to Cellpose's + defaults, so the record holds all. + """ + if settings.normalize is not True: # Settings refuses it; never reach Cellpose without it + raise SegmentationError(NORMALIZE_REFUSAL) + return { + **default_normalization(), + "normalize": True, + "percentile": list(NORMALIZE_PERCENTILE), + } + + +def eval_arguments(loaded: LoadedModel, settings: Settings) -> dict[str, Any]: + """Return every argument given to ``model.eval``, the effective inference settings. + + ``channel_axis`` is 0: the stack from :meth:`.segmentation_handoff.SegmentationPlan.read` + is ``(C, Y, X)`` in the order of the requested channel IDs. The tile size, the full + normalisation, the flow iterations and the other values Cellpose would default are given + explicitly, so what is recorded is what ran. + """ + return { + "batch_size": settings.batch_size, + "resample": True, + "channel_axis": 0, + "normalize": normalization(settings), + "diameter": settings.diameter, + "flow_threshold": settings.flow_threshold, + "cellprob_threshold": settings.cellprob_threshold, + "do_3D": False, + "min_size": MIN_SIZE, + "max_size_fraction": MAX_SIZE_FRACTION, + "niter": flow_iterations(settings), + "augment": False, + "tile_overlap": TILE_OVERLAP, + "bsize": loaded.tile_size, + } + + +def inference_parameters( + loaded: LoadedModel, settings: Settings, channel_ids: Sequence[str] +) -> dict[str, Any]: + """Return the parameters of a batch for the record: every effective setting, plain JSON. + + The diameter is in pixels, or null with the statement that it is the model's native + scale; ``rescale`` is the factor Cellpose derives from it (30 / diameter, or 1). The + normalisation is the full dictionary given to Cellpose and ``niter`` the flow iterations + it derives from the rescale. ``weights_downloaded`` says whether this session downloaded + the built-in weights; ``weights_source``, ``weights_repository`` and ``weights_revision`` + where from (the URL, the Hugging Face repository and its commit; null for a model file of + one's own); the file's SHA-256 is the batch's model ``sha256``. ``dinov3_source`` names + the DINOv3 repository of ``dinov3_commit`` and ``dinov3_installed`` whether this session + installed it. ``notes`` holds Cellpose's device behaviour + (:data:`.segmentation_cellpose_model.DEVICE_NOTE`) for a GPU run. + """ + arguments = eval_arguments(loaded, settings) + notes = [DEVICE_NOTE] if loaded.device != "cpu" else [] + return { + **arguments, + "diameter_unit": "pixels" if settings.diameter is not None else NATIVE_SCALE, + "rescale": rescale_factor(settings), + "channel_ids_order": list(channel_ids), + "device_type": loaded.device, + "backbone": loaded.backbone, + "use_bfloat16": True, + "cellpose_version": CELLPOSE_VERSION, + "dinov3_commit": loaded.dinov3_commit, + "dinov3_source": DINOV3_URL if loaded.dinov3_commit else None, + "dinov3_installed": loaded.dinov3_installed, + "weights_downloaded": loaded.downloaded, + "weights_source": loaded.source, + "weights_repository": loaded.repository, + "weights_revision": loaded.revision, + "notes": notes, + } + + +__all__ = [ + "MAX_SIZE_FRACTION", + "MIN_SIZE", + "NATIVE_SCALE", + "NORMALIZE_PERCENTILE", + "TILE_OVERLAP", + "eval_arguments", + "inference_parameters", + "normalization", +] diff --git a/src/morphobricks_preprocessing/segmentation_cellpose_model.py b/src/morphobricks_preprocessing/segmentation_cellpose_model.py index 6b1440f9..6b625fa8 100644 --- a/src/morphobricks_preprocessing/segmentation_cellpose_model.py +++ b/src/morphobricks_preprocessing/segmentation_cellpose_model.py @@ -1,4 +1,4 @@ -"""Loading a Cellpose model without substitution, device fallback or silent download. +"""Loading a Cellpose model without substitution, device fallback or unchecked download. Part of :mod:`.segmentation_cellpose` (which re-exports these names). Cellpose, ``torch`` and ``dinov3`` are imported only inside the functions here, so importing this module stays inert; @@ -11,9 +11,16 @@ device is unavailable-refused up front, and after loading **every parameter and every buffer** of the network (``model.net``) must sit on a device of the requested type (``cuda:1`` counts as ``cuda``; the index is not checked). ``model.device`` is not evidence: Cellpose 4.2.1.1 only -stores the device it was given. Uncached weights are downloaded only with ``allow_download``; -whether they were, and from where, goes into the record. The weights file is hashed for the -record. +stores the device it was given. + +Built-in weights are never downloaded by Cellpose: choosing the model and loading it is the +consent to download that model's file (owner, issue #574), which +:mod:`.segmentation_cellpose_weights` fetches from a pinned revision and checks against its +pinned SHA-256 (a copy on disk too); Cellpose is then handed the file's absolute path. A +``cpdino`` model also needs the DINOv3 package (the code of its network; its weights are all in +the Cellpose file), installed at :data:`DINOV3_COMMIT` on first use (:func:`ensure_dinov3`). +Whether the weights were downloaded, from which repository, revision and URL, and the file's +SHA-256 go into the record. """ from __future__ import annotations @@ -23,13 +30,23 @@ import importlib.util import json import os +import re import subprocess import sys +import warnings +from collections.abc import Iterator +from contextlib import contextmanager from dataclasses import dataclass from pathlib import Path from types import ModuleType from ._io import file_sha256 +from .segmentation_cellpose_weights import ( + WEIGHTS_REPOSITORY, + WEIGHTS_REVISION, + Progress, + fetch_weights, +) from .segmentation_record import DEVICES, SegmentationError CELLPOSE_VERSION = "4.2.1.1" @@ -44,6 +61,8 @@ """The DINOv3 commit installed for ``cpdino`` models: the head of its default branch on 22 November 2026, **not verified against cpdino** (it is a pin, not a tested pairing). A model that needs DINOv3 runs only with exactly this commit installed.""" +DINOV3_LABEL = "Installing DINOv3 (the network code of the cpdino models)…" +"""What the notebook shows while DINOv3 is installed (:func:`ensure_dinov3`).""" DEVICE_NOTE = ( "The device recorded is where the network's tensors were verified to sit; Cellpose's " "post-processing is not covered by that check. Cellpose may move the flow-threshold quality " @@ -52,6 +71,12 @@ "own behaviour; it is not refused." ) """Recorded with a batch that ran on a GPU (not refused: the network still runs on the device).""" +SPARSE_WARNING = "Sparse invariant checks are implicitly disabled" +"""The start of the one torch ``UserWarning`` hidden while Cellpose runs +(:func:`sparse_warning_hidden`).""" +SPARSE_WARNING_MODULES = r"(cellpose|torch)(\.|$)" +"""The modules it is hidden from: torch's own, or Cellpose's (``cellpose.dynamics`` builds the +sparse tensor; a warning from torch's C++ code is attributed to that caller).""" SAM_TILE, DINO_TILE = 256, 384 """The tile size (``bsize``) of a SAM model and of a DINOv3 model.""" @@ -117,6 +142,12 @@ def installed_version(distribution: str) -> str | None: def _cellpose_models() -> ModuleType: """Import ``cellpose.models`` of the pinned release, or refuse.""" + _check_cellpose_version() + return importlib.import_module("cellpose.models") + + +def _check_cellpose_version() -> None: + """Refuse unless the pinned Cellpose release is installed (nothing is imported).""" found = installed_version("cellpose") if found != CELLPOSE_VERSION: have = f"version {found} is installed" if found else "it is not installed" @@ -124,7 +155,6 @@ def _cellpose_models() -> ModuleType: f"This notebook runs Cellpose {CELLPOSE_VERSION}; {have}. Run the install cell, " "then restart the runtime if it asks." ) - return importlib.import_module("cellpose.models") def _torch() -> ModuleType: @@ -237,8 +267,14 @@ def dinov3_install_command() -> list[str]: ] +def dinov3_present() -> bool: + """Return whether a ``dinov3`` package is installed, whatever its commit (nothing imported).""" + importlib.invalidate_caches() + return bool(importlib.metadata.packages_distributions().get("dinov3")) + + def install_dinov3() -> None: - """Install DINOv3 at the pinned commit (only ever called when the user chooses to). + """Install DINOv3 at the pinned commit (:func:`ensure_dinov3`, for a ``cpdino`` model). Raises ------ @@ -253,11 +289,33 @@ def install_dinov3() -> None: ) from exc +def ensure_dinov3(progress: Progress | None = None) -> bool: + """Install DINOv3 at :data:`DINOV3_COMMIT` when no DINOv3 is installed; return True if it was. + + Called for a ``cpdino`` model only, before Cellpose is imported, so that Cellpose finds it + (choosing that model and loading it is the consent, as for its weights). A DINOv3 already + installed at another or an unknown commit is the user's own and is not replaced: + :func:`check_dinov3` refuses it, naming the command. + + Raises + ------ + SegmentationError + When the installation fails. + """ + if dinov3_present(): + return False + if progress is not None: + progress(DINOV3_LABEL, 0, 0) + install_dinov3() + return True + + def check_dinov3(models: ModuleType) -> str: """Return the commit of the installed DINOv3 if it is the pinned one, else refuse. - Cellpose imports DINOv3 when it is first imported, so DINOv3 installed after that needs a - restart of the runtime (the check says so): install it, restart, then load the model. + Cellpose 4.2.1.1 imports DINOv3 once, when ``cellpose.vit`` is first imported (it then + defines ``CPDINO`` whether or not that worked), so a DINOv3 installed after that needs a + restart of the runtime; the check looks at ``cellpose.vit`` itself and says so. """ command = " ".join(dinov3_install_command()[2:]) commit = installed_dinov3_commit() @@ -268,17 +326,41 @@ def check_dinov3(models: ModuleType) -> str: else "none is installed, or its commit is unknown" ) raise SegmentationError( - f"The DINOv3 models need DINOv3 at commit {DINOV3_COMMIT}; {found}. Tick the " - f"installation in the notebook (it runs: {command}), then restart the runtime." + f"The DINOv3 models need DINOv3 at commit {DINOV3_COMMIT}; {found}. A DINOv3 of " + f"your own is not replaced: uninstall it (pip uninstall dinov3), or install the " + f"pinned one ({command}), then restart the runtime and press the button again." ) - if not hasattr(models, "CPDINO"): + vit = sys.modules.get("cellpose.vit") # imported with ``models`` + if not hasattr(vit, "dinov3_vitl16"): raise SegmentationError( - "DINOv3 is installed but Cellpose was imported before it. Restart the runtime, then " - "run the cells again." + f"DINOv3 is installed (commit {commit[:12]}), but Cellpose was imported in this " + "runtime before it was there. Restart the runtime (Colab: Runtime > Restart " + "session), run the cells again and press the button again; nothing is downloaded " + "again." ) return commit +@contextmanager +def sparse_warning_hidden() -> Iterator[None]: + """Hide torch's "Sparse invariant checks are implicitly disabled" warning in the block only. + + Cellpose 4.2.1.1's ``dynamics.py`` builds a sparse tensor and torch warns that its invariant + checks are off. Those checks only validate sparse tensors; they change no result, so nothing + is recorded. Only a ``UserWarning`` starting :data:`SPARSE_WARNING` from the modules + :data:`SPARSE_WARNING_MODULES` is filtered, inside ``warnings.catch_warnings()`` (never a + global filter: the filters are put back when the block ends); every other warning shows. + """ + with warnings.catch_warnings(): + warnings.filterwarnings( + "ignore", + message=re.escape(SPARSE_WARNING), + category=UserWarning, + module=SPARSE_WARNING_MODULES, + ) + yield + + # --- loading and verifying a model ------------------------------------------------------------ @@ -304,14 +386,18 @@ class LoadedModel: downloaded True when this call downloaded the built-in weights (they were not on disk). source - Where Cellpose downloads the built-in weights from (its URL on Hugging Face), or None - for a custom model file. + The URL the built-in weights are downloaded from (the pinned revision on Hugging + Face, :func:`.segmentation_cellpose_weights.weights_url`), or None for a model file. + repository, revision + The Hugging Face repository and the commit of that URL, or None for a model file. backbone Cellpose's name of the network (``sam_vitl``, ``dino_vitl``, ...). tile_size The tile size (``bsize``) used: 256 for a SAM network, 384 otherwise. dinov3_commit The DINOv3 commit for a DINOv3 network, else None. + dinov3_installed + True when this call installed DINOv3 (it was not installed). """ model: object @@ -325,39 +411,9 @@ class LoadedModel: dinov3_commit: str | None = None downloaded: bool = False source: str | None = None - - -def _source(models: ModuleType, choice: ModelChoice) -> str | None: - """Return the URL Cellpose downloads built-in weights ``choice`` from, None for a file.""" - return None if choice.path is not None else f"{models._MODEL_URL}{choice.name}" - - -def _expected( - models: ModuleType, choice: ModelChoice, allow_download: bool -) -> tuple[Path, str, bool]: - """Return the weights file, what to hand to Cellpose to load it, and whether it downloads. - - A built-in model already on disk is handed over by its absolute path, so Cellpose looks - nowhere else (not in the working folder, not in its list of user models) and cannot - download. One that is not on disk is handed over by name only when ``allow_download``. - """ - if choice.path is not None: - return choice.path, os.fspath(choice.path), False - expected = Path(os.fspath(models.MODEL_DIR)) / choice.name - if expected.is_file(): - return expected, os.fspath(expected), False - if not allow_download: - raise SegmentationError( - f"The weights of {choice.name} are not on this computer ({expected}). The built-in " - f"weights are downloaded from Hugging Face ({_source(models, choice)}) on first use. " - "Allow the download on purpose (tick it in the notebook) and run the cell again." - ) - if os.path.lexists(choice.name): - raise SegmentationError( - f"A file or folder named {choice.name} is in the working folder, and Cellpose would " - "load it instead of downloading the model. Change to another working folder." - ) - return expected, choice.name, True + repository: str | None = None + revision: str | None = None + dinov3_installed: bool = False def _construct(models: ModuleType, request: str, device: str) -> object: @@ -417,30 +473,44 @@ def _verify(loaded: object, expected: Path, device: str, choice: ModelChoice) -> def load_model( - model: str | os.PathLike, device: str, *, allow_download: bool = False + model: str | os.PathLike, device: str, *, progress: Progress | None = None ) -> LoadedModel: """Load a Cellpose model, verified to be the weights file and device asked for. - The order is: the model and device are validated, Cellpose's version is checked, the - weights must be on disk (or the download allowed), a DINOv3 model needs the pinned - DINOv3; then the model is loaded and **verified** (the weights file it reports is the one - asked for; every parameter and buffer of the network sits on the stated device type), and - the weights file is hashed. + The order is: the model and device are validated; a DINOv3 model gets DINOv3 installed at + the pinned commit if none is (before Cellpose is imported); Cellpose's version is checked; + a built-in model's weights are downloaded if missing and checked against their pinned + SHA-256 (:func:`.segmentation_cellpose_weights.fetch_weights`); a DINOv3 model needs the + pinned DINOv3; then the model is loaded from that file's absolute path and **verified** + (the weights file it reports is the one asked for; every parameter and buffer of the + network sits on the stated device type). Choosing the model and calling this is the + consent to those downloads; nothing else is fetched and no other model is used. + + Parameters + ---------- + progress + Told ``(label, done, total)`` while weights download (bytes) or DINOv3 installs. Raises ------ SegmentationError For an unknown model or one that does not exist, a device that is not available or - not the one the model sits on, a substituted model, weights that are not downloaded - (and no ``allow_download``), another Cellpose version or another DINOv3 commit. + not the one the model sits on, a substituted model, weights that cannot be downloaded + or are not the pinned file, another Cellpose version or another DINOv3 commit. """ choice = choose_model(model) check_device(device) - models = _cellpose_models() dino = choice.name in DINO_MODELS + _check_cellpose_version() + installed = ensure_dinov3(progress) if dino else False + models = _cellpose_models() commit = check_dinov3(models) if dino else None - expected, request, downloads = _expected(models, choice, allow_download) - loaded = _construct(models, request, device) + if choice.path is not None: + expected, weights = choice.path, None + else: + weights = fetch_weights(choice.name, os.fspath(models.MODEL_DIR), progress) + expected = weights.path + loaded = _construct(models, os.fspath(expected), device) _verify(loaded, expected, device, choice) backbone = getattr(loaded, "backbone", None) if not isinstance(backbone, str): @@ -452,11 +522,14 @@ def load_model( name=choice.name, file=os.fspath(expected) if choice.path else expected.name, path=expected, - sha256=file_sha256(expected), + sha256=file_sha256(expected) if weights is None else weights.sha256, device=device, backbone=backbone, tile_size=SAM_TILE if backbone == "sam_vitl" else DINO_TILE, dinov3_commit=commit, - downloaded=downloads, - source=_source(models, choice), + downloaded=weights is not None and weights.downloaded, + source=None if weights is None else weights.url, + repository=None if weights is None else WEIGHTS_REPOSITORY, + revision=None if weights is None else WEIGHTS_REVISION, + dinov3_installed=installed, ) diff --git a/src/morphobricks_preprocessing/segmentation_cellpose_weights.py b/src/morphobricks_preprocessing/segmentation_cellpose_weights.py new file mode 100644 index 00000000..e8914518 --- /dev/null +++ b/src/morphobricks_preprocessing/segmentation_cellpose_weights.py @@ -0,0 +1,241 @@ +"""The built-in Cellpose weights: pinned, downloaded on first use, checked by their SHA-256. + +Part of :mod:`.segmentation_cellpose_model`. Owner decision (issue #574, 26 November 2026): +choosing a built-in model and pressing **Preview** or **Segment** (or **Load the model**) is the +consent to download that model's weights; there is no separate tick. What is downloaded, and +how, is fixed here rather than left to Cellpose 4.2.1.1, which fetches +``.../resolve/main/`` (a moving branch) with TLS verification turned off and checks +nothing: + +- **Only the chosen model's file.** One file of :data:`PINNED_WEIGHTS`, by its name, from the + Hugging Face repository :data:`WEIGHTS_REPOSITORY` at the commit :data:`WEIGHTS_REVISION` + (:func:`weights_url`), with the default TLS verification. Nothing else is fetched; another + model is never used instead. +- **Checked.** The bytes downloaded must have the pinned size and SHA-256 (the hashes are those + Hugging Face lists for the files at that commit, its LFS object IDs); they go to a temporary + file next to the target and replace it only once checked. A copy already in Cellpose's model + folder is hashed and must match too: a copy that differs is refused, never used or replaced. +- **A refusal, never a fallback.** A failed or blocked download, or bytes that do not match, + stop the load with a message naming the model and the source; no partial file is left. +- **Seen.** ``progress(label, done, total)`` is told the bytes received (``total`` is 0 when the + server gives no size) so the notebook can show "Downloading weights…" with a bar. +""" + +from __future__ import annotations + +import hashlib +import http.client +import os +import tempfile +import urllib.error +import urllib.request +from collections.abc import Callable +from dataclasses import dataclass +from pathlib import Path +from types import MappingProxyType + +from ._io import file_sha256 +from .segmentation_record import SegmentationError + +WEIGHTS_HOST = "https://huggingface.co" +WEIGHTS_REPOSITORY = "mouseland/cellpose-sam" +"""The Hugging Face repository Cellpose 4.2.1.1 downloads its built-in weights from.""" +WEIGHTS_REVISION = "7c61431b5fbb078f3296754bd15d9f51b320f837" +"""The commit of :data:`WEIGHTS_REPOSITORY` downloaded from: the head of ``main`` on +26 November 2026 (its last change, 17 May 2026, renamed ``cpdino_vitb`` to ``cpdino-vitb``).""" +CHUNK = 1 << 20 +"""Bytes read from the server at a time.""" +TIMEOUT = 60 +"""Seconds without an answer from the server before the download is refused.""" + + +@dataclass(frozen=True) +class PinnedFile: + """The SHA-256 and the size in bytes of one weights file at :data:`WEIGHTS_REVISION`.""" + + sha256: str + size: int + + +PINNED_WEIGHTS = MappingProxyType( + { + "cpsam_v2": PinnedFile( + "0f1cc3f7ecdd8a037a57c6c48d9d8921391be4cbce3fa9f13c3e3a2e1253c667", 1233586851 + ), + "cpsam": PinnedFile( + "e1440429eb384f95afe32bcba6510f90d518eaedc917ede549bed6804004abe2", 1233587898 + ), + "cpdino": PinnedFile( + "fad0dda262554922da1c5ab0e0004b00c1b14b8a48bea6781b89222567577573", 1213987717 + ), + "cpdino-vitb": PinnedFile( + "3ed4c06a3963ab13ff377d4e2957174aaaf637434eb031ae9931fcbfaf9a217f", 343599997 + ), + } +) +"""Every built-in model's file at :data:`WEIGHTS_REVISION`, as Hugging Face lists it.""" + +Progress = Callable[[str, int, int], None] +"""``progress(label, done, total)``: what is being fetched, bytes received, bytes in all (0 for +unknown).""" + + +@dataclass(frozen=True) +class WeightsFile: + """A built-in model's weights file on disk, checked against its pin. + + Attributes + ---------- + name + The built-in model's name (also the file's name). + path + The file in Cellpose's model folder. + sha256 + Its SHA-256, equal to the pinned one. + url + Where it is downloaded from (:func:`weights_url`). + repository, revision + :data:`WEIGHTS_REPOSITORY` and :data:`WEIGHTS_REVISION`. + downloaded + True when this call downloaded it; False when the copy on disk was used. + """ + + name: str + path: Path + sha256: str + url: str + repository: str = WEIGHTS_REPOSITORY + revision: str = WEIGHTS_REVISION + downloaded: bool = False + + +def weights_url(name: str) -> str: + """Return the URL of built-in model ``name``'s file at :data:`WEIGHTS_REVISION`.""" + return f"{WEIGHTS_HOST}/{WEIGHTS_REPOSITORY}/resolve/{WEIGHTS_REVISION}/{name}" + + +def download_label(name: str) -> str: + """Return what the notebook shows while ``name``'s weights download.""" + return f"Downloading {name} weights…" + + +def _pinned(name: str) -> PinnedFile: + """Return the pin of built-in model ``name``, or refuse a name without one.""" + pin = PINNED_WEIGHTS.get(name) + if pin is None: + raise SegmentationError( + f"There are no pinned weights for {name!r}; only {', '.join(PINNED_WEIGHTS)} are " + "downloaded. Give the path of a model file instead." + ) + return pin + + +def _open_url(url: str, timeout: float) -> object: + """Open ``url`` for reading (a seam for the tests: they never download).""" + return urllib.request.urlopen(url, timeout=timeout) + + +def _refusal(name: str, url: str, why: str) -> SegmentationError: + """Return the refusal of a download that did not give the pinned file.""" + return SegmentationError( + f"The weights of {name} could not be downloaded from {url} ({why}). Nothing was loaded, " + "no other model is used and no partial file is kept. Check the internet access (a " + "proxy or firewall may block huggingface.co), then press the button again." + ) + + +def fetch_weights( + name: str, model_dir: str | os.PathLike, progress: Progress | None = None +) -> WeightsFile: + """Return built-in model ``name``'s pinned weights file, downloading it when missing. + + Parameters + ---------- + name + One of :data:`PINNED_WEIGHTS`. + model_dir + Cellpose's model folder (``cellpose.models.MODEL_DIR``), where the file is kept. + progress + Told ``(label, bytes received, bytes in all)`` while downloading; not called for a + copy already on disk. + + Raises + ------ + SegmentationError + For a copy on disk that is not the pinned file, a download that fails or is blocked, + or bytes that are not the pinned size and SHA-256. Each names the model and the source. + """ + pin, url = _pinned(name), weights_url(name) + target = Path(model_dir) / name + if target.is_file(): + found = file_sha256(target) + if found != pin.sha256: + raise SegmentationError( + f"The weights of {name} on this computer ({target}) are not the pinned file of " + f"{url}: SHA-256 {found}, expected {pin.sha256}. They are not used, and not " + "replaced. Delete that file (or move it away), then press the button again to " + "download the pinned weights." + ) + return WeightsFile(name, target, found, url) + sha256 = _download(name, url, target, pin, progress) + return WeightsFile(name, target, sha256, url, downloaded=True) + + +def _download(name: str, url: str, target: Path, pin: PinnedFile, progress: Progress | None) -> str: + """Download ``url`` to ``target`` through a checked temporary file; return its SHA-256.""" + label = download_label(name) + try: + target.parent.mkdir(parents=True, exist_ok=True) + handle, temporary = tempfile.mkstemp(prefix=f".{name}.", suffix=".part", dir=target.parent) + except OSError as exc: + why = f"the model folder {target.parent} cannot be written: {exc}" + raise _refusal(name, url, why) from exc + digest, done = hashlib.sha256(), 0 + try: + with os.fdopen(handle, "wb") as out: + try: + with _open_url(url, TIMEOUT) as response: + size = response.headers.get("Content-Length") + total = int(size) if size and size.isdigit() else 0 + if progress is not None: + progress(label, 0, total) + for block in iter(lambda r=response: r.read(CHUNK), b""): + out.write(block) + digest.update(block) + done += len(block) + if progress is not None: + progress(label, done, total) + except urllib.error.HTTPError as exc: + raise _refusal(name, url, f"the server answered {exc.code} {exc.reason}") from exc + except (urllib.error.URLError, OSError, ValueError, http.client.HTTPException) as exc: + why = getattr(exc, "reason", None) or exc + raise _refusal(name, url, f"{type(exc).__name__}: {why}") from exc + found = digest.hexdigest() + if (done, found) != (pin.size, pin.sha256): + raise _refusal( + name, + url, + f"received {done:,} bytes with SHA-256 {found}; the pinned file has " + f"{pin.size:,} bytes and SHA-256 {pin.sha256}", + ) + os.replace(temporary, target) + finally: + if os.path.exists(temporary): + os.remove(temporary) + return found + + +__all__ = [ + "CHUNK", + "PINNED_WEIGHTS", + "TIMEOUT", + "WEIGHTS_HOST", + "WEIGHTS_REPOSITORY", + "WEIGHTS_REVISION", + "PinnedFile", + "Progress", + "WeightsFile", + "download_label", + "fetch_weights", + "weights_url", +] diff --git a/tests/cellpose_stub.py b/tests/cellpose_stub.py index f79fbf8f..c211885d 100644 --- a/tests/cellpose_stub.py +++ b/tests/cellpose_stub.py @@ -3,13 +3,19 @@ Cellpose is not a dependency of the brick and is not installed in CI. The stand-in keeps what the real ``CellposeModel`` does that matters here, read from the 4.2.1.1 source: a name or path it cannot find is replaced by ``cpsam_v2`` (downloaded if absent), a built-in name is looked for -in ``MODEL_DIR`` and fetched when missing, and ``pretrained_model`` / ``device`` / ``backbone`` -are set on the loaded model. As in 4.2.1.1 ``device`` is only the device it was given; where +in ``MODEL_DIR`` and fetched when missing (``cellpose_downloaded``: the brick hands Cellpose a +path, so this must stay empty), and ``pretrained_model`` / ``device`` / ``backbone`` are set on +the loaded model. Nothing is ever downloaded: the brick's own download +(:mod:`.segmentation_cellpose_weights`) gets the stand-in bytes of :func:`weights_bytes` +(``downloaded``), whose SHA-256 and size are made the pins; ``download_fail`` makes it fail. +As in 4.2.1.1 ``device`` is only the device it was given; where the weights sit is told by ``net`` (parameters and buffers with a ``device``). Its ``eval`` records every call (the stack and the keywords) and returns a fixed label image, so a test sees exactly what Cellpose was given. """ +import hashlib +import io import logging import sys import types @@ -19,6 +25,7 @@ import numpy as np from morphobricks_preprocessing import segmentation_cellpose_model as model_module +from morphobricks_preprocessing import segmentation_cellpose_weights as weights_module from morphobricks_preprocessing.run_inputs import RunInputs from test_segmentation_handoff import EXTRA_FIRST from test_stage3_channels import described_run, extra_stain @@ -106,7 +113,7 @@ def _resolve(requested): ) return str(state.models_dir / "cpsam_v2") # the silent substitution if not path.exists(): - state.downloaded.append(requested) + state.cellpose_downloaded.append(requested) data = weights_bytes(requested) # As cellpose.utils.download_url_to_file: a bar of cellpose.utils.tqdm. bar_class = sys.modules["cellpose.utils"].tqdm @@ -135,8 +142,10 @@ def modules(state): models._MODEL_URL = "https://huggingface.co/mouseland/cellpose-sam/resolve/main/" models.normalize_default = dict(state.normalize_default) models.CellposeModel = model_class(state) - if state.has_cpdino: - models.CPDINO = object + models.CPDINO = object # 4.2.1.1 defines it whether or not DINOv3 imports + vit = types.ModuleType("cellpose.vit") + if state.has_cpdino: # what cellpose.vit imports from DINOv3 when it can + vit.dinov3_vitl16 = vit.dinov3_vitb16 = object plot = types.ModuleType("cellpose.plot") def show_segmentation(fig, img, maski, flowi, channels=(0, 0), file_name=None): @@ -149,7 +158,7 @@ def show_segmentation(fig, img, maski, flowi, channels=(0, 0), file_name=None): utils = types.ModuleType("cellpose.utils") utils.tqdm = TextBar # Cellpose's own: tqdm's plain text bar package = types.ModuleType("cellpose") - package.models, package.plot, package.utils = models, plot, utils + package.models, package.plot, package.utils, package.vit = models, plot, utils, vit torch = types.ModuleType("torch") torch.device = Device torch.cuda = SimpleNamespace(is_available=lambda: state.cuda) @@ -159,6 +168,7 @@ def show_segmentation(fig, img, maski, flowi, channels=(0, 0), file_name=None): "cellpose.models": models, "cellpose.plot": plot, "cellpose.utils": utils, + "cellpose.vit": vit, "torch": torch, } @@ -169,8 +179,10 @@ def install(monkeypatch, tmp_path, **options): Switches (set on the returned state before loading): ``cuda`` / ``mps`` availability, ``substitute`` (the path every loaded model reports, whatever was asked), ``params`` / ``buffers`` (the device types of the network's tensors, when not the requested one), - ``no_net``, ``fail`` (a function of the stack that raises), ``version`` and - ``dinov3_commit``. + ``no_net``, ``fail`` (a function of the stack that raises), ``version``, + ``dinov3_commit`` (None: no DINOv3 installed; ``install_dinov3`` then installs the pinned + one and records it in ``dinov3_installs``), ``dinov3_present`` (a DINOv3 of unknown commit) + and ``download_fail`` (an exception the download raises). """ models_dir = tmp_path / "cellpose_models" models_dir.mkdir(exist_ok=True) @@ -180,6 +192,11 @@ def install(monkeypatch, tmp_path, **options): constructed=[], bars=[], downloaded=[], + urls=[], + cellpose_downloaded=[], + dinov3_installs=[], + dinov3_present=False, + download_fail=None, models_dir=models_dir, cuda=False, mps=False, @@ -217,9 +234,56 @@ def install(monkeypatch, tmp_path, **options): lambda name: state.version if name == "cellpose" else real_version(name), ) monkeypatch.setattr(model_module, "installed_dinov3_commit", lambda: state.dinov3_commit) + fetching(monkeypatch, state) return state +def fetching(monkeypatch, state): + """Stand in for DINOv3's installation and the weights download (nothing is fetched).""" + monkeypatch.setattr( + model_module, + "dinov3_present", + lambda: state.dinov3_commit is not None or state.dinov3_present, + ) + + def install_dinov3(): + state.dinov3_installs.append(model_module.DINOV3_COMMIT) + state.dinov3_commit = model_module.DINOV3_COMMIT + + monkeypatch.setattr(model_module, "install_dinov3", install_dinov3) + monkeypatch.setattr(weights_module, "PINNED_WEIGHTS", fake_pins()) + monkeypatch.setattr(weights_module, "_open_url", lambda url, timeout: served(state, url)) + + +def fake_pins(): + """Return pins for the stand-in bytes of every built-in model (as the real pins are).""" + return { + name: weights_module.PinnedFile( + hashlib.sha256(weights_bytes(name)).hexdigest(), len(weights_bytes(name)) + ) + for name in BUILTINS + } + + +class Response(io.BytesIO): + """What ``urlopen`` returns: a readable body with headers.""" + + def __init__(self, data, headers): + super().__init__(data) + self.headers = headers + + +def served(state, url): + """Answer the brick's download of ``url`` with the stand-in bytes (never the network).""" + name = url.rsplit("/", 1)[-1] + state.downloaded.append(name) + state.urls.append(url) + if state.download_fail is not None: + raise state.download_fail + data = weights_bytes(name) + return Response(data, {"Content-Length": str(len(data))}) + + def custom_model(tmp_path, name="my_model"): """Write a custom model file and return its path.""" path = tmp_path / "custom" / name diff --git a/tests/test_notebook_cellpose.py b/tests/test_notebook_cellpose.py index 63cc9d14..c395d5c0 100644 --- a/tests/test_notebook_cellpose.py +++ b/tests/test_notebook_cellpose.py @@ -11,6 +11,7 @@ import html import json import re +import urllib.error from pathlib import Path import numpy as np @@ -318,15 +319,28 @@ def test_an_unknown_or_missing_model_stops_the_cell_with_no_substitution(cells): assert cells.ns["workflow"].loaded.name == "my_model" -def test_the_weights_download_needs_its_box_and_the_cell_says_where_from(cells): +def test_loading_a_model_downloads_its_weights_and_the_cell_shows_it(cells): + # Owner (#574): choosing the model and pressing the button is the consent; no tick. cells.stub.models_dir.joinpath("cpsam_v2").unlink() open_and_choose(cells) - with pytest.raises(notebook_cellpose.CellStop, match="Hugging Face"): - run_cell(cells.ns, MODEL, device="cpu") - assert cells.stub.downloaded == [] - assert "downloaded from Hugging Face on first use" in " ".join(cells.ns["workflow"].shown) - run_cell(cells.ns, MODEL, device="cpu", download_weights=True) + run_cell(cells.ns, MODEL, device="cpu") + fields = cells.ns["workflow"].forms["model"].fields + assert "download_weights" not in fields and "install_dinov3" not in fields assert cells.stub.downloaded == ["cpsam_v2"] + shown = " ".join(cells.ns["workflow"].shown) + assert ( + "Downloading cpsam_v2 weights…" in shown and "checked against their pinned SHA-256" in shown + ) + + +def test_a_failed_download_stops_the_cell_naming_the_model_and_the_source(cells): + cells.stub.models_dir.joinpath("cpsam").unlink() + cells.stub.download_fail = urllib.error.URLError("blocked") + open_and_choose(cells) + with pytest.raises(notebook_cellpose.CellStop, match="weights of cpsam could not be") as caught: + run_cell(cells.ns, MODEL, model="cpsam", device="cpu") + assert "https://huggingface.co/mouseland/cellpose-sam/resolve/" in str(caught.value) + assert cells.ns["workflow"].loaded is None and cells.stub.constructed == [] def test_the_load_card_says_whether_the_weights_were_downloaded_and_from_where(cells): @@ -334,11 +348,13 @@ def test_the_load_card_says_whether_the_weights_were_downloaded_and_from_where(c run_cell(cells.ns, MODEL, device="cpu") assert "nothing downloaded" in cells.ns["workflow"].shown[-1] cells.stub.models_dir.joinpath("cpsam").unlink() - run_cell(cells.ns, MODEL, model="cpsam", device="cpu", download_weights=True) - assert "downloaded now from https://huggingface.co/" in cells.ns["workflow"].shown[-1] + run_cell(cells.ns, MODEL, model="cpsam", device="cpu") + url = "https://huggingface.co/mouseland/cellpose-sam/resolve/" + cp.WEIGHTS_REVISION + assert f"downloaded now from {url}/cpsam" in cells.ns["workflow"].shown[-1] run_cell(cells.ns, BATCH) params = read_record(cells.run.masks, "Cells").batches[0].parameters - assert params["weights_downloaded"] is True and params["weights_source"].endswith("/cpsam") + assert params["weights_downloaded"] is True and params["weights_source"] == url + "/cpsam" + assert params["weights_revision"] == cp.WEIGHTS_REVISION @pytest.mark.parametrize("cell", [PREVIEW, BATCH]) diff --git a/tests/test_notebook_cellpose_both.py b/tests/test_notebook_cellpose_both.py index 826ff4a4..d810b6d4 100644 --- a/tests/test_notebook_cellpose_both.py +++ b/tests/test_notebook_cellpose_both.py @@ -275,7 +275,7 @@ def test_the_record_of_both_is_plain_json_without_a_partner(cells): def settings_and_cell_model(workflow): """Set the cells' settings and load their model, as cell 5 does first.""" workflow.set_settings("", 0.4, 0.0, 8) - workflow.load("cpsam_v2", "", "cpu", False, False) + workflow.load("cpsam_v2", "", "cpu") def nothing_written(cells, *names): @@ -296,7 +296,7 @@ def refuse(*args, **kwargs): monkeypatch.setattr(cp, "load_model", refuse) with pytest.raises(notebook_cellpose.CellStop, match="no weights"): - workflow.load_nuclei("cpsam", "", "cpu", False, False) + workflow.load_nuclei("cpsam", "", "cpu") assert workflow.nuclei_loaded is None with pytest.raises( notebook_cellpose.CellStop, match="The nuclei have their own model: load it first" diff --git a/tests/test_notebook_cellpose_form.py b/tests/test_notebook_cellpose_form.py index 1d0e84a9..4f433ac4 100644 --- a/tests/test_notebook_cellpose_form.py +++ b/tests/test_notebook_cellpose_form.py @@ -84,8 +84,6 @@ def test_the_forms_start_with_the_former_defaults(): "model": "cpsam_v2", "custom_model_file": "", "device": "cuda", # never chosen for the user: an unavailable GPU is refused - "download_weights": False, - "install_dinov3": False, "diameter": "", "flow_threshold": 0.4, "cellprob_threshold": 0.0, @@ -121,8 +119,6 @@ def test_every_field_reaches_the_workflow_as_given(monkeypatch): "model": "cpdino", "custom_model_file": "/models/mine", "device": "mps", - "download_weights": True, - "install_dinov3": True, "diameter": "17.5", "flow_threshold": 0.7, "cellprob_threshold": -1.5, @@ -148,7 +144,7 @@ def test_every_field_reaches_the_workflow_as_given(monkeypatch): ("open", ("/data/run", "/data/masks")), ("choose_channels", ("Nuclear", "nuclei", "Nuclear2")), ("set_settings", ("17.5", 0.7, -1.5, 3)), - ("load", ("cpdino", "/models/mine", "mps", True, True)), + ("load", ("cpdino", "/models/mine", "mps")), ("preview", ("a/b.tif",)), ("run", (True,)), ] @@ -196,12 +192,19 @@ def test_a_refusal_is_shown_verbatim_in_a_red_card_and_the_form_can_be_pressed_a assert form.stopped is None and "Run opened" in workflow.shown[-1] -def test_nothing_downloads_without_the_tick(cells): - cells.stub.models_dir.joinpath("cpsam_v2").unlink() +def test_only_the_chosen_models_weights_download_and_only_when_it_loads(cells): + # Owner (#574): no tick; choosing the model and pressing the button is the consent. + for name in ("cpsam_v2", "cpsam"): + cells.stub.models_dir.joinpath(name).unlink() open_and_choose(cells) - with pytest.raises(notebook_cellpose.CellStop, match="Hugging Face"): - run_cell(cells.ns, MODEL, device="cpu") # the download box as the form starts: off - assert cells.stub.downloaded == [] and cells.stub.constructed == [] + assert cells.stub.downloaded == [] + run_cell(cells.ns, MODEL, device="cpu", model="cpsam") + assert cells.stub.downloaded == ["cpsam"] and cells.stub.cellpose_downloaded == [] + labels = [ + str(getattr(w, "description", "")) + for w in cells.ns["workflow"].forms["model"].fields.values() + ] + assert not any("download" in label.lower() or "DINOv3" in label for label in labels) def test_an_unavailable_gpu_is_refused_from_the_form_never_replaced_by_the_cpu(cells): @@ -212,25 +215,30 @@ def test_an_unavailable_gpu_is_refused_from_the_form_never_replaced_by_the_cpu(c assert cells.stub.constructed == [] and cells.ns["workflow"].loaded is None -def test_dinov3_is_installed_only_on_its_tick_and_says_to_restart(cells, monkeypatch): - installed = [] - monkeypatch.setattr(cp, "install_dinov3", lambda: installed.append(True)) +def test_dinov3_is_installed_on_first_use_of_a_cpdino_model_with_no_tick(cells): cells.stub.dinov3_commit = None open_and_choose(cells) - with pytest.raises(notebook_cellpose.CellStop, match="restart the runtime"): - run_cell(cells.ns, MODEL, device="cpu", model="cpdino", download_weights=True) - assert installed == [] - with pytest.raises(notebook_cellpose.CellStop, match="restart the runtime"): - run_cell( - cells.ns, - MODEL, - device="cpu", - model="cpdino", - download_weights=True, - install_dinov3=True, - ) - assert installed == [True] - assert "Installing DINOv3" in " ".join(cells.ns["workflow"].shown) + run_cell(cells.ns, MODEL, device="cpu", model="cpsam_v2") + assert cells.stub.dinov3_installs == [] # a SAM model does not need it + run_cell(cells.ns, MODEL, device="cpu", model="cpdino") + assert cells.stub.dinov3_installs == [cp.DINOV3_COMMIT] + shown = " ".join(cells.ns["workflow"].shown) + assert ( + "Installing DINOv3" in shown + and f"DINOv3 installed now at commit {cp.DINOV3_COMMIT}" in shown + ) + assert cells.ns["workflow"].loaded.dinov3_installed + + +def test_dinov3_installed_after_cellpose_was_imported_asks_for_a_restart(cells, monkeypatch): + import sys + + cells.stub.dinov3_commit = None + monkeypatch.delattr(sys.modules["cellpose.vit"], "dinov3_vitl16") # Cellpose imported first + open_and_choose(cells) + with pytest.raises(notebook_cellpose.CellStop, match="Restart the runtime"): + run_cell(cells.ns, MODEL, device="cpu", model="cpdino") + assert cells.stub.dinov3_installs == [cp.DINOV3_COMMIT] and cells.stub.constructed == [] def test_overwrite_stays_off_unless_ticked(cells): diff --git a/tests/test_notebook_cellpose_stepper.py b/tests/test_notebook_cellpose_stepper.py index 41dde69b..47a48b48 100644 --- a/tests/test_notebook_cellpose_stepper.py +++ b/tests/test_notebook_cellpose_stepper.py @@ -4,14 +4,14 @@ (chips, Back, Next): Folders, Output and channels, Model and preview, Segment. These tests press the widgets as a user would, with the stand-in Cellpose of ``tests/cellpose_stub.py``: the whole flow, the folder refusal at step 1, the run's images in the preprocessing viewer, -Preview loading the model once and reusing it, the download shown as one ``tqdm.auto`` bar, +Preview loading the model once and reusing it, the first-use download shown as one line (#574), and that no *What to do next* step is left. """ import html import logging import sys -import types +import urllib.error import pytest @@ -256,61 +256,67 @@ def test_the_nuclei_box_shows_for_both_only(mixed_run, stub): assert is_visible(box) and "Output Both: the nuclei" in texts(box) -# the download: one tqdm.auto bar, nothing else changes ----------------------------------------- +# the download on first use (#574): one "Downloading weights…" line, no tick ---------- -@pytest.fixture -def auto_bar(monkeypatch): - """A stand-in ``tqdm.auto`` that records the bars made (tqdm comes with Cellpose).""" - made = [] - - class Bar(TextBar): - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - made.append(self) - - auto = types.ModuleType("tqdm.auto") - auto.tqdm = Bar - package = types.ModuleType("tqdm") - package.auto = auto - monkeypatch.setitem(sys.modules, "tqdm", package) - monkeypatch.setitem(sys.modules, "tqdm.auto", auto) - return made - - -def test_a_download_shows_one_notebook_bar_and_the_same_weights(mixed_run, stub, auto_bar): +def test_preview_downloads_the_chosen_models_weights_with_a_visible_line(mixed_run, stub): (stub.models_dir / "cpsam").unlink() app = ready(mixed_run) fields = app.workflow.forms["model"].fields - fields["model"].value, fields["download_weights"].value = "cpsam", True + assert "download_weights" not in fields and "install_dinov3" not in fields + fields["model"].value = "cpsam" preview(app) - assert stub.downloaded == ["cpsam"] - assert stub.bars == [download.notebook_bar] # Cellpose's bar, drawn by tqdm.auto - (bar,) = auto_bar - assert bar.kwargs["desc"] == download.BAR_LABEL and bar.kwargs["unit"] == "B" - assert bar.done == len(b"weights of cpsam") - assert sys.modules["cellpose.utils"].tqdm is TextBar # put back + assert stub.downloaded == ["cpsam"] and stub.cellpose_downloaded == [] + shown = " ".join(app.workflow.shown) + assert "Downloading cpsam weights…" in shown # the line as first shown assert app.workflow.loaded.downloaded and app.workflow.loaded.name == "cpsam" assert app.workflow.loaded.path == stub.models_dir / "cpsam" + preview(app) # loaded once, then reused: nothing downloads again + assert stub.downloaded == ["cpsam"] -def test_no_download_without_the_tick_even_with_the_quiet_display(mixed_run, stub, auto_bar): +def test_the_download_line_counts_megabytes_and_says_how_it_ended(): + shown = [] + line = download.DownloadLine(shown.append) + line.finish(True) + assert shown == [] and line.widget.value == "" # nothing to say: nothing shown + mb = download.MEGABYTE + line("Downloading cpsam weights…", 0, 300 * mb) + assert shown == [line.widget] + line("Downloading cpsam weights…", 300 * mb, 300 * mb) + value = html.unescape(line.widget.value) + assert "Downloading cpsam weights…" in value and "300 of 300" in value and "MB" in value + line.finish(True) + assert ( + "Downloading cpsam weights: done in" in line.widget.value and "mb-ok" in line.widget.value + ) + now = [0.0] + stopped = download.DownloadLine(shown.append, clock=lambda: now[0]) + stopped("Downloading cpdino weights…", 0, 0) + now[0] = 1.0 + stopped("Downloading cpdino weights…", 5 * mb, 0) # no size from the server: MB so far + assert "5 so far" in stopped.widget.value + stopped.finish(False) + assert "stopped after" in stopped.widget.value and "mb-error" in stopped.widget.value + + +def test_a_failed_download_on_preview_is_a_refusal_and_nothing_loads(mixed_run, stub): (stub.models_dir / "cpsam").unlink() + stub.download_fail = urllib.error.URLError("blocked") app = ready(mixed_run) app.workflow.forms["model"].fields["model"].value = "cpsam" form = app.workflow.forms["preview"] form.button.click() - assert "Allow the download on purpose" in form.refusal - assert stub.downloaded == [] and auto_bar == [] and stub.constructed == [] + assert "weights of cpsam could not be downloaded from https://huggingface.co/" in form.refusal + assert stub.constructed == [] and app.workflow.loaded is None and stub.calls == [] -def test_cellpose_logs_are_quiet_and_its_warnings_are_kept(stub, auto_bar): +def test_cellpose_logs_are_quiet_and_its_warnings_are_kept(stub): logger = logging.getLogger("cellpose") before = logger.propagate with download.quiet_cellpose() as said: logging.getLogger("cellpose.models").info("Downloading: noise") logging.getLogger("cellpose.models").warning("pretrained model x not found") - assert sys.modules["cellpose.utils"].tqdm is download.notebook_bar assert said == ["Warning: pretrained model x not found"] assert logger.propagate is before and sys.modules["cellpose.utils"].tqdm is TextBar @@ -327,12 +333,6 @@ def test_there_is_no_what_to_do_next_step(mixed_run, stub): assert not any("What to do next" in (getattr(w, "description", "") or "") for w in walk(app)) -def test_without_tqdm_auto_cellposes_own_bar_is_left_as_it_is(stub, monkeypatch): - monkeypatch.setitem(sys.modules, "tqdm.auto", None) # import tqdm.auto fails - with download.quiet_cellpose(): - assert sys.modules["cellpose.utils"].tqdm is TextBar - - # review of #548 --------------------------------------------------------------------------------- @@ -402,7 +402,7 @@ def test_the_model_chip_is_not_done_once_the_model_changes(mixed_run, stub): assert app.stepper.states()[2].done and "cpsam" in app.stepper.states()[2].text -def test_cellposes_unpinned_dinov3_advice_becomes_the_notebooks_pinned_tick(mixed_run, stub): +def test_cellposes_unpinned_dinov3_advice_becomes_the_notebooks_pinned_install(mixed_run, stub): # L2: Cellpose logs "run pip install git+.../dinov3" (unpinned) when it cannot import # DINOv3; the card points to the notebook's own pinned installation instead. from cellpose_stub import CPDINO_WARNING @@ -412,7 +412,7 @@ def test_cellposes_unpinned_dinov3_advice_becomes_the_notebooks_pinned_tick(mixe preview(app) (card,) = [s for s in app.workflow.shown if "Cellpose said" in s] assert "pip install" not in card and "git+" not in card - assert "Install DINOv3 now" in html.unescape(card) and "pinned commit" in card + assert "installs the pinned commit" in html.unescape(card) and "restart" in card with download.quiet_cellpose() as said: logging.getLogger("cellpose.models").warning(CPDINO_WARNING) assert said == ["Warning: " + download.CPDINO_NOTE] diff --git a/tests/test_segmentation_cellpose.py b/tests/test_segmentation_cellpose.py index 9ab6a4c4..7be97de1 100644 --- a/tests/test_segmentation_cellpose.py +++ b/tests/test_segmentation_cellpose.py @@ -185,28 +185,29 @@ def test_the_gpu_is_used_when_asked_and_present(stub): cp.load_model("cpsam_v2", "gpu") -# no silent download, the weights are hashed (audit B9) -------------------------------------- +# downloads on first use, checked; the weights are hashed (audit B9, #574) ------------------- -def test_weights_that_are_not_on_disk_are_not_downloaded_unless_allowed(stub): +def test_weights_not_on_disk_are_downloaded_on_first_use_and_given_to_cellpose_by_path(stub): + # Owner (#574): choosing the model and loading it is the consent; Cellpose never downloads. (stub.models_dir / "cpsam").unlink() - with pytest.raises(SegmentationError, match="Hugging Face"): - cp.load_model("cpsam", "cpu") - assert stub.constructed == [] and stub.downloaded == [] - loaded = cp.load_model("cpsam", "cpu", allow_download=True) - assert stub.downloaded == ["cpsam"] and stub.constructed[0].pretrained_model == "cpsam" + loaded = cp.load_model("cpsam", "cpu") + assert stub.downloaded == ["cpsam"] and stub.cellpose_downloaded == [] + assert stub.constructed[0].pretrained_model == str(stub.models_dir / "cpsam") assert loaded.sha256 == hashlib.sha256(weights_bytes("cpsam")).hexdigest() + assert loaded.downloaded and (stub.models_dir / "cpsam").read_bytes() == weights_bytes("cpsam") + cp.load_model("cpsam", "cpu") + assert stub.downloaded == ["cpsam"] # the second time: the checked copy on disk -def test_a_file_in_the_working_folder_that_shadows_a_download_is_refused( - stub, tmp_path, monkeypatch -): +def test_a_file_in_the_working_folder_cannot_shadow_the_weights(stub, tmp_path, monkeypatch): (stub.models_dir / "cpsam").unlink() (tmp_path / "cpsam").write_bytes(b"not the model") monkeypatch.chdir(tmp_path) - with pytest.raises(SegmentationError, match="working folder"): - cp.load_model("cpsam", "cpu", allow_download=True) - assert stub.constructed == [] + loaded = cp.load_model("cpsam", "cpu") + assert loaded.path == stub.models_dir / "cpsam" + assert stub.constructed[0].pretrained_model == str(stub.models_dir / "cpsam") + assert (tmp_path / "cpsam").read_bytes() == b"not the model" @pytest.mark.parametrize("found", [None, "4.2.0", "4.3.0"]) @@ -230,7 +231,7 @@ def test_the_model_name_file_and_weights_hash_are_in_the_record(run, stub): assert batch.run_manifest_sha256 == hashlib.sha256(manifest).hexdigest() -# DINOv3 models: installed only when chosen, at a pinned commit ------------------------------ +# DINOv3 models: installed on first use of one, at a pinned commit (#574) -------------------- def test_the_dinov3_install_command_pins_the_commit(): @@ -241,28 +242,43 @@ def test_the_dinov3_install_command_pins_the_commit(): assert len(cp.DINOV3_COMMIT) == 40 -@pytest.mark.parametrize("commit", [None, "0" * 40]) -def test_a_dino_model_needs_the_pinned_dinov3_commit(stub, commit): - stub.dinov3_commit = commit +@pytest.mark.parametrize("commit", ["0" * 40, None]) +def test_a_dino_model_refuses_a_dinov3_of_another_commit_and_does_not_replace_it(stub, commit): + stub.dinov3_commit, stub.dinov3_present = commit, True # None: installed, commit unknown with pytest.raises(SegmentationError, match=f"commit {cp.DINOV3_COMMIT}.*pip install"): - cp.load_model("cpdino", "cpu", allow_download=True) - assert stub.constructed == [] + cp.load_model("cpdino", "cpu") + assert stub.constructed == [] and stub.dinov3_installs == [] and stub.downloaded == [] cp.load_model("cpsam_v2", "cpu") # a SAM model needs no DINOv3 at all +def test_a_dino_model_installs_the_pinned_dinov3_when_none_is_there(stub): + stub.dinov3_commit = None + told = [] + loaded = cp.load_model("cpdino", "cpu", progress=lambda *a: told.append(a)) + assert stub.dinov3_installs == [cp.DINOV3_COMMIT] and loaded.dinov3_installed + assert told[0] == (cp.DINOV3_LABEL, 0, 0) + assert loaded.dinov3_commit == cp.DINOV3_COMMIT + again = cp.load_model("cpdino", "cpu") + assert stub.dinov3_installs == [cp.DINOV3_COMMIT] and not again.dinov3_installed + stub.dinov3_commit = None + cp.load_model("cpsam_v2", "cpu") # a SAM model never installs it + assert stub.dinov3_installs == [cp.DINOV3_COMMIT] + + def test_a_dino_model_needs_cellpose_to_have_imported_dinov3(monkeypatch, tmp_path): state = install(monkeypatch, tmp_path, has_cpdino=False) with pytest.raises(SegmentationError, match="Restart the runtime"): - cp.load_model("cpdino-vitb", "cpu", allow_download=True) + cp.load_model("cpdino-vitb", "cpu") assert state.constructed == [] def test_a_dino_model_records_the_dinov3_commit(run, stub): - loaded = cp.load_model("cpdino", "cpu", allow_download=True) + loaded = cp.load_model("cpdino", "cpu") assert loaded.dinov3_commit == cp.DINOV3_COMMIT and loaded.tile_size == 384 assert stub.downloaded == ["cpdino"] params = cp.inference_parameters(loaded, cp.Settings(), ("DNA",)) assert params["dinov3_commit"] == cp.DINOV3_COMMIT and params["bsize"] == 384 + assert params["dinov3_source"] == cp.DINOV3_URL and params["dinov3_installed"] is False def test_dinov3_is_installed_only_when_asked_and_a_failure_is_refused(monkeypatch): diff --git a/tests/test_segmentation_cellpose_record.py b/tests/test_segmentation_cellpose_record.py index 63855396..b6b13691 100644 --- a/tests/test_segmentation_cellpose_record.py +++ b/tests/test_segmentation_cellpose_record.py @@ -27,16 +27,24 @@ def stub(monkeypatch, tmp_path): def test_the_record_says_whether_the_weights_were_downloaded_and_from_where(stub, tmp_path): - url = "https://huggingface.co/mouseland/cellpose-sam/resolve/main/" + revision = "7c61431b5fbb078f3296754bd15d9f51b320f837" + url = f"https://huggingface.co/mouseland/cellpose-sam/resolve/{revision}/" + assert (cp.WEIGHTS_REPOSITORY, cp.WEIGHTS_REVISION) == ("mouseland/cellpose-sam", revision) on_disk = cp.load_model("cpsam", "cpu") assert (on_disk.downloaded, on_disk.source) == (False, url + "cpsam") (stub.models_dir / "cpsam").unlink() - fetched = cp.load_model("cpsam", "cpu", allow_download=True) + fetched = cp.load_model("cpsam", "cpu") assert (fetched.downloaded, fetched.source) == (True, url + "cpsam") + assert stub.urls == [url + "cpsam"] params = cp.inference_parameters(fetched, cp.Settings(), ("DNA",)) assert params["weights_downloaded"] is True and params["weights_source"] == url + "cpsam" + assert params["weights_repository"] == "mouseland/cellpose-sam" + assert params["weights_revision"] == revision + assert params["dinov3_commit"] is None and params["dinov3_source"] is None own = cp.load_model(str(custom_model(tmp_path)), "cpu") - assert (own.downloaded, own.source) == (False, None) + assert (own.downloaded, own.source, own.repository, own.revision) == (False, None, None, None) + params = cp.inference_parameters(own, cp.Settings(), ("DNA",)) + assert (params["weights_source"], params["weights_revision"]) == (None, None) def test_the_full_normalisation_is_read_from_cellpose_now_copied_and_recorded(run, stub): diff --git a/tests/test_segmentation_cellpose_weights.py b/tests/test_segmentation_cellpose_weights.py new file mode 100644 index 00000000..03eb876f --- /dev/null +++ b/tests/test_segmentation_cellpose_weights.py @@ -0,0 +1,200 @@ +"""The built-in weights (#574): pinned, downloaded on first use, checked; one torch warning hidden. + +Nothing is downloaded here: the stand-in (``cellpose_stub.install``) answers the brick's +download with its own bytes, whose SHA-256 and size it makes the pins. +""" + +import email.message +import hashlib +import re +import urllib.error +import warnings + +import numpy as np +import pytest + +from cellpose_stub import BUILTINS, install, weights_bytes +from morphobricks_preprocessing import segmentation_cellpose as cp +from morphobricks_preprocessing import segmentation_cellpose_weights as weights_module +from morphobricks_preprocessing.segmentation_record import SegmentationError, read_record +from test_segmentation_cellpose import make_job + +SPARSE_MESSAGE = ( + "Sparse invariant checks are implicitly disabled. Memory errors (e.g. SEGFAULT) will occur " + "when operating on a sparse tensor which violates the invariants, but checks are disabled. " + "See torch.sparse.check_sparse_tensor_invariants.enable for more information." +) +"""torch's warning, as Cellpose 4.2.1.1's ``dynamics.py`` triggers it.""" + + +@pytest.fixture +def run(mixed_run): + return mixed_run + + +@pytest.fixture +def stub(monkeypatch, tmp_path): + return install(monkeypatch, tmp_path) + + +# the pins --------------------------------------------------------------------------------------- + + +def test_every_builtin_model_has_a_pinned_file_at_a_pinned_revision(): + assert tuple(weights_module.PINNED_WEIGHTS) == cp.BUILTIN_MODELS == BUILTINS + assert re.fullmatch("[0-9a-f]{40}", cp.WEIGHTS_REVISION) + for pin in weights_module.PINNED_WEIGHTS.values(): + assert re.fullmatch("[0-9a-f]{64}", pin.sha256) and pin.size > 100_000_000 + url = cp.weights_url("cpsam_v2") + assert url == ( + f"https://huggingface.co/mouseland/cellpose-sam/resolve/{cp.WEIGHTS_REVISION}/cpsam_v2" + ) + assert "/main/" not in url # never the moving branch Cellpose itself downloads from + + +# the download: only the chosen model's file, with its progress ------------------------------- + + +def test_only_the_chosen_models_weights_are_downloaded_with_their_progress(stub): + for name in BUILTINS: + (stub.models_dir / name).unlink(missing_ok=True) + told = [] + loaded = cp.load_model("cpsam", "cpu", progress=lambda *a: told.append(a)) + assert stub.downloaded == ["cpsam"] and stub.urls == [cp.weights_url("cpsam")] + assert sorted(p.name for p in stub.models_dir.iterdir()) == ["cpsam"] # no partial file + size = len(weights_bytes("cpsam")) + assert told == [ + ("Downloading cpsam weights…", 0, size), + ("Downloading cpsam weights…", size, size), + ] + assert (loaded.repository, loaded.revision) == (cp.WEIGHTS_REPOSITORY, cp.WEIGHTS_REVISION) + assert stub.cellpose_downloaded == [] # Cellpose was given the file, never a name + + +def test_a_copy_on_disk_shows_no_progress_and_is_not_downloaded(stub): + told = [] + loaded = cp.load_model("cpsam_v2", "cpu", progress=lambda *a: told.append(a)) + assert told == [] and stub.downloaded == [] and not loaded.downloaded + + +# refusals: the model and the source named, nothing substituted, nothing left ----------------- + + +def _http_error(url, code, reason): + return urllib.error.HTTPError(url, code, reason, email.message.Message(), None) + + +@pytest.mark.parametrize( + ("failure", "said"), + [ + (urllib.error.URLError("blocked by the proxy"), "blocked by the proxy"), + (TimeoutError("timed out"), "timed out"), + ("http", "the server answered 403 Forbidden"), + ], +) +def test_a_failed_or_blocked_download_is_a_refusal_naming_the_model_and_the_source( + stub, failure, said +): + (stub.models_dir / "cpsam").unlink() + url = cp.weights_url("cpsam") + stub.download_fail = _http_error(url, 403, "Forbidden") if failure == "http" else failure + with pytest.raises(SegmentationError) as caught: + cp.load_model("cpsam", "cpu") + message = str(caught.value) + assert "weights of cpsam could not be downloaded from " + url in message + assert said in message and "no other model is used" in message + assert stub.constructed == [] # nothing loaded, cpsam_v2 (on disk) not used instead + assert not (stub.models_dir / "cpsam").exists() + assert not [p for p in stub.models_dir.iterdir() if p.name.endswith(".part")] + + +def test_downloaded_bytes_that_are_not_the_pinned_file_are_refused_and_not_kept(stub, monkeypatch): + (stub.models_dir / "cpsam").unlink() + monkeypatch.setitem( + weights_module.PINNED_WEIGHTS, "cpsam", weights_module.PinnedFile("0" * 64, 16) + ) + with pytest.raises(SegmentationError, match="cpsam could not be downloaded") as caught: + cp.load_model("cpsam", "cpu") + assert "the pinned file has 16 bytes and SHA-256 " + "0" * 64 in str(caught.value) + assert stub.constructed == [] and sorted(p.name for p in stub.models_dir.iterdir()) == [ + "cpsam_v2" + ] + + +def test_a_copy_on_disk_that_is_not_the_pinned_file_is_refused_not_replaced(stub): + (stub.models_dir / "cpsam").write_bytes(b"older weights of cpsam") + with pytest.raises(SegmentationError, match="not the pinned file") as caught: + cp.load_model("cpsam", "cpu") + assert str(stub.models_dir / "cpsam") in str(caught.value) + assert hashlib.sha256(b"older weights of cpsam").hexdigest() in str(caught.value) + assert stub.constructed == [] and stub.downloaded == [] + assert (stub.models_dir / "cpsam").read_bytes() == b"older weights of cpsam" + + +def test_a_model_file_of_ones_own_is_never_checked_against_a_pin_or_downloaded(stub, tmp_path): + from cellpose_stub import custom_model + + loaded = cp.load_model(str(custom_model(tmp_path)), "cpu") + assert stub.downloaded == [] and loaded.source is None and loaded.revision is None + + +def test_the_written_record_names_the_weights_source_revision_and_hash(run, stub): + (stub.models_dir / "cpsam_v2").unlink() + result = cp.run_batch(make_job(run), batch_id="b1") + (batch,) = read_record(run.masks, "Cells").batches + assert batch == result.batch + assert batch.model_sha256 == hashlib.sha256(weights_bytes("cpsam_v2")).hexdigest() + params = batch.parameters + assert params["weights_source"] == cp.weights_url("cpsam_v2") + assert params["weights_repository"] == "mouseland/cellpose-sam" + assert params["weights_revision"] == cp.WEIGHTS_REVISION + assert params["weights_downloaded"] is True + + +# the torch warning (#574, item 5) ------------------------------------------------------------- + + +def _warn(message, module, category=UserWarning): + def warn(_stack): + warnings.warn_explicit(message, category, "dynamics.py", 541, module=module) + + return warn + + +def _evaluate(stub): + loaded = cp.load_model("cpsam_v2", "cpu") + with warnings.catch_warnings(record=True) as seen: + warnings.simplefilter("always") + before = list(warnings.filters) + cp.evaluate(loaded, cp.Settings(), np.zeros((2, 8, 8), np.uint16)) + assert warnings.filters == before # the filter was only there during the call + return [str(w.message) for w in seen] + + +@pytest.mark.parametrize("module", ["cellpose.dynamics", "torch", "torch.sparse"]) +def test_the_sparse_invariant_warning_is_hidden_while_cellpose_runs(stub, module): + stub.fail = _warn(SPARSE_MESSAGE, module) + assert _evaluate(stub) == [] + + +@pytest.mark.parametrize( + ("message", "module", "category"), + [ + (SPARSE_MESSAGE, "my_analysis", UserWarning), # another module + (SPARSE_MESSAGE, "cellposeextra", UserWarning), # not the cellpose package + (SPARSE_MESSAGE, "cellpose.dynamics", RuntimeWarning), # another category + ("Something else from torch", "torch", UserWarning), # another message + ("Note: " + SPARSE_MESSAGE, "cellpose.dynamics", UserWarning), # not its start + ], +) +def test_every_other_warning_is_still_shown(stub, message, module, category): + stub.fail = _warn(message, module, category) + assert _evaluate(stub) == [message] + + +def test_the_warning_is_shown_again_outside_the_cellpose_call(stub): + _evaluate(stub) + with warnings.catch_warnings(record=True) as seen: + warnings.simplefilter("always") + _warn(SPARSE_MESSAGE, "cellpose.dynamics")(None) + assert [str(w.message) for w in seen] == [SPARSE_MESSAGE] From 0597be51a33cda93e84bb8e28265101b87d0afe0 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 11:49:57 +0000 Subject: [PATCH 03/10] Cell 5: ask what each mask is; show Register's steps as they go (#574 items 6-7) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Item 6: the tick box "Declare as separate objects" under a TOML preview is replaced by a question per mask type with no answer chosen: "Each object has its own number (label image: every cell/nucleus is a separate object)" or "Foreground / background only (binary mask)", with one sentence on why we ask. The TOML is shown only folded (
). The recorded value (representation = "instances") and the refusal while a mask type is unanswered are unchanged; a binary answer is refused beside the button (Cellpose gives each object its own number), nothing records it. Item 7: Register showed nothing in cell 5 while it read, per image of a verify_content run, 4 whole files (SHA-256: cell 5's checks, the app's run, its pre-publish check, the tissue-mask step's opening) and per mask 5 (run, pre-publish check, mask step fingerprints before/after, pixels). Each read is a check or the data itself, so none is removed; reads per file and the normalized run-folder digests are identical to main. RegisterWait (notebook_progress.Wait and its ticking thread, #567) shows "Step k of 5 · " with the elapsed time and the step's own line: the run's checks counted through open_run(checking=) (open_checks and run_inputs.open_checked, identical to #575's hunks), and the app's own wait lines copied while each step runs. Notebook cells are unchanged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WX6rdMV1r5jUPUR94kxV5a --- AGENTS.md | 7 +- CHANGELOG.md | 1 + docs/user_guide.md | 17 +- pyproject.toml | 2 + .../notebook_mask_register.py | 220 +++++++++---- .../notebook_register_progress.py | 132 ++++++++ src/morphobricks_preprocessing/open_checks.py | 68 ++++ src/morphobricks_preprocessing/run_inputs.py | 46 ++- .../segmentation_cellpose_run.py | 16 +- tests/test_mask_register_progress.py | 310 ++++++++++++++++++ tests/test_notebook_preprocessing_cellpose.py | 22 +- 11 files changed, 738 insertions(+), 103 deletions(-) create mode 100644 src/morphobricks_preprocessing/notebook_register_progress.py create mode 100644 src/morphobricks_preprocessing/open_checks.py create mode 100644 tests/test_mask_register_progress.py diff --git a/AGENTS.md b/AGENTS.md index 39b56123..a4861871 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 @@ -312,8 +314,9 @@ src/morphobricks_preprocessing/ 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); 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 + question per mask type (objects or binary, none chosen; objects registered), + then the app's own check, Masks answer, save, run and Describe the masks, + each step shown by notebook_register_progress.py RegisterWait (#574) notebook_cellpose_preview.py MaskResult, preview_figures: the example result as ZeroCostDL4Mic draws it (cellpose.plot.show_segmentation), one result per mask notebook_cellpose_channels.py ChannelPicker, MaskTarget: the output's masks (Both: diff --git a/CHANGELOG.md b/CHANGELOG.md index 841cf7f1..9e4d8883 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ v0.5.1: no run before v0.5.1 is read.) ## Unreleased - **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`. +- **Cellpose cell 5, Register the masks: a clear question, and every step shown as it goes (#574, items 6 and 7; owner's Colab test of 26 November 2026).** Item 6: the tick box "Declare Cells as separate objects" under a TOML preview was awkward. Each mask type is now asked what it is, with no answer chosen: "Each object has its own number (label image: every cell/nucleus is a separate object)" or "Foreground / background only (binary mask)", with one sentence on why: "We ask because the two are measured differently, and we never guess which one a file is." The TOML is shown only folded (`
`) under the question. What is recorded is unchanged (`representation = "instances"` through the app's *Masks* question), and so is the refusal while a mask type is unanswered (the button stays disabled, saying "choose what Cells is", and pressing does nothing). Cellpose gives each object its own number, so the binary answer is refused beside the button, saying so; nothing records it (`BINARY_REFUSED`). Item 7: after **Register the masks** something ran for a long time with nothing in cell 5. Measured with a patched opener (`builtins.open`, bytes read per file) on main: per image of a `verify_content` run (the notebook's default), the press reads every image whole 4 times, each for its content SHA-256 (cell 5's own checks of the segmented run, the app's run, its check before it publishes, and the app's tissue-mask step that opens the run after it), and every mask whole 5 times (the run and its check before publishing, the mask step's fingerprints before and after reading, and its pixels for the piece counts, 1 per mask); a press that stops for the axes reads every image whole once, and showing cell 5 once more. The app drew its own waits in cell 3. Every one of these reads is a check or the data itself, so none was removed: what is read, and the run folder, are unchanged (normalized digests of every file of the run folder, and the reads per file, equal before and after). Cell 5 now shows the press with the waits of #567 (`notebook_progress.Wait` and its ticking thread, `notebook_register_progress.RegisterWait`): "Step k of 5 · " with the elapsed time, and under it the step's own line: the run's checks counted ("Reading each image whole for its content SHA-256 · 2 of 200 · ctrl/rep1/a.tif"), through `segmentation_cellpose_run.open_run(checking=)` (`run_inputs.open_checked` and `open_checks`, the same code as #575, unchanged checks), and the app's own wait lines of its folder check, run and mask step, copied as the app draws them; then "Took m:ss." (or "Stopped after m:ss."). The button is disabled while it goes. Cell 5's text is unchanged. `tests/test_mask_register_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. - **Earlier work that does not record its experiment folder no longer leaves the stepper at a dead end (owner's Colab test of v0.9.0 at ca3b3c6).** An output folder holding only saved answers (here an older version's `morphobricks.draft.json`) showed *"The experiment folder it is of is not recorded … Enter the experiment folder and click Check folder"*: the stepper has no *Check folder* button (its check, *Looks right: read all image headers*, stays disabled until **Scan the folders**), and entering the folder showed the same message again, with no scan and no picture. Now the experiment folder entered is scanned at once on the stepper (folder walk and one picture; nothing is written), the message names the stepper's own buttons, and the check, on the user's click, reads the saved answers as always. Saved answers written by another version of the software (`DraftFileError` `unknown_version`, `unknown_key` or `spec_commit_mismatch`; the owner's file is format 3, `unknown_version`) are not earlier work (`EarlierWork.old_answers`): one line says they are not used and the file is left as it is, and the experiment folder entered is scanned and shown as above (an early **Scan the folders** click, before the typed folder reached the kernel, is made good when it arrives). The same scan follows a record and a run that name different folders. Each message names the buttons of the layout shown (the stacked pages say **Check folder**). Tests: `tests/test_notebook_restore.py`. diff --git a/docs/user_guide.md b/docs/user_guide.md index 9aa3b28c..ae1a5339 100644 --- a/docs/user_guide.md +++ b/docs/user_guide.md @@ -365,11 +365,18 @@ run the experiment in the app of cell 3. Then: reuses it) and **Segment** (it reuses the loaded model, and says in one line exactly which model and settings it will use, in amber with what differs when the last Preview used others). One line after the batch points to cell 5. -- **5. Register the masks** shows, for each mask type cell 4 wrote, the declaration it would - add (`[masks.Cells]` with `source_type = "Cells"` and `representation = "instances"`). Tick - each one and press **Register the masks**: the app of cell 3 then checks the folders again - with the masks folder, answers the mask on **Masks**, saves the description, runs again - (the histograms of unchanged images are reused) and describes the masks. Masks written into +- **5. Register the masks** asks, for each mask type cell 4 wrote, what the mask is, with no + answer chosen: *Each object has its own number (label image: every cell/nucleus is a + separate object)* or *Foreground / background only (binary mask)*. They are measured + differently, and the notebook never guesses which one a file is. Cellpose gives each object + its own number, so only the first is registered (the second is refused, saying why); the + declaration it adds (`[masks.Cells]` with `source_type = "Cells"` and `representation = + "instances"`) is shown folded under the question. Answer each one and press **Register the + masks**: the app of cell 3 then checks the folders again with the masks folder, answers the + mask on **Masks**, saves the description, runs again (the histograms of unchanged images are + reused) and describes the masks. Each step is shown under the button as it goes ("Step 4 of + 5 · Running again…", its elapsed time, and the step's own line: the image read now, "n of + N"), then how long it took. Masks written into the masks folder the run already used are fine. If its folder check asks you to confirm the axes again, do it in cell 3 (step **Axes**) and press the button again (or run cell 5 again). It refuses, changing nothing, a mask type that collides with a mask already declared, diff --git a/pyproject.toml b/pyproject.toml index 00e113d2..f6b94bc1 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" @@ -195,6 +196,7 @@ baseline = "tools/code_rules_baseline.json" "morphobricks_preprocessing.notebook_cellpose_summary" = "ui" "morphobricks_preprocessing.notebook_cellpose_view" = "ui" "morphobricks_preprocessing.notebook_mask_register" = "ui" +"morphobricks_preprocessing.notebook_register_progress" = "ui" "morphobricks_preprocessing.notebook_preprocessing_cellpose" = "ui" "morphobricks_preprocessing.notebook_stop" = "ui" "morphobricks_preprocessing.notebook_channels" = "ui" diff --git a/src/morphobricks_preprocessing/notebook_mask_register.py b/src/morphobricks_preprocessing/notebook_mask_register.py index ccf0a8e2..756da90f 100644 --- a/src/morphobricks_preprocessing/notebook_mask_register.py +++ b/src/morphobricks_preprocessing/notebook_mask_register.py @@ -1,10 +1,14 @@ """Cell 5 of the combined notebook: declare the masks cell 4 wrote, rescan, describe them. -One declaration is offered per mask type cell 4 wrote, prefilled from the segmentation: -``[masks.]`` with ``source_type = ""`` and ``representation = "instances"`` -(Cellpose writes one label per object). Nothing is declared until the user ticks each one and -presses **Register the masks**. Then the Preprocessing app's own code does the rest, the same -code as its buttons (no second implementation): +For each mask type cell 4 wrote, the user says what the mask is, with no answer chosen for +them (owner, 26 Nov 2026, #574 item 6): *each object has its own number* (a label image) or +*foreground / background only* (a binary mask). The two are measured differently and a file is +never guessed to be one or the other. Cellpose writes one number per object, so only the first +is registered: ``[masks.]`` with ``source_type = ""`` and ``representation = +"instances"`` (shown folded, under the question); the second is refused, saying why. Nothing is +declared until every mask type is answered and **Register the masks** is pressed. Then the +Preprocessing app's own code does the rest, the same code as its buttons (no second +implementation), each step shown in cell 5 as it goes (:mod:`.notebook_register_progress`): 1. the app's folder check with the masks folder (``check_folder``, *Scan the folders*); 2. each mask answered on the app's *Masks* question (its ID box and its choice, which save the @@ -42,9 +46,11 @@ from .description_identity import nfc from .folder_rules import masks_folder_issues from .manifest import MANIFEST_FILENAME, ManifestFormatError, read_manifest -from .mask_answers import INSTANCES +from .mask_answers import BINARY, INSTANCES from .notebook_cellpose_app import app_folders +from .notebook_register_progress import RegisterWait from .notebook_render import blocked_line +from .open_checks import Checking, quiet from .report import mapping_summary from .run_inputs import RunInputsError, UnrecordedFilesError from .segmentation_cellpose_run import manifest_sha256, open_run @@ -91,6 +97,22 @@ "step Axes, confirm the recorded axes, then press Register the masks again. Nothing was " "declared." ) +CHOICES = [ + ( + "Each object has its own number (label image: every cell/nucleus is a separate object)", + INSTANCES, + ), + ("Foreground / background only (binary mask)", BINARY), +] +"""The answers to "what is this mask?", in this order; none is chosen for the user.""" +WHY_WE_ASK = ( + "We ask because the two are measured differently, and we never guess which one a file is." +) +BINARY_REFUSED = ( + "{mask_type} cannot be registered as foreground / background only: cell 4 wrote it with " + "Cellpose, which gives each object its own number" +) +"""Why a binary answer is not registered (a phrase beside the disabled button).""" NOT_SAVED = ( "Check and save did not save the description: open cell 3, step Check and save, answer " "what it lists, then press Register the masks again here." @@ -154,11 +176,15 @@ def _app_run(app: object, rechecked: bool) -> tuple[str, str]: return run, masks -def refusal(app: object, segmentation: object, *, rechecked: bool = False) -> str: +def refusal( + app: object, segmentation: object, *, rechecked: bool = False, checking: Checking = quiet +) -> str: """Return why the masks of cell 4 cannot be registered in the app's run, or "". ``rechecked``: cell 5 made the app's folder check for this run (also read from the segmentation's ``rechecked_run``, so cell 5 run again after the axes stop continues). + ``checking`` is told each phase of opening the run (:func:`.segmentation_cellpose_run. + open_run`); it changes nothing checked or decided. """ types = written_types(segmentation) if not types: @@ -179,7 +205,7 @@ def refusal(app: object, segmentation: object, *, rechecked: bool = False) -> st if app_masks and Path(app_masks).resolve() != masks: return OTHER_MASKS.format(segmented=masks, app_masks=app_masks) try: - open_run(os.fspath(segmented)) + open_run(os.fspath(segmented), checking=checking) except UnrecordedFilesError as exc: if not _only_written(exc, masks, types): return CHANGED.format(reason=exc) @@ -252,50 +278,71 @@ def _other_experiment(app: object, inputs: object) -> str: class MaskRegistration(widgets.VBox): - """Cell 5's widget: one declaration to tick per mask type, and **Register the masks**.""" + """Cell 5's widget: what each mask type is, and **Register the masks**.""" def __init__(self, app: object, segmentation: object) -> None: - """Offer the declarations, or show why the masks cannot be registered.""" + """Ask what each mask is, or show why the masks cannot be registered.""" super().__init__(layout=widgets.Layout(width="99%")) self.app, self.segmentation = app, segmentation self.status = widgets.HTML() - self.ticks: dict[str, widgets.Checkbox] = {} + self.choices: dict[str, widgets.RadioButtons] = {} self.registered = False why = refusal(app, segmentation) if why: self.status.value = ui.status("error", "The masks cannot be registered", [why]) self.children = [widgets.HTML(ui.STYLE_CSS), self.status] return - rows = [] - for mask_type in written_types(segmentation): - tick = widgets.Checkbox( - value=False, - description=f"Declare {mask_type} as separate objects", - indent=False, - layout=widgets.Layout(width="auto"), - ) - tick.observe(lambda _: self._update(), names="value") - self.ticks[mask_type] = tick - section = html.escape(toml_section(mask_type)) - rows += [widgets.HTML(f"
{section}
"), tick] + rows = [self._question(mask_type) for mask_type in written_types(segmentation)] self.button = ui.button("Register the masks", icon="check", main=True) self.button.on_click(lambda _: self.register()) self.blocker = widgets.HTML() + self.progress, self.progress_detail = widgets.HTML(), widgets.HTML() self._update() text = ( - "Each mask type cell 4 wrote, as it would be declared in the experiment description. " - "Tick each one you confirm, then press Register the masks: the app of cell 3 " - "checks the folders again with the masks folder, saves the description, runs again " - "(the histograms are reused) and describes the masks." + "For each mask type cell 4 wrote, say what the mask is. " + f"{html.escape(WHY_WE_ASK)} Then press Register the masks: the app of " + "cell 3 checks the folders again with the masks folder, saves the description, " + "runs again (the histograms are reused) and describes the masks; each step is " + "shown here as it goes." ) - body = [ui.help_text(text), *rows, widgets.HBox([self.button, self.blocker]), self.status] + body = [ + ui.help_text(text), + *rows, + widgets.HBox([self.button, self.blocker]), + self.progress, + self.progress_detail, + self.status, + ] self.children = [widgets.HTML(ui.STYLE_CSS), ui.card("Register the masks", body)] + def _question(self, mask_type: str) -> widgets.VBox: + """Return the question about ``mask_type``, with no answer chosen, and its declaration. + + The declaration it adds to the description is shown folded (``
``). + """ + choice = widgets.RadioButtons( + options=CHOICES, value=None, layout=widgets.Layout(width="auto") + ) + choice.observe(lambda _: self._update(), names="value") + self.choices[mask_type] = choice + section = html.escape(toml_section(mask_type)) + declared = ( + "
What registering it as separate objects adds " + f"to the experiment description
{section}
" + ) + title = f"{html.escape(mask_type)}: what is this mask?" + return widgets.VBox([widgets.HTML(title), choice, widgets.HTML(declared)]) + def _update(self) -> None: - """Enable the button once every declaration is ticked, saying which are not.""" - left = [t for t, tick in self.ticks.items() if not tick.value] - self.button.disabled = bool(left) - reasons = [f"tick the declaration of {', '.join(left)}"] if left else [] + """Enable the button once every mask type is answered as objects, saying what is left.""" + left = [t for t, choice in self.choices.items() if choice.value is None] + reasons = [f"choose what {', '.join(left)} is"] if left else [] + reasons += [ + BINARY_REFUSED.format(mask_type=t) + for t, choice in self.choices.items() + if choice.value == BINARY + ] + self.button.disabled = bool(reasons) self.blocker.value = blocked_line(reasons) def _stop(self, text: str) -> bool: @@ -304,54 +351,91 @@ def _stop(self, text: str) -> bool: return False def register(self) -> bool: - """Declare the ticked masks through the app, save, run and describe; True when done.""" + """Declare the masks through the app, save, run and describe; True when done. + + Each step is shown under the button while it goes (:class:`.RegisterWait`), and the + button is disabled meanwhile. + """ if self.button.disabled: return False - why = refusal(self.app, self.segmentation) + self.button.disabled = True + self.status.value = "" + try: + with RegisterWait(self.progress, self.progress_detail).running() as wait: + return self._register(wait) + finally: + self._update() + + def _register(self, wait: RegisterWait) -> bool: + """Do the steps of :meth:`register`, each named by ``wait``; True when done.""" + with wait.step("run"): + why = refusal(self.app, self.segmentation, checking=wait.checking) if why: return self._stop(why) + self._check_folders(wait) + app = self.app + if app.confirmed_mapping is None: + return self._stop(AXES_AGAIN) + why = _other_experiment(app, self.segmentation.workflow.inputs) + if why: # the axes stop lets the user change the app: check it is still the run's + return self._stop(why) + with wait.step("save"): + why = self._answer_masks() + if why: + return self._stop(why) + if not app.save_experiment(): + return self._stop(NOT_SAVED) + with wait.step("rerun", getattr(app, "run_status", None)): + result = app.run() + if result is None or not result.written: + return self._stop("The run of cell 3 stopped: its step Run says why.") + # Kept on cell 4's step: this publication is the registration's (cell 5 run again). + self.segmentation.registered_manifest = manifest_sha256(Path(result.output_folder)) + with wait.step("describe", getattr(app, "mask_step_status", None)): + app.mask_step_button.click() # the app's Describe the masks + self.registered = True + self.status.value = self._registered_html(result) + return True + + def _check_folders(self, wait: RegisterWait) -> None: + """Make the app's folder check with the masks folder, unless its last one has them.""" app, masks = self.app, Path(self.segmentation.workflow.masks_root).resolve() found = getattr(app.preflight, "masks", None) checked = getattr(found, "folder", None) if ( - checked is None - or Path(checked).resolve() != masks - or any(t not in found.types for t in self.ticks) # checked before cell 4 wrote + checked is not None + and Path(checked).resolve() == masks + and all(t in found.types for t in self.choices) # else checked before cell 4 wrote ): + return + with wait.step("folders", getattr(app, "folder_status", None)): app.masks_folder.value = os.fspath(masks) app.check_folder() # the app's Scan the folders, now with the masks folder - # Kept on cell 4's step, not this widget: cell 5 run again continues from here. - self.segmentation.rechecked_run = Path( - self.segmentation.workflow.inputs.output_folder - ).resolve() - if app.confirmed_mapping is None: - return self._stop(AXES_AGAIN) - why = _other_experiment(app, self.segmentation.workflow.inputs) - if why: # the axes stop lets the user change the app: check it is still the run's - return self._stop(why) - for mask_type in self.ticks: - question = app.mask_card.questions.get(mask_type) + # Kept on cell 4's step, not this widget: cell 5 run again continues from here. + self.segmentation.rechecked_run = Path( + self.segmentation.workflow.inputs.output_folder + ).resolve() + + def _answer_masks(self) -> str: + """Answer each mask on the app's *Masks* question as objects; return a refusal or "".""" + for mask_type in self.choices: + question = self.app.mask_card.questions.get(mask_type) if question is None: - return self._stop(f"The folder check of cell 3 found no {mask_type} masks.") + return f"The folder check of cell 3 found no {mask_type} masks." question.id_box.value = mask_type question.choice.value = INSTANCES if question.saved is None or question.saved[:2] != (mask_type, INSTANCES): - return self._stop(f"{mask_type}: {_plain(question.message.value)}") - if not app.save_experiment(): - return self._stop(NOT_SAVED) - result = app.run() - if result is None or not result.written: - return self._stop("The run of cell 3 stopped: its step Run says why.") - # Kept on cell 4's step: this publication is the registration's (cell 5 run again). - self.segmentation.registered_manifest = manifest_sha256(Path(result.output_folder)) - app.mask_step_button.click() # the app's Describe the masks - self.registered = True - self.status.value = ( + return f"{mask_type}: {_plain(question.message.value)}" + return "" + + def _registered_html(self, result: object) -> str: + """Return the card saying the masks are registered, with the app's mask step's.""" + return ( ui.status( "ok", "The masks are registered", [ - f"Declared: {', '.join(self.ticks)}; the run in {result.output_folder} now " + f"Declared: {', '.join(self.choices)}; the run in {result.output_folder} now " "records them and is ready for MorphoFeature.", f"Histograms reused for {len(result.unchanged)} images; images read again: " f"{len(result.read)}" @@ -359,9 +443,8 @@ def register(self) -> bool: + ".", ], ) - + app.mask_step_status.value + + self.app.mask_step_status.value ) - return True def _plain(text: str) -> str: @@ -374,4 +457,13 @@ def register_step(app: object, segmentation: object) -> MaskRegistration: return MaskRegistration(app, segmentation) -__all__ = ["MaskRegistration", "refusal", "register_step", "toml_section", "written_types"] +__all__ = [ + "BINARY_REFUSED", + "CHOICES", + "WHY_WE_ASK", + "MaskRegistration", + "refusal", + "register_step", + "toml_section", + "written_types", +] diff --git a/src/morphobricks_preprocessing/notebook_register_progress.py b/src/morphobricks_preprocessing/notebook_register_progress.py new file mode 100644 index 00000000..b037f3b8 --- /dev/null +++ b/src/morphobricks_preprocessing/notebook_register_progress.py @@ -0,0 +1,132 @@ +"""The wait shown while cell 5 registers the masks (owner Colab test, 26 Nov 2026, #574 item 7). + +**Register the masks** runs, one after another, the checks of the run cell 4 segmented and the +app's own steps: its folder check with the masks folder, its *Check and save*, its run and its +*Describe the masks*. In a ``verify_content`` run (the notebook's default) the run's checks read +every image whole for its SHA-256, the app's run reads every image and mask whole again for +theirs, and *Describe the masks* reads every mask; the app draws each wait in its own step, in +cell 3, far above cell 5, which showed nothing. :class:`RegisterWait` shows them in cell 5 with +the waits of #567 (:class:`.notebook_progress.Wait` and its ticking thread): one line +"Step k of N · " whose elapsed time goes on, and under it the step's own line: the run's +checks, counted here ("n of N" with the image read now), and the app's own wait line of the +folder check, the run and the mask step, copied as the app draws it. Nothing here reads a file +or decides anything. +""" + +from __future__ import annotations + +import html +import time +from collections.abc import Callable, Iterator +from contextlib import contextmanager + +import ipywidgets as widgets + +from .notebook_progress import Wait + +STEPS = { + "run": "Checking the run cell 4 segmented and its images", + "folders": "Checking the folders again with the masks folder", + "save": "Answering each mask and saving the description", + "rerun": "Running again (the histograms of unchanged images are reused)", + "describe": "Describing the masks", +} +"""The steps of **Register the masks**, in order; the folder check is made only when needed.""" +CHECKS = { + "run": "Reading the run's 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 files added since the run", +} +"""What the step line says in each phase of the run's checks (:data:`.open_checks.OPEN_PHASES`).""" +COUNTED = ("images", "contents", "masks") +"""The phases of the run's checks shown as done of total, each with its file.""" +TOOK = "Took {took}." +"""The line left once **Register the masks** ends, registered or refused (``{took}``: ``m:ss``).""" +STOPPED_AFTER = "Stopped after {took}." +"""The line left when an error or an interrupt went through it.""" + + +def step_label(key: str) -> str: + """Return the line of step ``key`` of :data:`STEPS`: ``"Step 2 of 5 · "``.""" + number = list(STEPS).index(key) + 1 + return f"Step {number} of {len(STEPS)} · {STEPS[key]}" + + +class RegisterWait: + """The wait of **Register the masks**: the step line, and the step's own line under it. + + Parameters + ---------- + line + The HTML widget of the step line (elapsed time of the whole press, ticking). + detail + The HTML widget of the step's own line (the run's checks, or the app's wait). + clock + Returns the time in seconds (monotonic); replaced in tests. + """ + + def __init__( + self, + line: widgets.HTML, + detail: widgets.HTML, + *, + clock: Callable[[], float] = time.monotonic, + ) -> None: + self.line, self.detail = line, detail + self.wait = Wait(line, bar=False, clock=clock) + self.checks = Wait(detail, clock=clock) + + @contextmanager + def running(self) -> Iterator[RegisterWait]: + """Show the wait while the block runs; then leave how long it took (or that it stopped).""" + self.wait.start(step_label("run")) + text = STOPPED_AFTER + try: + with self.wait.ticking(): + yield self + text = TOOK + finally: + self.detail.value = "" + took = html.escape(text.format(took=self.wait.took())) + self.line.value = f"
{took}
" + + @contextmanager + def step(self, key: str, shown: widgets.HTML | None = None) -> Iterator[None]: + """Name step ``key`` while the block runs; copy ``shown`` (the app's wait) under it. + + ``shown`` is the app's own status line of that step: each value the app draws there + while the block runs is drawn under the step line too, then the copy stops and the + line under it is emptied. + """ + if self.wait.label != step_label(key): + self.wait.phase(step_label(key)) + self.detail.value = "" + + def copy(change: dict) -> None: + self.detail.value = change["new"] + + if shown is not None: + shown.observe(copy, names="value") + try: + yield + finally: + if shown is not None: + shown.unobserve(copy, names="value") + self.detail.value = "" + + def checking(self, phase: str, done: int, total: int, path: str) -> None: + """Show the run's checks (``checking`` of :func:`.segmentation_cellpose_run.open_run`).""" + label = CHECKS[phase] + counted = phase in COUNTED + if self.checks.label != label: + if phase == "run" or not self.checks.label: # the first phase starts the clock + self.checks.start(label, total if counted else 0) + else: + self.checks.phase(label, total if counted else 0) + if counted: + self.checks.step(done, total, path) + + +__all__ = ["CHECKS", "COUNTED", "STEPS", "STOPPED_AFTER", "TOOK", "RegisterWait", "step_label"] 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_mask_register_progress.py b/tests/test_mask_register_progress.py new file mode 100644 index 00000000..9bbdcded --- /dev/null +++ b/tests/test_mask_register_progress.py @@ -0,0 +1,310 @@ +"""Cell 5's question and its wait (owner Colab test of 26 November 2026, issue #574 items 6-7). + +Item 6: "Declare Cells as separate objects" with a TOML preview was awkward. Each mask type is +now asked what it is, with no answer chosen: each object with its own number (a label image) or +foreground / background only (a binary mask); the TOML is folded under it. What is recorded, +and the refusal when nothing is chosen, are unchanged. + +Item 7: after **Register the masks** something ran for a long time with nothing in cell 5. It +reads, per image of a ``verify_content`` run, 4 whole files (the run's checks, then the app's +run, its check before it publishes and its tissue-mask step's opening, each for the content +SHA-256) and per mask 5 (the run, its check before publishing, the mask step's fingerprints +before and after, and the pixels); the app drew its waits in cell 3. Cell 5 now shows each step +with the waits of #567. What is read is unchanged: no check could read less without becoming +weaker (the reads per file are pinned here). +""" + +import os +from collections import Counter +from pathlib import Path + +import pytest + +from cellpose_stub import install +from channel_images import write_channels +from test_notebook_check_save import KINDS +from test_notebook_preprocessing_cellpose import ran_app, segment + +widgets = pytest.importorskip("ipywidgets") + +import builtins # noqa: E402 +import io # noqa: E402 + +import test_notebook_preprocessing_cellpose as cell_tests # noqa: E402 +from morphobricks_preprocessing import notebook_progress # noqa: E402 +from morphobricks_preprocessing.description_file import DESCRIPTION_FILENAME # noqa: E402 +from morphobricks_preprocessing.notebook_mask_register import ( # noqa: E402 + BINARY_REFUSED, + CHOICES, + WHY_WE_ASK, + refusal, + register_step, + toml_section, +) +from morphobricks_preprocessing.notebook_preprocessing_cellpose import ( # noqa: E402 + segmentation_step, +) +from morphobricks_preprocessing.notebook_register_progress import ( # noqa: E402 + CHECKS, + STOPPED_AFTER, + RegisterWait, + step_label, +) +from morphobricks_preprocessing.run_inputs import RunInputs # noqa: E402 + +pytestmark = pytest.mark.usefixtures("legacy_grid") + +SIDE = 256 +"""Images and masks large enough that reading a header is not reading the whole file.""" + + +@pytest.fixture +def stub(monkeypatch, tmp_path): + return install(monkeypatch, tmp_path) + + +@pytest.fixture +def larger(monkeypatch): + """Write the experiment of ``ran_app`` at :data:`SIDE` pixels.""" + + def add_folder(root, masks, folder, seed): + Path(masks).mkdir(parents=True, exist_ok=True) + write_channels(root / folder / "a.tif", ["DAPI", "Actin", "Ch3"], KINDS, seed, SIDE) + + monkeypatch.setattr(cell_tests, "add_folder", add_folder) + + +class Reads: + """Per file of the experiment and the masks folder: opens, and whole reads. + + A whole read is one opening of the file through which at least its size was read. + """ + + def __init__(self, base): + self.base = Path(base).resolve() + self.opens, self.whole = Counter(), Counter() + + def key(self, path): + where = Path(os.fspath(path)).resolve() + for folder in ("exp", "masks"): + if where.is_relative_to(self.base / folder): + return where.relative_to(self.base).as_posix() + return None + + +@pytest.fixture +def reads(monkeypatch, tmp_path): + """Count the reads with a patched opener (``builtins.open``, as tifffile and hashing use).""" + counted, real = Reads(tmp_path), builtins.open + + class Counting(io.BufferedReader): + def __init__(self, path, key): + super().__init__(io.FileIO(path, "rb")) + self.key, self.size, self.got = key, os.path.getsize(path), 0 + + def read(self, *args): + data = super().read(*args) + self.got += len(data) + return data + + def readinto(self, buffer): + n = super().readinto(buffer) + self.got += n or 0 + return n + + def close(self): + if not self.closed and self.got >= self.size > 0: + counted.whole[self.key] += 1 + super().close() + + def opener(file, mode="r", *args, **kwargs): + key = counted.key(file) if isinstance(file, (str, os.PathLike)) else None + if key is None: + return real(file, mode, *args, **kwargs) + counted.opens[key] += 1 + if mode in ("rb", "br") and not args and all(v is None for v in kwargs.values()): + return Counting(os.fspath(file), key) + return real(file, mode, *args, **kwargs) + + monkeypatch.setattr(builtins, "open", opener) + return counted + + +def segmented_app(tmp_path): + """Return the app and cell 4 after it segmented the app's run into ``tmp_path/masks``.""" + nb = ran_app(tmp_path) + step = segmentation_step(nb) + segment(step, tmp_path / "masks") + return nb, step + + +def answered(nb, step): + """Return cell 5 answered for Cells, after the axes stop of its first press.""" + registration = register_step(nb, step) + registration.choices["Cells"].value = "instances" + assert not registration.register() # the folder check asks for the axes again + nb.quick_confirm.click() + return registration + + +# item 6: the question -------------------------------------------------------------------------- + + +def test_each_mask_type_is_asked_what_it_is_with_no_answer_chosen(tmp_path, stub): + nb, step = segmented_app(tmp_path) + registration = register_step(nb, step) + choice = registration.choices["Cells"] + assert choice.value is None + assert [label for label, _ in CHOICES] == [ + "Each object has its own number (label image: every cell/nucleus is a separate object)", + "Foreground / background only (binary mask)", + ] + assert list(choice.options) == CHOICES + text = repr(registration.children) + assert WHY_WE_ASK in text.replace("\\'", "'") + assert "Declare Cells as separate objects" not in text + # The declaration is shown folded only. + section = toml_section("Cells").replace('"', """) + with_section = [w.value for w in _all_html(registration) if "[masks.Cells]" in w.value] + assert len(with_section) == 1 and with_section[0].startswith("
") + assert section in with_section[0] + + +def _all_html(widget): + """Yield every HTML widget inside ``widget``.""" + if isinstance(widget, widgets.HTML): + yield widget + for child in getattr(widget, "children", ()): + yield from _all_html(child) + + +def test_nothing_chosen_is_refused_as_before_and_nothing_is_declared(tmp_path, stub): + nb, step = segmented_app(tmp_path) + out = nb.result.output_folder + registration = register_step(nb, step) + assert registration.button.disabled and not registration.register() + assert "choose what Cells is" in registration.blocker.value + assert "[masks" not in (out / DESCRIPTION_FILENAME).read_text(encoding="utf-8") + assert registration.progress.value == "" # nothing ran + + +def test_a_binary_answer_is_refused_saying_why_and_nothing_is_declared(tmp_path, stub): + nb, step = segmented_app(tmp_path) + out = nb.result.output_folder + registration = register_step(nb, step) + registration.choices["Cells"].value = "binary" + assert registration.button.disabled and not registration.register() + text = BINARY_REFUSED.format(mask_type="Cells") + assert text.split(":")[0] in registration.blocker.value + assert "[masks" not in (out / DESCRIPTION_FILENAME).read_text(encoding="utf-8") + registration.choices["Cells"].value = "instances" + assert not registration.button.disabled and registration.blocker.value == "" + + +def test_the_recorded_declaration_is_unchanged(tmp_path, stub): + nb, step = segmented_app(tmp_path) + registration = answered(nb, step) + assert registration.register(), registration.status.value + text = (nb.result.output_folder / DESCRIPTION_FILENAME).read_text(encoding="utf-8") + assert '[masks.Cells]\nsource_type = "Cells"\nrepresentation = "instances"' in text + assert RunInputs.open(nb.result.output_folder).mask_types() == ("Cells",) + + +# item 7: what Register reads, and its wait ---------------------------------------------------- + + +def test_register_reads_each_file_as_many_times_as_before(tmp_path, stub, larger, reads): + # Measured on main before #574 with this opener; pinned so that showing the wait reads + # nothing more. Per image: the run's checks (cell 5), the app's run, its check before it + # publishes and the tissue-mask step's opening after it, each a content SHA-256. The two + # viewers Check and save redraws twice also read the first image, about 4 times its size in + # all, through openings that each read a part of it (not whole reads here). Per mask: + # the run and its check before publishing (SHA-256), the mask step's fingerprints before + # and after reading, and its pixels (the piece counts). + nb, step = segmented_app(tmp_path) + registration = answered(nb, step) + images = sorted(f"exp/{f.relative_path}" for f in step.workflow.inputs.fovs()) + masks = sorted(f"masks/Cells/{f.relative_path}" for f in step.workflow.inputs.fovs()) + assert len(images) == len(masks) == 4 + reads.opens.clear(), reads.whole.clear() + assert registration.register(), registration.status.value + first, *others = images + assert reads.whole == Counter({**dict.fromkeys(images, 4), **dict.fromkeys(masks, 5)}) + assert reads.opens == Counter( + {first: 21, **dict.fromkeys(others, 9), **dict.fromkeys(masks, 7)} + ) + + +def test_showing_cell_5_reads_each_image_whole_once(tmp_path, stub, larger, reads): + nb, step = segmented_app(tmp_path) + reads.opens.clear(), reads.whole.clear() + register_step(nb, step) + images = [f"exp/{f.relative_path}" for f in step.workflow.inputs.fovs()] + assert reads.whole == Counter(dict.fromkeys(images, 1)) == reads.opens + + +def test_register_names_each_step_counts_the_images_and_ticks(tmp_path, stub, monkeypatch): + nb, step = segmented_app(tmp_path) + registration = answered(nb, step) + 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) + lines, details = [], [] + registration.progress.observe(lambda c: lines.append(c["new"]), names="value") + registration.progress_detail.observe(lambda c: details.append(c["new"]), names="value") + names = [f.relative_path for f in step.workflow.inputs.fovs()] + assert registration.register(), registration.status.value + for label in (step_label(k) for k in ("run", "save", "rerun", "describe")): + assert any(label in line for line in lines), label + assert not any(step_label("folders") in line for line in lines) # made at the first press + hashed = [d for d in details if CHECKS["contents"] in d] + for done, name in enumerate(names): + assert any(f"{done} of 4" in d and name in d for d in hashed), name + assert any("Preparing:" in d for d in details) # the app's run's own wait, copied + assert any("Pairing the masks" in d for d in details) # the app's mask step's + assert ticking[0] is registration.progress # the timer thread of #567 redraws the line + assert "Took " in registration.progress.value and registration.progress_detail.value == "" + assert "The masks are registered" in registration.status.value + assert not registration.button.disabled # back once it ended + + +def test_the_first_press_shows_the_folder_check_of_the_app(tmp_path, stub): + nb, step = segmented_app(tmp_path) + registration = register_step(nb, step) + registration.choices["Cells"].value = "instances" + lines, details = [], [] + registration.progress.observe(lambda c: lines.append(c["new"]), names="value") + registration.progress_detail.observe(lambda c: details.append(c["new"]), names="value") + assert not registration.register() # the axes to confirm again + assert any(step_label("folders") in line for line in lines) + assert details and any(d for d in details) # the app's folder check, copied + assert "Took " in registration.progress.value + + +def test_the_run_checks_refuse_the_same_with_or_without_the_wait(tmp_path, stub): + nb, step = segmented_app(tmp_path) + image = tmp_path / "exp" / "ctrl" / "rep1" / "a.tif" + image.write_bytes(image.read_bytes()[:-1] + b"\x07") + told = [] + quiet = refusal(nb, step) + shown = refusal(nb, step, checking=lambda *args: told.append(args)) + assert quiet == shown and "The images changed since the run" in shown + assert told and told[0][0] == "run" + + +def test_the_wait_says_stopped_after_an_error_and_stops_copying(): + line, detail, source = widgets.HTML(), widgets.HTML(), widgets.HTML() + wait = RegisterWait(line, detail) + with pytest.raises(KeyboardInterrupt), wait.running(): + with wait.step("rerun", source): + source.value = "the app's line" + assert detail.value == "the app's line" + raise KeyboardInterrupt + assert STOPPED_AFTER.split("{")[0] in line.value and detail.value == "" + source.value = "later" + assert detail.value == "" # copied only while its step ran diff --git a/tests/test_notebook_preprocessing_cellpose.py b/tests/test_notebook_preprocessing_cellpose.py index c0a40ada..2bd26dcf 100644 --- a/tests/test_notebook_preprocessing_cellpose.py +++ b/tests/test_notebook_preprocessing_cellpose.py @@ -4,7 +4,7 @@ experiment; cell 4 (:func:`.notebook_preprocessing_cellpose.segmentation_step`) segments that run with the stand-in Cellpose of ``cellpose_stub.py`` (no GPU, no download) and cell 5 (:func:`.notebook_mask_register.register_step`) offers the declarations and registers them -through the app's own steps once the user ticked them. +through the app's own steps once the user answered what each mask is. """ import json @@ -218,19 +218,19 @@ def test_preprocessing_alone_never_imports_cellpose_or_torch(): # cell 5 --------------------------------------------------------------------------------------- -def test_cell_5_offers_the_declaration_and_registers_only_after_the_tick(tmp_path, stub): +def test_cell_5_asks_what_each_mask_is_and_registers_only_once_answered(tmp_path, stub): nb = ran_app(tmp_path) out = nb.result.output_folder step = segmentation_step(nb) segment(step, tmp_path / "masks") registration = register_step(nb, step) - assert list(registration.ticks) == ["Cells"] + assert list(registration.choices) == ["Cells"] section = toml_section("Cells") assert section == '[masks.Cells]\nsource_type = "Cells"\nrepresentation = "instances"' assert "[masks.Cells]" in repr(registration.children) assert registration.button.disabled and not registration.register() # nothing silent assert "[masks" not in (out / DESCRIPTION_FILENAME).read_text(encoding="utf-8") - registration.ticks["Cells"].value = True + registration.choices["Cells"].value = "instances" # The app's folder check with the masks folder asks for the axes again: the user's click. assert not registration.register() assert AXES_AGAIN.split(":")[0] in registration.status.value @@ -256,8 +256,8 @@ def test_cell_5_registers_masks_written_into_the_runs_own_masks_folder(tmp_path, assert step.masks_folder == str((tmp_path / "masks").resolve()) segment(step) # into the prefilled masks folder registration = register_step(nb, step) - assert list(registration.ticks) == ["Cells"], registration.status.value - registration.ticks["Cells"].value = True + assert list(registration.choices) == ["Cells"], registration.status.value + registration.choices["Cells"].value = "instances" assert not registration.register() # the folder check is made again: axes to confirm assert AXES_AGAIN.split(":")[0] in registration.status.value nb.quick_confirm.click() @@ -273,7 +273,7 @@ def stopped_for_the_axes(tmp_path, stub): step = segmentation_step(nb) segment(step, tmp_path / "masks") registration = register_step(nb, step) - registration.ticks["Cells"].value = True + registration.choices["Cells"].value = "instances" assert not registration.register() assert AXES_AGAIN.split(":")[0] in registration.status.value return nb, registration, nb._output_path(tmp_path / "exp") @@ -288,8 +288,8 @@ def test_cell_5_run_again_after_the_axes_stop_continues(tmp_path, stub): nb, registration, out = stopped_for_the_axes(tmp_path, stub) nb.quick_confirm.click() again = register_step(nb, registration.segmentation) # cell 5 run again - assert list(again.ticks) == ["Cells"], again.status.value - again.ticks["Cells"].value = True + assert list(again.choices) == ["Cells"], again.status.value + again.choices["Cells"].value = "instances" assert again.register(), again.status.value assert RunInputs.open(out).mask_types() == ("Cells",) @@ -339,7 +339,7 @@ def segmented(tmp_path, nb, masks, mask_type="Cells"): def refused(registration): - assert registration.ticks == {} + assert registration.choices == {} return registration.status.value.replace("'", "'") @@ -428,4 +428,4 @@ def test_cell_5_run_again_after_it_registered_the_masks_is_not_refused(tmp_path, nb.quick_confirm.click() assert registration.register(), registration.status.value again = register_step(nb, registration.segmentation) - assert list(again.ticks) == ["Cells"], again.status.value + assert list(again.choices) == ["Cells"], again.status.value From 1d43cd3d2af2bbf300e2af94e3887e86605b364f Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 11:52:16 +0000 Subject: [PATCH 04/10] Cellpose Preview: also clear it when the channels or the model fields change Review of #576: the channel dropdowns are live (Preview and Segment re-read them with current_targets()), but changing them after a Preview left the result on screen and in `previewed`; with a Both preview shown, removing the nuclear channel kept "Nuclei" on screen. The same was true of the model step's fields, which Preview and Segment also read when pressed. The preview is now also cleared when a channel dropdown, a channel number or By tag/number changes (ChannelPicker.on_edit; Segment's line then says "not previewed yet"), when a field of the model step changes (Segment's line still names what changed since the last Preview), and in the cell-by-cell workflow when the settings change, a model is loaded or the nuclei go back to the cells' model. The style sheet is shown once even when the first Preview fails (it was keyed on a card having been shown). figure_image's docstring: one period. Regression tests: tests/test_notebook_cellpose_preview_stale.py (5 new). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WX6rdMV1r5jUPUR94kxV5a --- CHANGELOG.md | 2 +- .../notebook_cellpose.py | 32 ++++++++-- .../notebook_cellpose_channels.py | 9 +++ .../notebook_cellpose_form.py | 12 +++- .../notebook_cellpose_preview.py | 2 +- tests/test_notebook_cellpose_preview_stale.py | 60 +++++++++++++++++++ 6 files changed, 108 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c7ab0576..fde1758b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,7 +8,7 @@ v0.5.1: no run before v0.5.1 is read.) ## Unreleased -- **Cellpose Preview shows only its own result (owner's Colab test of v0.9.0, 26 November 2026).** Some nuclei results of the first Preview stayed on screen after later ones. The result (the card and the figures) was displayed into the step's output area, and its clearing was left to the frontend; a Preview that failed (Cellpose, or the model's load) also kept the earlier result in `previewed` and the Segment step's line still compared with it. The result is now held by one box of widgets (`CellposeWorkflow.preview_box`, the figures as PNG pictures), emptied when Preview is pressed (before the model is loaded), when the channels or output change, and when a Preview fails. While Cellpose runs, the box says "Running on the preview image…". Nothing is written or recorded by a Preview, as before. `tests/test_notebook_cellpose_preview_stale.py`. +- **Cellpose Preview shows only its own result (owner's Colab test of v0.9.0, 26 November 2026).** Some nuclei results of the first Preview stayed on screen after later ones. The result (the card and the figures) was displayed into the step's output area, and its clearing was left to the frontend; a Preview that failed (Cellpose, or the model's load) also kept the earlier result in `previewed` and the Segment step's line still compared with it. The result is now held by one box of widgets (`CellposeWorkflow.preview_box`, the figures as PNG pictures), emptied when Preview is pressed (before the model is loaded); when the output or a mask type changes; when a channel dropdown, a channel number or By tag/number changes (Preview and Segment re-read them; Segment's line then says "not previewed yet"); when a field of the model step changes (model, device, diameter, thresholds, batch size, the nuclei's own model; Segment's line still names what changed since the last Preview); when a model is loaded; and when a Preview fails. The example image dropdown does not clear it: the result names its image. While Cellpose runs, the box says "Running on the preview image…". Nothing is written or recorded by a Preview, as before. `tests/test_notebook_cellpose_preview_stale.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. - **Earlier work that does not record its experiment folder no longer leaves the stepper at a dead end (owner's Colab test of v0.9.0 at ca3b3c6).** An output folder holding only saved answers (here an older version's `morphobricks.draft.json`) showed *"The experiment folder it is of is not recorded … Enter the experiment folder and click Check folder"*: the stepper has no *Check folder* button (its check, *Looks right: read all image headers*, stays disabled until **Scan the folders**), and entering the folder showed the same message again, with no scan and no picture. Now the experiment folder entered is scanned at once on the stepper (folder walk and one picture; nothing is written), the message names the stepper's own buttons, and the check, on the user's click, reads the saved answers as always. Saved answers written by another version of the software (`DraftFileError` `unknown_version`, `unknown_key` or `spec_commit_mismatch`; the owner's file is format 3, `unknown_version`) are not earlier work (`EarlierWork.old_answers`): one line says they are not used and the file is left as it is, and the experiment folder entered is scanned and shown as above (an early **Scan the folders** click, before the typed folder reached the kernel, is made good when it arrives). The same scan follows a record and a run that name different folders. Each message names the buttons of the layout shown (the stacked pages say **Check folder**). Tests: `tests/test_notebook_restore.py`. - **A saved repeat order is never replaced by an abandoned *Yes* (review of #546 at e40f1ad).** On a reopened per-repeat draft, picking *Yes*, filling its row with rep1's order and going back to *No, per repeat folder* showed rep1's order in every repeat row, under "Pre-answered from your saved tags", and one Submit published it for every unit. A row's own saved tags now rank above a broader choice of the session (`channel_scope.seed`: the row's choice, its saved tags, a broader choice, the header names), and the "Pre-answered" note goes at the first change of the answer or of a row. Tests: `tests/test_notebook_channel_guide_reopen.py`, `tests/test_channel_scope.py`. diff --git a/src/morphobricks_preprocessing/notebook_cellpose.py b/src/morphobricks_preprocessing/notebook_cellpose.py index 2f80bcfa..e8dab93c 100644 --- a/src/morphobricks_preprocessing/notebook_cellpose.py +++ b/src/morphobricks_preprocessing/notebook_cellpose.py @@ -119,14 +119,14 @@ def __init__(self) -> None: self.previewed: list[MaskResult] = [] self.preview_box = widgets.VBox() # the last Preview's result, and nothing else self.shown: list[str] = [] + self.styled = False # the style sheet is shown (once, by the first step or Preview) self.on_masks_written: Callable[[cp.BatchResult], object] | None = None self.register_with: str | None = None self.folders_refused = "" # the masks folder refusal of the last Open the run, or "" def _show(self, widget: widgets.Widget) -> None: """Display ``widget`` (the style sheet goes first, once).""" - if not self.shown: - display(widgets.HTML(STYLE_CSS)) + self._style() self.shown.append(getattr(widget, "value", "")) display(widget) @@ -150,6 +150,10 @@ def drop_choice(self) -> None: self.mask_types = {} self.clear_preview() # a preview of other channels says nothing of the next ones + def channels_edited(self) -> None: + """Take the preview off: a channel dropdown or number changed (Preview re-reads them).""" + self.clear_preview() + def clear_preview(self) -> None: """Take the last Preview's result off the screen and out of :attr:`previewed`.""" self.previewed = [] @@ -159,10 +163,15 @@ def clear_preview(self) -> None: def _mount_preview(self) -> None: """Show :attr:`preview_box` in the cell that previews (a form shows it on its page).""" - if not self.shown: - display(widgets.HTML(STYLE_CSS)) + self._style() display(self.preview_box) + def _style(self) -> None: + """Display the style sheet, the first time only.""" + if not self.styled: + self.styled = True + display(widgets.HTML(STYLE_CSS)) + def model_for(self, output: str) -> tuple[cp.LoadedModel, cp.Settings]: """Return the model and the settings that segment the masks of ``output``. @@ -252,6 +261,7 @@ def choose_channels( self.drop_choice() self.mask_types, self.mask_type = types, next(iter(types.values())) self.picker = ChannelPicker(self.inputs, output) + self.picker.on_edit(self.channels_edited) # the dropdowns are live: Preview re-reads them lines = tuple( f"{OUTPUT_NAMES[o]}, mask type {t}: {len(todo[o])} of {len(self.inputs.fovs())} " "images have no mask yet" @@ -273,7 +283,10 @@ def set_settings( Normalisation is not a choice: it is always Cellpose's own, per image (1st to 99th percentile of each channel). """ - self.settings = _settings(diameter, flow_threshold, cellprob_threshold, batch_size) + settings = _settings(diameter, flow_threshold, cellprob_threshold, batch_size) + if settings != self.settings: # a preview with other settings is taken off + self.clear_preview() + self.settings = settings @stops def set_nuclei_settings( @@ -285,7 +298,10 @@ def set_nuclei_settings( ) -> None: """Check the settings of a separate nuclei model (output Both, cell 5's Advanced).""" self._need_both() - self.nuclei_settings = _settings(diameter, flow_threshold, cellprob_threshold, batch_size) + settings = _settings(diameter, flow_threshold, cellprob_threshold, batch_size) + if settings != self.nuclei_settings: # a preview with other settings is taken off + self.clear_preview() + self.nuclei_settings = settings @stops def load( @@ -302,6 +318,7 @@ def load( if self.settings is None: raise SegmentationError("Set the settings first: press Load the model.") self.loaded = None + self.clear_preview() # a preview of the model loaded before is taken off self.loaded = self._load_model( model, custom_model_file, device, download_weights, install_dino, self.settings ) @@ -323,6 +340,7 @@ def load_nuclei( "step)." ) self.nuclei_loaded = None + self.clear_preview() # a preview of the nuclei model loaded before is taken off self.nuclei_loaded = self._load_model( model, custom_model_file, device, download_weights, install_dino, self.nuclei_settings ) @@ -339,6 +357,8 @@ def _need_both(self) -> None: def same_model_for_nuclei(self) -> None: """Segment the nuclei of Both with the model and the settings of the cells.""" + if self.nuclei_loaded is not None or self.nuclei_settings is not None: + self.clear_preview() # a preview of the nuclei's own model is taken off self.nuclei_loaded = self.nuclei_settings = None def _load_model( diff --git a/src/morphobricks_preprocessing/notebook_cellpose_channels.py b/src/morphobricks_preprocessing/notebook_cellpose_channels.py index 8a9ffb9d..053a6e76 100644 --- a/src/morphobricks_preprocessing/notebook_cellpose_channels.py +++ b/src/morphobricks_preprocessing/notebook_cellpose_channels.py @@ -9,6 +9,7 @@ from __future__ import annotations import html +from collections.abc import Callable from dataclasses import dataclass import ipywidgets as widgets @@ -205,6 +206,14 @@ def current_plan(self) -> SegmentationPlan: """ return self.current_targets()[0].plan + def on_edit(self, callback: Callable[[], object]) -> None: + """Call ``callback`` whenever a dropdown, a channel number or the By choice changes. + + Not when a step re-reads the choice (:meth:`current_targets`): only an edit. + """ + for field in (*self.dropdowns, *self.number_fields, self.by): + field.observe(lambda _: callback(), names="value") + def current_targets(self) -> tuple[MaskTarget, ...]: """Resolve the dropdowns as they are now and return every mask to make, or refuse. diff --git a/src/morphobricks_preprocessing/notebook_cellpose_form.py b/src/morphobricks_preprocessing/notebook_cellpose_form.py index e9bdb37b..5c1f22c1 100644 --- a/src/morphobricks_preprocessing/notebook_cellpose_form.py +++ b/src/morphobricks_preprocessing/notebook_cellpose_form.py @@ -293,6 +293,12 @@ def _drop_choice(self, fields: dict[str, widgets.Widget], changed: widgets.HTML) "warn", f"Changed: press Choose the channels again, then {then}." ) + def channels_edited(self) -> None: + """Take the preview off; Segment's line no longer says it used these channels.""" + super().channels_edited() + self._previewed_with = None + self._refresh_summary() + def drop_choice(self) -> None: """Forget the channels, the mask types and every loaded model (the choice changed).""" super().drop_choice() @@ -460,7 +466,11 @@ def _preview_and_note(self, image: str) -> None: self._refresh_summary() def _model_fields_changed(self) -> None: - """Update what shows the model form's values: Segment's line and the step strip.""" + """Take the preview off (Preview and Segment read these fields), then update the line. + + What the last Preview used is kept: Segment's line still says what changed since. + """ + self.clear_preview() self._refresh_summary() for callback in self.on_change: callback() diff --git a/src/morphobricks_preprocessing/notebook_cellpose_preview.py b/src/morphobricks_preprocessing/notebook_cellpose_preview.py index 0c18d881..3a39533e 100644 --- a/src/morphobricks_preprocessing/notebook_cellpose_preview.py +++ b/src/morphobricks_preprocessing/notebook_cellpose_preview.py @@ -100,7 +100,7 @@ def preview_figures(results: list[MaskResult]) -> list[Figure]: def figure_image(figure: Figure) -> widgets.Image: - """Return ``figure`` as a PNG picture widget, at most 99% of its box wide..""" + """Return ``figure`` as a PNG picture widget, at most 99% of its box wide.""" buffer = io.BytesIO() figure.savefig(buffer, format="png", bbox_inches="tight") layout = widgets.Layout(max_width="99%", height="auto") diff --git a/tests/test_notebook_cellpose_preview_stale.py b/tests/test_notebook_cellpose_preview_stale.py index fd99b877..b006149f 100644 --- a/tests/test_notebook_cellpose_preview_stale.py +++ b/tests/test_notebook_cellpose_preview_stale.py @@ -15,6 +15,7 @@ from cellpose_stub import install, two_channel_run from morphobricks_preprocessing.notebook_cellpose_app import segmentation_app +from morphobricks_preprocessing.notebook_cellpose_channels import BY_NUMBER from morphobricks_preprocessing.segmentation_record import record_path @@ -156,3 +157,62 @@ def test_previews_write_nothing(run, stub): assert snapshot(run.masks) == before assert app.workflow.results == {} and app.workflow.result is None assert all(not record_path(run.masks, t).exists() for t in ("Cells", "Nuclei")) + + +# Review of #576: the channel dropdowns are live (Preview and Segment re-read them), and so are +# the model step's fields; any change takes the preview off, as a change of output does. + + +def test_removing_the_nuclear_channel_takes_the_preview_of_both_off(run, stub): + app = both_previewed(run) + workflow = app.workflow + workflow.picker.nuclear.value = "" + assert workflow.previewed == [] + assert workflow.preview_box.children == () + assert "Nuclei" not in texts(app.stepper.pages[2]) + assert "not previewed yet" in workflow._summary.value + + +def test_changing_the_cell_channel_takes_the_preview_off(run, stub): + app = both_previewed(run) + workflow = app.workflow + workflow.picker.cell.value = "DNA" + assert workflow.previewed == [] + assert workflow.preview_box.children == () + assert "not previewed yet" in workflow._summary.value + workflow.picker.cell.value = "TUB" + press_preview(app) # a new Preview shows its own result again + assert [r.name for r in workflow.previewed] == ["Cell mask", "Nuclei mask"] + + +def test_a_channel_number_takes_the_preview_off(run, stub): + app = both_previewed(run) + workflow = app.workflow + workflow.picker.by.value = BY_NUMBER + assert workflow.previewed == [] and workflow.preview_box.children == () + + +def test_changing_a_model_setting_takes_the_preview_off_and_names_the_change(run, stub): + app = both_previewed(run) + workflow = app.workflow + workflow.forms["model"].fields["diameter"].value = "17" + assert workflow.previewed == [] + assert workflow.preview_box.children == () + assert "Changed since the last Preview" in workflow._summary.value + + +def test_the_style_sheet_is_shown_once_after_a_failed_first_preview(run, stub, monkeypatch): + from morphobricks_preprocessing import notebook_cellpose + from morphobricks_preprocessing.notebook_style import STYLE_CSS + + sheets = [] + monkeypatch.setattr( + notebook_cellpose, + "display", + lambda w: sheets.append(w) if getattr(w, "value", None) == STYLE_CSS else None, + ) + workflow = notebook_cellpose.CellposeWorkflow() + workflow._mount_preview() # a first Preview, refused: no card shown + workflow._mount_preview() + workflow._show(widgets.HTML("a card")) + assert len(sheets) == 1 From acfc4d5da1d1020aab0aa32dbec45946d997372c Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 15:23:46 +0000 Subject: [PATCH 05/10] Republished-run test: patch open_checked, as #575 does (identical hunk) open_run now opens through run_inputs.open_checked (the hunks shared with #575), so the test that publishes the run while it is opened patches that function instead of RunInputs.open. Same change, byte for byte, as #575's. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WX6rdMV1r5jUPUR94kxV5a --- tests/test_notebook_cellpose_republished.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) 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) From ae64ecc82900bb4ca803ace65d9a90b9d69f815f Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 15:31:34 +0000 Subject: [PATCH 06/10] Cellpose weights: check the file's identity around the load; write errors (review of #577) - The weights file's identity (device, inode, size, mtime_ns) taken when it is hashed must be unchanged right before Cellpose opens it and after it loaded it (also for a model file of one's own), else the load is refused: a file gone in between would make Cellpose fetch a model from its moving branch with TLS off while the record carried the pinned hash. - A local write error (a full disk) is a write refusal naming the folder, not a network one; a failed rename is a SegmentationError naming the target; the download is fsynced before the rename. - Tests: the identity checks (removed, replaced, gone before the load, own file), the sparse filter put back when Cellpose raises, the full disk, the failed rename and fsync before rename. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WX6rdMV1r5jUPUR94kxV5a --- CHANGELOG.md | 2 +- docs/contract.md | 6 +- .../segmentation_cellpose_model.py | 31 +++- .../segmentation_cellpose_weights.py | 137 ++++++++++++++---- tests/cellpose_stub.py | 3 + tests/test_segmentation_cellpose_weights.py | 133 +++++++++++++++++ 6 files changed, 276 insertions(+), 36 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 29f408d4..2073ff78 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,7 +8,7 @@ v0.5.1: no run before v0.5.1 is read.) ## Unreleased -- **Cellpose: no download ticks; the chosen model's weights download on first use, pinned and checked (v0.9.1, #574 item 3; owner decision of 26 November 2026).** Choosing the model and pressing **Preview** or **Segment** (or **Load the model** in the Cellpose notebook) is now the consent to download its weights: the "Allow the weights download from Hugging Face" and "Install DINOv3 now" ticks are removed from the model form (both notebooks share it). Cellpose no longer downloads anything itself: the new `segmentation_cellpose_weights.fetch_weights` downloads only the chosen model's file from `mouseland/cellpose-sam` at the pinned commit `WEIGHTS_REVISION` (`7c61431b5fbb`, not Cellpose's moving `main`, and with TLS verification, which Cellpose's own download turns off), through a temporary file kept only with the pinned size and SHA-256 (`PINNED_WEIGHTS`, as Hugging Face lists them at that commit), then hands Cellpose the absolute path. A copy already in Cellpose's model folder is hashed and must match the pin; one that differs is refused, not used and not replaced. A failed or blocked download, or bytes that do not match, is a refusal naming the model and the URL; nothing partial is kept and no other model is used. The notebook shows a "Downloading weights…" line with the megabytes received, a bar and the elapsed time (`notebook_cellpose_download.DownloadLine`), then how long it took; Cellpose's `tqdm` bar is no longer patched (`BAR_LABEL` and `notebook_bar` are removed). DINOv3, the code of the `cpdino` networks (their weights are all in the Cellpose file), is installed at its pinned commit on a `cpdino` model's first load when no DINOv3 is installed (`ensure_dinov3`, before Cellpose is imported); a DINOv3 of another commit is refused, not replaced. The check that Cellpose imported DINOv3 now looks at `cellpose.vit` (Cellpose 4.2.1.1 defines `CPDINO` whether or not DINOv3 imports, so the former `hasattr(models, "CPDINO")` check could not fail). The record's `parameters` add `weights_repository`, `weights_revision`, `dinov3_source` and `dinov3_installed`; `weights_source` is the pinned URL. **API change:** `load_model(model, device, *, progress=None)` (no `allow_download`), `CellposeWorkflow.load` and `load_nuclei` take `(model, custom_model_file, device)`, `LoadedModel` gains `repository`, `revision` and `dinov3_installed`. `normalization`, `eval_arguments` and `inference_parameters` moved, unchanged apart from the new fields, to `segmentation_cellpose_eval` (re-exported by `segmentation_cellpose`) to keep the file under the 600-line rule. `tests/test_segmentation_cellpose_weights.py`; nothing is downloaded in the tests. +- **Cellpose: no download ticks; the chosen model's weights download on first use, pinned and checked (v0.9.1, #574 item 3; owner decision of 26 November 2026).** Choosing the model and pressing **Preview** or **Segment** (or **Load the model** in the Cellpose notebook) is now the consent to download its weights: the "Allow the weights download from Hugging Face" and "Install DINOv3 now" ticks are removed from the model form (both notebooks share it). Cellpose no longer downloads anything itself: the new `segmentation_cellpose_weights.fetch_weights` downloads only the chosen model's file from `mouseland/cellpose-sam` at the pinned commit `WEIGHTS_REVISION` (`7c61431b5fbb`, not Cellpose's moving `main`, and with TLS verification, which Cellpose's own download turns off), through a temporary file kept only with the pinned size and SHA-256 (`PINNED_WEIGHTS`, as Hugging Face lists them at that commit), then hands Cellpose the absolute path. A copy already in Cellpose's model folder is hashed and must match the pin; one that differs is refused, not used and not replaced. The file's identity (device, inode, size, modification time) taken when it is hashed must be unchanged right before Cellpose opens it and after Cellpose loaded it (also for a model file of one's own), else the load is refused: a file gone in between would make Cellpose fetch a model from its moving branch with TLS off while the record carried the pinned hash (review of #577). The download is fsynced before the rename; a local write error (a full disk) is refused as a write error naming the folder, not as a network problem, and a failed rename names the target. A failed or blocked download, or bytes that do not match, is a refusal naming the model and the URL; nothing partial is kept and no other model is used. The notebook shows a "Downloading weights…" line with the megabytes received, a bar and the elapsed time (`notebook_cellpose_download.DownloadLine`), then how long it took; Cellpose's `tqdm` bar is no longer patched (`BAR_LABEL` and `notebook_bar` are removed). DINOv3, the code of the `cpdino` networks (their weights are all in the Cellpose file), is installed at its pinned commit on a `cpdino` model's first load when no DINOv3 is installed (`ensure_dinov3`, before Cellpose is imported); a DINOv3 of another commit is refused, not replaced. The check that Cellpose imported DINOv3 now looks at `cellpose.vit` (Cellpose 4.2.1.1 defines `CPDINO` whether or not DINOv3 imports, so the former `hasattr(models, "CPDINO")` check could not fail). The record's `parameters` add `weights_repository`, `weights_revision`, `dinov3_source` and `dinov3_installed`; `weights_source` is the pinned URL. **API change:** `load_model(model, device, *, progress=None)` (no `allow_download`), `CellposeWorkflow.load` and `load_nuclei` take `(model, custom_model_file, device)`, `LoadedModel` gains `repository`, `revision` and `dinov3_installed`. `normalization`, `eval_arguments` and `inference_parameters` moved, unchanged apart from the new fields, to `segmentation_cellpose_eval` (re-exported by `segmentation_cellpose`) to keep the file under the 600-line rule. `tests/test_segmentation_cellpose_weights.py`; nothing is downloaded in the tests. - **Cellpose: torch's "Sparse invariant checks are implicitly disabled" warning is hidden while Cellpose runs (v0.9.1, #574 item 5).** Cellpose's `dynamics.py` builds a sparse tensor and torch warns each session. `segmentation_cellpose.evaluate` now runs `model.eval` inside `segmentation_cellpose_model.sparse_warning_hidden()`, which filters only that `UserWarning`, by its message's start (`SPARSE_WARNING`), from the `torch` or `cellpose` modules, inside `warnings.catch_warnings()` (no global filter; every other warning is shown). The checks it is about only validate sparse tensors and do not change results, so nothing is recorded. `tests/test_segmentation_cellpose_weights.py`. - **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/docs/contract.md b/docs/contract.md index c4ab3a64..e423eed4 100644 --- a/docs/contract.md +++ b/docs/contract.md @@ -1404,8 +1404,10 @@ downloaded by Cellpose: choosing a built-in model and loading it is the consent model's file (owner, #574), which `segmentation_cellpose_weights` fetches from `mouseland/cellpose-sam` at a pinned commit (`WEIGHTS_REVISION`) and accepts only with its pinned size and SHA-256 (`PINNED_WEIGHTS`); a copy already in Cellpose's model folder must match -too, else it is refused and left as it is. A failed or blocked download is a refusal naming the -model and the URL; nothing partial is kept and no other model is used. Cellpose is then given +too, else it is refused and left as it is; the file's identity (device, inode, size, modification +time) taken when it is hashed must be unchanged right before and after Cellpose loads it, else +the load is refused. A failed or blocked download is a refusal naming the +model and the URL (a local write error names the folder instead); nothing partial is kept and no other model is used. Cellpose is then given the file's absolute path. While `model.eval` runs, torch's `UserWarning` starting "Sparse invariant checks are implicitly disabled" from the `torch` or `cellpose` modules is filtered (`warnings.catch_warnings`, never a global filter); it does not affect results. More than diff --git a/src/morphobricks_preprocessing/segmentation_cellpose_model.py b/src/morphobricks_preprocessing/segmentation_cellpose_model.py index 6b625fa8..d431ebee 100644 --- a/src/morphobricks_preprocessing/segmentation_cellpose_model.py +++ b/src/morphobricks_preprocessing/segmentation_cellpose_model.py @@ -45,7 +45,9 @@ WEIGHTS_REPOSITORY, WEIGHTS_REVISION, Progress, + changed_refusal, fetch_weights, + file_identity, ) from .segmentation_record import DEVICES, SegmentationError @@ -472,6 +474,14 @@ def _verify(loaded: object, expected: Path, device: str, choice: ModelChoice) -> ) +def _identity(path: Path) -> tuple[int, int, int, int] | None: + """Return the weights file's :func:`.segmentation_cellpose_weights.file_identity`, or None.""" + try: + return file_identity(path) + except OSError: + return None + + def load_model( model: str | os.PathLike, device: str, *, progress: Progress | None = None ) -> LoadedModel: @@ -483,8 +493,12 @@ def load_model( SHA-256 (:func:`.segmentation_cellpose_weights.fetch_weights`); a DINOv3 model needs the pinned DINOv3; then the model is loaded from that file's absolute path and **verified** (the weights file it reports is the one asked for; every parameter and buffer of the - network sits on the stated device type). Choosing the model and calling this is the - consent to those downloads; nothing else is fetched and no other model is used. + network sits on the stated device type). The file's identity (device, inode, size, + modification time) taken when it was hashed must be the same right before Cellpose opens it + and after Cellpose loaded it (and, for a model file of one's own, after it was hashed): + Cellpose would download ``cpsam_v2`` from its moving branch for a path that is gone, and a + file replaced in between is not the one recorded. Choosing the model and calling this is + the consent to those downloads; nothing else is fetched and no other model is used. Parameters ---------- @@ -496,7 +510,8 @@ def load_model( SegmentationError For an unknown model or one that does not exist, a device that is not available or not the one the model sits on, a substituted model, weights that cannot be downloaded - or are not the pinned file, another Cellpose version or another DINOv3 commit. + or are not the pinned file, a weights file that changed after it was checked, another + Cellpose version or another DINOv3 commit. """ choice = choose_model(model) check_device(device) @@ -507,11 +522,17 @@ def load_model( commit = check_dinov3(models) if dino else None if choice.path is not None: expected, weights = choice.path, None + identity = _identity(expected) else: weights = fetch_weights(choice.name, os.fspath(models.MODEL_DIR), progress) - expected = weights.path + expected, identity = weights.path, weights.identity + if _identity(expected) != identity: # gone now: Cellpose would download cpsam_v2 instead + raise changed_refusal(expected) loaded = _construct(models, os.fspath(expected), device) _verify(loaded, expected, device, choice) + sha256 = file_sha256(expected) if weights is None else weights.sha256 + if _identity(expected) != identity: # the file Cellpose read may not be the one hashed + raise changed_refusal(expected) backbone = getattr(loaded, "backbone", None) if not isinstance(backbone, str): raise SegmentationError("The loaded model does not say which network it is; refused.") @@ -522,7 +543,7 @@ def load_model( name=choice.name, file=os.fspath(expected) if choice.path else expected.name, path=expected, - sha256=file_sha256(expected) if weights is None else weights.sha256, + sha256=sha256, device=device, backbone=backbone, tile_size=SAM_TILE if backbone == "sam_vitl" else DINO_TILE, diff --git a/src/morphobricks_preprocessing/segmentation_cellpose_weights.py b/src/morphobricks_preprocessing/segmentation_cellpose_weights.py index e8914518..ebc44c9e 100644 --- a/src/morphobricks_preprocessing/segmentation_cellpose_weights.py +++ b/src/morphobricks_preprocessing/segmentation_cellpose_weights.py @@ -98,6 +98,8 @@ class WeightsFile: :data:`WEIGHTS_REPOSITORY` and :data:`WEIGHTS_REVISION`. downloaded True when this call downloaded it; False when the copy on disk was used. + identity + The file's :func:`file_identity` when it was hashed (checked again after loading). """ name: str @@ -107,6 +109,7 @@ class WeightsFile: repository: str = WEIGHTS_REPOSITORY revision: str = WEIGHTS_REVISION downloaded: bool = False + identity: tuple[int, int, int, int] | None = None def weights_url(name: str) -> str: @@ -144,6 +147,22 @@ def _refusal(name: str, url: str, why: str) -> SegmentationError: ) +def file_identity(path: str | os.PathLike) -> tuple[int, int, int, int]: + """Return a file's identity now: its device, inode, size and modification time (ns). + + Taken when the file is hashed and compared after Cellpose loads it + (:func:`.segmentation_cellpose_model.load_model`): a file replaced, removed or written to + in between is another file than the one hashed. + + Raises + ------ + OSError + When the file cannot be read (it is gone, say). + """ + found = os.stat(path) + return (found.st_dev, found.st_ino, found.st_size, found.st_mtime_ns) + + def fetch_weights( name: str, model_dir: str | os.PathLike, progress: Progress | None = None ) -> WeightsFile: @@ -162,12 +181,14 @@ def fetch_weights( Raises ------ SegmentationError - For a copy on disk that is not the pinned file, a download that fails or is blocked, - or bytes that are not the pinned size and SHA-256. Each names the model and the source. + For a copy on disk that is not the pinned file (or changed while it was hashed), a + download that fails or is blocked, bytes that are not the pinned size and SHA-256 (each + names the model and the source), or a file that cannot be written (it names the folder). """ pin, url = _pinned(name), weights_url(name) target = Path(model_dir) / name if target.is_file(): + before = file_identity(target) found = file_sha256(target) if found != pin.sha256: raise SegmentationError( @@ -176,41 +197,42 @@ def fetch_weights( "replaced. Delete that file (or move it away), then press the button again to " "download the pinned weights." ) - return WeightsFile(name, target, found, url) + if file_identity(target) != before: + raise changed_refusal(target) + return WeightsFile(name, target, found, url, identity=before) sha256 = _download(name, url, target, pin, progress) - return WeightsFile(name, target, sha256, url, downloaded=True) + return WeightsFile(name, target, sha256, url, downloaded=True, identity=file_identity(target)) + + +def changed_refusal(path: Path) -> SegmentationError: + """Return the refusal of a weights file that changed after it was hashed.""" + return SegmentationError( + f"The weights file {path} changed after it was checked (it was replaced, removed or " + "written to), so the model loaded may not be the file whose SHA-256 is recorded. " + "Nothing was segmented and that model is not used. Make sure nothing else writes to " + "Cellpose's model folder, then press the button again." + ) + + +def _write_refusal(name: str, folder: Path, exc: OSError) -> SegmentationError: + """Return the refusal of weights that could not be written on this computer.""" + return SegmentationError( + f"The weights of {name} could not be written to {folder} ({type(exc).__name__}: {exc}). " + "The disk may be full or the folder not writable; this is not a network problem. " + "Nothing was loaded and no partial file is kept. Free some space (the file is up to " + "1.2 GB) or make the folder writable, then press the button again." + ) def _download(name: str, url: str, target: Path, pin: PinnedFile, progress: Progress | None) -> str: """Download ``url`` to ``target`` through a checked temporary file; return its SHA-256.""" - label = download_label(name) try: target.parent.mkdir(parents=True, exist_ok=True) handle, temporary = tempfile.mkstemp(prefix=f".{name}.", suffix=".part", dir=target.parent) except OSError as exc: - why = f"the model folder {target.parent} cannot be written: {exc}" - raise _refusal(name, url, why) from exc - digest, done = hashlib.sha256(), 0 + raise _write_refusal(name, target.parent, exc) from exc try: - with os.fdopen(handle, "wb") as out: - try: - with _open_url(url, TIMEOUT) as response: - size = response.headers.get("Content-Length") - total = int(size) if size and size.isdigit() else 0 - if progress is not None: - progress(label, 0, total) - for block in iter(lambda r=response: r.read(CHUNK), b""): - out.write(block) - digest.update(block) - done += len(block) - if progress is not None: - progress(label, done, total) - except urllib.error.HTTPError as exc: - raise _refusal(name, url, f"the server answered {exc.code} {exc.reason}") from exc - except (urllib.error.URLError, OSError, ValueError, http.client.HTTPException) as exc: - why = getattr(exc, "reason", None) or exc - raise _refusal(name, url, f"{type(exc).__name__}: {why}") from exc - found = digest.hexdigest() + done, found = _stream(name, url, handle, target.parent, progress) if (done, found) != (pin.size, pin.sha256): raise _refusal( name, @@ -218,13 +240,70 @@ def _download(name: str, url: str, target: Path, pin: PinnedFile, progress: Prog f"received {done:,} bytes with SHA-256 {found}; the pinned file has " f"{pin.size:,} bytes and SHA-256 {pin.sha256}", ) - os.replace(temporary, target) + try: + os.replace(temporary, target) + except OSError as exc: + raise SegmentationError( + f"The weights of {name} were downloaded and checked but could not be moved to " + f"{target} ({type(exc).__name__}: {exc}). Nothing was loaded and no partial " + "file is kept. Check that the folder is writable, then press the button again." + ) from exc finally: if os.path.exists(temporary): os.remove(temporary) return found +def _stream( + name: str, url: str, handle: int, folder: Path, progress: Progress | None +) -> tuple[int, str]: + """Write ``url``'s bytes to the open file ``handle``, synced; return their count and hash. + + A network error is a download refusal; a write error (a full disk) is a write refusal. + """ + label, digest, done = download_label(name), hashlib.sha256(), 0 + network = (urllib.error.URLError, OSError, ValueError, http.client.HTTPException) + out = os.fdopen(handle, "wb") + try: + try: + response = _open_url(url, TIMEOUT) + except urllib.error.HTTPError as exc: + raise _refusal(name, url, f"the server answered {exc.code} {exc.reason}") from exc + except network as exc: + why = getattr(exc, "reason", None) or exc + raise _refusal(name, url, f"{type(exc).__name__}: {why}") from exc + with response: + size = response.headers.get("Content-Length") + total = int(size) if size and size.isdigit() else 0 + if progress is not None: + progress(label, 0, total) + while True: + try: + block = response.read(CHUNK) + except network as exc: + why = getattr(exc, "reason", None) or exc + raise _refusal(name, url, f"{type(exc).__name__}: {why}") from exc + if not block: + break + try: + out.write(block) + except OSError as exc: + raise _write_refusal(name, folder, exc) from exc + digest.update(block) + done += len(block) + if progress is not None: + progress(label, done, total) + try: + out.flush() + os.fsync(out.fileno()) # on disk before the rename makes it the weights file + out.close() + except OSError as exc: + raise _write_refusal(name, folder, exc) from exc + finally: + out.close() + return done, digest.hexdigest() + + __all__ = [ "CHUNK", "PINNED_WEIGHTS", @@ -235,7 +314,9 @@ def _download(name: str, url: str, target: Path, pin: PinnedFile, progress: Prog "PinnedFile", "Progress", "WeightsFile", + "changed_refusal", "download_label", "fetch_weights", + "file_identity", "weights_url", ] diff --git a/tests/cellpose_stub.py b/tests/cellpose_stub.py index c211885d..f2190256 100644 --- a/tests/cellpose_stub.py +++ b/tests/cellpose_stub.py @@ -94,6 +94,8 @@ def __init__(self, gpu=False, pretrained_model="cpsam_v2", device=None, **kwargs state.constructed.append( SimpleNamespace(gpu=gpu, pretrained_model=pretrained_model, device=device, **kwargs) ) + if state.on_construct is not None: # something else touches the file meanwhile + state.on_construct(pretrained_model) if state.cpdino_log: # 4.2.1.1 logs this when cellpose.models cannot import DINOv3 logging.getLogger("cellpose.models").warning(CPDINO_WARNING) self.pretrained_model = state.substitute or self._resolve(pretrained_model) @@ -209,6 +211,7 @@ def install(monkeypatch, tmp_path, **options): dinov3_commit=model_module.DINOV3_COMMIT, has_cpdino=True, cpdino_log=False, + on_construct=None, normalize_default={ "lowhigh": None, "percentile": None, diff --git a/tests/test_segmentation_cellpose_weights.py b/tests/test_segmentation_cellpose_weights.py index 03eb876f..179a5a01 100644 --- a/tests/test_segmentation_cellpose_weights.py +++ b/tests/test_segmentation_cellpose_weights.py @@ -5,7 +5,10 @@ """ import email.message +import errno import hashlib +import io +import os import re import urllib.error import warnings @@ -15,6 +18,7 @@ from cellpose_stub import BUILTINS, install, weights_bytes from morphobricks_preprocessing import segmentation_cellpose as cp +from morphobricks_preprocessing import segmentation_cellpose_model as model_module from morphobricks_preprocessing import segmentation_cellpose_weights as weights_module from morphobricks_preprocessing.segmentation_record import SegmentationError, read_record from test_segmentation_cellpose import make_job @@ -198,3 +202,132 @@ def test_the_warning_is_shown_again_outside_the_cellpose_call(stub): warnings.simplefilter("always") _warn(SPARSE_MESSAGE, "cellpose.dynamics")(None) assert [str(w.message) for w in seen] == [SPARSE_MESSAGE] + + +# review of #577 --------------------------------------------------------------------------------- + + +def test_the_sparse_filter_is_put_back_when_cellpose_raises(stub): + loaded = cp.load_model("cpsam_v2", "cpu") + + def broken(_stack): + raise RuntimeError("CUDA out of memory") + + stub.fail = broken + before = list(warnings.filters) + with pytest.raises(RuntimeError, match="out of memory"): + cp.evaluate(loaded, cp.Settings(), np.zeros((2, 8, 8), np.uint16)) + assert warnings.filters == before + with warnings.catch_warnings(record=True) as seen: + warnings.simplefilter("always") + _warn(SPARSE_MESSAGE, "cellpose.dynamics")(None) + assert [str(w.message) for w in seen] == [SPARSE_MESSAGE] + + +def _replace_with_same_bytes(path): + data = path.read_bytes() + path.unlink() + path.write_bytes(data) # another file (inode, time) with the very same bytes + + +@pytest.mark.parametrize("what", ["removed", "replaced"]) +def test_a_weights_file_that_changes_while_cellpose_loads_it_is_refused(stub, what): + # Removed: Cellpose 4.2.1.1 would fetch cpsam_v2 from its moving branch with TLS off, to + # the same path, while the record would carry the pinned hash. + path = stub.models_dir / "cpsam_v2" + stub.on_construct = ( + (lambda _r: path.unlink()) + if what == "removed" + else (lambda _r: _replace_with_same_bytes(path)) + ) + with pytest.raises(SegmentationError, match="changed after it was checked") as caught: + cp.load_model("cpsam_v2", "cpu") + assert str(path) in str(caught.value) and len(stub.constructed) == 1 + + +def test_a_weights_file_gone_before_cellpose_opens_it_is_refused_without_cellpose( + stub, monkeypatch +): + real = model_module.fetch_weights + + def fetch_then_lose(*args, **kwargs): + found = real(*args, **kwargs) + found.path.unlink() # between the check and the load + return found + + monkeypatch.setattr(model_module, "fetch_weights", fetch_then_lose) + with pytest.raises(SegmentationError, match="changed after it was checked"): + cp.load_model("cpsam_v2", "cpu") + assert stub.constructed == [] and stub.cellpose_downloaded == [] + + +def test_a_model_file_of_ones_own_that_changes_while_loading_is_refused(stub, tmp_path): + from cellpose_stub import custom_model + + path = custom_model(tmp_path) + stub.on_construct = lambda _r: path.write_bytes(b"retrained meanwhile") + with pytest.raises(SegmentationError, match="changed after it was checked"): + cp.load_model(str(path), "cpu") + + +class _OS: + """The ``os`` module as the weights module sees it, with some calls replaced.""" + + def __init__(self, **replaced): + self.__dict__.update(replaced) + + def __getattr__(self, name): + return getattr(os, name) + + +class _FullDisk(io.BufferedWriter): + def write(self, data): + raise OSError(errno.ENOSPC, "No space left on device") + + +def test_a_full_disk_is_a_write_refusal_not_a_network_one(stub, monkeypatch): + (stub.models_dir / "cpsam").unlink() + + def fdopen(handle, mode): + return _FullDisk(io.FileIO(handle, "w")) + + monkeypatch.setattr(weights_module, "os", _OS(fdopen=fdopen)) + with pytest.raises(SegmentationError, match="could not be written to") as caught: + cp.load_model("cpsam", "cpu") + message = str(caught.value) + assert "No space left on device" in message and str(stub.models_dir) in message + assert "not a network problem" in message and "internet" not in message + assert sorted(p.name for p in stub.models_dir.iterdir()) == ["cpsam_v2"] + assert stub.constructed == [] + + +def test_a_failed_rename_names_the_target_and_keeps_nothing(stub, monkeypatch): + (stub.models_dir / "cpsam").unlink() + + def replace(source, target): + raise PermissionError(errno.EACCES, "Permission denied") + + monkeypatch.setattr(weights_module, "os", _OS(replace=replace)) + with pytest.raises(SegmentationError, match="could not be moved to") as caught: + cp.load_model("cpsam", "cpu") + assert str(stub.models_dir / "cpsam") in str(caught.value) + assert "Permission denied" in str(caught.value) + assert sorted(p.name for p in stub.models_dir.iterdir()) == ["cpsam_v2"] + assert stub.constructed == [] + + +def test_the_download_is_synced_to_disk_before_the_rename(stub, monkeypatch): + (stub.models_dir / "cpsam").unlink() + calls = [] + + def fsync(handle): + calls.append("fsync") + os.fsync(handle) + + def replace(source, target): + calls.append("replace") + os.replace(source, target) + + monkeypatch.setattr(weights_module, "os", _OS(fsync=fsync, replace=replace)) + cp.load_model("cpsam", "cpu") + assert calls == ["fsync", "replace"] From cb7cb117461a69b1248483f4145358258ae1a90d Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 20:35:57 +0000 Subject: [PATCH 07/10] Register the masks: show a failed folder check in cell 5, never crash on the next press When the folder check that Register the masks makes with the masks folder failed (an OSError such as Drive not answering, or a coded refusal), cell 5 said to confirm the axes again in cell 3, the reason was drawn only in cell 3, and every later press (and cell 5 run again) raised AttributeError out of the click handler because app.preflight was None. Cell 5 now shows CHECK_FAILED with cell 3's reason and continues once cell 3's check is made again; an unexpected error during a press is shown in cell 5 (STOPPED) and re-raised. Nothing checked, declared or written changes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WX6rdMV1r5jUPUR94kxV5a --- CHANGELOG.md | 1 + .../notebook_mask_register.py | 29 +++++++++- tests/test_notebook_preprocessing_cellpose.py | 57 +++++++++++++++++++ 3 files changed, 84 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1b3114bd..fcb20792 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ v0.5.1: no run before v0.5.1 is read.) ## Unreleased +- **Register the masks (cell 5) says in its own cell when its folder check fails, and never crashes on the next press (owner's Colab test of v0.9.0).** When the app's folder check that **Register the masks** makes with the masks folder failed (an `OSError` such as a Google Drive that stopped answering, or a coded refusal), cell 5 said to confirm the axes again in cell 3 (there was no check to confirm), the reason was drawn only in cell 3, and the check had cleared the app's run: every later press and cell 5 run again raised `AttributeError` (`app.preflight` is None in `_app_run`) out of the click handler, with the axes line left on screen. Cell 5 now shows `CHECK_FAILED` with cell 3's reason, whatever the press (nothing is declared, saved or run, as before), and continues once cell 3's check is made again. An unexpected error during a press is shown in cell 5 (`STOPPED`) and still raised. What is checked, declared and written is unchanged. Tests: `tests/test_notebook_preprocessing_cellpose.py`. - **Cellpose step Folders: the run is opened once, on screen, with its wait (#574, item 2; owner's Colab test of 26 November 2026).** "Step 1 of 4 · Folders" showed nothing for about 4 minutes on ~200 images of 10-50 MB on Google Drive. Cell 4 opened the app's run twice before its widget was shown: once for the notice's refusal (`_refusal`) and once by **Open the run**, and each opening of a `verify_content` run reads every image whole for its content SHA-256 (`RunInputs._check_files` → `content_changed`): 2 whole reads per image, plus the viewer's first image. Cell 4 is unchanged (the pinned release's `segmentation = segmentation_step(notebook)` / `display(segmentation)`): in a notebook `segmentation_step` now displays its widget first itself (`show=` overrides it, None outside a kernel) and the cell's `display(segmentation)` then adds nothing (`SegmentationStep._ipython_display_`, once; it draws the widget with ipywidgets 7's `Widget._ipython_display_` when there is one, as on Colab, else with ipywidgets 8's `_repr_mimebundle_`). Then `SegmentationStep.check()` opens the run once (by **Open the run** when Cellpose is installed and the masks folder known, else for the refusal only): 1 whole read per image. The checks are unchanged: `run_inputs.open_checked(..., checking=)` is `RunInputs.open` (now a call of it, signature kept) telling a callback each phase of `open_checks.OPEN_PHASES` (manifest, image fingerprints, content SHA-256, mask fingerprints, the folders listed for unrecorded files), the `(phase, done, total, path)` of `RunMode(checking=)` (#567); same files, same order, same result and refusals (tests compare both). `notebook_open_progress.opening` shows it with `notebook_progress.Wait` and its ticking thread: the phase, "n of N" with the image read, the elapsed time, then "Opened and checked in m:ss". `segmentation_app(open_now=False)` leaves the opening to the caller. An error that is not a refusal while cell 4 opens the run still leaves the cell, as before (`StepForm.submit(reraise=True)`; a button's stays under it); after an error or an interrupt the line says "Stopped after m:ss." `tests/test_cellpose_folders_open.py` counts the whole reads per image (1, was 2), that the widget is shown before any read, the wait's lines and the identical result and refusal. - **Cellpose installation: what pip does now, then what it installed (#574, item 1).** Measured in a fresh Python 3.12 venv with real pip (no cache): the shared cell 1 installs preprocessing, normalization (both cloned and built from Git), imagecodecs (27.7 MB), ipywidgets and matplotlib (with numpy and scipy when missing): 42 s the first time, 1.6 s the second (nothing installed); it does not install Cellpose. Cell 4's own **Install Cellpose** step installs `cellpose==4.2.1.1`: 3.2 GB of downloads without PyTorch (torch 2.15 with its CUDA libraries, 3 GB of it), 5-8 s with PyTorch already installed, as on Colab (cellpose, opencv-python-headless 63.7 MB and five small packages). Its `pip` printed to the kernel's output, which a button callback does not show: `cellpose_install.install_cellpose(ticked, output=)` now streams pip's lines (`subprocess.Popen`), and the card shows "Installing Cellpose 4.2.1.1 (with PyTorch): finding/downloading/installing …" with the ticking elapsed time (`notebook_cellpose_install.PipProgress`), then a green card above the component: how long it took and every package pip installed or changed (`installed_distributions`, `install_changes`); a failed install shows pip's last 20 lines. As with `subprocess.run`, pip is killed and waited for when anything stops the reading (an interrupt included), and output that is not UTF-8 is replaced rather than stopping it. The tick, the pinned release, the restart rule and the shared cells 1 to 3 are unchanged. - **The run's masks counter ends at N of N (follow-up of #567).** The mask header check reported "done of N" before each mask and nothing after the last, so the run's wait stopped at "N-1 of N" (preflight's closing `("masks", 1, 1, "")` is a placeholder the wait ignores unless the total is 1). The check now also reports `(total, total, "")` after the last mask; what is read and recorded is unchanged. A stray docstring in `notebook_progress` (the one of `PREPARING` sat after `COUNTED_PHASES`) is back under `PREPARING`. Tests: `tests/test_run_checking_progress.py`, `tests/test_notebook_progress.py`. diff --git a/src/morphobricks_preprocessing/notebook_mask_register.py b/src/morphobricks_preprocessing/notebook_mask_register.py index ccf0a8e2..53d79ba8 100644 --- a/src/morphobricks_preprocessing/notebook_mask_register.py +++ b/src/morphobricks_preprocessing/notebook_mask_register.py @@ -91,6 +91,16 @@ "step Axes, confirm the recorded axes, then press Register the masks again. Nothing was " "declared." ) +CHECK_FAILED = ( + "The folder check of cell 3 with the masks folder did not finish: {reason} Nothing was " + "declared and the run folder is unchanged. Fix what it names, press Check folder (Scan the " + "folders) in cell 3, step Images, confirm the axes, then press Register the masks again." +) +STOPPED = ( + "Register the masks stopped on an unexpected problem ({problem}). The run records the " + "masks only once this step says The masks are registered; cell 3 shows what it saved. " + "Press Register the masks again." +) NOT_SAVED = ( "Check and save did not save the description: open cell 3, step Check and save, answer " "what it lists, then press Register the masks again here." @@ -149,8 +159,9 @@ def _app_run(app: object, rechecked: bool) -> tuple[str, str]: it runs again; the run is then the output folder the app's own rule gives now. """ run, masks = app_folders(app) - if not run and rechecked and getattr(app, "result", None) is None: - run = os.fspath(app._output_path(Path(app.preflight.discovery.root))) + pre = getattr(app, "preflight", None) + if not run and rechecked and getattr(app, "result", None) is None and pre is not None: + run = os.fspath(app._output_path(Path(pre.discovery.root))) return run, masks @@ -167,6 +178,8 @@ def refusal(app: object, segmentation: object, *, rechecked: bool = False) -> st inputs, masks = workflow.inputs, Path(workflow.masks_root).resolve() segmented = Path(inputs.output_folder).resolve() rechecked = rechecked or getattr(segmentation, "rechecked_run", None) == segmented + if rechecked and getattr(app, "preflight", None) is None: # cell 5's folder check failed + return CHECK_FAILED.format(reason=_plain(app.folder_status.value)) app_run, app_masks = _app_run(app, rechecked) if not app_run or Path(app_run).resolve() != segmented: held = app_run or "no finished run" @@ -307,6 +320,14 @@ def register(self) -> bool: """Declare the ticked masks through the app, save, run and describe; True when done.""" if self.button.disabled: return False + try: + return self._register() + except BaseException as exc: # a click handler's error is never shown in this cell + self._stop(STOPPED.format(problem=f"{type(exc).__name__}: {exc}")) + raise + + def _register(self) -> bool: + """Do the work of :meth:`register` once its button is enabled.""" why = refusal(self.app, self.segmentation) if why: return self._stop(why) @@ -319,11 +340,13 @@ def register(self) -> bool: or any(t not in found.types for t in self.ticks) # checked before cell 4 wrote ): app.masks_folder.value = os.fspath(masks) - app.check_folder() # the app's Scan the folders, now with the masks folder + pre = app.check_folder() # the app's Scan the folders, now with the masks folder # Kept on cell 4's step, not this widget: cell 5 run again continues from here. self.segmentation.rechecked_run = Path( self.segmentation.workflow.inputs.output_folder ).resolve() + if pre is None: # its reason is drawn in cell 3: say it here, not the axes + return self._stop(CHECK_FAILED.format(reason=_plain(app.folder_status.value))) if app.confirmed_mapping is None: return self._stop(AXES_AGAIN) why = _other_experiment(app, self.segmentation.workflow.inputs) diff --git a/tests/test_notebook_preprocessing_cellpose.py b/tests/test_notebook_preprocessing_cellpose.py index 2fd6f6f2..e656e1a0 100644 --- a/tests/test_notebook_preprocessing_cellpose.py +++ b/tests/test_notebook_preprocessing_cellpose.py @@ -40,6 +40,7 @@ from morphobricks_preprocessing.notebook_mask_register import ( # noqa: E402 AXES_AGAIN, NO_MASKS, + STOPPED, register_step, toml_section, ) @@ -535,3 +536,59 @@ def test_cell_5_run_again_after_it_registered_the_masks_is_not_refused(tmp_path, assert registration.register(), registration.status.value again = register_step(nb, registration.segmentation) assert list(again.ticks) == ["Cells"], again.status.value + + +def pressed_with_a_failed_check(tmp_path, monkeypatch, error): + """Return the app, cell 5 and the run after a press whose folder check raised ``error``.""" + from morphobricks_preprocessing import notebook_folder + + nb = ran_app(tmp_path) + out = nb.result.output_folder + step = segmentation_step(nb) + segment(step, tmp_path / "masks") + registration = register_step(nb, step) + registration.ticks["Cells"].value = True + real = notebook_folder.preflight + + def failing(*args, **kwargs): + raise error + + monkeypatch.setattr(notebook_folder, "preflight", failing) + before = snapshot(out) + return nb, registration, out, before, real + + +def test_a_failed_folder_check_says_so_in_cell_5_not_the_axes(tmp_path, stub, monkeypatch): + # Before, cell 5 said to confirm the axes again (there was no check to confirm), the + # reason was drawn only in cell 3, and every later press raised AttributeError out of the + # click handler with the axes line left on screen. + from morphobricks_preprocessing import notebook_folder + + nb, registration, out, before, real = pressed_with_a_failed_check( + tmp_path, monkeypatch, OSError("Drive stopped answering") + ) + assert not registration.register() + status = registration.status.value + assert "did not finish" in status and "Drive stopped answering" in status + assert AXES_AGAIN.split(":")[0] not in status + assert snapshot(out) == before # nothing declared, saved or run + assert not registration.register() # pressed again: the same refusal, no exception + assert "did not finish" in registration.status.value + again = register_step(nb, registration.segmentation) # cell 5 run again + assert "did not finish" in again.status.value + monkeypatch.setattr(notebook_folder, "preflight", real) # Drive answers again + nb.check_button.click() # cell 3's check, as the refusal says; the axes, then Register + nb.quick_confirm.click() + assert registration.register(), registration.status.value + assert RunInputs.open(out).mask_types() == ("Cells",) + + +def test_an_unexpected_error_during_register_is_shown_in_cell_5(tmp_path, stub, monkeypatch): + _nb, registration, out, before, _real = pressed_with_a_failed_check( + tmp_path, monkeypatch, RuntimeError("unexpected") + ) + with pytest.raises(RuntimeError): + registration.register() + assert STOPPED.split("(")[0] in registration.status.value + assert "RuntimeError: unexpected" in registration.status.value + assert snapshot(out) == before From 8f8ce08f7e2ad519db501968ae47db15b71cb503 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 21:12:00 +0000 Subject: [PATCH 08/10] cpdino: install DINOv3 before Cellpose; ask for a restart only when it helps The combined notebook's Install Cellpose step installs the pinned DINOv3 code (--no-deps, no weights) before Cellpose when none is installed, so a cpdino model loaded after a cpsam one needs no runtime restart. ensure_dinov3 clears the import caches after installing. check_dinov3 asks for a restart only when DINOv3 imports now but Cellpose missed it; a DINOv3 that does not import is refused with its import error. Tests for each. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VbytvF3Gsa85ix8Ne2yMDW --- docs/user_guide.md | 11 ++- .../cellpose_install.py | 37 +++++++--- .../notebook_preprocessing_cellpose.py | 5 +- .../segmentation_cellpose_model.py | 33 ++++++++- tests/cellpose_stub.py | 5 +- tests/test_notebook_preprocessing_cellpose.py | 31 ++++++++ tests/test_segmentation_cellpose_dinov3.py | 70 +++++++++++++++++++ 7 files changed, 176 insertions(+), 16 deletions(-) create mode 100644 tests/test_segmentation_cellpose_dinov3.py diff --git a/docs/user_guide.md b/docs/user_guide.md index 723a7457..452719e8 100644 --- a/docs/user_guide.md +++ b/docs/user_guide.md @@ -311,9 +311,14 @@ banner then says "commit unknown" and that the override is on). Then: all in the Cellpose file). When no DINOv3 is installed, the first load of a `cpdino` model installs it, without its dependencies, at a pinned commit (the head of its default branch on 22 November 2026, not verified against `cpdino`). A DINOv3 of another commit is not - replaced: the load is refused with the command to run. If Cellpose was already loaded in - this runtime (another model loaded first), the load asks you to restart the runtime and run - the cells again; nothing is downloaded again. + replaced: the load is refused with the command to run. In the combined notebook, cell 4's + **Install Cellpose** installs the pinned DINOv3 code just before Cellpose when none is + installed (v0.9.1), so a `cpdino` model works without a restart whichever model you load + first. A restart is asked for only when it is really needed: DINOv3 was installed after + Cellpose had been loaded in this runtime (for example a `cpsam` model loaded first in the + Cellpose notebook); then restart the runtime and run the cells again; nothing is downloaded + again. A DINOv3 that cannot be imported at all is refused with its import error instead, + since a restart would not fix it. - **Device.** The model form says, before anything loads, whether a GPU was found and which. You choose `cuda`, `mps` or `cpu`. A GPU that is not available is refused, never replaced by the CPU, and after loading every parameter and buffer of the network must be on diff --git a/src/morphobricks_preprocessing/cellpose_install.py b/src/morphobricks_preprocessing/cellpose_install.py index 9b548ddb..f41d7437 100644 --- a/src/morphobricks_preprocessing/cellpose_install.py +++ b/src/morphobricks_preprocessing/cellpose_install.py @@ -4,13 +4,20 @@ preprocessing in cell 1, exactly as the Preprocessing notebook does, and Cellpose (with PyTorch) only when the segmentation cell is used: :func:`install_cellpose` runs ``pip`` for the pinned :data:`.segmentation_cellpose_model.CELLPOSE_VERSION`, and only when the user ticked the -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. ``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. +installation (the consent). It keeps the rules of the Cellpose notebook's install cell: the +release pinned, 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. + +DINOv3 (v0.9.1): when no DINOv3 is installed, the pinned DINOv3 code +(:func:`.segmentation_cellpose_model.dinov3_install_command`, ``--no-deps``, no weights) is +installed *before* Cellpose, in the same ticked installation. Cellpose 4.2.1.1 imports DINOv3 +only once, when its network module is first imported, so a DINOv3 installed later (on the first +``cpdino`` load after a ``cpsam`` one) needed a runtime restart (owner's Colab test of v0.9.0). +A DINOv3 already installed, at any commit, is left as it is; the model step checks its commit. + +``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 @@ -131,6 +138,9 @@ def _pip(command: list[str], output: Callable[[str], object]) -> None: def install_cellpose(ticked: bool, output: Callable[[str], object] = print) -> str: """Install the pinned Cellpose release when it is not installed, if ``ticked``. + When no DINOv3 is installed, the pinned DINOv3 code is installed first (see the module + docstring), so that a ``cpdino`` model never needs a restart in this runtime. + Parameters ---------- ticked @@ -148,7 +158,8 @@ def install_cellpose(ticked: bool, output: Callable[[str], object] = print) -> s Raises ------ SegmentationError - Without the tick (nothing is installed), when ``pip`` fails, when it changed a package + Without the tick (nothing is installed), when ``pip`` fails (DINOv3's installation + included: Cellpose is then not installed), when it changed a package the kernel had loaded (restart the runtime), or when another version is still installed. """ if cellpose_ready(): @@ -156,6 +167,16 @@ def install_cellpose(ticked: bool, output: Callable[[str], object] = print) -> s if not ticked: raise SegmentationError(NOT_TICKED.format(version=CELLPOSE_VERSION)) before = {name: model.installed_version(name) for name in LOADED_BY_KERNEL} + if not model.dinov3_present(): + try: + _pip(model.dinov3_install_command(), output) + except (subprocess.CalledProcessError, OSError) as exc: + raise SegmentationError( + f"DINOv3 (the code of the cpdino models, installed before Cellpose) could not " + f"be installed ({exc}); Cellpose was not installed. Check the installation " + "output and internet access, then press the button again." + ) from exc + importlib.invalidate_caches() try: _pip(cellpose_install_command(), output) except (subprocess.CalledProcessError, OSError) as exc: diff --git a/src/morphobricks_preprocessing/notebook_preprocessing_cellpose.py b/src/morphobricks_preprocessing/notebook_preprocessing_cellpose.py index 398c4fbe..1cb65f4c 100644 --- a/src/morphobricks_preprocessing/notebook_preprocessing_cellpose.py +++ b/src/morphobricks_preprocessing/notebook_preprocessing_cellpose.py @@ -68,8 +68,9 @@ INSTALL_TEXT = ( "Cellpose {version} is not installed in this environment. It is installed only here, only " "when you tick the box: it brings PyTorch, a download of a few gigabytes. Preprocessing " - "alone never installs it. The command is {command}. DINOv3 is never installed here " - "(it is a choice of the model step)." + "alone never installs it. The command is {command}. When no DINOv3 is installed, " + "the pinned DINOv3 code (the network code of the cpdino models; no weights) is installed " + "just before Cellpose, so that a cpdino model never needs a runtime restart." ) diff --git a/src/morphobricks_preprocessing/segmentation_cellpose_model.py b/src/morphobricks_preprocessing/segmentation_cellpose_model.py index d431ebee..b49a2b5d 100644 --- a/src/morphobricks_preprocessing/segmentation_cellpose_model.py +++ b/src/morphobricks_preprocessing/segmentation_cellpose_model.py @@ -309,15 +309,36 @@ def ensure_dinov3(progress: Progress | None = None) -> bool: if progress is not None: progress(DINOV3_LABEL, 0, 0) install_dinov3() + # The import system caches folder listings: without this, Cellpose imported right after + # could miss the package just installed and need a restart for nothing. + importlib.invalidate_caches() return True +def dinov3_import_problem() -> str | None: + """Return why ``dinov3.hub.backbones`` cannot be imported here, or None when it can. + + What Cellpose 4.2.1.1's ``cellpose.vit`` imports from DINOv3. Used only after Cellpose + failed to get it, to tell a runtime that needs a restart (DINOv3 importable now, installed + after Cellpose was imported) from a DINOv3 that does not import at all, which a restart + would not fix. + """ + importlib.invalidate_caches() + try: + importlib.import_module("dinov3.hub.backbones") + except Exception as exc: # any import failure is the answer, reported as it is + return " ".join(f"{type(exc).__name__}: {exc}".split()) + return None + + def check_dinov3(models: ModuleType) -> str: """Return the commit of the installed DINOv3 if it is the pinned one, else refuse. Cellpose 4.2.1.1 imports DINOv3 once, when ``cellpose.vit`` is first imported (it then - defines ``CPDINO`` whether or not that worked), so a DINOv3 installed after that needs a - restart of the runtime; the check looks at ``cellpose.vit`` itself and says so. + defines ``CPDINO`` whether or not that worked), so the check looks at ``cellpose.vit`` + itself. When it has no DINOv3, a restart is asked for only when it would help: DINOv3 + imports now, so it was installed after Cellpose was imported. A DINOv3 that does not import + at all is refused with its import error, since a restart would not change that. """ command = " ".join(dinov3_install_command()[2:]) commit = installed_dinov3_commit() @@ -334,6 +355,14 @@ def check_dinov3(models: ModuleType) -> str: ) vit = sys.modules.get("cellpose.vit") # imported with ``models`` if not hasattr(vit, "dinov3_vitl16"): + problem = dinov3_import_problem() + if problem is not None: + raise SegmentationError( + f"DINOv3 is installed (commit {commit[:12]}) but cannot be imported here " + f"({problem}), so Cellpose cannot build the {', '.join(DINO_MODELS)} networks. " + "A restart does not fix this: check that PyTorch imports, or choose a SAM model " + "(cpsam_v2, cpsam)." + ) raise SegmentationError( f"DINOv3 is installed (commit {commit[:12]}), but Cellpose was imported in this " "runtime before it was there. Restart the runtime (Colab: Runtime > Restart " diff --git a/tests/cellpose_stub.py b/tests/cellpose_stub.py index f2190256..937cca46 100644 --- a/tests/cellpose_stub.py +++ b/tests/cellpose_stub.py @@ -183,7 +183,8 @@ def install(monkeypatch, tmp_path, **options): ``buffers`` (the device types of the network's tensors, when not the requested one), ``no_net``, ``fail`` (a function of the stack that raises), ``version``, ``dinov3_commit`` (None: no DINOv3 installed; ``install_dinov3`` then installs the pinned - one and records it in ``dinov3_installs``), ``dinov3_present`` (a DINOv3 of unknown commit) + one and records it in ``dinov3_installs``), ``dinov3_present`` (a DINOv3 of unknown commit), + ``dinov3_import_problem`` (why ``dinov3.hub.backbones`` would not import; None: it would) and ``download_fail`` (an exception the download raises). """ models_dir = tmp_path / "cellpose_models" @@ -198,6 +199,7 @@ def install(monkeypatch, tmp_path, **options): cellpose_downloaded=[], dinov3_installs=[], dinov3_present=False, + dinov3_import_problem=None, download_fail=None, models_dir=models_dir, cuda=False, @@ -254,6 +256,7 @@ def install_dinov3(): state.dinov3_commit = model_module.DINOV3_COMMIT monkeypatch.setattr(model_module, "install_dinov3", install_dinov3) + monkeypatch.setattr(model_module, "dinov3_import_problem", lambda: state.dinov3_import_problem) monkeypatch.setattr(weights_module, "PINNED_WEIGHTS", fake_pins()) monkeypatch.setattr(weights_module, "_open_url", lambda url, timeout: served(state, url)) diff --git a/tests/test_notebook_preprocessing_cellpose.py b/tests/test_notebook_preprocessing_cellpose.py index 2fd6f6f2..90ce46b4 100644 --- a/tests/test_notebook_preprocessing_cellpose.py +++ b/tests/test_notebook_preprocessing_cellpose.py @@ -223,6 +223,37 @@ def test_cellpose_is_installed_only_when_ticked_then_the_component_appears(tmp_p assert step.segmentation is not None and step.workflow.inputs is None # no masks folder yet +def test_dinov3_is_installed_before_cellpose_when_none_is_there(tmp_path, pip, stub): + # cpdino fix (v0.9.1): DINOv3 in place before Cellpose is ever imported, so a cpdino model + # loaded after a cpsam one needs no runtime restart. + stub.dinov3_commit = None + step = segmentation_step(ran_app(tmp_path)) + step.install_tick.value = True + assert step.install() + first, second = pip.commands + assert first == model.dinov3_install_command() and "--no-deps" in first + assert second[-1] == "cellpose==4.2.1.1" + + +def test_a_dinov3_already_installed_is_left_as_it_is(tmp_path, pip, stub): + stub.dinov3_commit, stub.dinov3_present = None, True # one of the user's own, commit unknown + step = segmentation_step(ran_app(tmp_path)) + step.install_tick.value = True + assert step.install() + (command,) = pip.commands + assert command[-1] == "cellpose==4.2.1.1" + + +def test_a_failed_dinov3_install_installs_no_cellpose(tmp_path, pip, stub): + stub.dinov3_commit, pip.returncode = None, 1 + step = segmentation_step(ran_app(tmp_path)) + step.install_tick.value = True + assert not step.install() + assert len(pip.commands) == 1 and "DINOv3" in step.install_status.value + assert "Cellpose was not installed" in step.install_status.value + assert step.segmentation is None + + def test_an_install_that_changes_a_loaded_numpy_asks_for_a_restart(tmp_path, pip): pip.numpy = ("2.0.0", "2.3.0") step = segmentation_step(ran_app(tmp_path)) diff --git a/tests/test_segmentation_cellpose_dinov3.py b/tests/test_segmentation_cellpose_dinov3.py new file mode 100644 index 00000000..9cf78ba5 --- /dev/null +++ b/tests/test_segmentation_cellpose_dinov3.py @@ -0,0 +1,70 @@ +"""The cpdino fix of v0.9.1: DINOv3 before Cellpose, and a restart asked only when needed. + +Cellpose 4.2.1.1 imports DINOv3 once, when ``cellpose.vit`` is first imported. The owner's Colab +test of v0.9.0 had ``cpdino`` ask for a runtime restart. A restart is now asked for only when +DINOv3 imports now but Cellpose missed it; a DINOv3 that does not import is refused with its +import error. The install step's half is in ``test_notebook_preprocessing_cellpose.py``. +""" + +import sys +import types + +import pytest + +from cellpose_stub import install +from morphobricks_preprocessing import segmentation_cellpose as cp +from morphobricks_preprocessing import segmentation_cellpose_model as model_module +from morphobricks_preprocessing.segmentation_record import SegmentationError + + +@pytest.fixture +def stub(monkeypatch, tmp_path): + return install(monkeypatch, tmp_path) + + +def test_a_restart_is_asked_only_when_dinov3_imports_now(monkeypatch, tmp_path): + # cpdino fix (v0.9.1): Cellpose imported without DINOv3, and DINOv3 does not import now + # either: a restart would not help, so the refusal names the import error instead. + state = install(monkeypatch, tmp_path, has_cpdino=False) + state.dinov3_import_problem = "ImportError: cannot import name 'x' from 'torch'" + with pytest.raises(SegmentationError) as refused: + cp.load_model("cpdino", "cpu") + assert "cannot be imported here (ImportError" in str(refused.value) + assert "A restart does not fix this" in str(refused.value) + assert "Restart the runtime" not in str(refused.value) and state.constructed == [] + state.dinov3_import_problem = None # importable now: installed after Cellpose was imported + with pytest.raises(SegmentationError, match="Restart the runtime"): + cp.load_model("cpdino", "cpu") + + +def test_no_restart_is_asked_when_dinov3_was_there_before_cellpose(stub): + stub.dinov3_import_problem = "would only be asked if Cellpose had missed DINOv3" + loaded = cp.load_model("cpdino", "cpu") # cellpose.vit has DINOv3: nothing else is asked + assert loaded.dinov3_commit == cp.DINOV3_COMMIT and stub.constructed + + +def test_dinov3_import_problem_reports_the_real_import(monkeypatch): + fresh = model_module # the real function: no stand-in installed in this test + hub = types.ModuleType("dinov3.hub") + backbones = types.ModuleType("dinov3.hub.backbones") + for name, module in ( + ("dinov3", types.ModuleType("dinov3")), + ("dinov3.hub", hub), + ("dinov3.hub.backbones", backbones), + ): + monkeypatch.setitem(sys.modules, name, module) + assert fresh.dinov3_import_problem() is None + monkeypatch.setitem(sys.modules, "dinov3.hub.backbones", None) # import refused + problem = fresh.dinov3_import_problem() + assert problem is not None and problem.startswith(("ModuleNotFoundError", "ImportError")) + + +def test_ensure_dinov3_clears_the_import_caches_after_installing(monkeypatch): + order = [] + monkeypatch.setattr(model_module, "dinov3_present", lambda: False) + monkeypatch.setattr(model_module, "install_dinov3", lambda: order.append("install")) + monkeypatch.setattr( + model_module.importlib, "invalidate_caches", lambda: order.append("invalidate") + ) + assert model_module.ensure_dinov3() is True + assert order == ["install", "invalidate"] # so Cellpose imported next finds DINOv3 From dd286d221e574842425070ad15d259a237f64138 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 21:36:14 +0000 Subject: [PATCH 09/10] Register the masks: #578 TODOs and one press when nothing changed - Binary answer for a Cellpose mask: coded refusal (cellpose_mask_not_binary) saying why (Cellpose numbers each object); binary masks from elsewhere stay declarable in cell 3. - Within one press, a content SHA-256 is reused while the file identity (st_dev, st_ino, st_size, st_mtime_ns, st_ctime_ns) is unchanged (content_memo.ContentMemo, created per press, passed explicitly; never at publication). Images: 2 whole reads per press instead of 4 (+1 for the former first press). A rewrite the identity cannot see is still refused by the run's check before it publishes (tested). - Cell 5 is displayed first (shared notebook_shown_first.ShownFirst with cell 4), then opens the run with its n-of-N wait; cell text unchanged. - One press: when the folders and image headers are unchanged since cell 3's check (register_checks.changes_since_check), the masks are paired with the app's Check the masks again and the confirmed axes are kept; otherwise the folder check is made again and the axes stop says what changed. - Refusal helpers moved to register_checks (600-line rule); install tests moved to their own file. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VbytvF3Gsa85ix8Ne2yMDW --- pyproject.toml | 3 + .../content_memo.py | 92 ++++++ .../notebook_mask_register.py | 295 ++++++++++-------- .../notebook_mask_step.py | 2 +- .../notebook_preprocessing_cellpose.py | 20 +- .../notebook_register_progress.py | 20 +- .../notebook_run.py | 1 + .../notebook_shown_first.py | 43 +++ .../notebook_tissue_mask.py | 13 +- .../register_checks.py | 178 +++++++++++ src/morphobricks_preprocessing/run/modes.py | 10 + .../run/pipeline.py | 10 +- src/morphobricks_preprocessing/run/state.py | 3 + src/morphobricks_preprocessing/run/steps.py | 6 +- src/morphobricks_preprocessing/run_inputs.py | 11 +- .../segmentation_cellpose_run.py | 10 +- .../source_content.py | 25 +- tests/test_cellpose_folders_open.py | 6 +- tests/test_content_memo.py | 123 ++++++++ tests/test_mask_register_progress.py | 126 +++++++- tests/test_notebook_preprocessing_cellpose.py | 228 +------------- ...notebook_preprocessing_cellpose_install.py | 230 ++++++++++++++ tests/test_register_checks.py | 63 ++++ 23 files changed, 1109 insertions(+), 409 deletions(-) create mode 100644 src/morphobricks_preprocessing/content_memo.py create mode 100644 src/morphobricks_preprocessing/notebook_shown_first.py create mode 100644 src/morphobricks_preprocessing/register_checks.py create mode 100644 tests/test_content_memo.py create mode 100644 tests/test_notebook_preprocessing_cellpose_install.py create mode 100644 tests/test_register_checks.py diff --git a/pyproject.toml b/pyproject.toml index 56257c89..1bccc9bc 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -197,6 +197,8 @@ baseline = "tools/code_rules_baseline.json" "morphobricks_preprocessing.notebook_cellpose_view" = "ui" "morphobricks_preprocessing.notebook_mask_register" = "ui" "morphobricks_preprocessing.notebook_register_progress" = "ui" +"morphobricks_preprocessing.register_checks" = "io" +"morphobricks_preprocessing.notebook_shown_first" = "ui" "morphobricks_preprocessing.notebook_preprocessing_cellpose" = "ui" "morphobricks_preprocessing.notebook_stop" = "ui" "morphobricks_preprocessing.notebook_channels" = "ui" @@ -367,6 +369,7 @@ baseline = "tools/code_rules_baseline.json" "morphobricks_preprocessing.manifest_versions" = "pure" "morphobricks_preprocessing.versions" = "io" "morphobricks_preprocessing.source_content" = "io" +"morphobricks_preprocessing.content_memo" = "io" "morphobricks_preprocessing.inventory" = "io" "morphobricks_preprocessing.fingerprint" = "io" "morphobricks_preprocessing.narrow_ranges" = "pure" diff --git a/src/morphobricks_preprocessing/content_memo.py b/src/morphobricks_preprocessing/content_memo.py new file mode 100644 index 00000000..692fd965 --- /dev/null +++ b/src/morphobricks_preprocessing/content_memo.py @@ -0,0 +1,92 @@ +"""Content SHA-256s taken during one press, reused while the file's identity is unchanged. + +Owner decision on #578 (26 November 2026): within **one** press of **Register the masks**, a +content SHA-256 already taken of an image is not taken again when the file is provably +unchanged since then. The proof is the file's identity, captured when it was hashed and +compared at reuse: device, inode, size, modification time and status-change time +(``st_dev``, ``st_ino``, ``st_size``, ``st_mtime_ns``, ``st_ctime_ns``). The owner's rule names +the first four; the status-change time is added because any doubt means hashing again, and on +POSIX it moves with every write and every ``os.utime``, which a user cannot set back. + +- A :class:`ContentMemo` is created at the start of a press and passed explicitly to every + check of that press; it is never a module global and never outlives the press. +- A file whose identity moved while it was hashed is not remembered; an OME-Zarr folder is + never remembered (its identity is not one file's): both are hashed every time. +- Checks across presses, and every check at publication, do not use it: they stay as strict + as before. + +What the identity rule cannot catch: a file rewritten in place with every one of those five +values the same. On POSIX the status-change time cannot be set back, so that needs a file +system that does not keep it (some network or FUSE mounts); on Windows ``st_ctime`` is the +creation time. Such a change is still caught by the run's check before it publishes, which +never reuses a SHA-256 (``tests/test_content_memo.py``). +""" + +from __future__ import annotations + +import os +from collections.abc import Callable +from pathlib import Path + +Identity = tuple[int, int, int, int, int] +"""``(st_dev, st_ino, st_size, st_mtime_ns, st_ctime_ns)`` of a file.""" + + +def file_identity(path: str | os.PathLike) -> Identity | None: + """Return the identity of a regular file, or None for a folder or a file that is gone.""" + try: + stat = os.stat(path) + except OSError: + return None + if not Path(path).is_file(): + return None + return (stat.st_dev, stat.st_ino, stat.st_size, stat.st_mtime_ns, stat.st_ctime_ns) + + +class ContentMemo: + """The content SHA-256s one press took, each with the file identity it was taken at. + + Attributes + ---------- + hashed, reused + How many SHA-256s were taken, and how many were reused (for tests and reports). + """ + + def __init__(self) -> None: + self._seen: dict[str, tuple[Identity, str]] = {} + self.hashed = 0 + self.reused = 0 + + def sha256(self, path: str | os.PathLike, compute: Callable[[Path], str]) -> str: + """Return ``compute(path)``, or the SHA-256 taken earlier in the press if unchanged. + + Parameters + ---------- + path + The image (a TIFF file or an OME-Zarr folder). + compute + Takes the SHA-256 (it reads the file whole); its errors propagate. + + Returns + ------- + str + The content SHA-256. + """ + path = Path(path) + key = os.fspath(path.resolve()) + before = file_identity(path) + kept = self._seen.get(key) + if before is not None and kept is not None and kept[0] == before: + self.reused += 1 + return kept[1] + sha = compute(path) + self.hashed += 1 + after = file_identity(path) + if before is not None and before == after: + self._seen[key] = (before, sha) + else: + self._seen.pop(key, None) # moved while hashed, or not a file: never reused + return sha + + +__all__ = ["ContentMemo", "Identity", "file_identity"] diff --git a/src/morphobricks_preprocessing/notebook_mask_register.py b/src/morphobricks_preprocessing/notebook_mask_register.py index 2d7d07dc..1e34412b 100644 --- a/src/morphobricks_preprocessing/notebook_mask_register.py +++ b/src/morphobricks_preprocessing/notebook_mask_register.py @@ -38,20 +38,32 @@ import html import os import re +from collections.abc import Callable, Iterator +from contextlib import contextmanager 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 .description_identity import nfc +from .content_memo import ContentMemo from .folder_rules import masks_folder_issues -from .manifest import MANIFEST_FILENAME, ManifestFormatError, read_manifest from .mask_answers import BINARY, INSTANCES from .notebook_cellpose_app import app_folders +from .notebook_open_progress import opening from .notebook_register_progress import RegisterWait from .notebook_render import blocked_line +from .notebook_shown_first import ShownFirst from .open_checks import Checking, quiet -from .report import mapping_summary +from .register_checks import ( + CHANGED, + _collision, + _only_written, + _other_experiment, + _same_publication, + changes_since_check, +) from .run_inputs import RunInputsError, UnrecordedFilesError from .segmentation_cellpose_run import manifest_sha256, open_run from .segmentation_record import SegmentationError, check_mask_type_folder @@ -69,34 +81,21 @@ "Cell 4 wrote the masks to {segmented}, but the run of cell 3 uses the masks folder " "{app_masks}. Segment into that folder in cell 4, then run this cell again." ) -COLLISION = ( - "The mask type {mask_type} collides with the mask {mask_id} the description already " - "declares (source type {source_type}). Choose another mask type in cell 4 and segment " - "again; nothing is declared twice." -) REPUBLISHED = ( "The run in {segmented} was published again since cell 4 segmented it (cell 3 run again): " "its masks were made on the run as cell 4 opened it. In cell 4 press Open the run again " "and Segment the whole experiment again (overwrite), then run this cell again. Nothing was " "declared." ) -CHANGED = "The images changed since the run, or the run cannot be opened: {reason}" AXES_AGAIN = ( "The folder check with the masks folder asks you to confirm the axes again: in cell 3, " "step Axes, check the example and press Confirm these axes. Then press Register the masks " "again here." ) -OTHER_EXPERIMENT = ( - "The app of cell 3 now holds another experiment ({app_root}) than the one cell 4 " - "segmented ({segmented}). Check {segmented} again in cell 3 and confirm its axes, then " - "press Register the masks again. Nothing was declared." -) -OTHER_AXES = ( - "The axes confirmed in cell 3 ({confirmed}) are not those the segmented run recorded " - "({recorded}): its masks were made on the images read with the recorded axes. In cell 3, " - "step Axes, confirm the recorded axes, then press Register the masks again. Nothing was " - "declared." -) +CHANGED_SINCE_CHECK = "It was made again because {reasons}." +"""What follows :data:`AXES_AGAIN`: why the folders were checked again (v0.9.1).""" +PAIRING = "Pairing the masks folder (folders and image headers unchanged: your axes are kept)" +"""The step line when the masks are paired without a new folder check (v0.9.1).""" CHOICES = [ ( "Each object has its own number (label image: every cell/nucleus is a separate object)", @@ -108,9 +107,13 @@ WHY_WE_ASK = ( "We ask because the two are measured differently, and we never guess which one a file is." ) +BINARY_REFUSED_CODE = "cellpose_mask_not_binary" +"""The code of the refusal of a binary answer for a mask cell 4 wrote (v0.9.1, #578).""" BINARY_REFUSED = ( "{mask_type} cannot be registered as foreground / background only: cell 4 wrote it with " - "Cellpose, which gives each object its own number" + "Cellpose, which gives each object its own number, so it is a label image and is never " + "taken for a binary mask (a binary mask from elsewhere is declared in cell 3, step Masks; " + f"{BINARY_REFUSED_CODE})" ) """Why a binary answer is not registered (a phrase beside the disabled button).""" CHECK_FAILED = ( @@ -153,27 +156,6 @@ def written_types(segmentation: object) -> tuple[str, ...]: ) -def _collision(app: object, mask_type: str) -> str: - """Return the refusal of ``mask_type`` when the app's description declares it, else "". - - A declaration whose mask ID or source type is ``mask_type`` (ignoring case) collides, - unless it is exactly the one offered (an earlier press of **Register the masks** that - stopped later, at the save or the run, already gave it). - """ - answers = getattr(app, "draft_answers", None) - masks = getattr(answers, "masks", None) or {} - folded = nfc(mask_type).casefold() - for mask_id, mask in masks.items(): - offered = (mask_id, mask.source_type, mask.representation) - if offered == (mask_type, mask_type, INSTANCES): - continue - if folded in (nfc(mask_id).casefold(), nfc(mask.source_type).casefold()): - return COLLISION.format( - mask_type=mask_type, mask_id=mask_id, source_type=mask.source_type - ) - return "" - - def _app_run(app: object, rechecked: bool) -> tuple[str, str]: """Return the app's run and masks folder (:func:`.notebook_cellpose_app.app_folders`). @@ -188,14 +170,20 @@ def _app_run(app: object, rechecked: bool) -> tuple[str, str]: def refusal( - app: object, segmentation: object, *, rechecked: bool = False, checking: Checking = quiet + app: object, + segmentation: object, + *, + rechecked: bool = False, + checking: Checking = quiet, + memo: ContentMemo | None = None, ) -> str: """Return why the masks of cell 4 cannot be registered in the app's run, or "". ``rechecked``: cell 5 made the app's folder check for this run (also read from the segmentation's ``rechecked_run``, so cell 5 run again after the axes stop continues). ``checking`` is told each phase of opening the run (:func:`.segmentation_cellpose_run. - open_run`); it changes nothing checked or decided. + open_run`); it changes nothing checked or decided. ``memo``: the press's content SHA-256s + (:mod:`.content_memo`). """ types = written_types(segmentation) if not types: @@ -218,7 +206,7 @@ def refusal( if app_masks and Path(app_masks).resolve() != masks: return OTHER_MASKS.format(segmented=masks, app_masks=app_masks) try: - open_run(os.fspath(segmented), checking=checking) + open_run(os.fspath(segmented), checking=checking, memo=memo) except UnrecordedFilesError as exc: if not _only_written(exc, masks, types): return CHANGED.format(reason=exc) @@ -235,88 +223,41 @@ def refusal( return "" -def _same_publication(segmentation: object, segmented: Path) -> bool: - """Return whether the run's manifest is the one cell 4 segmented, or cell 5's own. +class MaskRegistration(ShownFirst, widgets.VBox): + """Cell 5's widget: what each mask type is, and **Register the masks**. - Cell 4 pins the manifest's SHA-256 when it opens the run (``run_manifest_sha256``, - :func:`.segmentation_cellpose_run.open_pinned`); a run published again since (cell 3 run - again, perhaps on changed images or other axes) is not the run the masks were made on. The - only other publication accepted is the one cell 5 made registering them - (``registered_manifest``), so that cell 5 run again after it is not refused. + It is built without reading a file; :meth:`check` then opens the run cell 4 segmented, + with its wait on screen (the #575 show-first pattern, v0.9.1), and shows the refusal when + the masks cannot be registered. """ - now = manifest_sha256(segmented) - pinned = getattr(segmentation.workflow, "run_manifest_sha256", None) - ours = getattr(segmentation, "registered_manifest", None) - return now is not None and now in {pinned, ours} - - -def _only_written(exc: UnrecordedFilesError, masks: Path, types: tuple[str, ...]) -> bool: - """Return whether the run left out only masks cell 4 wrote: files in ``masks//``. - - Those are the masks to register (the run before them could not record them). An image, - a label image or any other mask the run did not record is still refused. - """ - return not exc.files.images and all( - len(Path(path).parts) > 1 and Path(path).parts[0] in types and (masks / path).is_file() - for path in exc.files.masks - ) - - -def _mapping_text(mapping: object) -> str: - """Return an axis mapping on one line (:func:`.report.mapping_summary`'s words).""" - return "; ".join(line.strip() for line in mapping_summary(mapping).splitlines()) - - -def _other_experiment(app: object, inputs: object) -> str: - """Return why the app's experiment or confirmed axes are not the segmented run's, or "". - - The app's checked experiment must be the run's experiment, and the axes confirmed in the - app must be the axis mapping the run's manifest records: the masks were made on the images - read with those axes. Read before anything is declared, saved or run. - """ - app_root = Path(app.preflight.discovery.root).resolve() - segmented = Path(inputs.experiment_root).resolve() - if app_root != segmented: - return OTHER_EXPERIMENT.format(app_root=app_root, segmented=segmented) - try: - recorded = read_manifest(Path(inputs.output_folder) / MANIFEST_FILENAME).mapping - except (OSError, ManifestFormatError) as exc: - return CHANGED.format(reason=exc) - confirmed = app.confirmed_mapping - if (confirmed.axes, tuple(confirmed.roles)) != (recorded.axes, tuple(recorded.roles)): - return OTHER_AXES.format( - confirmed=_mapping_text(confirmed), recorded=_mapping_text(recorded) - ) - return "" - - -class MaskRegistration(widgets.VBox): - """Cell 5's widget: what each mask type is, and **Register the masks**.""" def __init__(self, app: object, segmentation: object) -> None: - """Ask what each mask is, or show why the masks cannot be registered.""" + """Ask what each mask is; the run is checked by :meth:`check`.""" super().__init__(layout=widgets.Layout(width="99%")) self.app, self.segmentation = app, segmentation self.status = widgets.HTML() + self.opening = widgets.HTML() # the wait of the run's checks when cell 5 is shown self.choices: dict[str, widgets.RadioButtons] = {} self.registered = False - why = refusal(app, segmentation) - if why: - self.status.value = ui.status("error", "The masks cannot be registered", [why]) - self.children = [widgets.HTML(ui.STYLE_CSS), self.status] - return - rows = [self._question(mask_type) for mask_type in written_types(segmentation)] + self.refused = "" + self.skip_next_display = False self.button = ui.button("Register the masks", icon="check", main=True) self.button.on_click(lambda _: self.register()) self.blocker = widgets.HTML() self.progress, self.progress_detail = widgets.HTML(), widgets.HTML() + types = written_types(segmentation) + if not types: + self._show_refusal(NO_MASKS) + return + rows = [self._question(mask_type) for mask_type in types] self._update() text = ( "For each mask type cell 4 wrote, say what the mask is. " - f"{html.escape(WHY_WE_ASK)} Then press Register the masks: the app of " - "cell 3 checks the folders again with the masks folder, saves the description, " - "runs again (the histograms are reused) and describes the masks; each step is " - "shown here as it goes." + f"{html.escape(WHY_WE_ASK)} Then press Register the masks: it checks the " + "run cell 4 segmented, pairs the masks folder in the app of cell 3 (checking the " + "folders again only when something changed since cell 3 checked them), saves the " + "description, runs again (the histograms are reused) and describes the masks; each " + "step is shown here as it goes." ) body = [ ui.help_text(text), @@ -326,7 +267,27 @@ def __init__(self, app: object, segmentation: object) -> None: self.progress_detail, self.status, ] - self.children = [widgets.HTML(ui.STYLE_CSS), ui.card("Register the masks", body)] + self.children = [ + widgets.HTML(ui.STYLE_CSS), + self.opening, + ui.card("Register the masks", body), + ] + + def check(self) -> str: + """Open the run cell 4 segmented, showing the wait; return the refusal or "".""" + if not self.choices: + return self.refused + with opening(self.opening) as checking: + why = refusal(self.app, self.segmentation, checking=checking) + if why: + self._show_refusal(why) + return why + + def _show_refusal(self, why: str) -> None: + """Show why the masks cannot be registered, in place of the question.""" + self.refused, self.choices = why, {} + self.status.value = ui.status("error", "The masks cannot be registered", [why]) + self.children = [widgets.HTML(ui.STYLE_CSS), self.opening, self.status] def _question(self, mask_type: str) -> widgets.VBox: """Return the question about ``mask_type``, with no answer chosen, and its declaration. @@ -375,24 +336,31 @@ def register(self) -> bool: self.status.value = "" try: with RegisterWait(self.progress, self.progress_detail).running() as wait: - return self._register(wait) + return self._register(wait, ContentMemo()) # one memo per press, then gone except BaseException as exc: # a click handler's error is never shown in this cell self._stop(STOPPED.format(problem=f"{type(exc).__name__}: {exc}")) raise finally: self._update() - def _register(self, wait: RegisterWait) -> bool: - """Do the steps of :meth:`register`, each named by ``wait``; True when done.""" + def _register(self, wait: RegisterWait, memo: ContentMemo) -> bool: + """Do the steps of :meth:`register`, each named by ``wait``; True when done. + + ``memo`` holds the content SHA-256s this press takes: the run's content pass and its + opening after it reuse one while the file's identity is unchanged; the run's check + before it publishes never does (:mod:`.content_memo`, owner on #578). + """ with wait.step("run"): - why = refusal(self.app, self.segmentation, checking=wait.checking) + why = refusal(self.app, self.segmentation, checking=wait.checking, memo=memo) if why: return self._stop(why) - if not self._check_folders(wait): # its reason is drawn in cell 3: say it here + reasons: list[str] = [] + if not self._check_folders(wait, reasons): # its reason is drawn in cell 3: say it here return self._stop(CHECK_FAILED.format(reason=_plain(self.app.folder_status.value))) app = self.app - if app.confirmed_mapping is None: - return self._stop(AXES_AGAIN) + if app.confirmed_mapping is None: # only after a folder check made for a change + because = CHANGED_SINCE_CHECK.format(reasons="; ".join(reasons)) if reasons else "" + return self._stop(f"{AXES_AGAIN} {because}".strip()) why = _other_experiment(app, self.segmentation.workflow.inputs) if why: # the axes stop lets the user change the app: check it is still the run's return self._stop(why) @@ -402,32 +370,48 @@ def _register(self, wait: RegisterWait) -> bool: return self._stop(why) if not app.save_experiment(): return self._stop(NOT_SAVED) - with wait.step("rerun", getattr(app, "run_status", None)): + with wait.step("rerun", getattr(app, "run_status", None)), _pressed(app, memo): result = app.run() if result is None or not result.written: return self._stop("The run of cell 3 stopped: its step Run says why.") # Kept on cell 4's step: this publication is the registration's (cell 5 run again). self.segmentation.registered_manifest = manifest_sha256(Path(result.output_folder)) - with wait.step("describe", getattr(app, "mask_step_status", None)): + with wait.step("describe", getattr(app, "mask_step_status", None)), _pressed(app, memo): app.mask_step_button.click() # the app's Describe the masks self.registered = True self.status.value = self._registered_html(result) return True - def _check_folders(self, wait: RegisterWait) -> bool: - """Make the app's folder check with the masks folder, unless its last one has them. - - Returns False when the check was made and failed (#580): the app then has no check. - """ - app, masks = self.app, Path(self.segmentation.workflow.masks_root).resolve() - found = getattr(app.preflight, "masks", None) + def _has_masks(self) -> bool: + """Return whether the app's last check paired the masks folder with every mask type.""" + masks = Path(self.segmentation.workflow.masks_root).resolve() + found = getattr(getattr(self.app, "preflight", None), "masks", None) checked = getattr(found, "folder", None) - if ( + return ( checked is not None and Path(checked).resolve() == masks and all(t in found.types for t in self.choices) # else checked before cell 4 wrote - ): + ) + + def _check_folders(self, wait: RegisterWait, reasons: list[str]) -> bool: + """Pair the masks folder in the app; check the folders again only after a change. + + When nothing changed since the app's folder check (:func:`.register_unchanged. + changes_since_check`), the app's own *Check the masks again* pairs the masks and keeps + its confirmed axes (v0.9.1: one press). Otherwise the app's folder check is made again + and ``reasons`` gets what changed. Returns False when that check failed (#580). + """ + app, masks = self.app, Path(self.segmentation.workflow.masks_root).resolve() + if self._has_masks(): return True + reasons[:] = changes_since_check(app, self.segmentation.workflow.inputs) + if not reasons: + with wait.step("folders", getattr(app, "masks_wait", None), PAIRING): + app.masks_folder.value = os.fspath(masks) + app._check_masks() # the app's Check the masks again: only the masks' headers + if self._has_masks(): + return True + reasons.append("pairing the masks folder alone did not find every mask type") with wait.step("folders", getattr(app, "folder_status", None)): app.masks_folder.value = os.fspath(masks) pre = app.check_folder() # the app's Scan the folders, now with the masks folder @@ -468,18 +452,63 @@ def _registered_html(self, result: object) -> str: ) +@contextmanager +def _pressed(app: object, memo: ContentMemo) -> Iterator[None]: + """Give the app's run and its opening after it the press's ``memo`` while the block runs. + + Read by the app as ``_press_memo`` (:meth:`.notebook_run._RunStep._run_mode`, the tissue + mask card's opening); removed when the block ends, so no later click of cell 3 uses it. + """ + app._press_memo = memo + try: + yield + finally: + app._press_memo = None + + def _plain(text: str) -> str: """Return the text of an HTML message on one line.""" return " ".join(html.unescape(re.sub(r"<[^>]+>", " ", text)).split()) or "not saved" -def register_step(app: object, segmentation: object) -> MaskRegistration: - """Return cell 5's widget for the Preprocessing app of cell 3 and the segmentation of cell 4.""" - return MaskRegistration(app, segmentation) +def _shown_first(registration: MaskRegistration) -> None: + """Display cell 5's widget now; the cell's own ``display(registration)`` then adds nothing.""" + display(registration) + registration.skip_next_display = True + + +_DEFAULT = object() +"""``show`` not given: :func:`_shown_first` in a kernel, else None.""" + + +def register_step( + app: object, + segmentation: object, + *, + show: Callable[[MaskRegistration], object] | None | object = _DEFAULT, +) -> MaskRegistration: + """Return cell 5's widget for the Preprocessing app of cell 3 and the segmentation of cell 4. + + ``show`` is called with the widget before the run is checked, so that the wait of its + checks is on screen (#575's pattern for cell 4, applied to cell 5 in v0.9.1); None: the + widget is returned checked, for the caller to show. By default, in a notebook, it is + displayed first, and the cell's ``display(registration)`` that follows shows nothing more: + cell 5 is the same for the release it pins and for this code. + """ + registration = MaskRegistration(app, segmentation) + if show is _DEFAULT: + show = _shown_first if get_ipython() is not None else None + if show is not None: + show(registration) + registration.check() + return registration __all__ = [ "BINARY_REFUSED", + "BINARY_REFUSED_CODE", + "CHANGED_SINCE_CHECK", + "PAIRING", "CHOICES", "WHY_WE_ASK", "MaskRegistration", diff --git a/src/morphobricks_preprocessing/notebook_mask_step.py b/src/morphobricks_preprocessing/notebook_mask_step.py index 93a05d69..e3f8eaed 100644 --- a/src/morphobricks_preprocessing/notebook_mask_step.py +++ b/src/morphobricks_preprocessing/notebook_mask_step.py @@ -113,7 +113,7 @@ def _refresh_mask_step(self) -> None: ui.set_visible(self.mask_conversion.card, self._show_output) output = self._mask_step_output() self.mask_conversion.refresh(output) - self.tissue_mask.refresh(output) + self.tissue_mask.refresh(output, memo=getattr(self, "_press_memo", None)) ui.set_visible(self.tissue_mask.card, self._show_output and self.tissue_mask.has_rgb) manifest = None if output is None else current_fingerprint(output / MANIFEST_FILENAME) if self._mask_step_seen == (output, manifest): diff --git a/src/morphobricks_preprocessing/notebook_preprocessing_cellpose.py b/src/morphobricks_preprocessing/notebook_preprocessing_cellpose.py index 1cb65f4c..60b9f4a7 100644 --- a/src/morphobricks_preprocessing/notebook_preprocessing_cellpose.py +++ b/src/morphobricks_preprocessing/notebook_preprocessing_cellpose.py @@ -44,6 +44,7 @@ from .notebook_open_progress import opening from .notebook_progress import Wait from .notebook_render import blocked_line +from .notebook_shown_first import ShownFirst from .open_checks import Checking, quiet from .run_inputs import RunInputsError from .segmentation_cellpose_run import open_run @@ -74,7 +75,7 @@ ) -class SegmentationStep(widgets.VBox): +class SegmentationStep(ShownFirst, widgets.VBox): """Cell 4's widget: what it found in the app, the installation if needed, the component. Attributes @@ -146,23 +147,6 @@ def check(self) -> None: self.refused = _refusal(self.run_folder, checking) self.notice.value = self._notice() - 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 def workflow(self) -> CellposeNotebook | None: """The segmentation's state (its masks folder and results), or None before it shows.""" diff --git a/src/morphobricks_preprocessing/notebook_register_progress.py b/src/morphobricks_preprocessing/notebook_register_progress.py index b037f3b8..94e89cf0 100644 --- a/src/morphobricks_preprocessing/notebook_register_progress.py +++ b/src/morphobricks_preprocessing/notebook_register_progress.py @@ -48,10 +48,14 @@ """The line left when an error or an interrupt went through it.""" -def step_label(key: str) -> str: - """Return the line of step ``key`` of :data:`STEPS`: ``"Step 2 of 5 · "``.""" +def step_label(key: str, text: str | None = None) -> str: + """Return the line of step ``key`` of :data:`STEPS`: ``"Step 2 of 5 · "``. + + ``text`` words the step instead of :data:`STEPS` (the folders step when only the masks are + paired, v0.9.1). + """ number = list(STEPS).index(key) + 1 - return f"Step {number} of {len(STEPS)} · {STEPS[key]}" + return f"Step {number} of {len(STEPS)} · {text or STEPS[key]}" class RegisterWait: @@ -93,15 +97,17 @@ def running(self) -> Iterator[RegisterWait]: self.line.value = f"
{took}
" @contextmanager - def step(self, key: str, shown: widgets.HTML | None = None) -> Iterator[None]: + def step( + self, key: str, shown: widgets.HTML | None = None, text: str | None = None + ) -> Iterator[None]: """Name step ``key`` while the block runs; copy ``shown`` (the app's wait) under it. ``shown`` is the app's own status line of that step: each value the app draws there while the block runs is drawn under the step line too, then the copy stops and the - line under it is emptied. + line under it is emptied. ``text``: as :func:`step_label`. """ - if self.wait.label != step_label(key): - self.wait.phase(step_label(key)) + if self.wait.label != step_label(key, text): + self.wait.phase(step_label(key, text)) self.detail.value = "" def copy(change: dict) -> None: diff --git a/src/morphobricks_preprocessing/notebook_run.py b/src/morphobricks_preprocessing/notebook_run.py index 1d86534c..856381ed 100644 --- a/src/morphobricks_preprocessing/notebook_run.py +++ b/src/morphobricks_preprocessing/notebook_run.py @@ -250,6 +250,7 @@ def _run_mode(self, verify_content: bool | None) -> RunMode: workers=workers, max_ram=cap or None, checking=self._checking, + memo=getattr(self, "_press_memo", None), # cell 5's press (content_memo) ) def _build_histogram_range(self) -> list[widgets.Widget]: diff --git a/src/morphobricks_preprocessing/notebook_shown_first.py b/src/morphobricks_preprocessing/notebook_shown_first.py new file mode 100644 index 00000000..ec4415af --- /dev/null +++ b/src/morphobricks_preprocessing/notebook_shown_first.py @@ -0,0 +1,43 @@ +"""A cell's widget displayed before its long checks, then not again by the cell's ``display``. + +Cells 4 and 5 of the combined notebook keep their text (``x = step(...)`` then ``display(x)``), +so that they are the same for the release they pin and for this code (#575, v0.9.1). The step +function displays the widget first itself, so that the wait of the checks it then makes is on +screen, and sets :attr:`ShownFirst.skip_next_display`; the cell's own ``display`` then shows +nothing more, once. +""" + +from __future__ import annotations + +from IPython.display import display + + +class ShownFirst: + """Mixin for an ipywidgets box shown first by its step function (before ``widgets.VBox``). + + Attributes + ---------- + skip_next_display + True once the step function displayed the widget: the next display of this same widget + (the cell's own) is consumed and shows nothing; every later display shows it. + """ + + skip_next_display = False + + def _ipython_display_(self, **kwargs: object) -> None: + """Display the widget, unless its step function just did (then once nothing). + + 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) + + +__all__ = ["ShownFirst"] diff --git a/src/morphobricks_preprocessing/notebook_tissue_mask.py b/src/morphobricks_preprocessing/notebook_tissue_mask.py index dcb18918..723e3ffa 100644 --- a/src/morphobricks_preprocessing/notebook_tissue_mask.py +++ b/src/morphobricks_preprocessing/notebook_tissue_mask.py @@ -31,12 +31,13 @@ import numpy as np from . import notebook_style as ui +from .content_memo import ContentMemo from .fingerprint import current_fingerprint from .manifest import MANIFEST_FILENAME from .mask_conversion import _check_case_collision, _check_output_id from .notebook_render import blocked_line from .plane_errors import PlaneReadError -from .run_inputs import RunInputs +from .run_inputs import RunInputs, open_checked from .run_inputs_tissue import NOT_REUSED, PROVISIONAL_NOTE, tissue_next_steps INSTALL_HINT = 'pip install "morphobricks-preprocessing[he-mask]"' @@ -171,8 +172,12 @@ def _children(self) -> list[widgets.Widget]: self.result, ] - def refresh(self, output_folder: Path | None) -> None: - """Offer the RGB positions of the run in ``output_folder``; clear the card for another.""" + def refresh(self, output_folder: Path | None, *, memo: ContentMemo | None = None) -> None: + """Offer the RGB positions of the run in ``output_folder``; clear the card for another. + + ``memo``: the content SHA-256s the press that published the run already took + (:mod:`.content_memo`), reused while a file's identity is unchanged. + """ manifest = None if output_folder is None else output_folder / MANIFEST_FILENAME seen = (output_folder, None if manifest is None else current_fingerprint(manifest)) if seen == self._seen: # the same run: keep the last preview and result shown @@ -182,7 +187,7 @@ def refresh(self, output_folder: Path | None) -> None: greyed = [] if output_folder is not None and manifest.exists(): try: - self._run = RunInputs.open(output_folder) + self._run = open_checked(output_folder, memo=memo) except (OSError, ValueError) as exc: self._problem = str(exc) for fov in () if self._run is None else self._run.fovs(): diff --git a/src/morphobricks_preprocessing/register_checks.py b/src/morphobricks_preprocessing/register_checks.py new file mode 100644 index 00000000..9ad32fea --- /dev/null +++ b/src/morphobricks_preprocessing/register_checks.py @@ -0,0 +1,178 @@ +"""Cell 5's checks of the app of cell 3 against the run cell 4 segmented (moved, v0.9.1). + +The refusal helpers of :mod:`.notebook_mask_register` (a declaration that collides, a run +published again, files the run did not record, the app's experiment or axes) moved here +unchanged, to keep that module under the 600-line rule. + +Whether cell 5 can keep cell 3's confirmed axes: nothing changed since its folder check. + +v0.9.1 (owner, 26 November 2026): **Register the masks** needed two presses. Its first press +made the app's whole folder check again only to pair the masks folder, and that check always +clears the confirmed axes, so the press stopped to have them confirmed again. Now, when the +folders and the image headers are unchanged since cell 3's check, cell 5 pairs the masks with +the app's own *Check the masks again* (which reads only the masks' headers and keeps the rest) +and goes on in the same press. Unchanged means, for every image of the segmented run: + +- cell 3's check is of the run's experiment, and its axes are confirmed; +- the images it checked are exactly the run's images (the run's own opening has already listed + the folders for any file added since the run); +- each image's fingerprint now (size and modification time, :mod:`.fingerprint`) is the one + its header was read at (``Preflight.header_fingerprints``, bound when cell 3 checked it). + +Anything else is a change, and :func:`changes_since_check` says which, in words, so cell 5 can +say why the axes must be confirmed again. Nothing here decides an axis or reads a pixel. +""" + +from __future__ import annotations + +from pathlib import Path + +from .description_identity import nfc +from .fingerprint import current_fingerprint +from .manifest import MANIFEST_FILENAME, ManifestFormatError, read_manifest +from .mask_answers import INSTANCES +from .report import mapping_summary +from .run_inputs import UnrecordedFilesError +from .segmentation_cellpose_run import manifest_sha256 +from .validation import plural + +COLLISION = ( + "The mask type {mask_type} collides with the mask {mask_id} the description already " + "declares (source type {source_type}). Choose another mask type in cell 4 and segment " + "again; nothing is declared twice." +) +CHANGED = "The images changed since the run, or the run cannot be opened: {reason}" +OTHER_EXPERIMENT = ( + "The app of cell 3 now holds another experiment ({app_root}) than the one cell 4 " + "segmented ({segmented}). Check {segmented} again in cell 3 and confirm its axes, then " + "press Register the masks again. Nothing was declared." +) +OTHER_AXES = ( + "The axes confirmed in cell 3 ({confirmed}) are not those the segmented run recorded " + "({recorded}): its masks were made on the images read with the recorded axes. In cell 3, " + "step Axes, confirm the recorded axes, then press Register the masks again. Nothing was " + "declared." +) +SHOWN = 3 +"""How many changed images a reason names.""" + + +def changes_since_check(app: object, inputs: object) -> list[str]: + """Return what changed since the app's folder check, in plain words; [] when nothing did. + + Parameters + ---------- + app + The Preprocessing app of cell 3 (its ``preflight`` and ``confirmed_mapping``). + inputs + The run cell 4 segmented (:class:`.run_inputs.RunInputs`). + + Returns + ------- + list of str + Each reason the confirmed axes cannot be kept; empty when they can. + """ + pre = getattr(app, "preflight", None) + if pre is None: + return ["cell 3 holds no folder check"] + if getattr(app, "confirmed_mapping", None) is None: + return ["the axes are not confirmed in cell 3"] + root = Path(pre.discovery.root).resolve() + if root != Path(inputs.experiment_root).resolve(): + return [f"cell 3 checked another experiment ({root})"] + bound = pre.header_fingerprints + images = sorted(entry.relative_path for entry in inputs.manifest.files) + if not bound or sorted(bound) != images: + return ["the images cell 3 checked are not the images of the run"] + changed = [ + rel for rel in images if bound[rel] is None or current_fingerprint(root / rel) != bound[rel] + ] + if not changed: + return [] + named = ", ".join(changed[:SHOWN]) + (", …" if len(changed) > SHOWN else "") + return [f"{plural(len(changed), 'image')} changed since cell 3 checked the folder ({named})"] + + +def _collision(app: object, mask_type: str) -> str: + """Return the refusal of ``mask_type`` when the app's description declares it, else "". + + A declaration whose mask ID or source type is ``mask_type`` (ignoring case) collides, + unless it is exactly the one offered (an earlier press of **Register the masks** that + stopped later, at the save or the run, already gave it). + """ + answers = getattr(app, "draft_answers", None) + masks = getattr(answers, "masks", None) or {} + folded = nfc(mask_type).casefold() + for mask_id, mask in masks.items(): + offered = (mask_id, mask.source_type, mask.representation) + if offered == (mask_type, mask_type, INSTANCES): + continue + if folded in (nfc(mask_id).casefold(), nfc(mask.source_type).casefold()): + return COLLISION.format( + mask_type=mask_type, mask_id=mask_id, source_type=mask.source_type + ) + return "" + + +def _same_publication(segmentation: object, segmented: Path) -> bool: + """Return whether the run's manifest is the one cell 4 segmented, or cell 5's own. + + Cell 4 pins the manifest's SHA-256 when it opens the run (``run_manifest_sha256``, + :func:`.segmentation_cellpose_run.open_pinned`); a run published again since (cell 3 run + again, perhaps on changed images or other axes) is not the run the masks were made on. The + only other publication accepted is the one cell 5 made registering them + (``registered_manifest``), so that cell 5 run again after it is not refused. + """ + now = manifest_sha256(segmented) + pinned = getattr(segmentation.workflow, "run_manifest_sha256", None) + ours = getattr(segmentation, "registered_manifest", None) + return now is not None and now in {pinned, ours} + + +def _only_written(exc: UnrecordedFilesError, masks: Path, types: tuple[str, ...]) -> bool: + """Return whether the run left out only masks cell 4 wrote: files in ``masks//``. + + Those are the masks to register (the run before them could not record them). An image, + a label image or any other mask the run did not record is still refused. + """ + return not exc.files.images and all( + len(Path(path).parts) > 1 and Path(path).parts[0] in types and (masks / path).is_file() + for path in exc.files.masks + ) + + +def _mapping_text(mapping: object) -> str: + """Return an axis mapping on one line (:func:`.report.mapping_summary`'s words).""" + return "; ".join(line.strip() for line in mapping_summary(mapping).splitlines()) + + +def _other_experiment(app: object, inputs: object) -> str: + """Return why the app's experiment or confirmed axes are not the segmented run's, or "". + + The app's checked experiment must be the run's experiment, and the axes confirmed in the + app must be the axis mapping the run's manifest records: the masks were made on the images + read with those axes. Read before anything is declared, saved or run. + """ + app_root = Path(app.preflight.discovery.root).resolve() + segmented = Path(inputs.experiment_root).resolve() + if app_root != segmented: + return OTHER_EXPERIMENT.format(app_root=app_root, segmented=segmented) + try: + recorded = read_manifest(Path(inputs.output_folder) / MANIFEST_FILENAME).mapping + except (OSError, ManifestFormatError) as exc: + return CHANGED.format(reason=exc) + confirmed = app.confirmed_mapping + if (confirmed.axes, tuple(confirmed.roles)) != (recorded.axes, tuple(recorded.roles)): + return OTHER_AXES.format( + confirmed=_mapping_text(confirmed), recorded=_mapping_text(recorded) + ) + return "" + + +__all__ = [ + "CHANGED", + "COLLISION", + "OTHER_AXES", + "OTHER_EXPERIMENT", + "changes_since_check", +] diff --git a/src/morphobricks_preprocessing/run/modes.py b/src/morphobricks_preprocessing/run/modes.py index d71ffb32..316d5409 100644 --- a/src/morphobricks_preprocessing/run/modes.py +++ b/src/morphobricks_preprocessing/run/modes.py @@ -27,6 +27,7 @@ from dataclasses import dataclass, field from typing import Literal +from ..content_memo import ContentMemo from ..lab_links import LabLinks RESTART = "restart" @@ -97,6 +98,11 @@ class RunMode: then in a ``verify_content`` run :data:`.phases.CONTENTS`, once per image hashed. On a large experiment this check takes minutes (owner test of v0.9.0). Operational only, like ``workers``: not recorded, not compared, and the outputs are the same. + memo + Within one press of the notebook, the content SHA-256s the press already took + (:mod:`..content_memo`): the run's content pass reuses one while the file's identity is + unchanged. Its check before it publishes never does. Operational only, like + ``checking``; None (the default): every image is read whole. """ name: str = RESTART @@ -105,6 +111,7 @@ class RunMode: workers: int | Literal["auto"] = 1 max_ram: int | None = None checking: Callable[[str, int, int, str], None] | None = field(default=None, compare=False) + memo: ContentMemo | None = field(default=None, compare=False) def run_mode(mode: object) -> RunMode: @@ -138,6 +145,8 @@ def run_mode(mode: object) -> RunMode: check_workers(mode.workers, mode.max_ram) if mode.checking is not None and not callable(mode.checking): raise ValueError(f"checking must be callable or None; found {mode.checking!r}") + if mode.memo is not None and not isinstance(mode.memo, ContentMemo): + raise ValueError(f"memo must be a ContentMemo or None; found {mode.memo!r}") return RunMode( check_mode(mode.name), mode.verify_content, @@ -145,6 +154,7 @@ def run_mode(mode: object) -> RunMode: mode.workers, mode.max_ram, mode.checking, + mode.memo, ) diff --git a/src/morphobricks_preprocessing/run/pipeline.py b/src/morphobricks_preprocessing/run/pipeline.py index 8522b68d..fc0c4923 100644 --- a/src/morphobricks_preprocessing/run/pipeline.py +++ b/src/morphobricks_preprocessing/run/pipeline.py @@ -219,7 +219,13 @@ def run_experiment( # noqa: PLR0913 with output_lock(output): reading = Workers(chosen.workers, chosen.max_ram) options = RunOptions( - mode, memory_limit, progress, chosen.lab_links, reading, chosen.checking + mode, + memory_limit, + progress, + chosen.lab_links, + reading, + chosen.checking, + chosen.memo, ) return _locked_run(given, output, options) except OutputLockedError as exc: @@ -276,7 +282,7 @@ def _locked_run(given: GivenInputs, output: Path, options: RunOptions) -> RunRes histogram=inputs.histogram_settings, verify_content=inputs.verify_content, ) - reporting = Reporting(options.progress, options.checking) + reporting = Reporting(options.progress, options.checking, options.memo) rows = compute_rows( pre, checked, settings, output, previous, options.mode, reporting, options.workers ) diff --git a/src/morphobricks_preprocessing/run/state.py b/src/morphobricks_preprocessing/run/state.py index 3081eb80..ad8ef1ee 100644 --- a/src/morphobricks_preprocessing/run/state.py +++ b/src/morphobricks_preprocessing/run/state.py @@ -10,6 +10,7 @@ from dataclasses import dataclass, field from pathlib import Path +from ..content_memo import ContentMemo from ..lab_links import LabLinks from ..manifest import RunManifest from .description_run import RunDescription @@ -30,6 +31,8 @@ class RunOptions: workers: Workers = field(default_factory=Workers) checking: Callable[[str, int, int, str], None] | None = None """The progress of the run's own folder and header check (:func:`.preflight.preflight`).""" + memo: ContentMemo | None = None + """The content SHA-256s one notebook press already took (:attr:`.modes.RunMode.memo`).""" @dataclass(frozen=True) diff --git a/src/morphobricks_preprocessing/run/steps.py b/src/morphobricks_preprocessing/run/steps.py index 86a16bd1..d1b96503 100644 --- a/src/morphobricks_preprocessing/run/steps.py +++ b/src/morphobricks_preprocessing/run/steps.py @@ -16,6 +16,7 @@ from ..axes import AxisReview from ..axis_review import review_axes +from ..content_memo import ContentMemo from ..dataset import check_dataset from ..design import DesignTable, design_issues, reconcile_design from ..discovery_report import RunOutcome @@ -181,10 +182,13 @@ class Reporting: checking As :attr:`.modes.RunMode.checking`: here the phase :data:`.phases.CONTENTS`, each image's content SHA-256 in a ``verify_content`` run. + memo + As :attr:`.modes.RunMode.memo`: the SHA-256s one notebook press already took. """ reading: Callable[[int, int, str], None] | None = None checking: Callable[[str, int, int, str], None] | None = None + memo: ContentMemo | None = None def contents(self, done: int, total: int, path: str) -> None: """Report the content SHA-256 of image ``done`` of ``total`` (phase ``contents``).""" @@ -291,7 +295,7 @@ def compute_rows( # Strict reuse: each image's content SHA-256 joins its row key; an unreadable one fails. # Each image read whole (minutes on Google Drive): reported, before the first read. entries, unhashed = ( - with_content(entries, root, reporting.contents) + with_content(entries, root, reporting.contents, reporting.memo) if settings.verify_content else (entries, []) ) diff --git a/src/morphobricks_preprocessing/run_inputs.py b/src/morphobricks_preprocessing/run_inputs.py index 53dc76ae..c863466d 100644 --- a/src/morphobricks_preprocessing/run_inputs.py +++ b/src/morphobricks_preprocessing/run_inputs.py @@ -98,7 +98,7 @@ ) from .run_inputs_tissue import TissueMaskInputs from .run_inputs_window import WindowInputs, _check_planes, _coordinate, _mapping -from .source_content import content_changed +from .source_content import ContentMemo, content_changed from .unrecorded import UnrecordedFiles, unrecorded_files from .zarr_input import NgffError, ZarrUnavailableError @@ -379,13 +379,13 @@ def histograms(self) -> tuple[PlaneRecord, ...]: """Return the table's rows, as read when the run was opened.""" return self.records - def _check_files(self, checking: Checking = quiet) -> None: + def _check_files(self, checking: Checking = quiet, memo: ContentMemo | None = None) -> None: """Refuse changed or gone files, masks without axes or shared, unrecorded files.""" 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: entries = counted(checking, "contents", self.manifest.files, RELATIVE) - changed = content_changed(entries, self.experiment_root) + changed = content_changed(entries, self.experiment_root, memo) if changed: raise RunInputsError(_changed_text(changed)) recorded = (self.manifest.masks or {}).get("files", ()) @@ -461,8 +461,9 @@ def open_checked( masks_root: str | os.PathLike | None = None, *, checking: Checking = quiet, + memo: ContentMemo | None = None, ) -> RunInputs: - """Open a run as :meth:`RunInputs.open` does, telling ``checking`` (:mod:`.open_checks`).""" + """Open a run as :meth:`RunInputs.open` does, with ``checking`` and ``memo`` (one press).""" output = Path(output_folder).resolve() checking("run", 0, 0, "") # One generation of the outputs (contract §9): read again if a run published meanwhile. @@ -472,7 +473,7 @@ def open_checked( 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) + inputs._check_files(checking, memo) return inputs diff --git a/src/morphobricks_preprocessing/segmentation_cellpose_run.py b/src/morphobricks_preprocessing/segmentation_cellpose_run.py index 19d38de3..1bddcd8e 100644 --- a/src/morphobricks_preprocessing/segmentation_cellpose_run.py +++ b/src/morphobricks_preprocessing/segmentation_cellpose_run.py @@ -10,6 +10,7 @@ from pathlib import Path from ._io import file_sha256 +from .content_memo import ContentMemo from .manifest import MANIFEST_FILENAME from .open_checks import Checking, quiet from .run_inputs import RunInputs, open_checked @@ -39,11 +40,14 @@ """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, *, checking: Checking = quiet) -> RunInputs: +def open_run( + run_folder: str, *, checking: Checking = quiet, memo: ContentMemo | None = None +) -> 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. + changes nothing they check or decide. ``memo``: the content SHA-256s one notebook press + already took (:mod:`.content_memo`). Raises ------ @@ -54,7 +58,7 @@ def open_run(run_folder: str, *, checking: Checking = quiet) -> RunInputs: """ if not run_folder.strip(): raise SegmentationError("Give the run's output folder (the one holding run_manifest.json).") - return open_checked(Path(run_folder.strip()), checking=checking) + return open_checked(Path(run_folder.strip()), checking=checking, memo=memo) def open_pinned(run_folder: str, *, checking: Checking = quiet) -> tuple[RunInputs, str | None]: diff --git a/src/morphobricks_preprocessing/source_content.py b/src/morphobricks_preprocessing/source_content.py index 31ba8d41..88c2a3c0 100644 --- a/src/morphobricks_preprocessing/source_content.py +++ b/src/morphobricks_preprocessing/source_content.py @@ -24,6 +24,7 @@ from dataclasses import replace from pathlib import Path +from .content_memo import ContentMemo from .inventory import store_files from .manifest import FileEntry, file_sha256 @@ -58,9 +59,15 @@ def source_content_sha256(path: str | os.PathLike) -> str: return digest.hexdigest() -def current_content(path: Path) -> str | None: - """Return an image's content SHA-256 now, or None when it cannot be read.""" +def current_content(path: Path, memo: ContentMemo | None = None) -> str | None: + """Return an image's content SHA-256 now, or None when it cannot be read. + + With ``memo`` (one press of the notebook, :mod:`.content_memo`), a SHA-256 the press + already took is reused while the file's identity is unchanged. + """ try: + if memo is not None: + return memo.sha256(path, source_content_sha256) return source_content_sha256(path) except OSError: logger.warning("Cannot hash the content of %s", path, exc_info=True) @@ -71,6 +78,7 @@ def with_content( entries: Mapping[str, FileEntry], root: Path, progress: Callable[[int, int, str], None] | None = None, + memo: ContentMemo | None = None, ) -> tuple[dict[str, FileEntry], list[str]]: """Record each image's content SHA-256 in its entry. @@ -84,6 +92,9 @@ def with_content( Called as ``progress(done, total, relative_path)`` before each image is hashed, and as ``progress(total, total, "")`` at the end: each image is read whole, which takes seconds for a large image on slow storage. It changes nothing about the result. + memo + The SHA-256s one press already took (:mod:`.content_memo`), reused only while a + file's identity is unchanged; None: every image is read whole. Returns ------- @@ -96,7 +107,7 @@ def with_content( for done, (rel, entry) in enumerate(entries.items()): if progress is not None: progress(done, total, rel) - sha = current_content(root / rel) + sha = current_content(root / rel, memo) if sha is None: unreadable.append(rel) found[rel] = replace(entry, content_sha256=sha) @@ -105,7 +116,9 @@ def with_content( return found, unreadable -def content_changed(entries: Iterable[FileEntry], root: Path) -> list[str]: +def content_changed( + entries: Iterable[FileEntry], root: Path, memo: ContentMemo | None = None +) -> list[str]: """Return the images whose content SHA-256 now is not the one recorded (gone ones too). Parameters @@ -114,6 +127,8 @@ def content_changed(entries: Iterable[FileEntry], root: Path) -> list[str]: The entries of a ``verify_content`` run. root The experiment folder. + memo + As :func:`with_content`; the check before a run publishes never passes one. Returns ------- @@ -124,5 +139,5 @@ def content_changed(entries: Iterable[FileEntry], root: Path) -> list[str]: entry.relative_path for entry in entries if entry.content_sha256 is None - or current_content(root / entry.relative_path) != entry.content_sha256 + or current_content(root / entry.relative_path, memo) != entry.content_sha256 ) diff --git a/tests/test_cellpose_folders_open.py b/tests/test_cellpose_folders_open.py index b73e85ab..ea864dd8 100644 --- a/tests/test_cellpose_folders_open.py +++ b/tests/test_cellpose_folders_open.py @@ -221,8 +221,12 @@ def test_with_ipywidgets_7_the_step_is_displayed_by_the_widgets_own_display(app, 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)") + from morphobricks_preprocessing import notebook_shown_first # the shared mixin (v0.9.1) + published = [] - monkeypatch.setattr(step_module, "display", lambda obj, raw=False: published.append(obj)) + monkeypatch.setattr( + notebook_shown_first, "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_") diff --git a/tests/test_content_memo.py b/tests/test_content_memo.py new file mode 100644 index 00000000..5aff2829 --- /dev/null +++ b/tests/test_content_memo.py @@ -0,0 +1,123 @@ +"""One press's content SHA-256s, reused only while the file's identity is unchanged (#578 TODO 2). + +Owner decision on #578: within one press of **Register the masks**, a SHA-256 already taken of a +file is reused when its identity (device, inode, size, modification time; here also the +status-change time) is unchanged since it was hashed; any doubt means hashing again, and the +checks at publication never reuse one. +""" + +import hashlib +import os + +from morphobricks_preprocessing import content_memo +from morphobricks_preprocessing.content_memo import ContentMemo, file_identity +from morphobricks_preprocessing.manifest import FileEntry +from morphobricks_preprocessing.source_content import content_changed, with_content + + +def entry(name, sha256=None): + return FileEntry( + relative_path=name, size=0, mtime_ns=0, labels={}, axes="YX", content_sha256=sha256 + ) + + +def sha(data): + return hashlib.sha256(data).hexdigest() + + +def counting(calls): + def compute(path): + calls.append(path.name) + return sha(path.read_bytes()) + + return compute + + +def test_an_unchanged_file_is_hashed_once_per_memo(tmp_path): + image = tmp_path / "a.tif" + image.write_bytes(b"pixels") + memo, calls = ContentMemo(), [] + assert memo.sha256(image, counting(calls)) == sha(b"pixels") + assert memo.sha256(image, counting(calls)) == sha(b"pixels") + assert calls == ["a.tif"] and (memo.hashed, memo.reused) == (1, 1) + other, again = ContentMemo(), [] # another press: hashed again + other.sha256(image, counting(again)) + assert again == ["a.tif"] + + +def test_a_file_rewritten_with_the_same_size_and_mtime_is_hashed_again(tmp_path): + # Mutated between two checks of one press, keeping its size and modification time: the + # status-change time moved (os.utime cannot set it back), so the SHA-256 is taken again. + image = tmp_path / "a.tif" + image.write_bytes(b"pixels") + stat = image.stat() + memo, calls = ContentMemo(), [] + memo.sha256(image, counting(calls)) + image.write_bytes(b"PIXELS") + os.utime(image, ns=(stat.st_atime_ns, stat.st_mtime_ns)) + assert image.stat().st_size == stat.st_size and image.stat().st_mtime_ns == stat.st_mtime_ns + assert memo.sha256(image, counting(calls)) == sha(b"PIXELS") + assert calls == ["a.tif", "a.tif"] + + +def test_a_file_replaced_by_another_inode_is_hashed_again(tmp_path): + image = tmp_path / "a.tif" + image.write_bytes(b"pixels") + memo, calls = ContentMemo(), [] + memo.sha256(image, counting(calls)) + replacement = tmp_path / "b.tif" + replacement.write_bytes(b"pixels") + os.replace(replacement, image) + memo.sha256(image, counting(calls)) + assert len(calls) == 2 + + +def test_a_file_that_moves_while_it_is_hashed_is_not_remembered(tmp_path): + image = tmp_path / "a.tif" + image.write_bytes(b"pixels") + memo, calls = ContentMemo(), [] + + def touching(path): + calls.append(path.name) + path.write_bytes(b"pixel2") + return sha(b"pixels") + + memo.sha256(image, touching) + memo.sha256(image, counting(calls)) + assert calls == ["a.tif", "a.tif"] + + +def test_a_folder_is_never_remembered(tmp_path): + store = tmp_path / "image.zarr" + store.mkdir() + assert file_identity(store) is None and file_identity(tmp_path / "gone") is None + memo, calls = ContentMemo(), [] + memo.sha256(store, lambda path: calls.append(path) or "0" * 64) + memo.sha256(store, lambda path: calls.append(path) or "0" * 64) + assert len(calls) == 2 + + +def test_the_identity_rule_cannot_see_what_keeps_every_value(tmp_path, monkeypatch): + # Documented limit: a file system that keeps no status-change time (or a rewrite that keeps + # all five values) is not seen by the memo. The run's check before it publishes never uses + # a memo, so such a change is still caught there (see test_mask_register_progress.py). + image = tmp_path / "a.tif" + image.write_bytes(b"pixels") + frozen = file_identity(image) + monkeypatch.setattr(content_memo, "file_identity", lambda path: frozen) + memo = ContentMemo() + memo.sha256(image, counting([])) + image.write_bytes(b"PIXELS") + assert memo.sha256(image, counting([])) == sha(b"pixels") # the limit, as documented + assert content_changed([entry("a.tif", sha(b"pixels"))], tmp_path) == ["a.tif"] # caught + + +def test_with_content_and_content_changed_use_the_memo(tmp_path): + for name in ("a.tif", "b.tif"): + (tmp_path / name).write_bytes(name.encode()) + entries = {name: entry(name) for name in ("a.tif", "b.tif")} + memo = ContentMemo() + found, unreadable = with_content(entries, tmp_path, memo=memo) + assert unreadable == [] and memo.hashed == 2 + assert content_changed(found.values(), tmp_path, memo) == [] + assert (memo.hashed, memo.reused) == (2, 2) diff --git a/tests/test_mask_register_progress.py b/tests/test_mask_register_progress.py index 9bbdcded..e9d2aa1c 100644 --- a/tests/test_mask_register_progress.py +++ b/tests/test_mask_register_progress.py @@ -35,7 +35,9 @@ from morphobricks_preprocessing.description_file import DESCRIPTION_FILENAME # noqa: E402 from morphobricks_preprocessing.notebook_mask_register import ( # noqa: E402 BINARY_REFUSED, + BINARY_REFUSED_CODE, CHOICES, + PAIRING, WHY_WE_ASK, refusal, register_step, @@ -139,11 +141,9 @@ def segmented_app(tmp_path): def answered(nb, step): - """Return cell 5 answered for Cells, after the axes stop of its first press.""" + """Return cell 5 answered for Cells (one press registers it since v0.9.1).""" registration = register_step(nb, step) registration.choices["Cells"].value = "instances" - assert not registration.register() # the folder check asks for the axes again - nb.quick_confirm.click() return registration @@ -196,6 +196,9 @@ def test_a_binary_answer_is_refused_saying_why_and_nothing_is_declared(tmp_path, assert registration.button.disabled and not registration.register() text = BINARY_REFUSED.format(mask_type="Cells") assert text.split(":")[0] in registration.blocker.value + # #578 TODO 1: a coded refusal that says why (Cellpose numbers each object). + assert BINARY_REFUSED_CODE in registration.blocker.value + assert "gives each object its own number" in registration.blocker.value assert "[masks" not in (out / DESCRIPTION_FILENAME).read_text(encoding="utf-8") registration.choices["Cells"].value = "instances" assert not registration.button.disabled and registration.blocker.value == "" @@ -213,14 +216,16 @@ def test_the_recorded_declaration_is_unchanged(tmp_path, stub): # item 7: what Register reads, and its wait ---------------------------------------------------- -def test_register_reads_each_file_as_many_times_as_before(tmp_path, stub, larger, reads): - # Measured on main before #574 with this opener; pinned so that showing the wait reads - # nothing more. Per image: the run's checks (cell 5), the app's run, its check before it - # publishes and the tissue-mask step's opening after it, each a content SHA-256. The two - # viewers Check and save redraws twice also read the first image, about 4 times its size in - # all, through openings that each read a part of it (not whole reads here). Per mask: - # the run and its check before publishing (SHA-256), the mask step's fingerprints before - # and after reading, and its pixels (the piece counts). +def test_one_press_reads_each_image_whole_twice(tmp_path, stub, larger, reads): + # Before v0.9.1 (pinned here then): 4 whole reads per image per registering press (the + # run's checks in cell 5, the app's run, its check before it publishes, the tissue-mask + # step's opening), after a first press that stopped for the axes and read each image whole + # once more. Now one press, and within it a SHA-256 is reused while the file's identity is + # unchanged (#578 TODO 2): the run's content pass and the tissue-mask step's opening reuse + # the one cell 5's checks took; the check before the run publishes takes its own. Per mask: + # the run and its check before publishing (SHA-256), the mask step's fingerprints before and + # after reading, and its pixels, as before; the first mask is read once more, whole (it is + # small here), by the masks pairing that the first press's folder check used to make. nb, step = segmented_app(tmp_path) registration = answered(nb, step) images = sorted(f"exp/{f.relative_path}" for f in step.workflow.inputs.fovs()) @@ -229,12 +234,51 @@ def test_register_reads_each_file_as_many_times_as_before(tmp_path, stub, larger reads.opens.clear(), reads.whole.clear() assert registration.register(), registration.status.value first, *others = images - assert reads.whole == Counter({**dict.fromkeys(images, 4), **dict.fromkeys(masks, 5)}) + first_mask, *other_masks = masks + assert reads.whole == Counter( + {**dict.fromkeys(images, 2), first_mask: 6, **dict.fromkeys(other_masks, 5)} + ) assert reads.opens == Counter( - {first: 21, **dict.fromkeys(others, 9), **dict.fromkeys(masks, 7)} + {first: 24, **dict.fromkeys(others, 8), first_mask: 9, **dict.fromkeys(other_masks, 8)} ) +def test_a_file_changed_mid_press_is_still_caught(tmp_path, stub, monkeypatch): + # #578 TODO 2: an image rewritten between two checks of one press. Its status-change time + # moves, so the memo hashes it again. Where the identity cannot see a change (frozen here, + # as on a file system without one), the run's check before it publishes, which never uses + # the memo, still refuses it: nothing is declared as registered. + from morphobricks_preprocessing import content_memo + + nb, step = segmented_app(tmp_path) + registration = answered(nb, step) + image = tmp_path / "exp" / step.workflow.inputs.fovs()[0].relative_path + frozen = {} + real_identity = content_memo.file_identity + + def blind(path): + key = str(path) + frozen.setdefault(key, real_identity(path)) + return frozen[key] + + monkeypatch.setattr(content_memo, "file_identity", blind) + save = nb.save_experiment + + def save_then_change(): + saved = save() + stat = image.stat() + data = bytearray(image.read_bytes()) + data[-1] ^= 0xFF # same size; the modification time is set back below + image.write_bytes(bytes(data)) + os.utime(image, ns=(stat.st_atime_ns, stat.st_mtime_ns)) + return saved + + monkeypatch.setattr(nb, "save_experiment", save_then_change) + assert not registration.register() + assert not registration.registered + assert "The run of cell 3 stopped" in registration.status.value + + def test_showing_cell_5_reads_each_image_whole_once(tmp_path, stub, larger, reads): nb, step = segmented_app(tmp_path) reads.opens.clear(), reads.whole.clear() @@ -261,7 +305,8 @@ def spy(self, *args, **kwargs): assert registration.register(), registration.status.value for label in (step_label(k) for k in ("run", "save", "rerun", "describe")): assert any(label in line for line in lines), label - assert not any(step_label("folders") in line for line in lines) # made at the first press + assert not any(step_label("folders") in line for line in lines) # no folder check made + assert any(step_label("folders", PAIRING) in line for line in lines) # the masks paired hashed = [d for d in details if CHECKS["contents"] in d] for done, name in enumerate(names): assert any(f"{done} of 4" in d and name in d for d in hashed), name @@ -273,10 +318,11 @@ def spy(self, *args, **kwargs): assert not registration.button.disabled # back once it ended -def test_the_first_press_shows_the_folder_check_of_the_app(tmp_path, stub): +def test_a_press_after_a_change_shows_the_folder_check_of_the_app(tmp_path, stub): nb, step = segmented_app(tmp_path) registration = register_step(nb, step) registration.choices["Cells"].value = "instances" + nb.confirm_button.click() # the axes taken back in cell 3: the folders are checked again lines, details = [], [] registration.progress.observe(lambda c: lines.append(c["new"]), names="value") registration.progress_detail.observe(lambda c: details.append(c["new"]), names="value") @@ -308,3 +354,53 @@ def test_the_wait_says_stopped_after_an_error_and_stops_copying(): assert STOPPED_AFTER.split("{")[0] in line.value and detail.value == "" source.value = "later" assert detail.value == "" # copied only while its step ran + + +# #578 TODO 3: cell 5 is shown first, then opens the run with its wait (#575's pattern) ------- + + +def test_cell_5_is_shown_before_the_run_is_read_then_says_how_long(tmp_path, stub, reads): + from morphobricks_preprocessing import notebook_mask_register as cell_5 + from morphobricks_preprocessing.notebook_open_progress import TOOK + + nb, step = segmented_app(tmp_path) + reads.opens.clear(), reads.whole.clear() + seen = [] + + def show(registration): + seen.append((sum(reads.whole.values()), list(registration.choices))) + cell_5.display(registration) + + shown = [] + cell_5_display = cell_5.display + cell_5.display = shown.append + try: + registration = register_step(nb, step, show=show) + finally: + cell_5.display = cell_5_display + assert seen == [(0, ["Cells"])] # shown, with its question, before any image is read + assert shown == [registration] + assert sum(reads.whole.values()) == 4 # then the run is opened: each image once + assert TOOK.split("{")[0] in registration.opening.value + + +def test_cell_5_shown_first_is_not_shown_twice_by_the_cell(tmp_path, stub, monkeypatch): + from morphobricks_preprocessing import notebook_mask_register as module + + nb, step = segmented_app(tmp_path) + monkeypatch.setattr(module, "get_ipython", lambda: object()) # as in a notebook + shown = [] + monkeypatch.setattr(module, "display", shown.append) + registration = register_step(nb, step) + assert shown == [registration] and registration.skip_next_display + registration._ipython_display_() # the cell's own display(registration): nothing more + assert not registration.skip_next_display + + +def test_a_refusal_found_when_cell_5_opens_replaces_the_question(tmp_path, stub): + nb, step = segmented_app(tmp_path) + image = tmp_path / "exp" / step.workflow.inputs.fovs()[0].relative_path + image.write_bytes(image.read_bytes()[:-1] + b"\x07") + registration = register_step(nb, step, show=None) + assert registration.choices == {} and registration.refused + assert "The images changed since the run" in registration.status.value diff --git a/tests/test_notebook_preprocessing_cellpose.py b/tests/test_notebook_preprocessing_cellpose.py index d3a4f333..3742f0b8 100644 --- a/tests/test_notebook_preprocessing_cellpose.py +++ b/tests/test_notebook_preprocessing_cellpose.py @@ -10,8 +10,6 @@ import json import os import shutil -import subprocess -import sys from types import SimpleNamespace import pytest @@ -22,21 +20,11 @@ pytest.importorskip("ipywidgets") pytest.importorskip("matplotlib") -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, @@ -161,198 +149,6 @@ def test_the_line_after_the_batch_in_cell_4_names_cell_5_and_no_form_is_left(tmp assert "step 4" not in shown and "Save the description" not in shown -# installing Cellpose on first use ------------------------------------------------------------ - - -@pytest.fixture -def pip(monkeypatch, stub): - """Cellpose not installed; ``pip`` installs it (and may change numpy) when it runs.""" - state = SimpleNamespace(commands=[], numpy=None, lines=PIP_LINES, returncode=0, seen=[]) - stub.version = None - real = model.installed_version - - def version(name): - if name == "cellpose": - return stub.version - if name == "numpy" and state.numpy: - return state.numpy[1 if state.commands else 0] - return real(name) - - 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, "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 - assert "tick the installation" in step.install_blocker.value - assert not step.install() # a press without the tick installs nothing - assert pip.commands == [] and "Tick the installation first" in step.install_status.value - step.install_tick.value = True - assert not step.install_button.disabled and step.install() - (command,) = pip.commands - assert command[1:4] == ["-m", "pip", "install"] and command[-1] == "cellpose==4.2.1.1" - assert step.segmentation is not None and step.workflow.inputs is None # no masks folder yet - - -def test_dinov3_is_installed_before_cellpose_when_none_is_there(tmp_path, pip, stub): - # cpdino fix (v0.9.1): DINOv3 in place before Cellpose is ever imported, so a cpdino model - # loaded after a cpsam one needs no runtime restart. - stub.dinov3_commit = None - step = segmentation_step(ran_app(tmp_path)) - step.install_tick.value = True - assert step.install() - first, second = pip.commands - assert first == model.dinov3_install_command() and "--no-deps" in first - assert second[-1] == "cellpose==4.2.1.1" - - -def test_a_dinov3_already_installed_is_left_as_it_is(tmp_path, pip, stub): - stub.dinov3_commit, stub.dinov3_present = None, True # one of the user's own, commit unknown - step = segmentation_step(ran_app(tmp_path)) - step.install_tick.value = True - assert step.install() - (command,) = pip.commands - assert command[-1] == "cellpose==4.2.1.1" - - -def test_a_failed_dinov3_install_installs_no_cellpose(tmp_path, pip, stub): - stub.dinov3_commit, pip.returncode = None, 1 - step = segmentation_step(ran_app(tmp_path)) - step.install_tick.value = True - assert not step.install() - assert len(pip.commands) == 1 and "DINOv3" in step.install_status.value - assert "Cellpose was not installed" in step.install_status.value - assert step.segmentation is None - - -def test_an_install_that_changes_a_loaded_numpy_asks_for_a_restart(tmp_path, pip): - pip.numpy = ("2.0.0", "2.3.0") - step = segmentation_step(ran_app(tmp_path)) - step.install_tick.value = True - assert not step.install() - assert "numpy 2.0.0 -> 2.3.0" in step.install_status.value - assert "Restart the runtime" in step.install_status.value and step.segmentation is None - 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_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 - 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" - "from morphobricks_preprocessing.notebook_ui import PreprocessingNotebook\n" - "nb = PreprocessingNotebook()\n" - "nb.welcome(); nb.steps(); nb.results_step()\n" - "names = ('cellpose', 'torch', 'morphobricks_preprocessing.cellpose_install',\n" - " 'morphobricks_preprocessing.notebook_preprocessing_cellpose')\n" - "print(sorted(m for m in sys.modules if m.split('.')[0] in names[:2] or m in names))\n" - ) - out = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True, check=True) - assert out.stdout.strip() == "[]" - - # cell 5 --------------------------------------------------------------------------------------- @@ -369,11 +165,10 @@ def test_cell_5_asks_what_each_mask_is_and_registers_only_once_answered(tmp_path assert registration.button.disabled and not registration.register() # nothing silent assert "[masks" not in (out / DESCRIPTION_FILENAME).read_text(encoding="utf-8") registration.choices["Cells"].value = "instances" - # The app's folder check with the masks folder asks for the axes again: the user's click. - assert not registration.register() - assert AXES_AGAIN.split(":")[0] in registration.status.value - nb.quick_confirm.click() - assert registration.register() and registration.registered + # v0.9.1: nothing changed since cell 3's check, so its confirmed axes are kept and the + # masks are paired by the app's Check the masks again: one press registers them. + assert registration.register() and registration.registered, registration.status.value + assert AXES_AGAIN.split(":")[0] not in registration.status.value assert section in (out / DESCRIPTION_FILENAME).read_text(encoding="utf-8") assert nb.result.written and nb.result.read == () and nb.result.rebuild_reason is None manifest = json.loads((out / MANIFEST_FILENAME).read_text(encoding="utf-8")) @@ -396,24 +191,28 @@ def test_cell_5_registers_masks_written_into_the_runs_own_masks_folder(tmp_path, registration = register_step(nb, step) assert list(registration.choices) == ["Cells"], registration.status.value registration.choices["Cells"].value = "instances" - assert not registration.register() # the folder check is made again: axes to confirm - assert AXES_AGAIN.split(":")[0] in registration.status.value - nb.quick_confirm.click() - assert registration.register(), registration.status.value + assert registration.register(), registration.status.value # one press (v0.9.1) manifest = json.loads((out / MANIFEST_FILENAME).read_text(encoding="utf-8")) assert sorted(manifest["masks"]["types"]) == ["Cells", "Nuclei"] assert RunInputs.open(out).mask_types() == ("Cells", "Nuclei") def stopped_for_the_axes(tmp_path, stub): - """Return the app and cell 5 after its first press stopped for the axes, and the output.""" + """Return the app and cell 5 after its first press stopped for the axes, and the output. + + Since v0.9.1 the press stops only when something changed since cell 3's check: here the + user took the axes confirmation back in cell 3 (Change axis roles). + """ nb = ran_app(tmp_path) step = segmentation_step(nb) segment(step, tmp_path / "masks") registration = register_step(nb, step) registration.choices["Cells"].value = "instances" + nb.confirm_button.click() # Change axis roles: the axes are no longer confirmed + assert nb.confirmed_mapping is None assert not registration.register() assert AXES_AGAIN.split(":")[0] in registration.status.value + assert "the axes are not confirmed in cell 3" in registration.status.value # says why return nb, registration, nb._output_path(tmp_path / "exp") @@ -579,6 +378,7 @@ def pressed_with_a_failed_check(tmp_path, monkeypatch, error): segment(step, tmp_path / "masks") registration = register_step(nb, step) registration.choices["Cells"].value = "instances" + nb.confirm_button.click() # a change since cell 3's check: the press checks the folders real = notebook_folder.preflight def failing(*args, **kwargs): diff --git a/tests/test_notebook_preprocessing_cellpose_install.py b/tests/test_notebook_preprocessing_cellpose_install.py new file mode 100644 index 00000000..9bf03656 --- /dev/null +++ b/tests/test_notebook_preprocessing_cellpose_install.py @@ -0,0 +1,230 @@ +"""Cell 4's Install Cellpose step of the combined notebook (#441, #574 item 1, cpdino fix). + +Moved from ``test_notebook_preprocessing_cellpose.py`` (600-line rule). ``pip`` is replaced by +a stand-in that prints pip's lines; nothing is installed. +""" + +import subprocess +import sys +from types import SimpleNamespace + +import pytest + +from cellpose_stub import install + +pytest.importorskip("ipywidgets") +pytest.importorskip("matplotlib") + +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.cellpose_install import ( # noqa: E402 + install_changes, + installed_distributions, +) +from morphobricks_preprocessing.notebook_cellpose_install import pip_step # noqa: E402 +from morphobricks_preprocessing.notebook_preprocessing_cellpose import ( # noqa: E402 + segmentation_step, +) +from test_notebook_preprocessing_cellpose import ran_app # noqa: E402 + +pytestmark = pytest.mark.usefixtures("legacy_grid") + + +@pytest.fixture +def stub(monkeypatch, tmp_path): + return install(monkeypatch, tmp_path) + + +# installing Cellpose on first use ------------------------------------------------------------ + + +@pytest.fixture +def pip(monkeypatch, stub): + """Cellpose not installed; ``pip`` installs it (and may change numpy) when it runs.""" + state = SimpleNamespace(commands=[], numpy=None, lines=PIP_LINES, returncode=0, seen=[]) + stub.version = None + real = model.installed_version + + def version(name): + if name == "cellpose": + return stub.version + if name == "numpy" and state.numpy: + return state.numpy[1 if state.commands else 0] + return real(name) + + 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, "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 + assert "tick the installation" in step.install_blocker.value + assert not step.install() # a press without the tick installs nothing + assert pip.commands == [] and "Tick the installation first" in step.install_status.value + step.install_tick.value = True + assert not step.install_button.disabled and step.install() + (command,) = pip.commands + assert command[1:4] == ["-m", "pip", "install"] and command[-1] == "cellpose==4.2.1.1" + assert step.segmentation is not None and step.workflow.inputs is None # no masks folder yet + + +def test_dinov3_is_installed_before_cellpose_when_none_is_there(tmp_path, pip, stub): + # cpdino fix (v0.9.1): DINOv3 in place before Cellpose is ever imported, so a cpdino model + # loaded after a cpsam one needs no runtime restart. + stub.dinov3_commit = None + step = segmentation_step(ran_app(tmp_path)) + step.install_tick.value = True + assert step.install() + first, second = pip.commands + assert first == model.dinov3_install_command() and "--no-deps" in first + assert second[-1] == "cellpose==4.2.1.1" + + +def test_a_dinov3_already_installed_is_left_as_it_is(tmp_path, pip, stub): + stub.dinov3_commit, stub.dinov3_present = None, True # one of the user's own, commit unknown + step = segmentation_step(ran_app(tmp_path)) + step.install_tick.value = True + assert step.install() + (command,) = pip.commands + assert command[-1] == "cellpose==4.2.1.1" + + +def test_a_failed_dinov3_install_installs_no_cellpose(tmp_path, pip, stub): + stub.dinov3_commit, pip.returncode = None, 1 + step = segmentation_step(ran_app(tmp_path)) + step.install_tick.value = True + assert not step.install() + assert len(pip.commands) == 1 and "DINOv3" in step.install_status.value + assert "Cellpose was not installed" in step.install_status.value + assert step.segmentation is None + + +def test_an_install_that_changes_a_loaded_numpy_asks_for_a_restart(tmp_path, pip): + pip.numpy = ("2.0.0", "2.3.0") + step = segmentation_step(ran_app(tmp_path)) + step.install_tick.value = True + assert not step.install() + assert "numpy 2.0.0 -> 2.3.0" in step.install_status.value + assert "Restart the runtime" in step.install_status.value and step.segmentation is None + 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_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 + 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" + "from morphobricks_preprocessing.notebook_ui import PreprocessingNotebook\n" + "nb = PreprocessingNotebook()\n" + "nb.welcome(); nb.steps(); nb.results_step()\n" + "names = ('cellpose', 'torch', 'morphobricks_preprocessing.cellpose_install',\n" + " 'morphobricks_preprocessing.notebook_preprocessing_cellpose')\n" + "print(sorted(m for m in sys.modules if m.split('.')[0] in names[:2] or m in names))\n" + ) + out = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True, check=True) + assert out.stdout.strip() == "[]" diff --git a/tests/test_register_checks.py b/tests/test_register_checks.py new file mode 100644 index 00000000..a8ee1445 --- /dev/null +++ b/tests/test_register_checks.py @@ -0,0 +1,63 @@ +"""When cell 5 keeps cell 3's confirmed axes: nothing changed since its folder check (v0.9.1). + +Register the masks needed two presses: the first always checked the folders again and stopped +for the axes. Now the axes are kept, and the masks paired alone, only when the folders and the +image headers are unchanged (by fingerprint); anything else is named, in words. +""" + +import os +from pathlib import Path +from types import SimpleNamespace + +from morphobricks_preprocessing.fingerprint import current_fingerprint +from morphobricks_preprocessing.register_checks import changes_since_check + + +def checked(tmp_path, names=("a.tif", "b.tif")): + root = tmp_path / "exp" + root.mkdir() + for name in names: + (root / name).write_bytes(name.encode()) + pre = SimpleNamespace( + discovery=SimpleNamespace(root=str(root)), + header_fingerprints={name: current_fingerprint(root / name) for name in names}, + ) + app = SimpleNamespace(preflight=pre, confirmed_mapping=object()) + entries = [SimpleNamespace(relative_path=name) for name in names] + inputs = SimpleNamespace(experiment_root=root, manifest=SimpleNamespace(files=entries)) + return app, inputs, root + + +def test_nothing_changed_keeps_the_axes(tmp_path): + app, inputs, _ = checked(tmp_path) + assert changes_since_check(app, inputs) == [] + + +def test_each_change_is_named(tmp_path): + app, inputs, root = checked(tmp_path) + stat = (root / "a.tif").stat() + os.utime(root / "a.tif", ns=(stat.st_atime_ns, stat.st_mtime_ns + 10**9)) + assert changes_since_check(app, inputs) == [ + "1 image changed since cell 3 checked the folder (a.tif)" + ] + app.confirmed_mapping = None + assert changes_since_check(app, inputs) == ["the axes are not confirmed in cell 3"] + app.preflight = None + assert changes_since_check(app, inputs) == ["cell 3 holds no folder check"] + + +def test_another_experiment_or_other_images_are_changes(tmp_path): + app, inputs, root = checked(tmp_path) + inputs.experiment_root = Path(tmp_path / "elsewhere") + assert changes_since_check(app, inputs)[0].startswith("cell 3 checked another experiment") + inputs.experiment_root = root + inputs.manifest.files = inputs.manifest.files[:1] + assert changes_since_check(app, inputs) == [ + "the images cell 3 checked are not the images of the run" + ] + + +def test_a_header_not_bound_to_its_file_is_a_change(tmp_path): + app, inputs, _ = checked(tmp_path) + app.preflight.header_fingerprints["b.tif"] = None # the file moved while its header was read + assert "1 image changed" in changes_since_check(app, inputs)[0] From 7118214c214c4461a8d877f94ea56afffd140897 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 26 Nov 2026 21:46:19 +0000 Subject: [PATCH 10/10] Folders: scan and restore on the button press only, ticking check line (#579) Owner decision on #579: typing or pasting a folder path never starts a scan, a check or a restore. Editing a box only clears what came from the old folders and says which button to press (Scan the folders / Check folder); the restore of earlier work (#547/#566) runs on that press. The folder check and the quick scan run inside Wait.ticking(), stale results are hidden before each check and cleared when the folders change, and the comparison phase reports its parts as n of N (preflight.ACQUISITION_PARTS). Also, in the same area: - #517: a new run attempt, or another output folder, clears the result the Run step showed (no "done" chip for another folder or a failed attempt). - #519: the earlier run's inputs are resolved again for another experiment root with the same output folder; its confirmations are never inherited. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01VbytvF3Gsa85ix8Ne2yMDW --- .../notebook_folder.py | 40 ++-- .../notebook_prefill.py | 13 +- .../notebook_quick_scan.py | 24 ++- .../notebook_restore.py | 55 ++++-- .../notebook_run.py | 1 + .../run/preflight.py | 29 ++- tests/test_folder_press.py | 182 ++++++++++++++++++ tests/test_notebook_prefill.py | 26 +++ tests/test_notebook_restore.py | 66 +++++-- 9 files changed, 386 insertions(+), 50 deletions(-) create mode 100644 tests/test_folder_press.py diff --git a/src/morphobricks_preprocessing/notebook_folder.py b/src/morphobricks_preprocessing/notebook_folder.py index de2b4c8b..8a3f05a2 100644 --- a/src/morphobricks_preprocessing/notebook_folder.py +++ b/src/morphobricks_preprocessing/notebook_folder.py @@ -50,7 +50,7 @@ def check_progress(wait: Wait) -> Callable[[str, int, int, str], None]: def report(phase: str, done: int, total: int, path: str) -> None: if phase != state["phase"]: state["phase"] = phase - wait.phase(CHECK_PHASES[phase], total if phase == "headers" else 0) + wait.phase(CHECK_PHASES[phase], total if phase in ("headers", "acquisitions") else 0) if not path: return if phase == "folders": @@ -120,7 +120,7 @@ def _build_folder_step(self, folder: str, output: str) -> None: self._build_issues_card() self.folder_browse.on_click(lambda _: self._browse(self.folder)) self.output_browse.on_click(lambda _: self._browse(self.output)) - self.check_button.on_click(lambda _: self.check_folder()) + self.check_button.on_click(lambda _: self._check_pressed()) self.exclude_button.on_click(lambda _: self._exclude_blocking_images()) self.folder.observe(lambda _: self._folder_edited(), names="value") self.output.observe(lambda _: self._output_edited(), names="value") @@ -252,6 +252,10 @@ def check_folder(self) -> Preflight | None: """Run the folder and header check (pass 1) and show its results.""" return self._run_check() + def _check_pressed(self) -> None: + """*Check folder* pressed: the only start of a check (#579; the restore adds to it).""" + self.check_folder() + def _run_check(self, recorded: object = None) -> Preflight | None: """Run the check; ``recorded`` headers are reused where unchanged (a restore).""" folder = ui.clean_path(self.folder.value) @@ -264,9 +268,10 @@ def _run_check(self, recorded: object = None) -> Preflight | None: self.folder_next.value = "" wait = self._folder_wait = Wait(self.folder_status) wait.start(CHECK_PHASES["folders"]) + self._clear_shown_check() # nothing of an earlier check stays on screen meanwhile (#579) try: # the earlier check never stays shown as valid, whatever stops this one (#101) try: - with self.log.attached(): + with self.log.attached(), wait.ticking(): # the time goes on (#579) masks, mask_axes = self._check_masks_arguments(Path(folder).resolve()) pre = preflight( folder, @@ -280,6 +285,7 @@ def _run_check(self, recorded: object = None) -> Preflight | None: progress=check_progress(wait), recorded=recorded, ) + wait.phase("Comparing the images within each folder") pre = unit_checked(pre) # a described run checks inside each unit self._note_edits() # a check fills only what the user left as filled self.missing_as_singleton.set( @@ -432,12 +438,8 @@ def _folder_edited(self) -> None: return if self.preflight is not None and ui.clean_path(self.folder.value) != self._checked_folder: # A different folder makes every later choice stale. - self._clear_checked( - ui.status( - "info", "The folder changed.", ["Press Check folder to check the new folder."] - ) - ) - self._restore_earlier_work() # the earlier work of the output folder it now has + self._clear_checked(ui.status("info", "The folder changed.", [self._press_words()])) + self._folders_edited() # nothing is read or restored until a button is pressed (#579) def _fail_check(self, folder: str, exc: BaseException, heading: str) -> None: """Clear the earlier check for ``exc``; return only if it is an expected failure. @@ -505,15 +507,27 @@ def _clear_checked(self, status: str) -> None: def _clear_check_views(self) -> None: """Clear what other views show of the checked folder (the stepper's, #101).""" - def _restore_earlier_work(self) -> None: - """Restore the output folder's earlier work (:mod:`.notebook_restore`); here nothing.""" + def _folders_edited(self) -> None: + """Clear what came from the old folders (:mod:`.notebook_restore`); here nothing.""" + + def _press_words(self) -> str: + """Return what to press after a folder box was edited (#579).""" + return "Press Check folder to continue: nothing is read until then." + + def _clear_shown_check(self) -> None: + """Hide the results of the check on screen while a new check runs (#579).""" + self.folder_tiles.value = self.folder_next.value = "" + for card in (self.labels_card, self.consistency_card, self.issues_card): + ui.set_visible(card, False) def _output_edited(self) -> None: self._update_output_hint() # The inputs start from the earlier run in the new output folder (audit I4). self._prefill_from_output() - # Its earlier work is restored when no check is on screen (owner, 25 November 2026). - self._restore_earlier_work() + if self.result and self.result.output_folder.resolve() != self._prefill_target(): + self.result = None # #517: the run shown was written to another output folder + # Its earlier work is restored on the button press only (owner, #579). + self._folders_edited() # The answers belong to their output folder (issue #98): another folder's draft is # read, or the questions asked again; nothing is carried over or written here. if self.pairing is not None and self._design_folder() != self._design_output: diff --git a/src/morphobricks_preprocessing/notebook_prefill.py b/src/morphobricks_preprocessing/notebook_prefill.py index eeb9e01b..86246576 100644 --- a/src/morphobricks_preprocessing/notebook_prefill.py +++ b/src/morphobricks_preprocessing/notebook_prefill.py @@ -32,6 +32,7 @@ class _Prefill: def _init_prefill(self) -> None: self._recorded: ResolvedInputs | None = None self._prefill_for: Path | None = None + self._prefill_root: Path | None = None # the experiment root ``_recorded`` is of (#519) self._prefilled: dict[str, object] = {} # The inputs filled at each check that the user changed: a check keeps them. self._edited: set[str] = set() @@ -43,12 +44,18 @@ def _prefill_from_output(self) -> None: if not hasattr(self, "run_checks"): return # still building the pages output = self._prefill_target() + folder = ui.clean_path(self.folder.value) + root = Path(folder).resolve() if folder else None if output == self._prefill_for: + if root != self._prefill_root and output is not None: + # #519: the earlier run's confirmations are scoped by the experiment folder; + # another one, with the same output folder, never inherits them. The inputs + # shown (the output folder's settings, and the user's edits) are kept. + self._recorded = recorded_inputs(output, root) + self._prefill_root = root return - self._prefill_for = output + self._prefill_for, self._prefill_root = output, root self._edited = set() - folder = ui.clean_path(self.folder.value) - root = Path(folder).resolve() if folder else None self._recorded = None if output is None else recorded_inputs(output, root) if self._recorded is None: self._unfill() diff --git a/src/morphobricks_preprocessing/notebook_quick_scan.py b/src/morphobricks_preprocessing/notebook_quick_scan.py index b63ee68e..9e65166c 100644 --- a/src/morphobricks_preprocessing/notebook_quick_scan.py +++ b/src/morphobricks_preprocessing/notebook_quick_scan.py @@ -124,7 +124,7 @@ def _build_quick_scan(self) -> None: self.scan_box.add_class("mb-scan") ui.set_visible(self.scan_box, False) self.check_blocker = widgets.HTML() - self.scan_button.on_click(lambda _: self._quick_scan()) + self.scan_button.on_click(lambda _: self._scan_pressed()) self.scan_another.on_click(lambda _: self._show_scan_example(None)) self._check_label = (DEEP_LABEL, "check") self.check_button.description, self.check_button.icon = self._check_label @@ -152,8 +152,11 @@ def _refresh_scan_gate(self) -> None: current = self._scan_current() if self._scanned is not None and not current: ui.set_visible(self.scan_box, False) # the tree and picture are of other folders + self.scan_tree.value, self.scan_example.children = "", [] # cleared, not hidden self.scan_status.value = ui.status( - "info", "The folders changed.", ["Scan the folders again."] + "info", + "The folders changed.", + ["Press Scan the folders: nothing is read until then."], ) usable = current and self._scan is not None and bool(self._scan.images) self.check_button.disabled = not usable @@ -167,6 +170,19 @@ def _refresh_scan_gate(self) -> None: reasons = ["the scan found no image to read"] self.check_blocker.value = blocked_line(reasons) + def _scan_pressed(self) -> None: + """*Scan the folders* pressed: restore the earlier work first, else scan (#579). + + The only start of a scan or a restore in the stepper: an edited folder box starts + neither. + """ + before = (self.preflight, self._scanned) + restore = getattr(self, "_restore_earlier_work", None) + if restore is not None: + restore() + if (self.preflight, self._scanned) == before: + self._quick_scan() + def _quick_scan(self) -> DiscoveryResult | None: """Walk the folders (no header is read), show the tree and one random image. @@ -182,6 +198,8 @@ def _quick_scan(self) -> DiscoveryResult | None: ) return None self._busy(self.scan_button, "Scanning…") + ui.set_visible(self.scan_box, False) # nothing of an earlier scan stays shown (#579) + self.scan_tree.value, self.scan_example.children = "", [] wait = Wait(self.scan_status) wait.start("Listing the folders") seen = [0] @@ -191,7 +209,7 @@ def listed(path: str) -> None: wait.step(seen[0], 0, path) try: - with self.log.attached(): + with self.log.attached(), wait.ticking(): # the time goes on between folders found = discover_experiment(folder, self._output_folder(), progress=listed) finally: self._idle(self.scan_button, SCAN_LABEL, "search") diff --git a/src/morphobricks_preprocessing/notebook_restore.py b/src/morphobricks_preprocessing/notebook_restore.py index b57f5626..543ea48b 100644 --- a/src/morphobricks_preprocessing/notebook_restore.py +++ b/src/morphobricks_preprocessing/notebook_restore.py @@ -1,9 +1,10 @@ -"""Restore the earlier work of an output folder as soon as it is set (owner, 25 November 2026). +"""Restore the earlier work of an output folder on the button press (owner, 25 and 26 Nov 2026). -When the output folder is typed or chosen (or follows a new experiment folder) and no check -is on screen, the notebook looks at what the folder holds (:func:`.earlier_work.earlier_work`) -and, when it holds earlier work of this experiment folder, restores it through the paths that -already exist, then says exactly what it restored, from when, and what it read again: +When **Scan the folders** (the stepper) or **Check folder** is pressed and no check is on +screen, the notebook first looks at what the output folder holds +(:func:`.earlier_work.earlier_work`) and, when it holds earlier work of this experiment +folder, restores it through the paths that already exist, then says exactly what it +restored, from when, and what it read again: 1. **The folder check.** The check runs as *Check folder* runs it, but the header of an image whose fingerprint equals the one in ``check_headers.json`` is the recorded header @@ -28,6 +29,10 @@ folder clears what was restored from the first, until the user answers, confirms, saves or runs (:meth:`_RestoreEarlier._acted`): then it is their work, kept as after a manual check. The folder boxes are read once typed (``continuous_update=False``), never at each key. + +Owner decision on #579 (26 November 2026): typing or pasting a folder path never starts a scan, +a check or a restore. Editing a folder box only clears what came from the old folders and says +which button to press; the restore and any reading of the folders start on that press. """ from __future__ import annotations @@ -76,23 +81,47 @@ def _build_restore(self) -> None: # The trigger ------------------------------------------------------------------------- - def _restore_earlier_work(self) -> None: - """Restore the output folder's earlier work, once per output and experiment folder.""" + def _folders_edited(self) -> None: + """Clear what was restored from another output folder, after a folder box was edited. + + Nothing is read here (#579): the restore waits for the button press. + """ if self._restoring or not hasattr(self, "restore_box") or not self._show_output: - return # an embedding brick that hides the output folder writes nothing - target = self._prefill_target() - folder = ui.clean_path(self.folder.value) - if (target, folder) == self._restore_key: return - self._restore_key = (target, folder) + target = self._prefill_target() if self._restored_from is not None and self._restored_from != target: before = self._restored_from self._clear_checked(ui.status("info", "The output folder changed.")) self._say( "info", "The output folder changed: nothing restored from the earlier one is used.", - [f"It was {before}. No file was changed or deleted."], + [f"It was {before}. No file was changed or deleted.", self._press_words()], ) + + def _press_words(self) -> str: + """Return what to press after a folder box was edited (#579).""" + button = "Scan the folders" if getattr(self, "_stepper", None) else "Check folder" + return f"Press {button} to continue: nothing is read or restored until then." + + def _check_pressed(self) -> None: + """*Check folder* pressed: restore the earlier work first, else check (#579).""" + before = self.preflight + self._restore_earlier_work() + if self.preflight is before: + super()._check_pressed() + + def _restore_earlier_work(self) -> None: + """Restore the output folder's earlier work, once per output and experiment folder. + + Called by a button press only (#579), never by an edit of a folder box. + """ + if self._restoring or not hasattr(self, "restore_box") or not self._show_output: + return # an embedding brick that hides the output folder writes nothing + target = self._prefill_target() + folder = ui.clean_path(self.folder.value) + if (target, folder) == self._restore_key: + return + self._restore_key = (target, folder) if target is None or self.preflight is not None or self._fresh_for == target: return self._restoring = True diff --git a/src/morphobricks_preprocessing/notebook_run.py b/src/morphobricks_preprocessing/notebook_run.py index 856381ed..7f32292b 100644 --- a/src/morphobricks_preprocessing/notebook_run.py +++ b/src/morphobricks_preprocessing/notebook_run.py @@ -420,6 +420,7 @@ def run(self) -> RunResult | None: def _start_run(self) -> None: """Clear the results of an earlier run and show that this one is starting.""" self._busy(self.run_button, "Computing…") + self.result = None # #517: a new attempt; an earlier one's result is not this one's self.run_next.value = BUSY_NOTE self.run_checks.clear() self.run_lock.hide() diff --git a/src/morphobricks_preprocessing/run/preflight.py b/src/morphobricks_preprocessing/run/preflight.py index 0434cc77..edc01de4 100644 --- a/src/morphobricks_preprocessing/run/preflight.py +++ b/src/morphobricks_preprocessing/run/preflight.py @@ -260,26 +260,41 @@ def preflight( lambda done, total, path: report("masks", done, total, path), ) report("masks", 1, 1, "") - report("acquisitions", 0, 1, "") + # Each part of the comparison is reported, n of N (#579: the line seemed stuck). + total = len(ACQUISITION_PARTS) + report("acquisitions", 0, total, ACQUISITION_PARTS[0]) + suggested = prefill_experiment_mapping(metadata) + report("acquisitions", 1, total, ACQUISITION_PARTS[1]) + dataset = check_dataset(discovery, excluded=excluded) + report("acquisitions", 2, total, ACQUISITION_PARTS[2]) + conversion = review_conversion( + root, discovery.images, images, [(m.image, m.path) for m in _mask_files(masks)] + ) result = Preflight( discovery=discovery, metadata=metadata, excluded=excluded, exclusion_issues=tuple(_exclusion_issues(discovery, excluded)), - suggested_mapping=prefill_experiment_mapping(metadata), - dataset=check_dataset(discovery, excluded=excluded), + suggested_mapping=suggested, + dataset=dataset, masks=masks, calibration=calibration, - conversion=review_conversion( - root, discovery.images, images, [(m.image, m.path) for m in _mask_files(masks)] - ), + conversion=conversion, header_fingerprints=bound, headers_reused=reused, ) - report("acquisitions", 1, 1, "") + report("acquisitions", total, total, "") return result +ACQUISITION_PARTS = ( + "the axes every header suggests", + "the images per condition and repeat", + "the named-axis copies and their record", +) +"""The parts of the phase ``acquisitions``, reported as n of N with their names (#579).""" + + def _mask_files(masks: MaskInventory | None) -> tuple[MaskFile, ...]: """Return the masks found for the analysed images (none when masks were not asked for).""" return () if masks is None else masks.files diff --git a/tests/test_folder_press.py b/tests/test_folder_press.py new file mode 100644 index 00000000..b8a7eeb1 --- /dev/null +++ b/tests/test_folder_press.py @@ -0,0 +1,182 @@ +"""Folders are read on a button press only, and old results never stay on screen (#579, #517). + +Owner decision on #579 (26 November 2026): typing or pasting a folder path never starts a +scan, a check or a restore; editing a folder box only clears what came from the old folders +and says which button to press. The folder check's line has a ticking time and counts the +parts of its comparison. #517: the Run step's result never outlives its output folder or a +new attempt. +""" + +import re +import shutil + +import pytest + +from test_notebook_check_save import FOLDERS, add_folder + +pytest.importorskip("ipywidgets") +pytest.importorskip("matplotlib") + +from morphobricks_preprocessing import notebook_folder, notebook_progress # noqa: E402 +from morphobricks_preprocessing import notebook_style as ui # noqa: E402 +from morphobricks_preprocessing.notebook_ui import PreprocessingNotebook # noqa: E402 +from morphobricks_preprocessing.run.preflight import ACQUISITION_PARTS, preflight # noqa: E402 + + +def _text(html): + return re.sub(r"\s+", " ", re.sub(r"<[^>]+>", " ", html)).strip() + + +def experiment(base, name, seed=1): + root = base / name + for i, folder in enumerate(FOLDERS): + add_folder(root, base / f"{name}_masks", folder, seed + i) + shutil.rmtree(base / f"{name}_masks") + return root + + +def nothing_read(monkeypatch): + """Make every reading of a folder fail the test: the scan, the check and the restore.""" + + def refuse(*args, **kwargs): + raise AssertionError("a folder was read on an edit") + + monkeypatch.setattr( + "morphobricks_preprocessing.notebook_quick_scan.discover_experiment", refuse + ) + monkeypatch.setattr(notebook_folder, "preflight", refuse) + monkeypatch.setattr("morphobricks_preprocessing.notebook_restore.earlier_work", refuse) + + +@pytest.mark.parametrize("stepper", [True, False]) +def test_typing_a_folder_path_starts_no_scan_check_or_restore(tmp_path, monkeypatch, stepper): + root = experiment(tmp_path, "A") + nb = PreprocessingNotebook() + nb.steps() if stepper else nb.folder_step() + nothing_read(monkeypatch) + for typed in (str(root)[:3], str(root)[:-1], str(root)): # on the way, and the path + nb.folder.value = typed + for typed in (str(tmp_path / "o"), str(tmp_path / "out")): + nb.output.value = typed + assert nb.preflight is None and not ui.is_visible(nb.restore_box) + + +def test_two_scans_of_two_folders_leave_nothing_of_the_first(tmp_path): + first, second = experiment(tmp_path, "A", 1), experiment(tmp_path, "B", 7) + nb = PreprocessingNotebook(str(first), output_folder=str(tmp_path / "outA")) + nb.steps() + nb.scan_button.click() + nb.check_button.click() + nb.quick_confirm.click() + assert nb.preflight is not None and nb.confirmed_mapping is not None + assert str(first) in nb._scanned[0] + nb.folder.value = str(second) # edited: everything of A is cleared at once, nothing read + nb.output.value = str(tmp_path / "outB") + assert nb.preflight is None and nb.confirmed_mapping is None and nb.result is None + assert not ui.is_visible(nb.scan_box) and nb.scan_tree.value == "" + assert nb.scan_example.children == () + assert not ui.is_visible(nb.labels_card) and nb.folder_tiles.value == "" + assert "Press Scan the folders" in _text(nb.scan_status.value) + assert nb.check_button.disabled + nb.scan_button.click() + assert nb._scanned[0] == str(second) and nb._scan.root.name == "B" + nb.check_button.click() + assert str(nb.preflight.discovery.root) == str(second.resolve()) + assert all(str(first) not in str(path) for path in nb.preflight.header_fingerprints) + assert str(first) not in nb.labels_table.value + + +def test_the_folder_check_runs_with_a_ticking_time(tmp_path, monkeypatch): + # #579: the line stayed at "Comparing the images · 0:20 elapsed": the check did not run + # inside Wait.ticking(), so the time moved only when a step was reported. + root = experiment(tmp_path, "A") + nb = PreprocessingNotebook(str(root), output_folder=str(tmp_path / "out")) + nb.folder_step() + ticking = [] + real_ticking = notebook_progress.Wait.ticking + + def spy(self, *args, **kwargs): + ticking.append(self.target) + return real_ticking(self, *args, **kwargs) + + monkeypatch.setattr(notebook_progress.Wait, "ticking", spy) + inside = [] + real_preflight = notebook_folder.preflight + + def watched(*args, **kwargs): + inside.append(list(ticking)) + return real_preflight(*args, **kwargs) + + monkeypatch.setattr(notebook_folder, "preflight", watched) + nb.check_button.click() + assert inside == [[nb.folder_status]] and nb.preflight is not None + + +def test_the_elapsed_time_moves_during_an_uncounted_phase(): + import ipywidgets as widgets + + target = widgets.HTML() + now = [0.0] + wait = notebook_progress.Wait(target, clock=lambda: now[0]) + wait.start("Comparing the images") + with wait.ticking(interval=0.01): + now[0] = 75.0 + drawn = wait.drawn + for _ in range(500): # the thread redraws without any step being reported + if wait.drawn > drawn: + break + notebook_progress.threading.Event().wait(0.01) + assert "1:15" in target.value + + +def test_the_comparison_of_the_images_is_counted_part_by_part(tmp_path): + root = experiment(tmp_path, "A") + told = [] + preflight(root, tmp_path / "out", progress=lambda *call: told.append(call)) + parts = [call for call in told if call[0] == "acquisitions"] + total = len(ACQUISITION_PARTS) + assert parts == [ + *(("acquisitions", done, total, part) for done, part in enumerate(ACQUISITION_PARTS)), + ("acquisitions", total, total, ""), + ] + + +def test_the_check_line_counts_the_comparison(tmp_path, monkeypatch): + monkeypatch.setattr(notebook_progress, "MIN_INTERVAL", 0.0) # every step drawn + root = experiment(tmp_path, "A") + nb = PreprocessingNotebook(str(root), output_folder=str(tmp_path / "out")) + nb.folder_step() + lines = [] + nb.folder_status.observe(lambda change: lines.append(_text(change["new"])), names="value") + nb.check_button.click() + assert any("Comparing the images" in line and "1 of 3" in line for line in lines), lines + + +# #517: the Run step's result is of its output folder and of the latest attempt --------------- + + +def ran(tmp_path): + from test_notebook_preprocessing_cellpose import ran_app + + return ran_app(tmp_path) + + +@pytest.mark.usefixtures("legacy_grid") +def test_another_output_folder_clears_the_result_shown(tmp_path): + nb = ran(tmp_path) + assert nb.result is not None and nb.result.written + nb.output.value = str(tmp_path / "empty_output") + assert nb.result is None and not nb._run_state().done + + +@pytest.mark.usefixtures("legacy_grid") +def test_a_run_that_raises_leaves_no_earlier_result(tmp_path, monkeypatch): + nb = ran(tmp_path) + assert nb.result is not None + + def broken(*args, **kwargs): + raise OSError(5, "Input/output error") + + monkeypatch.setattr(nb, "_call_run", broken) + assert nb.run() is None + assert nb.result is None diff --git a/tests/test_notebook_prefill.py b/tests/test_notebook_prefill.py index eaf30a4b..a10395b2 100644 --- a/tests/test_notebook_prefill.py +++ b/tests/test_notebook_prefill.py @@ -218,3 +218,29 @@ def test_recorded_intensity_limits_come_back_exactly(experiment, saturation): assert "intensity_settings" not in { c.name for c in nb._planned_changes(output_of(experiment).resolve()) } + + +def test_another_experiment_with_the_same_output_does_not_inherit_its_confirmations(tmp_path): + # #519: the cache of the earlier run's inputs was keyed by the output folder alone, so a + # copy of the experiment (same sizes and dates, shutil.copytree keeps them) checked with the + # same output folder kept the first root's confirmations for a one-click offer. + import shutil + + from morphobricks_preprocessing.axes import AxisMapping + from morphobricks_preprocessing.run.planned import recorded_inputs + + first = tmp_path / "A" + write_plain(first / "ctrl/rep1/a.tif", np.zeros((2, 8, 8), np.uint8)) + out = tmp_path / "out" + assert run_described(first, AxisMapping("IYX", ("T", "Y", "X")), output_folder=out).written + second = tmp_path / "B" + shutil.copytree(first, second) + nb = PreprocessingNotebook(str(first), output_folder=str(out)) + nb.folder_step() + nb.run_step() + assert nb._recorded == recorded_inputs(out, first.resolve()) + nb.folder.value = str(second) + assert nb._recorded == recorded_inputs(out, second.resolve()) + assert nb._recorded != recorded_inputs(out, first.resolve()) + nb.folder.value = str(first) # A -> B -> A: the first root's again + assert nb._recorded == recorded_inputs(out, first.resolve()) diff --git a/tests/test_notebook_restore.py b/tests/test_notebook_restore.py index 38e5daee..6a9de4bc 100644 --- a/tests/test_notebook_restore.py +++ b/tests/test_notebook_restore.py @@ -1,10 +1,14 @@ -"""The notebook restores an output folder's earlier work as soon as it is set (v0.9.0). +"""The notebook restores an output folder's earlier work on the button press (v0.9.0, #579). -Owner decision of 25 November 2026: when the output folder is set, earlier work found there is -restored with a message saying what, from when, and what was read again; *Start fresh* starts a -new session state without touching any file. The check reuses a recorded header only while its +Owner decision of 25 November 2026: earlier work found in the output folder is restored with a +message saying what, from when, and what was read again; *Start fresh* starts a new session +state without touching any file. The check reuses a recorded header only while its image's fingerprint is unchanged; anything uncertain reads the header again and says so. Both notebooks (Preprocessing and Preprocessing_Cellpose) run this same app in cell 3. + +Owner decision on #579 (26 November 2026): typing a folder path never starts a scan or a +restore; the restore runs on **Scan the folders** (the stepper) or **Check folder** (the +pages), here :func:`press`. """ from __future__ import annotations @@ -56,6 +60,11 @@ def stepper(): return nb +def press(nb): + """The user's press that starts the restore or the scan (#579): the only start of either.""" + (nb.scan_button if getattr(nb, "_stepper", None) else nb.check_button).click() + + def checked(root, out): """Check the folder in a first session: the check writes its report and its record.""" nb = PreprocessingNotebook(str(root), str(out)) @@ -97,6 +106,7 @@ def test_a_fresh_output_folder_restores_nothing_and_says_nothing(exp): nb = stepper() nb.folder.value = str(root) nb.output.value = str(out) + press(nb) assert nb.preflight is None and not ui.is_visible(nb.restore_box) assert nb.restore_status.value == "" and not out.exists() @@ -108,7 +118,9 @@ def test_a_recorded_check_with_unchanged_images_is_reused_without_reading_a_head checked(root, out) no_header_read(monkeypatch) nb = stepper() - nb.output.value = str(out) # the experiment folder comes from the record + nb.output.value = str(out) # the experiment folder comes from the record, on the press + assert nb.folder.value == "" and nb.preflight is None # typed: nothing read (#579) + press(nb) assert nb.folder.value == str(root.resolve()) assert nb.preflight is not None and nb.preflight.headers_reused == tuple(IMAGES) text = _text(nb.restore_status.value) @@ -126,6 +138,7 @@ def test_one_changed_image_is_read_again_and_the_message_says_so(exp, monkeypatc seen = counted_header_reads(monkeypatch) nb = stepper() nb.output.value = str(out) + press(nb) assert seen == [IMAGES[1]] assert nb.preflight.headers_reused == (IMAGES[0],) text = _text(nb.restore_status.value) @@ -145,6 +158,7 @@ def test_a_record_that_cannot_be_used_reads_every_header_and_says_why(exp, monke nb = stepper() nb.folder.value = str(root) nb.output.value = str(out) + press(nb) assert sorted(seen) == IMAGES and nb.preflight.headers_reused == () text = _text(nb.restore_status.value) assert f"{CHECK_RECORD_FILENAME} is not a usable record" in text @@ -161,6 +175,7 @@ def test_a_record_of_another_software_version_is_not_reused(exp, monkeypatch): seen = counted_header_reads(monkeypatch) nb = stepper() nb.output.value = str(out) + press(nb) assert sorted(seen) == IMAGES assert "written by another version of the software" in _text(nb.restore_status.value) @@ -173,6 +188,7 @@ def test_saved_answers_are_restored_and_open_on_the_first_step_still_to_do(exp): assert (out / DRAFT_FILENAME).is_file() nb = stepper() nb.output.value = str(out) + press(nb) assert nb._draft_saved and nb.reference_boxes["drug"].value == "ctrl" text = _text(nb.restore_status.value) assert "restored the folder check, your saved answers" in text @@ -187,6 +203,7 @@ def test_a_published_description_is_reopened(exp): nb = stepper() nb.folder.value = str(root) nb.output.value = str(out) + press(nb) assert nb._published() is not None and not nb._published().changed text = _text(nb.restore_status.value) assert "restored the folder check, the saved experiment description" in text @@ -199,6 +216,7 @@ def test_without_a_recorded_experiment_folder_nothing_is_restored_and_it_says_so describe_tree(root, out) # a description only: no check, no run recorded the folder nb = stepper() nb.output.value = str(out) + press(nb) assert nb.preflight is None and nb.folder.value == "" text = _text(nb.restore_status.value) assert "the saved experiment description" in text and "is not recorded" in text @@ -214,6 +232,7 @@ def test_a_finished_run_shows_its_results_and_the_next_steps(exp): nb = stepper() nb.folder.value = str(root) nb.output.value = str(out) + press(nb) assert nb.restored_run == out.resolve() and nb.result is None assert "the finished run of" in _text(nb.restore_status.value) assert _text(nb.run_status.value).startswith("The earlier run is complete") @@ -231,6 +250,7 @@ def test_the_combined_notebook_segments_the_restored_run(exp, monkeypatch): run_described(root, prefill_mapping("TYX"), output_folder=out, image_type="fluorescence") nb = stepper() nb.output.value = str(out) + press(nb) monkeypatch.setattr(cell4, "cellpose_ready", lambda: False) # no Cellpose installed here step = cell4.segmentation_step(nb) assert step.run_folder == str(out.resolve()) and step.refused == "" @@ -244,6 +264,7 @@ def test_a_run_whose_images_changed_is_not_shown_as_finished(exp): nb = stepper() nb.folder.value = str(root) nb.output.value = str(out) + press(nb) assert nb.restored_run is None and app_folders(nb) == ("", "") assert "is not current" in _text(nb.restore_status.value) @@ -255,6 +276,7 @@ def test_start_fresh_forgets_the_restore_and_touches_no_file(exp): before = files_of(out), files_of(root) nb = stepper() nb.output.value = str(out) + press(nb) assert nb.preflight is not None and nb.restored_run is not None restored = files_of(out) nb.restore_fresh.click() @@ -275,6 +297,7 @@ def test_another_output_folder_clears_what_was_restored(exp, tmp_path): checked(root, out) nb = stepper() nb.output.value = str(out) + press(nb) assert nb.preflight is not None nb.output.value = str(tmp_path / "other") assert nb.preflight is None and nb.mapping is None and nb.draft is None @@ -290,6 +313,7 @@ def test_earlier_work_of_another_experiment_restores_nothing(exp, tmp_path): nb = stepper() nb.folder.value = str(other) nb.output.value = str(out) + press(nb) assert nb.preflight is None assert "of another experiment folder" in _text(nb.restore_status.value) @@ -304,6 +328,7 @@ def broken(*args, **kwargs): monkeypatch.setattr(notebook_folder, "preflight", broken) nb = stepper() nb.output.value = str(out) + press(nb) assert nb.preflight is None and nb.restored_run is None assert "the folder could not be checked" in _text(nb.restore_status.value) assert "Input/output error" in _text(nb.folder_status.value) @@ -321,6 +346,7 @@ def broken(output): monkeypatch.setattr("morphobricks_preprocessing.notebook_restore.earlier_work", broken) nb = stepper() nb.output.value = str(out) + press(nb) assert nb.preflight is None text = _text(nb.restore_status.value) assert "it could not be restored" in text and "RuntimeError: cannot read it" in text @@ -332,6 +358,7 @@ def test_check_folder_after_a_restore_reads_every_header_again(exp, monkeypatch) checked(root, out) nb = stepper() nb.output.value = str(out) + press(nb) seen = counted_header_reads(monkeypatch) nb.check_button.click() assert sorted(seen) == IMAGES and nb.preflight.headers_reused == () @@ -344,6 +371,7 @@ def test_the_stacked_pages_restore_too(exp): nb = PreprocessingNotebook() nb.folder_step() nb.output.value = str(out) + press(nb) assert nb.preflight is not None and nb.preflight.headers_reused == tuple(IMAGES) assert ui.is_visible(nb.restore_box) and "Opened on" not in _text(nb.restore_status.value) @@ -378,6 +406,7 @@ def test_an_answer_after_a_restore_keeps_it_when_the_output_folder_changes(exp, checked(root, out) nb = stepper() nb.output.value = str(out) + press(nb) nb.reference_boxes["drug"].value = "ctrl" # the user's own work on the restored check nb.output.value = str(tmp_path / "other") assert nb.preflight is not None # kept, as after a manual Check folder (issue #98 rules) @@ -389,6 +418,7 @@ def test_a_confirmation_after_a_restore_keeps_it_too(exp, tmp_path): checked(root, out) nb = stepper() nb.output.value = str(out) + press(nb) assert ui.is_visible(nb.quick_card) nb.quick_confirm.click() assert nb.confirmed_mapping is not None @@ -401,6 +431,7 @@ def test_a_run_started_after_a_restore_makes_it_the_user_s(exp): checked(root, out) nb = stepper() nb.output.value = str(out) + press(nb) assert nb._restored_from is not None nb._start_run() assert nb._restored_from is None and nb.restored_run is None @@ -414,6 +445,7 @@ def test_a_record_and_a_run_of_different_experiment_folders_restore_nothing(exp, write_check_record(out, tmp_path / "elsewhere", {}, ()) nb = stepper() nb.output.value = str(out) + press(nb) assert nb.preflight is None and nb.folder.value == "" text = _text(nb.restore_status.value) assert "names two experiment folders" in text and "They disagree" in text @@ -456,11 +488,14 @@ def test_the_folder_entered_after_unrecorded_earlier_work_is_scanned_and_shown(e answers_only(root, out) nb = stepper() nb.output.value = str(out) + press(nb) text = _text(nb.restore_status.value) assert "is not recorded" in text assert "Check folder" not in text # the stepper has no such button: it names its own assert "Scan the folders" in text and "Looks right: read all image headers" in text - nb.folder.value = str(root) # Enter, or leaving the box + nb.folder.value = str(root) # Enter, or leaving the box: nothing is read yet (#579) + assert nb._scanned is None or nb._scanned[0] != str(root) + press(nb) # Scan the folders scanned_and_shown(nb, root) text = _text(nb.restore_status.value) assert f"The folders of {root} are scanned below" in text @@ -469,14 +504,17 @@ def test_the_folder_entered_after_unrecorded_earlier_work_is_scanned_and_shown(e assert nb.reference_boxes["drug"].value == "ctrl" -def test_a_scan_clicked_before_the_folder_arrives_is_made_good_when_it_arrives(exp): +def test_a_scan_clicked_before_the_folder_arrives_scans_on_the_next_press(exp): + # #579: the folder arriving never starts the scan itself; the next press does. root, out = exp answers_only(root, out) nb = stepper() nb.output.value = str(out) - nb.scan_button.click() # the click reached the kernel before the typed folder + press(nb) # the click reached the kernel before the typed folder assert "Enter the experiment folder first" in _text(nb.scan_status.value) nb.folder.value = str(root) + assert nb._scanned is None + press(nb) scanned_and_shown(nb, root) @@ -487,12 +525,14 @@ def test_saved_answers_of_an_older_version_are_ignored_and_never_block_a_scan(ex before = files_of(out) nb = stepper() nb.output.value = str(out) + press(nb) text = _text(nb.restore_status.value) assert text.startswith("The saved answers in this output folder") assert "another version" in text and "Found earlier work" not in text assert not ui.is_visible(nb.restore_fresh) and files_of(out) == before assert "Scan the folders" in text and "Check folder" not in text - nb.folder.value = str(root) # the owner's case: the folder entered is scanned and shown + nb.folder.value = str(root) # the owner's case: the folder entered is scanned on the press + press(nb) scanned_and_shown(nb, root) assert f"The folders of {root} are scanned below" in _text(nb.restore_status.value) assert files_of(out) == before # the scan writes nothing @@ -506,14 +546,15 @@ def old_answers_only(out): (out / DRAFT_FILENAME).write_text(json.dumps(OLD_DRAFT), encoding="utf-8") -def test_an_early_scan_click_is_made_good_with_older_answers_too(exp): +def test_an_early_scan_click_with_older_answers_scans_on_the_next_press(exp): root, out = exp old_answers_only(out) nb = stepper() nb.output.value = str(out) - nb.scan_button.click() # the click reached the kernel before the typed folder + press(nb) # the click reached the kernel before the typed folder assert "Enter the experiment folder first" in _text(nb.scan_status.value) nb.folder.value = str(root) + press(nb) scanned_and_shown(nb, root) @@ -523,6 +564,7 @@ def test_the_older_answers_line_names_the_pages_check_folder_button(exp): nb = PreprocessingNotebook() nb.folder_step() nb.output.value = str(out) + press(nb) text = _text(nb.restore_status.value) assert "another version" in text and "Scan the folders" not in text assert "click Check folder." in text @@ -534,6 +576,7 @@ def test_older_answers_beside_a_recorded_check_restore_the_check_without_a_scan_ (out / DRAFT_FILENAME).write_text(json.dumps(OLD_DRAFT), encoding="utf-8") nb = stepper() nb.output.value = str(out) + press(nb) text = _text(nb.restore_status.value) assert "restored the folder check" in text and "another version" in text assert "scan the folders" not in text.lower() and "again reads" not in text @@ -546,6 +589,7 @@ def test_the_stacked_pages_name_their_check_folder_button(exp): nb = PreprocessingNotebook() nb.folder_step() nb.output.value = str(out) + press(nb) assert "Enter the experiment folder and click Check folder." in _text(nb.restore_status.value) nb.folder.value = str(root) assert nb.preflight is None # the pages have no scan: Check folder is the user's click