diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index 99126b2..56da1de 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -1,14 +1,15 @@ -# The documentation site (mkdocs.yml, built with Zensical from docs/): built on every pull request and push that touches it, so a -# broken link or a page missing from the build fails here (--strict); published to GitHub Pages from main. -# Pages must be switched on for this repository (Settings > Pages > Source: GitHub Actions) before the deploy job can run. +# This repository's GitHub Pages site: only redirects. The documentation is published on the LabConstrictor website, which fetches +# docs/; every address of the old docs site (https://cellmigrationlab.github.io/LabConstrictor-Tools//) leads to the page's new +# home (scripts/build_redirect_site.py). Built on pull requests that touch it (a docs page without a destination fails the build); +# published from main. name: docs on: push: branches: [main] - paths: [docs/**, overrides/**, mkdocs.yml, requirements-docs.txt, .github/workflows/docs.yml] + paths: [docs/**, scripts/build_redirect_site.py, .github/workflows/docs.yml] pull_request: - paths: [docs/**, overrides/**, mkdocs.yml, requirements-docs.txt, .github/workflows/docs.yml] + paths: [docs/**, scripts/build_redirect_site.py, .github/workflows/docs.yml] workflow_dispatch: permissions: @@ -28,17 +29,14 @@ jobs: - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 with: python-version: "3.12" - cache: pip - cache-dependency-path: requirements-docs.txt - - run: pip install -r requirements-docs.txt - - name: Build the site (warnings, e.g. a broken link, fail the build) - run: zensical build --strict --clean + - name: Build the redirect pages (a docs page with no destination fails the build) + run: python scripts/build_redirect_site.py --out site - name: Upload preview (pull requests) if: github.event_name == 'pull_request' uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: - name: docs-preview + name: redirect-site-preview path: site/ retention-days: 14 - name: Upload site for GitHub Pages diff --git a/.gitignore b/.gitignore index 59b6f8e..f33f106 100644 --- a/.gitignore +++ b/.gitignore @@ -10,5 +10,5 @@ mutants/ .hypothesis/ htmlcov/ -# documentation site build output (mkdocs.yml) +# GitHub Pages build output (scripts/build_redirect_site.py) site/ diff --git a/AGENTS.md b/AGENTS.md index f72180f..bd7cdfc 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -6,14 +6,21 @@ Notes for people and coding agents who change this repository. Each topic of the LabConstrictor documentation has one owner page; every other page links to it instead of copying it. The table of owners is in LabConstrictor-Site's `AGENTS.md`, section "Sources of truth" (). -This repository owns these pages. LabConstrictor-Site fetches them and publishes them, so links in them must be absolute: - -| Page | On the LabConstrictor website | -|---|---| -| `docs/user-guide.md`, "Use apps inside napari, Fiji and QuPath" | | -| `docs/CAPABILITIES.md`, "What works where" | | -| `docs/PUBLISHING.md`, "Publish the plugins and apps" | | -| `docs/AUTHORING.md`, "Writing tools" | the "Build an app" track (being added) | +This repository owns these pages. LabConstrictor-Site fetches them and publishes them. Their first heading is the menu title on the site. Relative links are fine: the site resolves them (a link to another published page becomes that page, a link to any other file becomes the file on GitHub). + +| Page | Track | On the LabConstrictor website | +|---|---|---| +| `docs/user-guide.md`, "Use apps inside napari, Fiji and QuPath" | Use an app | | +| `docs/CAPABILITIES.md`, "What works where" | Use an app | | +| `docs/AUTHORING.md`, "Writing tools" | Connect an app | | +| `docs/MANIFEST.md`, "Tool markers" | Connect an app | | +| `docs/HOST_FEATURES.md`, "What each host does with each feature" | Connect an app | | +| `docs/INSTALL.md`, "Install LabConstrictor Tools" | Connect an app | | +| `docs/OPERATIONS.md`, "Operations: shared installs, security, troubleshooting" | Connect an app | | +| `docs/PUBLISHING.md`, "Publish the plugins and apps" | Connect an app | | +| `docs/REPOSITORIES.md`, "Where the LabConstrictor tools live" | Connect an app | | +| `docs/LABCONSTRICTOR_INTEGRATION.md`, "How the template registers an app's tools" | Connect an app | | +| `docs/PROTOCOL.md`, "Protocol reference" | Connect an app | | It also owns the developer topics: the protocol, the manifest, what each host does with each feature, testing, releases and tags, shared and network installs, security, and the install of `labconstrictor-tools` itself. @@ -23,4 +30,4 @@ Pages owned elsewhere, which pages here link to and never copy: - Install and open each plugin (commands, menu paths, current release): `docs/user-guide.md` of LabConstrictor-napari, LabConstrictor-Fiji and LabConstrictor-QuPath, at , `/guides/fiji/` and `/guides/qupath/`. - The Tools tag that app installers pin: `LC_TOOLS_PIN` in the template's `app/bash_bat_scripts/post_install.sh` and `post_install.bat`. -This repository's own docs site (, built from `mkdocs.yml`) is the developer reference only. Pages for people who use apps live on LabConstrictor-Site. +Every page a user or a tool author needs is on LabConstrictor-Site; maintainers' material (TESTING.md, REGRESSION_LEDGER.md, SPEC_WRONG_SCIENCE.md, CONFORMANCE.md) stays on GitHub. This repository's GitHub Pages site () is only redirects: `scripts/build_redirect_site.py` sends each address of the old docs site to the page's new home (keeping a `#section`). A new page in docs/ needs a line there (its website address, or `NOT_PUBLISHED` for a maintainers' page), or that build fails. diff --git a/docs/AUTHORING.md b/docs/AUTHORING.md index 3ffa257..b174bc1 100644 --- a/docs/AUTHORING.md +++ b/docs/AUTHORING.md @@ -1,120 +1,120 @@ -# Writing tools for LabConstrictor apps (10 minutes) +# Writing tools -> The whole manifest on one page: [The manifest](https://cellmigrationlab.github.io/LabConstrictor-Tools/MANIFEST/). What each host does with each feature: [What each host does with each feature](https://cellmigrationlab.github.io/LabConstrictor-Tools/HOST_FEATURES/). +A *tool* is a Python function with type hints. napari, Fiji, QuPath, notebooks and the command line all build their forms from its signature, so you write no interface code and no JSON. -A *tool* is a normal Python function with type hints. Napari, Fiji, notebooks and the command line all build their -forms from the signature - you write no GUI code and no JSON. +Every marker is listed in [Tool markers](https://cellmigrationlab.github.io/LabConstrictor-Site/guides/tool-markers/). What each host does with each one is in [What each host does with each feature](https://cellmigrationlab.github.io/LabConstrictor-Site/guides/host-features/). + +## A first tool ```python -# src/my_app_lc_tools/__init__.py (next to your package `my_app`; the name MUST be _lc_tools, see below) +# src/my_app_lc_tools/__init__.py (next to your package `my_app`; the name must be _lc_tools) from typing import Annotated -from labconstrictor_tools import Image, ImageOut, Min, progress, check_cancel, tool +from labconstrictor_tools import Image, ImageOut, Min, Name, progress, check_cancel, tool @tool("Gaussian blur") -def blur(image: Image, sigma: Annotated[float, Min(0)] = 2.0) -> ImageOut: +def blur(image: Image, sigma: Annotated[float, Min(0)] = 2.0) -> Annotated[ImageOut, Name("blurred")]: """Smooth an image. Args: image: The image to smooth. sigma: Width of the Gaussian in pixels. """ - from skimage.filters import gaussian # heavy imports go INSIDE the function + from skimage.filters import gaussian # heavy imports go inside the function progress(0.1, "smoothing") - check_cancel() # lets the Cancel button stop long loops cleanly + check_cancel() # lets the Cancel button stop long loops return gaussian(image, sigma, preserve_range=True) ``` -`labconstrictor-tools init my_app_lc_tools.py` writes this starter for you. +To get a starter file, let `init` write it: + +```bash +labconstrictor-tools init src/my_app_lc_tools/__init__.py +``` + +The starter is this example without `Name("blurred")`, so its output is named `image`, after its type. `init` creates the folder and prints the `check` and `register` commands for it. -**Naming rule.** The LabConstrictor installer registers an app's tools only if the app's Python package `` is -accompanied by a module named exactly **`_lc_tools`** (for the package `nucleisky`: `src/nucleisky_lc_tools/__init__.py`, which the -app lists in `construct.yaml` under `extra_files` like the rest of `src/`). Any other name works from the command line but is never registered by the installer. +**Name the module `_lc_tools`.** The app's installer registers its tools only if the app's Python package `` comes with a module named exactly `_lc_tools`. For the package `nucleisky` that is `src/nucleisky_lc_tools/__init__.py`. Any other name works from the command line but is never registered by the installer. The app's release bundles everything under `src/` automatically, so you do not edit `construct.yaml` or `setup.py`. -## What you declare, what is inferred +## Inputs -| You write | Becomes | +| You write | The person sees, your function receives | |---|---| -| `x: int / float / bool / str` | number / checkbox / text field | -| `x: Literal["a", "b"]` or an `Enum` | dropdown | -| `x: Image` / `Labels` | an image chosen from the host (you receive a numpy array) | -| `x: Table` | a CSV file (you receive a pandas DataFrame; floats exact, column names as written even if duplicated or empty, empty cells NaN, texts such as `NA` or `None` stay text unless the column is numeric: see PROTOCOL.md) | -| `x: Path` / `File` | a file (you receive a `Path`) | -| `x: Folder` | a folder (you receive a `Path`; the worker checks that it exists; hosts show a folder chooser) | -| a default value | the form's default; no default = required | -| `Optional[T]`, `T \| None`, or a default of `None` | optional **and unset by default**: Napari shows a "set" checkbox, Fiji "Set "; if it stays unticked your function receives `None` (never 0 or an empty string) | -| `Annotated[float, Min(0), Max(1), Unit("um/px"), Description("..."), Label("...")]` | bounds (enforced everywhere), unit, the input's help (see rule 8), label | -| `Annotated[Image, Axes("YX")]` | the tool wants exactly that many dimensions; a clear error otherwise | -| `Annotated[float, PixelSizeOf("image")]` | hosts prefill this from the image's calibration (converted to um) | -| `Annotated[..., Group("Segmentation")]` | the parameter is listed under that heading; the parameters of a group are shown together | -| `Annotated[..., Advanced()]` | listed last, behind "Show advanced settings" (Napari) / under "Advanced settings" (Fiji) | -| `Annotated[Image, Axes("YX"), PickChannel()]` | the person chooses a channel of a multi-channel image in the host (QuPath: the channel names; Fiji: the channel number) and your function receives only that channel as a 2D array. Napari layers are one channel each, so it only offers R/G/B for an RGB layer or the channels of a TIFF file given as "or file"; the command line and notebooks pass the image as it is | -| `Annotated[Optional[Labels], RegionOf("image")] = None` | run on the selection: Napari the selected Shapes layer, Fiji the ROI, QuPath the selected annotations arrive as a label image; `from labconstrictor_tools.region import bbox` gives the box to crop to (an empty selection raises a readable error) | -| `Annotated[float, Min(0), Max(1), Widget("slider")]` / `Annotated[Literal[...], Widget("radio")]` | a slider (with a typed box) for a bounded number; radio buttons for 2 to 5 choices | -| `Annotated[..., Group("Advanced options"), Collapsed()]` | the group is an accordion section that starts folded (Napari); Fiji shows the heading and the fields | -| `Annotated[str, ChoicesFrom("list_conditions", depends=["results_folder", "user_name"])]` | a dropdown filled by another tool (which returns `Scalars` with a `choices` list); a text field when it cannot be answered, so the tool accepts any string | -| `Annotated[str, ClearAfterRun()]` | Napari empties/resets the field after a successful run (a stale answer cannot be sent twice) | -| `Annotated[..., EnabledWhen("other")]` or `EnabledWhen("other", "a", "b")` | greyed out in Napari unless `other` is set/true or equals one of the values; **Fiji ignores it** (all fields stay editable) | -| docstring `Args:` section | the inputs' help, as `Description` (`Description` wins when both are given) | - -Return one value or a tuple. Annotate the return type with what it is: - -| Return annotation | Meaning | +| `x: int`, `float`, `bool`, `str` | a number, a checkbox or a text field | +| `x: Literal["a", "b"]` or an `Enum` | a dropdown | +| `x: Image`, `x: Labels` | an open image or a file; you receive a NumPy array | +| `x: Table` | a CSV file; you receive a pandas DataFrame read exactly as written (the details are in the [protocol reference](https://cellmigrationlab.github.io/LabConstrictor-Site/guides/protocol/)) | +| `x: Path`, `x: File` | a file; you receive a `Path` | +| `x: Folder` | a folder chooser; you receive a `Path` to a folder that exists | +| a default value | the form's default; no default means required | +| `Optional[T]`, `T \| None` or a default of `None` | optional and unset by default: a "set" box. If it stays unticked your function receives `None`, never 0 or an empty string | +| `Annotated[float, Min(0), Max(1), Unit("um/px"), Description("..."), Label("...")]` | bounds (enforced everywhere), a unit, the input's help, a label | +| `Annotated[Image, Axes("YX")]` | the tool takes exactly that many dimensions; anything else is refused with a clear error | +| `Annotated[float, PixelSizeOf("image")]` | prefilled from the image's calibration, converted to µm | +| `Annotated[..., Group("Segmentation")]` | the parameter is listed under that heading, with the rest of its group | +| `Annotated[..., Advanced()]` | listed last, under "Advanced settings" (in napari behind a "Show advanced settings" box) | +| `Annotated[..., Group("Advanced options"), Collapsed()]` | the group starts folded where the host can fold it | +| `Annotated[float, Min(0), Max(1), Widget("slider")]`, `Annotated[Literal[...], Widget("radio")]` | a slider (with a typed box) for a bounded number; radio buttons for 2 to 5 choices | +| `Annotated[Image, Axes("YX"), PickChannel()]` | the person chooses one channel of a multi-channel image; you receive that channel as a 2D array | +| `Annotated[Optional[Labels], RegionOf("image")] = None` | the person's selection (napari Shapes layer, Fiji ROI, QuPath annotations) as a label image; `from labconstrictor_tools.region import bbox` gives the box to crop to | +| `Annotated[str, ChoicesFrom("list_conditions", depends=["results_folder", "user_name"])]` | a dropdown filled by another tool, which returns `Scalars` with a `choices` list. It is a text field when that tool cannot answer, so accept any string | +| `Annotated[str, ClearAfterRun()]` | the field goes back to its default after a successful run, so a stale answer is not sent twice | +| `Annotated[..., EnabledWhen("other")]` or `EnabledWhen("other", "a", "b")` | greyed out unless `other` is set or true, or equals one of the values (Fiji ignores it) | +| a docstring `Args:` section | the inputs' help, as `Description` (`Description` wins when both are given) | + +## Outputs + +Return one value or a tuple, and annotate the return type: + +| Return annotation | What you return, what the person gets | |---|---| -| `ImageOut`, `LabelsOut` | numpy array -> TIFF (Fiji-unsafe dtypes such as float64 are converted) | -| `TableOut` | DataFrame / list of dicts / dict of lists -> table | -| `Scalars` | dict of numbers/strings shown to the user | -| `Affine` + `ApplyTo("query", "reference")` | 3x3 matrix mapping *query pixels -> reference pixels* (y, x order); hosts apply it for you | +| `ImageOut`, `LabelsOut` | a NumPy array, saved as TIFF (types ImageJ cannot open, such as float64, are converted) | +| `TableOut` | a DataFrame, a list of dicts or a dict of lists, shown as a table | +| `Scalars` | a dict of numbers or text, shown to the person | +| `MessageOut` | a short text (plain; `**bold**` is fine): instructions, a readout, a warning | | `FileOut` | a file path | -| `MessageOut` | a short text for the user (plain; `**bold**` is fine): instructions, a readout, a warning. Shown in a dialog / the status line, never in the log | -| `Annotated[PointsOut, ApplyTo("image")]` | a DataFrame / list of dicts with columns `y` and `x` (pixels of that image; other columns become properties) -> Napari points layer, Fiji point ROIs, QuPath point annotations | -| `Annotated[ShapesOut, ApplyTo("image")]` | `labels_to_shapes(labels)` from `labconstrictor_tools.shapes` (needs scikit-image), a GeoJSON FeatureCollection, or a list of polygons (arrays of `(y, x)` vertices, or dicts with `polygon` plus properties) -> Napari shapes layer, Fiji polygon ROIs, QuPath annotations | -| `Annotated[ImageOut, Name("view"), Replace()]` | each run replaces the previous result named `view` (Napari layer / Fiji window) instead of adding "view [1]" | -| `Annotated[ImageOut, Name("aligned"), Axes("YX")]` | name the output / say what its axes are | -| `return WithAxes(array, axes)` (for an `ImageOut` / `LabelsOut`) | the axes of this result, when they depend on the input (for example the axes the person typed). With axes in ImageJ order (`TYX`, `TZYX`, `ZCYX`, `TZCYX`...), from `Axes` or `WithAxes`, Fiji opens the result as a hyperstack with its dimensions instead of one long stack; the array is never reordered | - -## Rules that keep it fast and pleasant - -1. **Light module-level imports.** Only `labconstrictor_tools` and the standard library at the top of the file. Hosts load the - declarations to show the tool list; `labconstrictor-tools check` warns if you import numpy/torch/... at module level. -2. **Raise `ToolError(code, "what the user should do")`** for problems the user can fix. Any other exception is reported with its traceback. -3. **Call `check_cancel()` in long loops** and `progress(fraction, "message")` as work advances. A tool that never checks is - killed after 3 s when the user cancels - fine for short tools, wasteful for long ones. -4. **Do not keep state between runs in module globals** - hosts may reuse the worker (faster repeat runs), so a stale global will - leak into the next run. (Caching a loaded model is fine if it is keyed by its settings.) -5. **Write outputs through the return value**, not into the app folder (it may be read-only, e.g. on a network share). -6. **"Nothing found" is not an error.** When the honest answer is "no result" (no match, no nuclei), raise `ToolError("no_match", "No match found: ...say what to try...")` (or code `no_result`). Napari shows it as a notice (a warning sign, not a red cross) and Fiji as a plain message window instead of an error dialog. -7. **Presentation hints are only hints.** `Group`, `Advanced` and `EnabledWhen` may be ignored by a host (Fiji ignores `EnabledWhen`; older hosts ignore all three), so the function must accept every parameter whether or not it is "enabled". -8. **Describe every input.** The description is the input's help: hosts show it when the person points at the field, and an - ⓘ after the label says it is there (each host's status is in [What each host does with each feature](https://cellmigrationlab.github.io/LabConstrictor-Tools/HOST_FEATURES/)). It is expected for technical parameters and unfamiliar terms, and recommended - for all. One line: what the value does and a typical value, e.g. `Description("Fraction of the intensity range that separates - blobs from background; 0.3 suits most images")`. Write it with `Description("...")` or in the docstring's `Args:` section. - `labconstrictor-tools check` and `test` print a warning for each tool with inputs that have none (it never fails them): +| `Annotated[PointsOut, ApplyTo("image")]` | a DataFrame or list of dicts with columns `y` and `x` in pixels of that image (other columns become properties): points on the image | +| `Annotated[ShapesOut, ApplyTo("image")]` | `labels_to_shapes(labels)` from `labconstrictor_tools.shapes` (needs scikit-image), a GeoJSON FeatureCollection, or a list of polygons (arrays of `(y, x)` vertices, or dicts with `polygon` plus properties): outlines on the image | +| `Affine` with `ApplyTo("query", "reference")` | a 3x3 matrix mapping query pixels to reference pixels, in (y, x) order | +| `Annotated[ImageOut, Name("view"), Replace()]` | each run replaces the previous result named `view` instead of adding "view [1]" | +| `Annotated[ImageOut, Name("aligned"), Axes("YX")]` | names the output and states its axes | +| `return WithAxes(array, axes)` for an `ImageOut` or `LabelsOut` | the axes of this result, when they depend on the input. With axes in ImageJ order (`TYX`, `TZYX`, `ZCYX`, `TZCYX`, ...), from `Axes` or `WithAxes`, Fiji opens the result as a hyperstack; the array is never reordered | + +How each host shows each output is in [What works where](https://cellmigrationlab.github.io/LabConstrictor-Site/guides/capabilities/). + +## Rules for fast, pleasant tools + +1. **Keep module-level imports light.** Import only `labconstrictor_tools` and the standard library at the top of the file. Hosts load the declarations to show the tool list; `labconstrictor-tools check` warns about numpy, torch and other heavy imports at module level. +2. **Raise `ToolError(code, "what the person should do")`** for problems the person can fix. Any other exception is reported with its traceback. +3. **Call `check_cancel()` in long loops** and `progress(fraction, "message")` as work advances. The hosts stop a tool that does not react to Cancel after 3 seconds, which is wasteful for a long tool. +4. **Keep no state between runs in module globals.** Hosts may reuse the worker for faster repeat runs, so a stale global leaks into the next run. Caching a loaded model is fine if the cache is keyed by its settings. +5. **Write outputs through the return value**, not into the app folder, which may be read-only (for example on a network share). +6. **"Nothing found" is not an error.** When the honest answer is "no result", raise `ToolError("no_match", "No match found: ...say what to try...")` or use the code `no_result`. Hosts show it as a notice, not as an error. +7. **Treat presentation markers as hints.** A host may ignore `Group`, `Advanced` or `EnabledWhen`, so the function must accept every parameter whether or not it is "enabled". +8. **Describe every input.** The description is the input's help: hosts show it when the person points at the field, with an ⓘ after the label. Write one line that says what the value does and gives a typical value, for example `Description("Fraction of the intensity range that separates blobs from background; 0.3 suits most images")`, or put it in the docstring's `Args:` section. `labconstrictor-tools check` and `test` warn about inputs without one: `⚠ tool find_spots: 2 inputs have no description (threshold, min_size): add Description("...") or an Args: entry in the docstring`. -## Where do images come from? +## Where images come from -You do not decide: every `Image`/`Labels` parameter offers **an open image or a file** in every front-end (command line: a path). -Napari shows the layer chooser plus an "or file" row (a chosen file wins and greys the layer out); Fiji shows the open-image -chooser plus "(or file)", and with no image open only the file field. Your function always receives a NumPy array. TIFF/OME-TIFF are -read with `tifffile`; other formats (PNG, JPEG, ...) are read if the app environment has `imageio`, otherwise the user gets -"not a TIFF ... save it as TIFF". Pixel size stored in a TIFF is used to pre-fill a linked `PixelSizeOf` parameter, as for open images. +You do not decide: every `Image` or `Labels` parameter offers an open image or a file in every host, and a path on the command line. Your function always receives a NumPy array. TIFF and OME-TIFF are read with `tifffile`. Other formats (PNG, JPEG, ...) are read only if the app's environment has `imageio`; otherwise the person sees `'' is not a TIFF and this app has no imageio to read it; save it as TIFF`. The pixel size stored in a TIFF prefills a linked `PixelSizeOf` parameter, as for open images. -## Try it without any GUI +## Try it without a host + +Run these from the repository root: ```bash -labconstrictor-tools check --module my_app_lc_tools --pythonpath . -labconstrictor-tools register --name myapp --prefix --module my_app_lc_tools --pythonpath . # by hand; the installer does it -labconstrictor-tools run myapp blur image=cells.tif sigma=3 --out results/ # without --out: /results/