From 32f98aec6272139d63fbd2ed68e4aee0cba39632 Mon Sep 17 00:00:00 2001 From: greenpolo Date: Fri, 20 Nov 2026 13:30:58 -0500 Subject: [PATCH] Library: every tool a real method, help(job) and help(langslice) as the index A script's job handle now has a class made for its job: each tool is a method of it, so help(job), dir(job) and an editor list every tool with its arguments, and the class docstring indexes them by group with the handle's own methods and the job.context parts. Before, the tools came through __getattr__ and help(job) showed none of them. help(langslice) is the start-here index of the library. The handle's properties carry their real types. The job statement and the job folder's AGENTS.md point at help(job). tests/test_library_index.py checks that help(job) lists every tool with its signature and that every public name a script reaches has a docstring. The synthetic job fixture moved to conftest so both tests open it. Co-Authored-By: Claude Opus 5.5 --- docs/developers/library.md | 6 +- src/langslice/__init__.py | 53 ++++--- src/langslice/doors/library/handle.py | 135 +++++++++++++----- src/langslice/doors/reference_card.py | 8 +- src/langslice/tools/descriptions/door_text.py | 3 +- tests/conftest.py | 32 ++++- tests/synthetic_job.py | 30 ++++ tests/test_library_index.py | 83 +++++++++++ tests/test_smoke.py | 44 +----- 9 files changed, 287 insertions(+), 107 deletions(-) create mode 100644 tests/synthetic_job.py create mode 100644 tests/test_library_index.py diff --git a/docs/developers/library.md b/docs/developers/library.md index 0519ff57..bd2bd9ad 100644 --- a/docs/developers/library.md +++ b/docs/developers/library.md @@ -20,8 +20,10 @@ with langslice.open_job("/scans/brain1") as job: ``` `open_job` accepts a job folder or its image folder. Each enabled verb is a -method with the same name and arguments as the agent tool. Discover them -with `job.verbs` and `langslice job FOLDER schema VERB`. +method with the same name and arguments as the agent tool. `help(job)` lists +them, grouped, with the handle's own methods; `help(job.look)` gives one +verb's arguments, `job.verbs` their names. `help(langslice)` is the index of +the rest of the library. Sections are named by filename or a unique filename stem. A reply is a JSON-safe dict: the full tool result plus `artifacts` (saved diff --git a/src/langslice/__init__.py b/src/langslice/__init__.py index 24fb6314..f8f0bba4 100644 --- a/src/langslice/__init__.py +++ b/src/langslice/__init__.py @@ -1,35 +1,46 @@ """LangSlice: register histology sections to BrainGlobe atlases. -The library a script uses (one import path, nothing of the agent framework -loaded):: +Start here. The library a script uses, one import path, nothing of the agent +framework loaded:: import langslice job = langslice.open_job("/data/brain1") # a job folder, or its images - job.status() # the verbs, as methods - xyz = langslice.coordinate_map(".../view.json") # atlas µm per pixel - atlas = langslice.load_atlas("allen_mouse_25um") # a BrainGlobe atlas - - model = langslice.image_model("openai-oauth") # or a profile of your own - job = langslice.create_job("/data/brain1", positions=..., image_model=model) - job.trace_borders(section="s01.tif") # any verb, by name - -- :func:`open_job` (:mod:`langslice.doors.library.handle`), :func:`create_job` - (:mod:`langslice.doors.library.handle`): the job's verbs as methods, the same - names and arguments as the agent tools and ``langslice job FOLDER VERB`` - (``langslice job FOLDER ops``, ``langslice job FOLDER schema VERB``); ``create_job`` makes - the job of a folder of sections. -- :func:`image_model`, :func:`default_prompt` - (:mod:`langslice.providers.profiles`): the image model profile the border - trace calls (a provider's model and LangSlice's prompt, or a model and - prompt of your own), and LangSlice's prompt text to start from. + help(job) # every tool of this job + job.status() # a tool, as a method + reply = job.look(mode="overlay", sections=["s01.tif"]) + reply["artifacts"] # the picture files + +Where everything is: + +- ``help(job)``: the job's tools, grouped, each a method with the agent + tool's name and arguments (``help(job.look)``), and the handle's own + methods: ``wait``, ``close``, ``section_maps``, ``export_stack``, + ``export_abba``, ``export_dmc_brainmap``. +- ``help(job.context)``: a method of your own written into the job (your own + affine, warp field or section image, a preview that writes nothing), in six + parts, each with its own ``help``: ``reads`` (sections, atlas, images, + masks), ``frames`` (fit grid, atlas planes, points to atlas micrometres), + ``proposals`` (a transform or deformation as LangSlice stores it), + ``fits`` (FireANTs, elastix, an outside engine's ITK files), ``writes`` + and ``pictures``. +- :func:`open_job`, :func:`create_job` (:mod:`langslice.doors.library.handle`): + open a job, or make one from a folder of sections. - :func:`coordinate_map` (:mod:`langslice.core.pictures.layers`): a saved picture's pixels in atlas micrometres, ``(rows, cols, 3)`` float32, the atlas's own axis order, voxel ``i``'s centre at ``i * resolution``. - :func:`load_atlas` (:mod:`langslice.core.atlas.load`): a cached BrainGlobe atlas. - -Each is loaded on first use, so ``import langslice`` stays light. +- :func:`image_model`, :func:`default_prompt` + (:mod:`langslice.providers.profiles`): the image model ``trace_borders`` + calls (a provider's model and LangSlice's prompt, or your own), and + LangSlice's prompt text to start from. +- :mod:`langslice.plugin_api`: the types the context parts return, and how to + add a tool of your own to a job. +- The job folder's ``AGENTS.md``: its files (``state.json`` is the truth, + the rest is derived) and its coordinates. + +Each name is loaded on first use, so ``import langslice`` stays light. ``docs/developers/library.md`` is the scripting guide. """ diff --git a/src/langslice/doors/library/handle.py b/src/langslice/doors/library/handle.py index 0d434b81..3de4c2e9 100644 --- a/src/langslice/doors/library/handle.py +++ b/src/langslice/doors/library/handle.py @@ -51,13 +51,14 @@ from __future__ import annotations import functools +import inspect import logging import math import os import weakref from collections.abc import Callable, Mapping, Sequence from pathlib import Path -from typing import Any +from typing import TYPE_CHECKING, Any from langslice.core.fits.trace.request import ImageModel from langslice.doors.jobs import Opened, open_folder @@ -70,6 +71,12 @@ export_dmc_brainmap, ) +if TYPE_CHECKING: + from langslice.core.maps.section_maps import SectionMaps + from langslice.core.stack.stack import Stack + from langslice.core.workspace import Workspace + from langslice.job.job import Job + logger = logging.getLogger(__name__) IMAGE_MODEL_KEY = "image_model" @@ -107,45 +114,48 @@ def _close_open() -> None: class JobHandle: - """One open job folder; every verb its settings have is a method.""" + """One open LangSlice job folder: ``job = langslice.open_job(folder)``. + + Tools: every tool this job's settings have is a method, with the same name + and arguments as the agent's tool (listed below, ``help(job.look)`` for one). + Each returns a :class:`~langslice.doors.library.replies.Reply`: the tool's + reply as a JSON-safe dict, ``reply["artifacts"]`` the picture files (open them + to see them), ``reply.images`` the pictures as PIL images. A refusal is a + reply too: check ``reply["status"]`` and ``reply["error"]``. + + The handle's own methods: :meth:`wait` (background fits and traces land), + :meth:`close`, :meth:`section_maps` (a section's atlas coordinates and labels + as arrays), :meth:`export_stack`, :meth:`export_abba`, + :meth:`export_dmc_brainmap`; and :attr:`verbs`, :attr:`folder`, + :attr:`state` (the stack, read only), :attr:`job`, :attr:`workspace` (atlas + and section files), :attr:`image_model`, :attr:`imported`. + + A method of your own (your own affine, warp field, section image, or a + preview that writes nothing) goes in through :attr:`context`: + ``help(job.context)`` and ``help(job.context.reads)``, ``.frames``, + ``.proposals``, ``.fits``, ``.writes``, ``.pictures``. + + The job folder's ``AGENTS.md`` describes its files; ``help(langslice)`` lists + the rest of the library. + """ def __init__(self, opened: Opened, imported: dict[str, Any] | None = None) -> None: self._opened = opened - self._tools = {tool.__name__: self._method(tool) for tool in opened.tools().tools} self._imported = imported self._context: ScriptContext | None = None _track(opened) - def _method(self, tool: Callable[..., Any]) -> Callable[..., Reply]: - """The verb *tool* as a method: the tool's call, then its pictures - written, then its reply for a script (:func:`library_reply`).""" - from langslice.job.pictures import captured - - job = self._opened.job - name = tool.__name__ - - @functools.wraps(tool) - def method(*args: Any, **kwargs: Any) -> Reply: - with captured() as saved: - reply = tool(*args, **kwargs) - job.views.flush() - return library_reply(name, reply, saved) - - return method - @property def verbs(self) -> list[str]: """The verbs this job has (its tasks decide), in registry order.""" return self._opened.listed_verbs() - def __getattr__(self, name: str) -> Callable[..., Reply]: - tools = self.__dict__.get("_tools") or {} - if name in tools: - return tools[name] + def __getattr__(self, name: str) -> Any: from langslice.tools.catalog import verbs_for - if name in verbs_for(self._opened.spec): - spec = self._opened.spec + opened = self.__dict__.get("_opened") + if opened is not None and name in verbs_for(opened.spec): + spec = opened.spec raise AttributeError( f"This job's settings have no {name!r} (tasks " f"{spec.tasks}" @@ -154,9 +164,6 @@ def __getattr__(self, name: str) -> Callable[..., Reply]: ) raise AttributeError(name) - def __dir__(self) -> list[str]: - return sorted({*super().__dir__(), *self.verbs}) - @property def context(self) -> ScriptContext: """The job as a method of the script's own reads and writes it @@ -174,7 +181,7 @@ def folder(self) -> str: return str(self._opened.job.folder) @property - def image_model(self) -> Any: + def image_model(self) -> ImageModel | None: """The image model ``trace_borders`` calls when one was handed in (:class:`langslice.core.fits.trace.request.ImageModel`), else None.""" return self._opened.image_model @@ -189,23 +196,23 @@ def imported(self) -> dict[str, Any] | None: return self._imported @property - def job(self) -> Any: + def job(self) -> Job: """The job itself (:class:`langslice.job.job.Job`: state, undo, gates).""" return self._opened.job @property - def state(self) -> Any: + def state(self) -> Stack: """The stack as it stands (:class:`langslice.core.stack.stack.Stack`); read it, write through the verbs.""" return self._opened.job.state @property - def workspace(self) -> Any: + def workspace(self) -> Workspace: """The atlas and the section files (:class:`langslice.core.workspace.Workspace`).""" return self._opened.ctx - def section_maps(self, section: str, *, full_resolution: bool = False) -> Any: + def section_maps(self, section: str, *, full_resolution: bool = False) -> SectionMaps: """One section's maps in memory, written nowhere: the arrays ``export_maps`` writes to ``sections//`` (:class:`langslice.core.maps.section_maps.SectionMaps`). ``coords`` @@ -342,6 +349,62 @@ def __repr__(self) -> str: return f"" +def _method(opened: Opened, tool: Callable[..., Any]) -> Callable[..., Reply]: + """The tool *tool* as a method of a script's handle: the tool's call, then + its pictures written, then its reply for a script (:func:`library_reply`).""" + from langslice.job.pictures import captured + + job = opened.job + name = tool.__name__ + + @functools.wraps(tool) + def method(*args: Any, **kwargs: Any) -> Reply: + with captured() as saved: + reply = tool(*args, **kwargs) + job.views.flush() + return library_reply(name, reply, saved) + + return method + + +def tool_index(tools: Mapping[str, Callable[..., Any]], groups: Mapping[str, str]) -> str: + """The tools of a job, grouped as the hosts list them, each with the first + line of its description: the tail of ``help(job)``.""" + from langslice.core.tool_kinds import GROUPS + + lines = ["This job's tools:"] + for group in (*GROUPS, ""): + names = [name for name in tools if groups.get(name, "") == group] + if not names: + continue + lines.append(f"\n{group or 'Other'}:") + for name in names: + first = (inspect.getdoc(tools[name]) or "").split("\n", 1)[0].strip() + lines.append(f"- {name}: {first}") + return "\n".join(lines) + + +def job_handle(opened: Opened, imported: dict[str, Any] | None = None) -> JobHandle: + """A :class:`JobHandle` of a class made for this job, whose tools are its + own methods and whose docstring lists them, so ``help(job)``, ``dir(job)`` + and an editor show every tool with its arguments.""" + from langslice.tools.catalog import verbs_for + + tools = {tool.__name__: _method(opened, tool) for tool in opened.tools().tools} + groups = {name: verb.group for name, verb in verbs_for(opened.spec).items()} + guide = inspect.cleandoc(JobHandle.__doc__ or "") + own = type( + JobHandle.__name__, + (JobHandle,), + { + "__doc__": f"{guide}\n\n{tool_index(tools, groups)}\n", + "__module__": JobHandle.__module__, + **{name: staticmethod(method) for name, method in tools.items()}, + }, + ) + return own(opened, imported) + + def as_image_model(value: Any) -> ImageModel | None: """*value* as the image model the tools call: None stays None; a provider name, an ``ImageModel``, an object with a ``call`` or a function goes @@ -408,7 +471,7 @@ def open_job( f"[job] made with the untested image-model profile " f"{held.get('profile')!r}: pass image_model= to trace borders" ) - return JobHandle(opened) + return job_handle(opened) except BaseException: opened.close() raise @@ -612,7 +675,7 @@ def create_job( try: if model is not None: write_job_file(opened.job.layout, **{IMAGE_MODEL_KEY: profile_record(model)}) - return JobHandle(opened, imported) + return job_handle(opened, imported) except BaseException: opened.close() raise diff --git a/src/langslice/doors/reference_card.py b/src/langslice/doors/reference_card.py index 45dcb20c..efccbf1f 100644 --- a/src/langslice/doors/reference_card.py +++ b/src/langslice/doors/reference_card.py @@ -178,9 +178,11 @@ def card_text(layout: JobLayout) -> str: ## Python `import langslice; job = langslice.open_job("{layout.folder}")`; the verbs are methods -with the same arguments {example}. Each returns, once its pictures are on disk, a JSON-safe -dict: the tool's reply in full (status rows with every field, null where unset) plus -`artifacts`, the files of its pictures; `reply.images` holds the pictures as PIL images. +with the same arguments {example}; `help(job)` lists every one and the handle's own +methods, `help(langslice)` the rest of the library. Each returns, once its pictures are +on disk, a JSON-safe dict: the tool's reply in full (status rows with every field, null +where unset) plus `artifacts`, the files of its pictures; `reply.images` holds the +pictures as PIL images. A script's writes and a registration agent's tools share the folder's lock; a long fit re-checks each section before it applies (`STALE_INPUT`: run it again for that section). {background}Atlases: `langslice.load_atlas("allen_mouse_25um")`. diff --git a/src/langslice/tools/descriptions/door_text.py b/src/langslice/tools/descriptions/door_text.py index 1d8d6a12..2fddf991 100644 --- a/src/langslice/tools/descriptions/door_text.py +++ b/src/langslice/tools/descriptions/door_text.py @@ -40,7 +40,8 @@ ) SCRIPT_LIBRARY = ( '- In a script, `langslice.open_job(r"{folder}")` opens this job: every ' - "tool is a method of it with the same arguments, without the tools' " + "tool is a method of it with the same arguments (`help(job)` lists them " + "all), without the tools' " "limit on pictures or sections per call, and `job.context` holds the " "parts for a method of your own (`help(job.context)`: the section " "images and the atlas as arrays, a transform or a deformation of your " diff --git a/tests/conftest.py b/tests/conftest.py index 015dd48f..af70f6da 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,11 +1,41 @@ -"""Keep the smoke run off the user's own LangSlice settings and caches.""" +"""Keep the test jobs off the user's own LangSlice settings and caches, and +make the synthetic job they open (``images``). + +The settings are switched off before any test imports LangSlice, so the +fixture imports LangSlice inside its body. +""" from __future__ import annotations import os +from pathlib import Path + +import pytest os.environ.setdefault("LANGSLICE_ATLAS_CACHE", "off") os.environ.setdefault("LANGSLICE_RECENT_JOBS", "off") os.environ.setdefault("LANGSLICE_SETTINGS", "off") os.environ.setdefault("LANGSLICE_CLAUDE_TRANSCRIPTS", "off") os.environ["LANGSLICE_DETACH"] = "0" + + +@pytest.fixture +def images(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path: + """Three synthetic sections in a folder, opened on the synthetic atlas.""" + import langslice.doors.jobs as jobs + from tests.deformable_synthetic import SyntheticAtlas + from tests.synthetic_job import write_sections + + atlas = SyntheticAtlas() + make_context = jobs.context + + def context_on_synthetic_atlas(*args: object, **kwargs: object) -> object: + kwargs["atlas_loader"] = lambda _name: atlas + return make_context(*args, **kwargs) + + monkeypatch.setattr(jobs, "context", context_on_synthetic_atlas) + monkeypatch.setenv("HOME", str(tmp_path / "home")) + monkeypatch.setenv("USERPROFILE", str(tmp_path / "home")) + folder = tmp_path / "stack" + write_sections(folder) + return folder diff --git a/tests/synthetic_job.py b/tests/synthetic_job.py new file mode 100644 index 00000000..baef3f1a --- /dev/null +++ b/tests/synthetic_job.py @@ -0,0 +1,30 @@ +"""Three synthetic sections with known positions: the job the library tests open.""" + +from __future__ import annotations + +from pathlib import Path + +import cv2 +import numpy as np +from PIL import Image + +from tests.deformable_synthetic import SMOOTH_FIELD, SyntheticAtlas, render_section + +SECTION_SHRINK = 0.8 +PIXEL_SIZE_UM = 25.0 / SECTION_SHRINK +POSITIONS = {"s0.png": 0.1, "s1.png": 0.15, "s2.png": 0.2} + + +def write_sections(folder: Path) -> None: + """Three grey sections of the synthetic atlas under a smooth known field.""" + atlas = SyntheticAtlas() + folder.mkdir(parents=True) + for seed, name in enumerate(POSITIONS): + drawn, _ = render_section(atlas, SMOOTH_FIELD(), seed=seed) + plane = cv2.GaussianBlur(np.asarray(drawn)[..., 0], (0, 0), 1.2) + size = ( + round(plane.shape[1] * SECTION_SHRINK), + round(plane.shape[0] * SECTION_SHRINK), + ) + small = cv2.resize(plane, size, interpolation=cv2.INTER_AREA) + Image.fromarray(np.stack([small] * 3, axis=-1)).save(folder / name) diff --git a/tests/test_library_index.py b/tests/test_library_index.py new file mode 100644 index 00000000..e44b9e1b --- /dev/null +++ b/tests/test_library_index.py @@ -0,0 +1,83 @@ +"""A script finds every part of the library from ``help()``. + +A coding agent learns the library by calling ``help(langslice)``, +``help(job)`` and ``help(job.context)``. These tests hold that every tool of +a job is a method ``help(job)`` lists with its arguments, and that every +public name a script reaches (the package, the job handle, the context and +its six parts, :mod:`langslice.plugin_api`) says what it does in a +docstring. +""" + +from __future__ import annotations + +import inspect +import pydoc +from pathlib import Path + +import langslice +import langslice.plugin_api as plugin_api +from langslice.doors.library.handle import JobHandle +from langslice.doors.library.script_context import ScriptContext +from langslice.plugins.fits import Fits +from langslice.plugins.frames import Frames +from langslice.plugins.pictures import Pictures +from langslice.plugins.proposals import Proposals +from langslice.plugins.reads import Reads +from langslice.plugins.writes import Writes +from tests.synthetic_job import PIXEL_SIZE_UM, POSITIONS + +SCRIPT_CLASSES = (JobHandle, ScriptContext, Reads, Frames, Proposals, Fits, Writes, Pictures) + + +def undocumented_members(owner: type) -> list[str]: + return [ + f"{owner.__name__}.{name}" + for name, member in inspect.getmembers(owner) + if not name.startswith("_") + and (callable(member) or isinstance(member, property)) + and not (inspect.getdoc(member) or "").strip() + ] + + +def test_every_public_name_a_script_reaches_has_a_docstring() -> None: + missing = [name for owner in SCRIPT_CLASSES for name in undocumented_members(owner)] + missing += [ + f"langslice.{name}" + for name in langslice.__all__ + if callable(getattr(langslice, name)) + and not (inspect.getdoc(getattr(langslice, name)) or "").strip() + ] + missing += [ + f"plugin_api.{name}" + for name in plugin_api.__all__ + if ( + inspect.isclass(getattr(plugin_api, name)) + or inspect.isfunction(getattr(plugin_api, name)) + ) + and not (inspect.getdoc(getattr(plugin_api, name)) or "").strip() + ] + assert not missing, "Give each a docstring that says what it does:\n" + "\n".join(missing) + + +def test_the_package_help_names_every_way_in() -> None: + text = inspect.getdoc(langslice) or "" + named = ["help(job)", "help(job.context)", "plugin_api", "AGENTS.md", *langslice.__all__] + absent = [name for name in named if name != "__version__" and name not in text] + assert not absent, f"help(langslice) does not name {absent}" + + +def test_help_of_a_job_lists_every_tool_with_its_arguments(images: Path) -> None: + with langslice.create_job( + images, positions=POSITIONS, pixel_size_um=PIXEL_SIZE_UM, preprocess="none" + ) as job: + text = pydoc.render_doc(job, renderer=pydoc.plaintext) + verbs = job.verbs + unlisted = [name for name in verbs if f"- {name}: " not in text] + unsigned = [ + name for name in verbs if f"{name}{inspect.signature(getattr(job, name))}" not in text + ] + undocumented = [name for name in verbs if not inspect.getdoc(getattr(job, name))] + assert verbs + assert not unlisted, f"help(job)'s index leaves out {unlisted}" + assert not unsigned, f"help(job) shows no signature for {unsigned}" + assert not undocumented, f"these tools have no docstring: {undocumented}" diff --git a/tests/test_smoke.py b/tests/test_smoke.py index ec64c803..6fc6ff0c 100644 --- a/tests/test_smoke.py +++ b/tests/test_smoke.py @@ -10,50 +10,8 @@ import json from pathlib import Path -import cv2 -import numpy as np -import pytest -from PIL import Image - import langslice -import langslice.doors.jobs as jobs -from tests.deformable_synthetic import SMOOTH_FIELD, SyntheticAtlas, render_section - -SECTION_SHRINK = 0.8 -PIXEL_SIZE_UM = 25.0 / SECTION_SHRINK -POSITIONS = {"s0.png": 0.1, "s1.png": 0.15, "s2.png": 0.2} - - -def write_sections(folder: Path) -> None: - """Three grey sections of the synthetic atlas under a smooth known field.""" - atlas = SyntheticAtlas() - folder.mkdir(parents=True) - for seed, name in enumerate(POSITIONS): - drawn, _ = render_section(atlas, SMOOTH_FIELD(), seed=seed) - plane = cv2.GaussianBlur(np.asarray(drawn)[..., 0], (0, 0), 1.2) - size = ( - round(plane.shape[1] * SECTION_SHRINK), - round(plane.shape[0] * SECTION_SHRINK), - ) - small = cv2.resize(plane, size, interpolation=cv2.INTER_AREA) - Image.fromarray(np.stack([small] * 3, axis=-1)).save(folder / name) - - -@pytest.fixture -def images(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path: - atlas = SyntheticAtlas() - make_context = jobs.context - - def context_on_synthetic_atlas(*args: object, **kwargs: object) -> object: - kwargs["atlas_loader"] = lambda _name: atlas - return make_context(*args, **kwargs) - - monkeypatch.setattr(jobs, "context", context_on_synthetic_atlas) - monkeypatch.setenv("HOME", str(tmp_path / "home")) - monkeypatch.setenv("USERPROFILE", str(tmp_path / "home")) - folder = tmp_path / "stack" - write_sections(folder) - return folder +from tests.synthetic_job import PIXEL_SIZE_UM, POSITIONS def test_a_brain_registers_from_start_to_export(images: Path) -> None: