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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions docs/developers/library.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
53 changes: 32 additions & 21 deletions src/langslice/__init__.py
Original file line number Diff line number Diff line change
@@ -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.
"""

Expand Down
135 changes: 99 additions & 36 deletions src/langslice/doors/library/handle.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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"
Expand Down Expand Up @@ -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}"
Expand All @@ -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
Expand All @@ -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
Expand All @@ -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/<name>/``
(:class:`langslice.core.maps.section_maps.SectionMaps`). ``coords``
Expand Down Expand Up @@ -342,6 +349,62 @@ def __repr__(self) -> str:
return f"<langslice job {self.folder} ({len(self.state.slices)} sections)>"


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()},

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Prevent plugin tools from overriding handle members

When a job includes a plugin tool named close, wait, state, or another existing handle member, installing every tool directly on the subclass overrides the inherited member. These names are accepted by job.plugins.check_tool, which checks native-tool collisions but not handle-member collisions. For example, a plugin named close now causes JobHandle.__exit__ to invoke the plugin instead of closing the opened job and waiting for background writes; previously, the handle's own method took precedence over __getattr__. Reject conflicting names or otherwise preserve the handle's lifecycle methods and properties.

Useful? React with 👍 / 👎.

},
)
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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
8 changes: 5 additions & 3 deletions src/langslice/doors/reference_card.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")`.
Expand Down
3 changes: 2 additions & 1 deletion src/langslice/tools/descriptions/door_text.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 "
Expand Down
32 changes: 31 additions & 1 deletion tests/conftest.py
Original file line number Diff line number Diff line change
@@ -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
Loading
Loading