Skip to content

Turn any AI agent into an AI Scientist. The #1 Agent Skills library for science, used by 250,000+ scientists worldwide. 177 ready-to-use validated skills plus 100+ scientific databases covering biology, chemistry, medicine, and drug discovery. Compatible with Cursor, Claude Code, Codex, Pi, Antigravity, and the open Agent Skills standard.

Update OMERO skill for current clients

Timothy Kassis90e825e53423
diff --git a/skills/omero-integration/SKILL.md b/skills/omero-integration/SKILL.md
index 97c44b37..1f1bf66a 100644
--- a/skills/omero-integration/SKILL.md
+++ b/skills/omero-integration/SKILL.md
@@ -1,249 +1,222 @@
---
name: omero-integration
-description: Microscopy data management platform. Access images via Python, retrieve datasets, analyze pixels, manage ROIs/annotations, batch processing, for high-content screening and microscopy workflows.
-license: Unknown
-required_environment_variables: [{"name": "OMERO_HOST", "prompt": "OMERO server hostname.", "required_for": "full functionality"}, {"name": "OMERO_PORT", "prompt": "OMERO server port (default 4064).", "required_for": "optional features"}, {"name": "OMERO_USER", "prompt": "OMERO username.", "required_for": "full functionality"}, {"name": "OMERO_PASSWORD", "prompt": "OMERO password.", "required_for": "full functionality"}]
-metadata: {"version": "1.1", "skill-author": "K-Dense Inc.", "openclaw": {"envVars": [{"name": "OMERO_HOST", "required": true, "description": "OMERO server hostname."}, {"name": "OMERO_PORT", "required": false, "description": "OMERO server port (default 4064)."}, {"name": "OMERO_USER", "required": true, "description": "OMERO username."}, {"name": "OMERO_PASSWORD", "required": true, "description": "OMERO password."}]}}
+description: Securely inspect and automate microscopy data workflows against OMERO.server with omero-py, BlitzGateway, OMERO CLI, tables, annotations, ROIs, rendering, and documented OMERO.web APIs. Use for scoped OMERO inventory, metadata export, import/export planning, or reviewed write workflows.
+license: MIT
+compatibility: >-
+ Requires network access to a user-selected OMERO.server for remote operations.
+ The 2026-07-23 snapshot uses OMERO.py 5.22.1 with ZeroC IcePy 3.6.5;
+ OMERO supports Python 3.10-3.12 (3.12 recommended) while 3.13-3.14 remain
+ upcoming in its support matrix. Bundled local planners require Python 3.10+
+ and read only named OMERO_* variables; they never load .env files.
+metadata:
+ version: "1.2"
+ skill-author: K-Dense Inc.
+ openclaw:
+ envVars:
+ - name: OMERO_HOST
+ required: true
+ description: OMERO.server hostname.
+ - name: OMERO_PORT
+ required: false
+ description: OMERO SSL router port; default 4064.
+ - name: OMERO_USER
+ required: false
+ description: Username when not reusing a session.
+ - name: OMERO_PASSWORD
+ required: false
+ description: Password when not reusing a session.
+ - name: OMERO_SESSION_KEY
+ required: false
+ description: Existing session key as an alternative credential.
+ - name: OMERO_SECURE
+ required: false
+ description: Secure transport toggle; default true.
---
# OMERO Integration
-## Overview
-
-OMERO is an open-source platform for managing, visualizing, and analyzing microscopy images and metadata. Access images via Python API, retrieve datasets, analyze pixels, manage ROIs and annotations, for high-content screening and microscopy workflows.
-
-## When to Use This Skill
-
-This skill should be used when:
-- Working with OMERO Python API (omero-py) to access microscopy data
-- Retrieving images, datasets, projects, or screening data programmatically
-- Analyzing pixel data and creating derived images
-- Creating or managing ROIs (regions of interest) on microscopy images
-- Adding annotations, tags, or metadata to OMERO objects
-- Storing measurement results in OMERO tables
-- Creating server-side scripts for batch processing
-- Performing high-content screening analysis
-
-## Core Capabilities
-
-This skill covers eight major capability areas. Each is documented in detail in the references/ directory:
-
-### 1. Connection & Session Management
-**File**: `references/connection.md`
-
-Establish secure connections to OMERO servers, manage sessions, handle authentication, and work with group contexts. Use this for initial setup and connection patterns.
-
-**Common scenarios:**
-- Connect to OMERO server with credentials
-- Use existing session IDs
-- Switch between group contexts
-- Manage connection lifecycle with context managers
-
-### 2. Data Access & Retrieval
-**File**: `references/data_access.md`
-
-Navigate OMERO's hierarchical data structure (Projects → Datasets → Images) and screening data (Screens → Plates → Wells). Retrieve objects, query by attributes, and access metadata.
-
-**Common scenarios:**
-- List all projects and datasets for a user
-- Retrieve images by ID or dataset
-- Access screening plate data
-- Query objects with filters
-
-### 3. Metadata & Annotations
-**File**: `references/metadata.md`
-
-Create and manage annotations including tags, key-value pairs, file attachments, and comments. Link annotations to images, datasets, or other objects.
-
-**Common scenarios:**
-- Add tags to images
-- Attach analysis results as files
-- Create custom key-value metadata
-- Query annotations by namespace
-
-### 4. Image Processing & Rendering
-**File**: `references/image_processing.md`
-
-Access raw pixel data as NumPy arrays, manipulate rendering settings, create derived images, and manage physical dimensions.
-
-**Common scenarios:**
-- Extract pixel data for computational analysis
-- Generate thumbnail images
-- Create maximum intensity projections
-- Modify channel rendering settings
-
-### 5. Regions of Interest (ROIs)
-**File**: `references/rois.md`
-
-Create, retrieve, and analyze ROIs with various shapes (rectangles, ellipses, polygons, masks, points, lines). Extract intensity statistics from ROI regions.
-
-**Common scenarios:**
-- Draw rectangular ROIs on images
-- Create polygon masks for segmentation
-- Analyze pixel intensities within ROIs
-- Export ROI coordinates
-
-### 6. OMERO Tables
-**File**: `references/tables.md`
-
-Store and query structured tabular data associated with OMERO objects. Useful for analysis results, measurements, and metadata.
-
-**Common scenarios:**
-- Store quantitative measurements for images
-- Create tables with multiple column types
-- Query table data with conditions
-- Link tables to specific images or datasets
-
-### 7. Scripts & Batch Operations
-**File**: `references/scripts.md`
-
-Create OMERO.scripts that run server-side for batch processing, automated workflows, and integration with OMERO clients.
-
-**Common scenarios:**
-- Process multiple images in batch
-- Create automated analysis pipelines
-- Generate summary statistics across datasets
-- Export data in custom formats
-
-### 8. Advanced Features
-**File**: `references/advanced.md`
-
-Covers permissions, filesets, cross-group queries, delete operations, and other advanced functionality.
-
-**Common scenarios:**
-- Handle group permissions
-- Access original imported files
-- Perform cross-group queries
-- Delete objects with callbacks
-
-## Installation
+Use current OME documentation and the smallest explicit data scope. OMERO data
+may contain unpublished images, identifiers, annotations, original files, and
+derived measurements.
+
+## Verified Baseline
+
+This skill was refreshed on **2026-07-23**:
+
+- **OMERO.server 5.6.18** (May 2026) is the current documented stable server.
+- It was tested by OME with **OMERO.py/omero-py 5.22.1** and
+ **OMERO.web 5.31.0**.
+- `omero-py==5.22.1` requires Python 3.10 or newer. The OMERO support matrix
+ supports 3.10 and 3.11, recommends 3.12, and still labels 3.13/3.14
+ “upcoming.”
+- OMERO 5.6 uses **IcePy 3.6**, with 3.6.5 prebuilt client wheels documented
+ for Python versions through 3.12.
+
+The pin above is a reproducible skill snapshot, not a promise that every
+OMERO.server release accepts that client. For another server version, consult
+its release entry and use the OMERO.py version tested with it. See
+[`references/sources.md`](references/sources.md).
+
+## Operating Contract
+
+1. Start with local validation or a dry run. Do not connect until the user has
+ selected the host, group, object type, IDs, and result limit.
+2. Read credentials only from the named `OMERO_*` variables in the frontmatter.
+ Never search parent directories or load `.env` files.
+3. Never place a password or session key in command arguments, source code,
+ output JSON, logs, tracebacks, or chat. A session key is a bearer credential.
+4. Default to `secure=True`. OMERO encrypts login by default, but post-login
+ data and the session ID may otherwise travel unencrypted. `secure=True` does
+ not by itself guarantee certificate hostname verification.
+5. Bound every list, page, ROI, shape, annotation, table row, pixel plane, and
+ local file scan. Do not turn an object request into a group-wide or
+ cross-group export without explicit approval.
+6. Treat all writes separately: annotation/link creation, rendering-default
+ saves, image creation, imports, script uploads, table writes, ownership or
+ group changes, and deletion require an exact reviewed target.
+7. Close `BlitzGateway`, table handles, raw stores, thumbnail stores, rendering
+ engines, script clients, and other stateful services in `finally` blocks or
+ documented context-manager patterns.
+8. Never connect to a real server merely to “test” examples.
+
+## Choose the Interface
+
+- **BlitzGateway (`omero-py`)**: primary Python client for object traversal,
+ pixels, annotations, ROIs, rendering, and services.
+- **OMERO CLI**: sessions, import scanning/import, OME-TIFF or XML export,
+ scripts, and administrative plugins. Most client commands are remote; import
+ also needs the matching server-side Java libraries through `OMERODIR`.
+- **OMERO.web `api` and `webgateway`**: the only OMERO.web apps that official
+ documentation calls stable public APIs. The documented JSON API is
+ version-discovered and has limited object coverage; it is not evidence that
+ every webclient URL is a supported REST endpoint.
+- **OMERO.server scripts**: uploaded plugins executed by server infrastructure.
+ They are different from the bundled local client helpers in `scripts/`.
+
+## Install a Reproducible Client
+
+Create a Python 3.12 environment:
```bash
-uv pip install omero-py
+uv venv --python 3.12 .venv
+source .venv/bin/activate
```
-**Requirements:**
-- Python 3.7+
-- Zeroc Ice 3.6+
-- Access to an OMERO server (host, port, credentials)
-
-## Quick Start
-
-Basic connection pattern:
-
-```python
-from omero.gateway import BlitzGateway
-
-# Connect to OMERO server
-conn = BlitzGateway(username, password, host=host, port=port)
-connected = conn.connect()
-
-if connected:
- # Perform operations
- for project in conn.listProjects():
- print(project.getName())
+Install the exact IcePy 3.6.5 wheel matching the interpreter, OS, architecture,
+and wheel tags, then OMERO.py:
- # Always close connection
- conn.close()
-else:
- print("Connection failed")
-```
-
-**Recommended pattern with context manager:**
-
-```python
-from omero.gateway import BlitzGateway
-
-with BlitzGateway(username, password, host=host, port=port) as conn:
- # Connection automatically managed
- for project in conn.listProjects():
- print(project.getName())
- # Automatically closed on exit
+```bash
+# Download the matching 3.6.5 wheel from the official OMERO-linked matrix.
+uv pip install "/absolute/path/to/zeroc_ice-3.6.5-<matching-tags>.whl"
+uv pip install "omero-py==5.22.1"
```
-## Selecting the Right Capability
+Do not substitute Ice 3.7: the OMERO 5.6 support matrix marks Ice 3.6 as
+recommended and 3.7 as unsupported. A plain install may attempt to compile
+IcePy from source; prefer a reviewed matching wheel. The upstream package is
+GPL-2.0-or-later; this skill’s own files are MIT.
-**For data exploration:**
-- Start with `references/connection.md` to establish connection
-- Use `references/data_access.md` to navigate hierarchy
-- Check `references/metadata.md` for annotation details
+For import/admin commands only, `OMERODIR` must point to a compatible extracted
+OMERO.server directory. A normal remote BlitzGateway client does not require
+that server tree. Read [`references/connection.md`](references/connection.md)
+before installation or authentication work.
-**For image analysis:**
-- Use `references/image_processing.md` for pixel data access
-- Use `references/rois.md` for region-based analysis
-- Use `references/tables.md` to store results
+## Credentials and Connection
-**For automation:**
-- Use `references/scripts.md` for server-side processing
-- Use `references/data_access.md` for batch data retrieval
+Set named variables in the calling environment or secret manager. Do not put
+the password on an `omero` CLI command:
-**For advanced operations:**
-- Use `references/advanced.md` for permissions and deletion
-- Check `references/connection.md` for cross-group queries
-
-## Common Workflows
-
-### Workflow 1: Retrieve and Analyze Images
-
-1. Connect to OMERO server (`references/connection.md`)
-2. Navigate to dataset (`references/data_access.md`)
-3. Retrieve images from dataset (`references/data_access.md`)
-4. Access pixel data as NumPy array (`references/image_processing.md`)
-5. Perform analysis
-6. Store results as table or file annotation (`references/tables.md` or `references/metadata.md`)
-
-### Workflow 2: Batch ROI Analysis
-
-1. Connect to OMERO server
-2. Retrieve images with existing ROIs (`references/rois.md`)
-3. For each image, get ROI shapes
-4. Extract pixel intensities within ROIs (`references/rois.md`)
-5. Store measurements in OMERO table (`references/tables.md`)
-
-### Workflow 3: Create Analysis Script
-
-1. Design analysis workflow
-2. Use OMERO.scripts framework (`references/scripts.md`)
-3. Access data through script parameters
-4. Process images in batch
-5. Generate outputs (new images, tables, files)
-
-## Error Handling
+```bash
+export OMERO_HOST="omero.example.org"
+export OMERO_PORT="4064"
+export OMERO_USER="researcher"
+export OMERO_SECURE="true"
+# Supply OMERO_PASSWORD through the environment/secret manager, or use
+# OMERO_SESSION_KEY as an alternative. Do not echo either value.
+```
-Always wrap OMERO operations in try-except blocks and ensure connections are properly closed:
+A password-authenticated, exception-safe read pattern is:
```python
+import os
from omero.gateway import BlitzGateway
-import traceback
+conn = None
try:
- conn = BlitzGateway(username, password, host=host, port=port)
+ conn = BlitzGateway(
+ os.environ["OMERO_USER"],
+ os.environ["OMERO_PASSWORD"],
+ host=os.environ["OMERO_HOST"],
+ port=int(os.environ.get("OMERO_PORT", "4064")),
+ secure=True,
+ )
if not conn.connect():
- raise Exception("Connection failed")
-
- # Perform operations
-
-except Exception as e:
- print(f"Error: {e}")
- traceback.print_exc()
+ raise RuntimeError("OMERO connection failed")
+
+ images = conn.getObjects(
+ "Image",
+ opts={"limit": 25, "offset": 0, "order_by": "obj.id"},
+ )
+ for image in images:
+ print(image.getId()) # Do not print names unless requested.
finally:
- if conn:
+ if conn is not None:
conn.close()
```
-## Additional Resources
+For existing-session and CLI prompt patterns, certificate verification,
+group context, and cleanup details, read
+[`references/connection.md`](references/connection.md).
-- **Official Documentation**: https://omero.readthedocs.io/en/stable/developers/Python.html
-- **BlitzGateway API**: https://omero.readthedocs.io/en/stable/developers/Python.html#omero-blitzgateway
-- **OMERO Model**: https://omero.readthedocs.io/en/stable/developers/Model.html
-- **Community Forum**: https://forum.image.sc/tag/omero
+## Bundled Safe Helpers
-## Notes
+All helpers use `argparse`; `--help` works without OMERO installed. Remote
+helpers are dry-run by default and require `--execute`.
-- OMERO uses group-based permissions (READ-ONLY, READ-ANNOTATE, READ-WRITE)
-- Images in OMERO are organized hierarchically: Project > Dataset > Image
-- Screening data uses: Screen > Plate > Well > WellSample > Image
-- Always close connections to free server resources
-- Use context managers for automatic resource management
-- Pixel data is returned as NumPy arrays for analysis
+```bash
+python -B scripts/validate_config.py --help
+python -B scripts/inventory.py --help
+python -B scripts/export_image_metadata.py --help
+python -B scripts/plan_transfer.py --help
+```
+- `validate_config.py`: validates only named endpoint/auth variables locally;
+ optional DNS resolution still does not contact OMERO.
+- `inventory.py`: bounded, read-only object inventory with paged JSON output.
+- `export_image_metadata.py`: explicit-image annotation/ROI JSON export with
+ redaction defaults and per-category limits; it never downloads file bytes or
+ pixels.
+- `plan_transfer.py`: local-only import scan or per-image export plan; it never
+ invokes OMERO and never emits credential flags.
+
+Read [`references/scripts.md`](references/scripts.md) before using them.
+
+## Capability Guide
+
+- Connection, sessions, groups, TLS:
+ [`references/connection.md`](references/connection.md)
+- Hierarchies, pagination, screening data, import/export:
+ [`references/data_access.md`](references/data_access.md)
+- Tags, map/file/comment annotations, namespaces:
+ [`references/metadata.md`](references/metadata.md)
+- Raw planes, tiles, thumbnails, rendering:
+ [`references/image_processing.md`](references/image_processing.md)
+- ROI model, shape export, statistics caveat:
+ [`references/rois.md`](references/rois.md)
+- Bounded table creation, paging, querying, closure:
+ [`references/tables.md`](references/tables.md)
+- Local helpers and OMERO.server scripts:
+ [`references/scripts.md`](references/scripts.md)
+- Permissions, filesets, web/public links, destructive operations:
+ [`references/advanced.md`](references/advanced.md)
+
+## Final Review Before Remote Work
+
+- Confirm server version and its tested OMERO.py pairing.
+- Confirm target host, SSL router port, user/session, and one group.
+- Confirm exact object IDs/types and hard limits.
+- Confirm whether names, annotation values, file names, ROI labels, owner names,
+ pixels, or original files may leave the server.
+- Show the proposed output path and refuse overwrite unless explicitly allowed.
+- For a write, show the mutation and target IDs separately from any read plan.
+- Close every connection/service even after partial failure.
diff --git a/skills/omero-integration/references/advanced.md b/skills/omero-integration/references/advanced.md
index 966d100d..aab94472 100644
--- a/skills/omero-integration/references/advanced.md
+++ b/skills/omero-integration/references/advanced.md
@@ -1,631 +1,273 @@
-# Advanced Features
+# Permissions, Filesets, Web APIs, and High-Risk Operations
-This reference covers advanced OMERO operations including permissions, deletion, filesets, and administrative tasks.
+This reference covers features that can broaden scope, expose original data,
+or mutate server state. Apply the operating contract in `SKILL.md` first.
-## Deleting Objects
-
-### Delete with Wait
-
-```python
-# Delete objects and wait for completion
-project_ids = [1, 2, 3]
-conn.deleteObjects("Project", project_ids, wait=True)
-print("Deletion complete")
-
-# Delete without waiting (asynchronous)
-conn.deleteObjects("Dataset", [dataset_id], wait=False)
-```
-
-### Delete with Callback Monitoring
-
-```python
-from omero.callbacks import CmdCallbackI
-
-# Start delete operation
-handle = conn.deleteObjects("Project", [project_id])
-
-# Create callback to monitor progress
-cb = CmdCallbackI(conn.c, handle)
-print("Deleting, please wait...")
-
-# Poll for completion
-while not cb.block(500): # Check every 500ms
- print(".", end="", flush=True)
-
-print("\nDeletion finished")
-
-# Check for errors
-response = cb.getResponse()
-if isinstance(response, omero.cmd.ERR):
- print("Error occurred:")
- print(response)
-else:
- print("Deletion successful")
-
-# Clean up
-cb.close(True) # Also closes handle
-```
-
-### Delete Different Object Types
-
-```python
-# Delete images
-image_ids = [101, 102, 103]
-conn.deleteObjects("Image", image_ids, wait=True)
-
-# Delete datasets
-dataset_ids = [10, 11]
-conn.deleteObjects("Dataset", dataset_ids, wait=True)
-
-# Delete ROIs
-roi_ids = [201, 202]
-conn.deleteObjects("Roi", roi_ids, wait=True)
-
-# Delete annotations
-annotation_ids = [301, 302]
-conn.deleteObjects("Annotation", annotation_ids, wait=True)
-```
-
-### Delete with Cascade
-
-```python
-# Deleting a project will cascade to contained datasets
-# This behavior depends on server configuration
-project_id = 123
-conn.deleteObjects("Project", [project_id], wait=True)
+## Group Permissions
-# Datasets and images may be deleted or orphaned
-# depending on delete specifications
-```
+OMERO group permissions are commonly represented as:
-## Filesets
+- private: `rw----`
+- read-only: `rwr---`
+- read-annotate: `rwra--`
+- read-write: `rwrw--`
-Filesets represent collections of original imported files. They were introduced in OMERO 5.0.
+The string describes group policy, not a guarantee that a specific operation
+is allowed. Ownership, administrator privileges, object state, and link rules
+also matter.
-### Check if Image Has Fileset
+Inspect, do not infer:
```python
image = conn.getObject("Image", image_id)
+if image is None:
+ raise LookupError("Image unavailable")
-fileset = image.getFileset()
-if fileset:
- print(f"Image is part of fileset {fileset.getId()}")
-else:
- print("Image has no fileset (pre-OMERO 5.0)")
+details = image.getDetails()
+permissions = details.getPermissions()
+print(
+ {
+ "group_id": details.getGroup().getId(),
+ "owner_id": details.getOwner().getId(),
+ "can_edit": permissions.canEdit(),
+ "can_annotate": permissions.canAnnotate(),
+ "can_link": permissions.canLink(),
+ "can_delete": permissions.canDelete(),
+ }
+)
```
-### Access Fileset Information
+Do not print owner/group names or email addresses unless needed.
-```python
-image = conn.getObject("Image", image_id)
-fileset = image.getFileset()
+## Cross-Group and Substitute-User Operations
-if fileset:
- fs_id = fileset.getId()
- print(f"Fileset ID: {fs_id}")
+`conn.SERVICE_OPTS.setOmeroGroup("-1")` requests all accessible groups. It can
+multiply query scope and expose data from collaborations not intended for the
+current task. Require explicit cross-group approval, a total cap, and
+group IDs in output.
- # List all images in this fileset
- print("Images in fileset:")
- for fs_image in fileset.copyImages():
- print(f" {fs_image.getId()}: {fs_image.getName()}")
+`suConn()` and CLI `--sudo` are privileged impersonation mechanisms. Use only
+for an administrator-approved task with:
- # List original imported files
- print("\nOriginal files:")
- for orig_file in fileset.listFiles():
- print(f" {orig_file.getPath()}/{orig_file.getName()}")
- print(f" Size: {orig_file.getSize()} bytes")
-```
+- initiating administrator identity;
+- target user;
+- target group;
+- exact operation and IDs;
+- audit/logging expectations;
+- immediate closure of the substitute connection.
-### Get Fileset Directly
+Never create a substitute connection merely to work around a permission error.
-```python
-# Get fileset object
-fileset = conn.getObject("Fileset", fileset_id)
-
-if fileset:
- # Access images
- for image in fileset.copyImages():
- print(f"Image: {image.getName()}")
-
- # Access files
- for orig_file in fileset.listFiles():
- print(f"File: {orig_file.getName()}")
-```
+## Filesets and Original Data
-### Download Original Files
+Filesets represent original imported file collections. One fileset may back
+multiple images and include nested paths:
```python
-import os
-
fileset = image.getFileset()
-
-if fileset:
- download_dir = "./original_files"
- os.makedirs(download_dir, exist_ok=True)
-
- for orig_file in fileset.listFiles():
- file_name = orig_file.getName()
- file_path = os.path.join(download_dir, file_name)
-
- print(f"Downloading: {file_name}")
-
- # Get file as RawFileStore
- raw_file_store = conn.createRawFileStore()
- raw_file_store.setFileId(orig_file.getId())
-
- # Download in chunks
- with open(file_path, 'wb') as f:
- offset = 0
- chunk_size = 1024 * 1024 # 1MB chunks
- size = orig_file.getSize()
-
- while offset < size:
- chunk = raw_file_store.read(offset, chunk_size)
- f.write(chunk)
- offset += len(chunk)
-
- raw_file_store.close()
- print(f"Saved to: {file_path}")
-```
-
-## Group Permissions
-
-OMERO uses group-based permissions to control data access.
-
-### Permission Levels
-
-- **PRIVATE** (`rw----`): Only owner can read/write
-- **READ-ONLY** (`rwr---`): Group members can read, only owner can write
-- **READ-ANNOTATE** (`rwra--`): Group members can read and annotate
-- **READ-WRITE** (`rwrw--`): Group members can read and write
-
-### Check Current Group Permissions
-
-```python
-# Get current group
-group = conn.getGroupFromContext()
-
-# Get permissions
-permissions = group.getDetails().getPermissions()
-perm_string = str(permissions)
-
-# Map to readable names
-permission_names = {
- 'rw----': 'PRIVATE',
- 'rwr---': 'READ-ONLY',
- 'rwra--': 'READ-ANNOTATE',
- 'rwrw--': 'READ-WRITE'
-}
-
-perm_name = permission_names.get(perm_string, 'UNKNOWN')
-print(f"Group: {group.getName()}")
-print(f"Permissions: {perm_name} ({perm_string})")
-```
-
-### List User's Groups
-
-```python
-# Get all groups for current user
-print("User's groups:")
-for group in conn.getGroupsMemberOf():
- print(f" {group.getName()} (ID: {group.getId()})")
-
- # Get group permissions
- perms = group.getDetails().getPermissions()
- print(f" Permissions: {perms}")
-```
-
-### Get Group Members
-
-```python
-# Get group
-group = conn.getObject("ExperimenterGroup", group_id)
-
-# List members
-print(f"Members of {group.getName()}:")
-for member in group.getMembers():
- print(f" {member.getFullName()} ({member.getOmeName()})")
-```
-
-## Cross-Group Queries
-
-### Query Across All Groups
-
-```python
-# Set context to query all accessible groups
-conn.SERVICE_OPTS.setOmeroGroup('-1')
-
-# Now queries span all groups
-image = conn.getObject("Image", image_id)
-if image:
- group = image.getDetails().getGroup()
- print(f"Image found in group: {group.getName()}")
-
-# List projects across all groups
-for project in conn.getObjects("Project"):
- group = project.getDetails().getGroup()
- print(f"Project: {project.getName()} (Group: {group.getName()})")
-```
-
-### Switch to Specific Group
-
-```python
-# Get image's group
-image = conn.getObject("Image", image_id)
-group_id = image.getDetails().getGroup().getId()
-
-# Switch to that group's context
-conn.SERVICE_OPTS.setOmeroGroup(group_id)
-
-# Subsequent operations use this group
-projects = conn.listProjects() # Only from this group
-```
-
-### Reset to Default Group
-
-```python
-# Get default group
-default_group_id = conn.getEventContext().groupId
-
-# Switch back to default
-conn.SERVICE_OPTS.setOmeroGroup(default_group_id)
+if fileset is not None:
+ print(fileset.getId())
```
-## Administrative Operations
-
-### Check Admin Status
-
-```python
-# Check if current user is admin
-if conn.isAdmin():
- print("User has admin privileges")
-
-# Check if full admin
-if conn.isFullAdmin():
- print("User is full administrator")
-else:
- # Check specific privileges
- privileges = conn.getCurrentAdminPrivileges()
- print(f"Admin privileges: {privileges}")
-```
+Original-file paths and names can expose acquisition layout or identifiers.
+Do not enumerate them in a general inventory.
-### List Administrators
+The current CLI can download one explicit object:
-```python
-# Get all administrators
-print("Administrators:")
-for admin in conn.getAdministrators():
- print(f" ID: {admin.getId()}")
- print(f" Username: {admin.getOmeName()}")
- print(f" Full Name: {admin.getFullName()}")
+```bash
+omero download OriginalFile:123 ./reviewed-file
+omero download FileAnnotation:456 ./reviewed-file
+omero download Image:789 ./reviewed-empty-directory
+omero download Fileset:321 ./reviewed-empty-directory
```
-### Set Object Owner (Admin Only)
-
-```python
-import omero.model
-
-# Create annotation with specific owner (requires admin)
-tag_ann = omero.gateway.TagAnnotationWrapper(conn)
-tag_ann.setValue("Admin-created tag")
-
-# Set owner
-user_id = 5
-tag_ann._obj.details.owner = omero.model.ExperimenterI(user_id, False)
-tag_ann.save()
+`Image` and `Fileset` may expand to multiple files. First inspect count/size,
+then use a dedicated destination with collision/symlink checks. Authenticate
+through a prompted stored session; do not add password or key flags.
-print(f"Created annotation owned by user {user_id}")
-```
-
-### Substitute User Connection (Admin Only)
+Direct `RawFileStore` usage must be bounded and closed:
```python
-# Connect as admin
-admin_conn = BlitzGateway(admin_user, admin_pass, host=host, port=4064)
-admin_conn.connect()
-
-# Get target user
-target_user_id = 10
-user = admin_conn.getObject("Experimenter", target_user_id)
-username = user.getOmeName()
-
-# Create connection as that user
-user_conn = admin_conn.suConn(username)
-
-print(f"Connected as {username}")
-
-# Perform operations as that user
-for project in user_conn.listProjects():
- print(f" {project.getName()}")
-
-# Close connections
-user_conn.close()
-admin_conn.close()
+max_bytes = 50 * 1024 * 1024
+store = conn.createRawFileStore()
+try:
+ store.setFileId(original_file_id)
+ size = store.size()
+ if size > max_bytes:
+ raise ValueError("OriginalFile exceeds approved byte limit")
+ chunk = store.read(0, min(size, 1024 * 1024))
+finally:
+ store.close()
```
-### List All Users
+This sample intentionally reads at most one chunk. A full download needs a
+loop with cumulative byte checks and a caller-selected safe path.
-```python
-# Get all users (admin operation)
-print("All users:")
-for user in conn.getObjects("Experimenter"):
- print(f" ID: {user.getId()}")
- print(f" Username: {user.getOmeName()}")
- print(f" Full Name: {user.getFullName()}")
- print(f" Email: {user.getEmail()}")
- print()
-```
+## Destructive Commands
-## Service Access
+`conn.deleteObjects(type, ids, wait=True)` submits an OMERO command. The exact
+impact depends on object type, links, ownership, and server graph rules. Do not
+promise a cascade/orphan result from intuition.
-OMERO provides various services for specific operations.
+Required delete workflow:
-### Update Service
+1. Resolve explicit object type and IDs in one group.
+2. Read current object/link summaries and permissions.
+3. Show counts and likely related objects from documented queries.
+4. Obtain explicit approval for those exact IDs.
+5. Submit with `wait=True` or monitor the returned command callback.
+6. Inspect command response for errors.
+7. Record success/failure per ID.
+8. Close callbacks/handles and the gateway.
-```python
-# Get update service
-updateService = conn.getUpdateService()
+Never select delete targets by a broad name/namespace query without an ID
+review. Never add delete mode to inventory/export scripts.
-# Save and return object
-roi = omero.model.RoiI()
-roi.setImage(image._obj)
-saved_roi = updateService.saveAndReturnObject(roi)
+Unlinking an annotation, table, image, or dataset is a different graph change
+from deleting the child. State which one is intended.
-# Save multiple objects
-objects = [obj1, obj2, obj3]
-saved_objects = updateService.saveAndReturnArray(objects)
-```
+## Ownership and Group Changes
-### ROI Service
+Changing ownership or moving data between groups can alter access for many
+linked objects. Current CLI documentation says ownership changes require full
+admin, an appropriately privileged restricted admin, or group owner.
-```python
-# Get ROI service
-roi_service = conn.getRoiService()
+Before:
-# Find ROIs for image
-result = roi_service.findByImage(image_id, None)
+- enumerate exact root objects and affected links;
+- confirm source and destination groups;
+- confirm target owner membership;
+- check whether filesets/annotations/tables move with the object graph;
+- obtain administrator approval;
+- use current documented CLI/API methods, not direct `_obj.details.owner`
+ manipulation copied from old examples.
-# Get shape statistics
-shape_ids = [shape.id.val for roi in result.rois
- for shape in roi.copyShapes()]
-stats = roi_service.getShapeStatsRestricted(shape_ids, 0, 0, [0])
-```
+Do not write private model fields to bypass service-level policy.
-### Metadata Service
+## HQL and Query Service
-```python
-# Get metadata service
-metadataService = conn.getMetadataService()
-
-# Load annotations by type and namespace
-ns_to_include = ["mylab.analysis"]
-ns_to_exclude = []
-
-annotations = metadataService.loadSpecifiedAnnotations(
- 'omero.model.FileAnnotation',
- ns_to_include,
- ns_to_exclude,
- None
-)
-
-for ann in annotations:
- print(f"Annotation: {ann.getId().getValue()}")
-```
-
-### Query Service
+Use fixed HQL and typed parameters:
```python
-# Get query service
-queryService = conn.getQueryService()
+import omero.sys
-# Build query (more complex queries)
-params = omero.sys.ParametersI()
-params.addLong("image_id", image_id)
+parameters = omero.sys.ParametersI()
+parameters.addLong("image_id", image_id)
query = "select i from Image i where i.id = :image_id"
-image = queryService.findByQuery(query, params)
-```
-
-### Thumbnail Service
-
-```python
-# Get thumbnail service
-thumbnailService = conn.createThumbnailStore()
-
-# Set current image
-thumbnailService.setPixelsId(image.getPrimaryPixels().getId())
-
-# Get thumbnail
-thumbnail = thumbnailService.getThumbnail(96, 96)
-
-# Close service
-thumbnailService.close()
-```
-
-### Raw File Store
-
-```python
-# Get raw file store
-rawFileStore = conn.createRawFileStore()
-
-# Set file ID
-rawFileStore.setFileId(orig_file_id)
-
-# Read file
-data = rawFileStore.read(0, rawFileStore.size())
-
-# Close
-rawFileStore.close()
+model_image = conn.getQueryService().findByQuery(query, parameters)
```
-## Object Ownership and Details
+Never interpolate names, namespaces, IDs, ordering, or arbitrary user text
+into HQL. Map user choices to allowlisted fixed query templates. Apply a
+server-side result limit to list queries.
-### Get Object Details
+## Deprecated Service Surface
-```python
-image = conn.getObject("Image", image_id)
+The current generated API marks at least these interfaces deprecated:
-# Get details
-details = image.getDetails()
+- `IRoi`
+- `IShare`
-# Owner information
-owner = details.getOwner()
-print(f"Owner ID: {owner.getId()}")
-print(f"Username: {owner.getOmeName()}")
-print(f"Full Name: {owner.getFullName()}")
+`IRoi.findByImage` remains in current official Python examples, but should be
+isolated and version-checked. Do not build new sharing workflows on
+`IShare`; use current administrator-supported OMERO.web/public-data features
+instead.
-# Group information
-group = details.getGroup()
-print(f"Group: {group.getName()} (ID: {group.getId()})")
+Deprecation does not mean immediate removal. It means callers must not claim
+long-term stability or invent a replacement.
-# Creation information
-creation_event = details.getCreationEvent()
-print(f"Created: {creation_event.getTime()}")
+## OMERO.web: What Is Publicly Supported
-# Update information
-update_event = details.getUpdateEvent()
-print(f"Updated: {update_event.getTime()}")
-```
+Official OMERO.web developer documentation says only these included apps are
+stable public APIs:
-### Get Permissions
+- `api`
+- `webgateway`
-```python
-# Get object permissions
-details = image.getDetails()
-permissions = details.getPermissions()
+Other apps, including `webclient`, expose internal URLs and methods that may
+change in minor releases. A URL currently used by the UI is not automatically
+a supported integration endpoint.
-# Check specific permissions
-can_edit = permissions.canEdit()
-can_annotate = permissions.canAnnotate()
-can_link = permissions.canLink()
-can_delete = permissions.canDelete()
+### JSON API
-print(f"Can edit: {can_edit}")
-print(f"Can annotate: {can_annotate}")
-print(f"Can link: {can_link}")
-print(f"Can delete: {can_delete}")
-```
+The documented OMERO JSON API:
-## Event Context
+- is implemented by the `api` Django app;
+- advertises supported major versions at `GET /api/`;
+- advertises starting URLs at `GET /api/v0/`;
+- reports the full API version in `X-OMERO-ApiVersion`;
+- uses `limit` and `offset` pagination;
+- reports `totalCount`, `limit`, `offset`, and server `maxLimit`;
+- requires a CSRF token for POST/PUT/DELETE;
+- documents login at `/api/v0/login/`;
+- supports read endpoints for documented model types, including ROI listing;
+- currently limits object creation/update to Projects, Datasets, and Screens.
-### Get Current Event Context
+Official docs describe create/read/update/delete access but also explicitly
+limit type coverage. Do not call it a complete generic REST interface, assume
+OAuth, assume token authentication, or infer endpoints not listed by the
+server's discovery response.
-```python
-# Get event context (current session info)
-ctx = conn.getEventContext()
-
-print(f"User ID: {ctx.userId}")
-print(f"Username: {ctx.userName}")
-print(f"Group ID: {ctx.groupId}")
-print(f"Group Name: {ctx.groupName}")
-print(f"Session ID: {ctx.sessionId}")
-print(f"Is Admin: {ctx.isAdmin}")
-```
+Use HTTPS. A JSON API password is sent in the documented login POST and must
+never be logged. Honor the returned `maxLimit`; apply a smaller client cap.
-## Complete Admin Example
+### WebGateway
-```python
-from omero.gateway import BlitzGateway
+`webgateway` provides documented rendered images and JSON data. Confirm the
+current endpoint page before implementing, cap image size/quality, and use
+HTTPS. Do not substitute a webclient AJAX route.
-# Connect as admin
-ADMIN_USER = 'root'
-ADMIN_PASS = 'password'
-HOST = 'omero.example.com'
-PORT = 4064
+## Public Data and Links
-with BlitzGateway(ADMIN_USER, ADMIN_PASS, host=HOST, port=PORT) as admin_conn:
- print("=== Administrator Operations ===\n")
+Publishing is an administrator configuration, not a client-side “make public”
+API call. Current official guidance:
- # List all users
- print("All Users:")
- for user in admin_conn.getObjects("Experimenter"):
- print(f" {user.getOmeName()}: {user.getFullName()}")
+- create a dedicated read-only group;
+- create/add a public user with only intended data access;
+- `omero.web.public.enabled` defaults to false;
+- public users default to GET-only;
+- `omero.web.public.url_filter` must explicitly allow routes and otherwise
+ matches nothing;
+- download/export routes can be excluded;
+- a dedicated public OMERO.web deployment may be appropriate.
- # List all groups
- print("\nAll Groups:")
- for group in admin_conn.getObjects("ExperimenterGroup"):
- perms = group.getDetails().getPermissions()
- print(f" {group.getName()}: {perms}")
+OME shows examples such as `webclient/?show=project-...` for publication
+navigation, but the webclient itself is explicitly not a stable public API.
+Do not promise that such links are permanent integration contracts. For
+durable publication URLs, use administrator-owned redirects/DOIs and test them
+after upgrades.
- # List members
- for member in group.getMembers():
- print(f" - {member.getOmeName()}")
+Never generate a public link merely because an object is readable to the
+current authenticated user. Confirm:
- # Query across all groups
- print("\nAll Projects (all groups):")
- admin_conn.SERVICE_OPTS.setOmeroGroup('-1')
+- the public user is enabled;
+- its group membership permits the object;
+- GET-only remains enabled;
+- URL filter permits only intended routes;
+- download/export routes are intentionally allowed or blocked;
+- the institution approves public release.
- for project in admin_conn.getObjects("Project"):
- owner = project.getDetails().getOwner()
- group = project.getDetails().getGroup()
- print(f" {project.getName()}")
- print(f" Owner: {owner.getOmeName()}")
- print(f" Group: {group.getName()}")
+## OMERO CLI Import/Admin Boundary
- # Connect as another user
- target_user_id = 5
- user = admin_conn.getObject("Experimenter", target_user_id)
+Installing `omero-py` provides the CLI framework, but import/admin commands
+also depend on a compatible extracted OMERO.server tree through `OMERODIR`.
+Do not point `OMERODIR` at an arbitrary or mismatched server distribution.
- if user:
- print(f"\n=== Operating as {user.getOmeName()} ===\n")
+Remote client commands and local server administration have different risk.
+Before any admin command, confirm it is being run on the intended host with the
+intended server installation/configuration.
- user_conn = admin_conn.suConn(user.getOmeName())
-
- # List that user's projects
- for project in user_conn.listProjects():
- print(f" {project.getName()}")
-
- user_conn.close()
-```
-
-## Best Practices
-
-1. **Permissions**: Always check permissions before operations
-2. **Group Context**: Set appropriate group context for queries
-3. **Admin Operations**: Use admin privileges sparingly and carefully
-4. **Delete Confirmation**: Always confirm before deleting objects
-5. **Callback Monitoring**: Monitor long delete operations with callbacks
-6. **Fileset Awareness**: Check for filesets when working with images
-7. **Service Cleanup**: Close services when done (thumbnailStore, rawFileStore)
-8. **Cross-Group Queries**: Use `-1` group ID for cross-group access
-9. **Error Handling**: Always handle permission and access errors
-10. **Documentation**: Document administrative operations clearly
-
-## Troubleshooting
-
-### Permission Denied
-
-```python
-try:
- conn.deleteObjects("Project", [project_id], wait=True)
-except Exception as e:
- if "SecurityViolation" in str(e):
- print("Permission denied: You don't own this object")
- else:
- raise
-```
-
-### Object Not Found
-
-```python
-# Check if object exists before accessing
-obj = conn.getObject("Image", image_id)
-if obj is None:
- print(f"Image {image_id} not found or not accessible")
-else:
- # Process object
- pass
-```
-
-### Group Context Issues
-
-```python
-# If object not found, try cross-group query
-conn.SERVICE_OPTS.setOmeroGroup('-1')
-obj = conn.getObject("Image", image_id)
-
-if obj:
- # Switch to object's group for further operations
- group_id = obj.getDetails().getGroup().getId()
- conn.SERVICE_OPTS.setOmeroGroup(group_id)
-```
+## Advanced Operation Checklist
+
+- Current server/client/API docs verified
+- Exact user, group, object type, and IDs
+- Cross-group/impersonation separately authorized
+- Permission checks do not replace authorization
+- Original-file count/bytes and destination reviewed
+- Fixed queries with typed parameters
+- Deprecated services isolated and documented
+- Only `api`/`webgateway` treated as stable OMERO.web APIs
+- Public access configured by administrators, not inferred
+- Destructive commands previewed, confirmed, monitored, and recorded
+- Every stateful service/callback/connection closed
diff --git a/skills/omero-integration/references/connection.md b/skills/omero-integration/references/connection.md
index 3c7612d3..7e876ed8 100644
--- a/skills/omero-integration/references/connection.md
+++ b/skills/omero-integration/references/connection.md
@@ -1,369 +1,293 @@
-# Connection & Session Management
+# Connection, Sessions, and Transport Security
-This reference covers establishing and managing connections to OMERO servers using BlitzGateway.
+This reference is current for the skill snapshot dated 2026-07-23. It uses
+`omero-py==5.22.1` and the OMERO.server 5.6.18 documentation.
-## Basic Connection
+## Compatibility Before Credentials
-### Standard Connection Pattern
+OMERO.server and its Python, web, Java, Bio-Formats, and Ice components have
+independent release numbers. Do not compare their version strings as if they
+were one package.
-```python
-from omero.gateway import BlitzGateway
-
-# Create connection
-conn = BlitzGateway(username, password, host=host, port=4064)
+For the current stable pairing:
-# Connect to server
-if conn.connect():
- print("Connected successfully")
- # Perform operations
- conn.close()
-else:
- print("Failed to connect")
-```
+- OMERO.server 5.6.18 was tested with OMERO.py 5.22.1 and OMERO.web 5.31.0.
+- `omero-py==5.22.1` declares Python `>=3.10`.
+- The OMERO matrix supports Python 3.10/3.11 and recommends 3.12.
+- Python 3.13/3.14 are listed as upcoming, not supported.
+- Ice 3.6 is recommended; Ice 3.7 is unsupported.
+- The OMERO-linked Glencoe wheel matrix provides IcePy 3.6.5 wheels through
+ Python 3.12 for documented platforms.
-### Connection Parameters
+For a different server release, read that release's history entry and use its
+tested OMERO.py version. A newest-client/old-server pairing may appear to work
+but is not the documented compatibility guarantee.
-- **username** (str): OMERO user account name
-- **password** (str): User password
-- **host** (str): OMERO server hostname or IP address
-- **port** (int): Server port (default: 4064)
-- **secure** (bool): Force encrypted connection (default: False)
+## Installation
-### Secure Connection
+Use an isolated Python 3.12 environment and a platform-matched Ice wheel:
-To ensure all data transfers are encrypted:
+```bash
+uv venv --python 3.12 .venv
+source .venv/bin/activate
-```python
-conn = BlitzGateway(username, password, host=host, port=4064, secure=True)
-conn.connect()
+# Obtain the matching wheel from the OMERO-linked Ice binary matrix.
+uv pip install "/absolute/path/to/zeroc_ice-3.6.5-<matching-tags>.whl"
+uv pip install "omero-py==5.22.1"
```
-## Context Manager Pattern (Recommended)
+Wheel tags must match all of:
-Use context managers for automatic connection management and cleanup:
+- CPython version (`cp310`, `cp311`, or `cp312`)
+- operating system
+- architecture
+- platform compatibility tags
-```python
-from omero.gateway import BlitzGateway
+Do not silently fall back to compiling IcePy if the wheel is rejected. Inspect
+the interpreter and platform first. Do not install Ice 3.7 as a substitute.
-with BlitzGateway(username, password, host=host, port=4064) as conn:
- # Connection automatically established
- for project in conn.getObjects('Project'):
- print(project.getName())
- # Connection automatically closed on exit
-```
+`OMERODIR` is required for some CLI configuration and must point to a
+compatible extracted OMERO.server tree to enable import and admin commands.
+It is not required merely to use BlitzGateway against a remote server.
-**Benefits:**
-- Automatic `connect()` call
-- Automatic `close()` call on exit
-- Exception-safe resource cleanup
-- Cleaner code
+## Named Configuration
-## Session Management
+The bundled helpers read exactly these variables:
-### Connection from Existing Client
+- `OMERO_HOST`: required hostname, without `http://`, `https://`, or path
+- `OMERO_PORT`: optional integer, default `4064`
+- `OMERO_USER`: username for password authentication
+- `OMERO_PASSWORD`: password for password authentication
+- `OMERO_SESSION_KEY`: existing session key, alternative to user/password
+- `OMERO_SECURE`: boolean, default `true`
-Create BlitzGateway from an existing `omero.client` session:
+Rules:
-```python
-import omero.clients
-from omero.gateway import BlitzGateway
-
-# Create client and session
-client = omero.client(host, port)
-session = client.createSession(username, password)
-
-# Create BlitzGateway from existing client
-conn = BlitzGateway(client_obj=client)
+1. Never crawl for `.env` files or read unrelated environment variables.
+2. Never accept a password/session key as a command argument.
+3. Never print an environment dump, password, or session key.
+4. Treat a session key as a bearer credential and expire/logout when finished.
+5. Prefer a secret manager or process-scoped environment over shell history.
-# Use connection
-# ...
-
-# Close when done
-conn.close()
-```
-
-### Retrieve Session Information
-
-```python
-# Get current user information
-user = conn.getUser()
-print(f"User ID: {user.getId()}")
-print(f"Username: {user.getName()}")
-print(f"Full Name: {user.getFullName()}")
-print(f"Is Admin: {conn.isAdmin()}")
-
-# Get current group
-group = conn.getGroupFromContext()
-print(f"Current Group: {group.getName()}")
-print(f"Group ID: {group.getId()}")
-```
+## Password Connection
-### Check Admin Privileges
+Use `try/finally` when connection success must be checked explicitly:
```python
-if conn.isAdmin():
- print("User has admin privileges")
-
-if conn.isFullAdmin():
- print("User is full administrator")
-else:
- # Check specific admin privileges
- privileges = conn.getCurrentAdminPrivileges()
- print(f"Admin privileges: {privileges}")
-```
-
-## Group Context Management
-
-OMERO uses groups to manage data access permissions. Users can belong to multiple groups.
+import os
+from omero.gateway import BlitzGateway
-### Get Current Group Context
+conn = BlitzGateway(
+ os.environ["OMERO_USER"],
+ os.environ["OMERO_PASSWORD"],
+ host=os.environ["OMERO_HOST"],
+ port=int(os.environ.get("OMERO_PORT", "4064")),
+ secure=True,
+)
-```python
-# Get the current group context
-group = conn.getGroupFromContext()
-print(f"Current group: {group.getName()}")
-print(f"Group ID: {group.getId()}")
+try:
+ if not conn.connect():
+ raise RuntimeError("OMERO connection failed")
+
+ # Keep reads bounded and group-scoped.
+ for image in conn.getObjects(
+ "Image",
+ opts={"limit": 25, "offset": 0, "order_by": "obj.id"},
+ ):
+ print(image.getId())
+finally:
+ conn.close()
```
-### Query Across All Groups
-
-Use group ID `-1` to query across all accessible groups:
+BlitzGateway can also be a context manager. Its context manager calls
+`connect()` and closes the underlying client:
```python
-# Set context to query all groups
-conn.SERVICE_OPTS.setOmeroGroup('-1')
+import os
+from omero.gateway import BlitzGateway
-# Now queries span all accessible groups
-image = conn.getObject("Image", image_id)
-projects = conn.listProjects()
+with BlitzGateway(
+ os.environ["OMERO_USER"],
+ os.environ["OMERO_PASSWORD"],
+ host=os.environ["OMERO_HOST"],
+ port=int(os.environ.get("OMERO_PORT", "4064")),
+ secure=True,
+) as conn:
+ for project in conn.getObjects(
+ "Project",
+ opts={"limit": 10, "offset": 0, "order_by": "obj.id"},
+ ):
+ print(project.getId())
```
-### Switch to Specific Group
-
-Switch context to work within a specific group:
+Do not catch an exception merely to print its full representation: connection
+errors may include endpoint or identity details. Report the exception class
+and a scrubbed message; never include credential values.
-```python
-# Get group ID from an object
-image = conn.getObject("Image", image_id)
-group_id = image.getDetails().getGroup().getId()
-
-# Switch to that group's context
-conn.SERVICE_OPTS.setOmeroGroup(group_id)
-
-# Subsequent operations use this group context
-projects = conn.listProjects()
-```
+## Existing Session
-### List Available Groups
+`BlitzGateway.connect()` accepts `sUuid`, the existing session UUID:
```python
-# Get all groups for current user
-for group in conn.getGroupsMemberOf():
- print(f"Group: {group.getName()} (ID: {group.getId()})")
-```
-
-## Advanced Connection Features
-
-### Substitute User Connection (Admin Only)
+import os
+from omero.gateway import BlitzGateway
-Administrators can create connections acting as other users:
+conn = BlitzGateway(
+ host=os.environ["OMERO_HOST"],
+ port=int(os.environ.get("OMERO_PORT", "4064")),
+ secure=True,
+)
-```python
-# Connect as admin
-admin_conn = BlitzGateway(admin_user, admin_pass, host=host, port=4064)
-admin_conn.connect()
+try:
+ if not conn.connect(sUuid=os.environ["OMERO_SESSION_KEY"]):
+ raise RuntimeError("Could not join the OMERO session")
+ print(conn.getEventContext().groupId)
+finally:
+ conn.close()
+```
-# Get target user
-target_user = admin_conn.getObject("Experimenter", user_id).getName()
+Joining a session does not make it safe to log the key. If a low-level
+`omero.client` is supplied through `BlitzGateway(client_obj=client)`, the
+gateway does not necessarily own every other use of that client. Close it only
+when ownership is clear; the official context-manager example is appropriate
+when nothing else uses the client.
-# Create connection as that user
-user_conn = admin_conn.suConn(target_user)
+## CLI Login Without a Password Argument
-# Operations performed as target user
-for project in user_conn.listProjects():
- print(project.getName())
+The CLI stores sessions locally. Let it prompt:
-# Close substitute connection
-user_conn.close()
-admin_conn.close()
+```bash
+omero login -s "$OMERO_HOST" -p "$OMERO_PORT" -u "$OMERO_USER"
+omero sessions list
+omero sessions file
+omero logout
```
-### List Administrators
+Do not use `-w` or `--password`. Although the CLI supports
+`OMERO_PASSWORD`, avoid putting the secret in a persistent shell profile.
-```python
-# Get all administrators
-for admin in conn.getAdministrators():
- print(f"ID: {admin.getId()}, Name: {admin.getFullName()}, "
- f"Username: {admin.getOmeName()}")
-```
+The CLI also supports joining a session with `-k`, but entering a session key
+on the command line exposes it in shell history and process listings. Prefer a
+short-lived, protected workflow and never paste the key into logs.
-## Connection Lifecycle
+By default, session files are under `~/omero/sessions`. `OMERO_USERDIR` or
+`OMERO_SESSIONDIR` can change the location. Protect any custom directory with
+user-only permissions and remove stale sessions with `omero logout`.
-### Closing Connections
+## Group Context
-Always close connections to free server resources:
+The default connection group comes from the session event context:
```python
-try:
- conn = BlitzGateway(username, password, host=host, port=4064)
- conn.connect()
-
- # Perform operations
-
-except Exception as e:
- print(f"Error: {e}")
-finally:
- if conn:
- conn.close()
+ctx = conn.getEventContext()
+print(ctx.groupId) # Avoid printing the session ID.
```
-### Check Connection Status
+Set one explicit accessible group before scoped queries:
```python
-if conn.isConnected():
- print("Connection is active")
-else:
- print("Connection is closed")
+group_id = 42
+conn.SERVICE_OPTS.setOmeroGroup(str(group_id))
```
-## Error Handling
-
-### Robust Connection Pattern
+`-1` requests cross-group behavior. It is not a harmless convenience:
```python
-from omero.gateway import BlitzGateway
-import traceback
-
-def connect_to_omero(username, password, host, port=4064):
- """
- Establish connection to OMERO server with error handling.
-
- Returns:
- BlitzGateway connection object or None if failed
- """
- try:
- conn = BlitzGateway(username, password, host=host, port=port, secure=True)
- if conn.connect():
- print(f"Connected to {host}:{port} as {username}")
- return conn
- else:
- print("Failed to establish connection")
- return None
- except Exception as e:
- print(f"Connection error: {e}")
- traceback.print_exc()
- return None
-
-# Usage
-conn = connect_to_omero(username, password, host)
-if conn:
- try:
- # Perform operations
- pass
- finally:
- conn.close()
+# Only after the user explicitly requests all accessible groups:
+conn.SERVICE_OPTS.setOmeroGroup("-1")
```
-## Common Connection Patterns
-
-### Pattern 1: Simple Script
+Do not set `-1` by default, and do not combine it with an unbounded query.
+Record the original group if temporarily changing context and restore it
+before subsequent writes.
-```python
-from omero.gateway import BlitzGateway
-
-# Connection parameters
-HOST = 'omero.example.com'
-PORT = 4064
-USERNAME = 'user'
-PASSWORD = 'pass'
+The CLI can switch its current session group:
-# Connect
-with BlitzGateway(USERNAME, PASSWORD, host=HOST, port=PORT) as conn:
- print(f"Connected as {conn.getUser().getName()}")
- # Perform operations
+```bash
+omero group list
+omero sessions group 42
```
-### Pattern 2: Configuration-Based Connection
+Confirm the target group before import, link creation, table writes, ownership
+changes, or script execution.
-```python
-import yaml
-from omero.gateway import BlitzGateway
+## What `secure=True` Does
-# Load configuration
-with open('omero_config.yaml', 'r') as f:
- config = yaml.safe_load(f)
+Official OMERO security documentation distinguishes authentication from later
+traffic:
-# Connect using config
-with BlitzGateway(
- config['username'],
- config['password'],
- host=config['host'],
- port=config.get('port', 4064),
- secure=config.get('secure', True)
-) as conn:
- # Perform operations
- pass
-```
+- Login and password changes use SSL by default.
+- After login, other traffic is unencrypted by default for performance.
+- In that mode, the session ID is the critical value sent in clear text.
+- `BlitzGateway(..., secure=True)` requests encryption for all transfers.
+- Servers can redirect/disable insecure connections.
+- Default router ports are 4063 (insecure) and 4064 (SSL), but admins may
+ change or prefix them.
+- OMERO.web HTTPS normally uses port 443 and is a separate transport path.
-### Pattern 3: Environment Variables
+Therefore, default to `secure=True` and the administrator-provided SSL router
+port. Do not infer security merely from the number `4064`.
-```python
-import os
-from omero.gateway import BlitzGateway
+## Certificate and Host Verification
-# Get credentials from environment
-USERNAME = os.environ.get('OMERO_USER')
-PASSWORD = os.environ.get('OMERO_PASSWORD')
-HOST = os.environ.get('OMERO_HOST', 'localhost')
-PORT = int(os.environ.get('OMERO_PORT', 4064))
+Encryption is not the same as server identity verification. OME explicitly
+states that standard OMERO clients do not automatically verify the host, so a
+man-in-the-middle attack remains possible without additional configuration.
-# Connect
-with BlitzGateway(USERNAME, PASSWORD, host=HOST, port=PORT) as conn:
- # Perform operations
- pass
-```
+The official developer guidance lists these Ice properties for certificate
+validation:
-## Best Practices
+- `IceSSL.Ciphers=HIGH` (or a supported explicit cipher family)
+- `IceSSL.VerifyPeer=1`
+- `IceSSL.VerifyDepthMax=0`
+- `IceSSL.UsePlatformCAs=1`, or `IceSSL.CAs=/path/to/cacert.pem`
+- `IceSSL.CheckCertName=1` for exact hostname checking
+- `IceSSL.TrustOnly=...` for documented alternative name restrictions
+- optionally `IceSSL.Protocols=tls1_2` if required by server policy
-1. **Use Context Managers**: Always prefer context managers for automatic cleanup
-2. **Secure Connections**: Use `secure=True` for production environments
-3. **Error Handling**: Wrap connection code in try-except blocks
-4. **Close Connections**: Always close connections when done
-5. **Group Context**: Set appropriate group context before queries
-6. **Credential Security**: Never hardcode credentials; use environment variables or config files
-7. **Connection Pooling**: For web applications, implement connection pooling
-8. **Timeouts**: Consider implementing connection timeouts for long-running operations
+These are site-specific low-level client settings. Do not invent them from a
+hostname or disable verification to make a connection succeed. Ask the OMERO
+administrator for the CA, expected certificate name, router port, and policy.
+The bundled helpers enforce encrypted transport by default but do not claim to
+configure hostname verification.
-## Troubleshooting
+For OMERO.web, use an administrator-managed HTTPS deployment with a recognized
+certificate. Never send JSON API credentials over plain HTTP.
-### Connection Refused
+## Stateful Services and Reconnection
-```
-Unable to contact ORB
-```
+BlitzGateway reuses stateless `get...Service()` proxies. Stateful services such
+as rendering engines, raw stores, thumbnail stores, tables, and other
+`create...` services should be created, used, and closed in the shortest
+practicable scope.
-**Solutions:**
-- Verify host and port are correct
-- Check firewall settings
-- Ensure OMERO server is running
-- Verify network connectivity
+Gateway recovery may recreate its own services after a connection failure.
+Client-held stateful proxies can then be stale. Do not retain them across long
+idle periods or reconnects.
-### Authentication Failed
+Generic pattern:
+```python
+store = conn.createRawFileStore()
+try:
+ store.setFileId(original_file_id)
+ # Perform one explicitly bounded read.
+finally:
+ store.close()
```
-Cannot connect to server
-```
-**Solutions:**
-- Verify username and password
-- Check user account is active
-- Verify group membership
-- Check server logs for details
+Closing the gateway is still mandatory even if every stateful child was closed.
+
+## Connection Failure Checklist
-### Session Timeout
+Without exposing credentials:
-**Solutions:**
-- Increase session timeout on server
-- Implement session keepalive
-- Reconnect on timeout
-- Use connection pools for long-running applications
+1. Validate `OMERO_HOST` has no URL scheme/path and `OMERO_PORT` is in range.
+2. Confirm the server release and tested OMERO.py pairing.
+3. Confirm Python and Ice wheel tags match.
+4. Confirm the SSL router port and `secure=True`.
+5. Confirm the account is active and has access to the selected group.
+6. For an existing session, confirm it is still valid without printing it.
+7. For certificate verification, confirm CA and expected certificate name.
+8. Close the failed connection before retrying.
+9. Do not retry authentication in a tight loop; server throttling may apply.
diff --git a/skills/omero-integration/references/data_access.md b/skills/omero-integration/references/data_access.md
index e1c5b3b2..1984097d 100644
--- a/skills/omero-integration/references/data_access.md
+++ b/skills/omero-integration/references/data_access.md
@@ -1,544 +1,359 @@
-# Data Access & Retrieval
+# Data Access, Hierarchies, and Transfers
-This reference covers navigating OMERO's hierarchical data structure and retrieving objects.
+Use this reference for bounded reads and explicit import/export scopes. Read
+[`connection.md`](connection.md) first.
-## OMERO Data Hierarchy
+## Object Hierarchies
-### Standard Hierarchy
+Common container paths are:
-```
-Project
- └─ Dataset
- └─ Image
+```text
+Project -> Dataset -> Image
+Screen -> Plate -> Well -> WellSample -> Image
+Image -> Pixels -> Channel
+Image -> Fileset -> OriginalFile(s)
```
-### Screening Hierarchy
+Links are model objects and may be many-to-many. Do not assume an image has
+exactly one dataset or a dataset exactly one project. Traverse links returned
+by the server instead of synthesizing parent paths.
-```
-Screen
- └─ Plate
- └─ Well
- └─ WellSample
- └─ Image
-```
+Common BlitzGateway object names documented by OME include:
-## Listing Objects
+- `Project`, `Dataset`, `Image`
+- `Screen`, `Plate`, `PlateAcquisition`, `Well`
+- `Roi`, `Shape`
+- `Experimenter`, `ExperimenterGroup`
+- `OriginalFile`, `Fileset`
+- `Annotation` and specific annotation subtypes
-### List Projects
+Object-name support is not permission. A returned `None` may mean nonexistent
+or inaccessible.
-```python
-# List all projects for current user
-for project in conn.listProjects():
- print(f"Project: {project.getName()} (ID: {project.getId()})")
-```
+## One Object by ID
-### List Projects with Filtering
+Use explicit IDs whenever possible:
```python
-# Get current user and group
-my_exp_id = conn.getUser().getId()
-default_group_id = conn.getEventContext().groupId
-
-# List projects with filters
-for project in conn.getObjects("Project", opts={
- 'owner': my_exp_id, # Filter by owner
- 'group': default_group_id, # Filter by group
- 'order_by': 'lower(obj.name)', # Sort alphabetically
- 'limit': 10, # Limit results
- 'offset': 0 # Pagination offset
-}):
- print(f"Project: {project.getName()}")
-```
-
-### List Datasets
-
-```python
-# List all datasets
-for dataset in conn.getObjects("Dataset"):
- print(f"Dataset: {dataset.getName()} (ID: {dataset.getId()})")
-
-# List orphaned datasets (not in any project)
-for dataset in conn.getObjects("Dataset", opts={'orphaned': True}):
- print(f"Orphaned Dataset: {dataset.getName()}")
-```
-
-### List Images
+image_id = 123
+image = conn.getObject("Image", image_id)
+if image is None:
+ raise LookupError("Image was not found or is not accessible")
-```python
-# List all images
-for image in conn.getObjects("Image"):
- print(f"Image: {image.getName()} (ID: {image.getId()})")
-
-# List images in specific dataset
-dataset_id = 123
-for image in conn.getObjects("Image", opts={'dataset': dataset_id}):
- print(f"Image: {image.getName()}")
-
-# List orphaned images
-for image in conn.getObjects("Image", opts={'orphaned': True}):
- print(f"Orphaned Image: {image.getName()}")
+print(image.getId())
+print(image.getSizeX(), image.getSizeY())
```
-## Retrieving Objects by ID
+Do not print names, descriptions, owner names, or acquisition metadata unless
+the requested output includes them.
-### Get Single Object
+For multiple explicit IDs:
```python
-# Get project by ID
-project = conn.getObject("Project", project_id)
-if project:
- print(f"Project: {project.getName()}")
-else:
- print("Project not found")
-
-# Get dataset by ID
-dataset = conn.getObject("Dataset", dataset_id)
-
-# Get image by ID
-image = conn.getObject("Image", image_id)
+requested_ids = [101, 102, 103]
+for image in conn.getObjects(
+ "Image",
+ requested_ids,
+ respect_order=True,
+):
+ print(image.getId())
```
-### Get Multiple Objects by ID
-
-```python
-# Get multiple projects at once
-project_ids = [1, 2, 3, 4, 5]
-projects = conn.getObjects("Project", project_ids)
-
-for project in projects:
- print(f"Project: {project.getName()}")
-```
+Keep the input list bounded. Check whether inaccessible IDs were omitted.
-### Supported Object Types
+## Bounded Pagination
-The `getObject()` and `getObjects()` methods support:
-- `"Project"`
-- `"Dataset"`
-- `"Image"`
-- `"Screen"`
-- `"Plate"`
-- `"Well"`
-- `"Roi"`
-- `"Annotation"` (and specific types: `"TagAnnotation"`, `"FileAnnotation"`, etc.)
-- `"Experimenter"`
-- `"ExperimenterGroup"`
-- `"Fileset"`
-
-## Query by Attributes
-
-### Query Objects by Name
+`getObjects()` returns a generator. Use both an overall cap and page size:
```python
-# Find images with specific name
-images = conn.getObjects("Image", attributes={"name": "sample_001.tif"})
+def iter_bounded(conn, object_type, *, limit=100, page_size=25):
+ if not 1 <= limit <= 1000:
+ raise ValueError("limit must be between 1 and 1000")
+ if not 1 <= page_size <= min(limit, 200):
+ raise ValueError("page_size must be between 1 and min(limit, 200)")
+
+ emitted = 0
+ offset = 0
+ while emitted < limit:
+ size = min(page_size, limit - emitted)
+ page = list(
+ conn.getObjects(
+ object_type,
+ opts={
+ "limit": size,
+ "offset": offset,
+ "order_by": "obj.id",
+ },
+ )
+ )
+ if not page:
+ return
+
+ for obj in page:
+ yield obj
+ emitted += 1
+
+ if len(page) < size:
+ return
+ offset += len(page)
+```
+
+Do not write `list(conn.getObjects(...))` without server-side limits. If
+another process changes rows during offset paging, results may shift; record
+the extraction time and selected group.
+
+The bundled inventory helper implements a cap of 1000 and page cap of 200:
+
+```bash
+python -B scripts/inventory.py \
+ --object-type Image \
+ --limit 50 \
+ --page-size 25
+
+# Review the dry-run JSON, then explicitly connect:
+python -B scripts/inventory.py \
+ --object-type Image \
+ --limit 50 \
+ --page-size 25 \
+ --execute \
+ --output ./image-inventory.json
+```
+
+Names are redacted unless `--include-names` is requested.
+
+## Group and Owner Filters
+
+Prefer one selected group:
-for image in images:
- print(f"Found image: {image.getName()} (ID: {image.getId()})")
+```python
+group_id = 42
+conn.SERVICE_OPTS.setOmeroGroup(str(group_id))
-# Find datasets with specific name
-datasets = conn.getObjects("Dataset", attributes={"name": "Control Group"})
+for project in conn.getObjects(
+ "Project",
+ opts={"limit": 20, "offset": 0, "order_by": "obj.id"},
+):
+ print(project.getId())
```
-### Query Annotations by Value
+Filters can further narrow a query:
```python
-# Find tags with specific text value
-tags = conn.getObjects("TagAnnotation",
- attributes={"textValue": "experiment_tag"})
-
-for tag in tags:
- print(f"Tag: {tag.getValue()}")
-
-# Find map annotations
-map_anns = conn.getObjects("MapAnnotation",
- attributes={"ns": "custom.namespace"})
+owner_id = conn.getUser().getId()
+projects = conn.getObjects(
+ "Project",
+ opts={
+ "owner": owner_id,
+ "group": group_id,
+ "limit": 20,
+ "offset": 0,
+ "order_by": "obj.id",
+ },
+)
```
-## Navigating Hierarchies
+Cross-group context (`-1`) must be separately approved and paired with a hard
+limit. Never use it as a fallback when an object is not found.
+
+## Traversing Containers
-### Navigate Down (Parent to Children)
+Downward traversal lazily loads children:
```python
-# Project → Datasets → Images
project = conn.getObject("Project", project_id)
+if project is None:
+ raise LookupError("Project unavailable")
-for dataset in project.listChildren():
- print(f"Dataset: {dataset.getName()}")
+dataset_limit = 10
+for dataset_index, dataset in enumerate(project.listChildren()):
+ if dataset_index >= dataset_limit:
+ break
+ print(dataset.getId())
- for image in dataset.listChildren():
- print(f" Image: {image.getName()}")
+ image_limit = 25
+ for image_index, image in enumerate(dataset.listChildren()):
+ if image_index >= image_limit:
+ break
+ print(image.getId())
```
-### Navigate Up (Child to Parent)
+`countChildren()` can help plan a cap but does not replace one. A count may
+change before retrieval.
-```python
-# Image → Dataset → Project
-image = conn.getObject("Image", image_id)
-
-# Get parent dataset
-dataset = image.getParent()
-if dataset:
- print(f"Dataset: {dataset.getName()}")
-
- # Get parent project
- project = dataset.getParent()
- if project:
- print(f"Project: {project.getName()}")
-```
-
-### Complete Hierarchy Traversal
+For a direct dataset image query, prefer a server filter:
```python
-# Traverse complete project hierarchy
-for project in conn.getObjects("Project", opts={'order_by': 'lower(obj.name)'}):
- print(f"Project: {project.getName()} (ID: {project.getId()})")
-
- for dataset in project.listChildren():
- image_count = dataset.countChildren()
- print(f" Dataset: {dataset.getName()} ({image_count} images)")
-
- for image in dataset.listChildren():
- print(f" Image: {image.getName()}")
- print(f" Size: {image.getSizeX()} x {image.getSizeY()}")
- print(f" Channels: {image.getSizeC()}")
+images = conn.getObjects(
+ "Image",
+ opts={
+ "dataset": dataset_id,
+ "limit": 50,
+ "offset": 0,
+ "order_by": "obj.id",
+ },
+)
```
-## Screening Data Access
-
-### List Screens and Plates
-
-```python
-# List all screens
-for screen in conn.getObjects("Screen"):
- print(f"Screen: {screen.getName()} (ID: {screen.getId()})")
-
- # List plates in screen
- for plate in screen.listChildren():
- print(f" Plate: {plate.getName()} (ID: {plate.getId()})")
-```
+## Screening Data
-### Access Plate Wells
+Bound each hierarchy level:
```python
-# Get plate
plate = conn.getObject("Plate", plate_id)
+if plate is None:
+ raise LookupError("Plate unavailable")
-# Plate metadata
-print(f"Plate: {plate.getName()}")
-print(f"Grid size: {plate.getGridSize()}") # e.g., (8, 12) for 96-well
-print(f"Number of fields: {plate.getNumberOfFields()}")
-
-# Iterate through wells
-for well in plate.listChildren():
- print(f"Well at row {well.row}, column {well.column}")
-
- # Count images in well (fields)
- field_count = well.countWellSample()
- print(f" Number of fields: {field_count}")
+for well_index, well in enumerate(plate.listChildren()):
+ if well_index >= 96:
+ break
+ print(well.getId())
- # Access images in well
- for index in range(field_count):
- image = well.getImage(index)
- print(f" Field {index}: {image.getName()}")
+ field_count = min(well.countWellSample(), 10)
+ for field_index in range(field_count):
+ image = well.getImage(field_index)
+ if image is not None:
+ print(image.getId())
```
-### Direct Well Access
+Well rows/columns and field counts can reveal experiment design. Include them
+only when requested.
-```python
-# Get specific well by row and column
-well = plate.getWell(row=0, column=0) # Top-left well
-
-# Get image from well
-if well.countWellSample() > 0:
- image = well.getImage(0) # First field
- print(f"Image: {image.getName()}")
-```
+## Image Metadata
-### Well Sample Access
+Basic dimensions do not retrieve pixel planes:
```python
-# Access well samples directly
-for well in plate.listChildren():
- for ws in well.listChildren(): # ws = WellSample
- image = ws.getImage()
- print(f"WellSample {ws.getId()}: {image.getName()}")
+summary = {
+ "id": image.getId(),
+ "size_x": image.getSizeX(),
+ "size_y": image.getSizeY(),
+ "size_z": image.getSizeZ(),
+ "size_c": image.getSizeC(),
+ "size_t": image.getSizeT(),
+ "pixels_type": image.getPixelsType(),
+}
```
-## Image Properties
-
-### Basic Dimensions
+Physical sizes may be absent:
```python
-image = conn.getObject("Image", image_id)
-
-# Pixel dimensions
-print(f"X: {image.getSizeX()}")
-print(f"Y: {image.getSizeY()}")
-print(f"Z: {image.getSizeZ()} (Z-sections)")
-print(f"C: {image.getSizeC()} (Channels)")
-print(f"T: {image.getSizeT()} (Time points)")
-
-# Image type
-print(f"Type: {image.getPixelsType()}") # e.g., 'uint16', 'uint8'
+size_x = image.getPixelSizeX(units=True)
+if size_x is not None:
+ print(size_x.getValue(), size_x.getSymbol())
```
-### Physical Dimensions
+Names, descriptions, acquisition dates, owner names, group names, and channel
+labels are potentially sensitive metadata. Redact by default in broad reports.
-```python
-# Get pixel sizes with units (OMERO 5.1.0+)
-size_x_obj = image.getPixelSizeX(units=True)
-size_y_obj = image.getPixelSizeY(units=True)
-size_z_obj = image.getPixelSizeZ(units=True)
-
-print(f"Pixel Size X: {size_x_obj.getValue()} {size_x_obj.getSymbol()}")
-print(f"Pixel Size Y: {size_y_obj.getValue()} {size_y_obj.getSymbol()}")
-print(f"Pixel Size Z: {size_z_obj.getValue()} {size_z_obj.getSymbol()}")
-
-# Get as floats (micrometers)
-size_x = image.getPixelSizeX() # Returns float in µm
-size_y = image.getPixelSizeY()
-size_z = image.getPixelSizeZ()
-```
+## Filesets and Original Files
-### Channel Information
+A fileset groups original imported files and may represent several images.
+Inspect metadata before downloading:
```python
-# Iterate through channels
-for channel in image.getChannels():
- print(f"Channel {channel.getLabel()}:")
- print(f" Color: {channel.getColor().getRGB()}")
- print(f" Lookup Table: {channel.getLut()}")
- print(f" Wavelength: {channel.getEmissionWave()}")
+fileset = image.getFileset()
+if fileset is not None:
+ print(fileset.getId())
```
-### Image Metadata
+Downloading an `Image` or `Fileset` may retrieve several original files and
+their directory structure. Estimate scope first; never use a container-wide
+download merely because it is convenient.
-```python
-# Acquisition date
-acquired = image.getAcquisitionDate()
-if acquired:
- print(f"Acquired: {acquired}")
-
-# Description
-description = image.getDescription()
-if description:
- print(f"Description: {description}")
-
-# Owner and group
-details = image.getDetails()
-print(f"Owner: {details.getOwner().getFullName()}")
-print(f"Username: {details.getOwner().getOmeName()}")
-print(f"Group: {details.getGroup().getName()}")
-print(f"Created: {details.getCreationEvent().getTime()}")
-```
+The current CLI supports:
-## Object Ownership and Permissions
+```bash
+# One OriginalFile:
+omero download OriginalFile:123 ./explicit-local-file
-### Get Owner Information
+# Original files linked to one image:
+omero download Image:123 ./explicit-empty-directory
-```python
-# Get object owner
-obj = conn.getObject("Dataset", dataset_id)
-owner = obj.getDetails().getOwner()
-
-print(f"Owner ID: {owner.getId()}")
-print(f"Username: {owner.getOmeName()}")
-print(f"Full Name: {owner.getFullName()}")
-print(f"Email: {owner.getEmail()}")
+# Original files in one fileset:
+omero download Fileset:456 ./explicit-empty-directory
```
-### Get Group Information
-
-```python
-# Get object's group
-obj = conn.getObject("Image", image_id)
-group = obj.getDetails().getGroup()
-
-print(f"Group: {group.getName()} (ID: {group.getId()})")
-```
+Authenticate through an already prompted CLI session. Do not add `-w`,
+`--password`, or `-k` to reusable command text. Reject symlinked destinations
+and collisions; never derive a local path directly from an untrusted remote
+filename.
-### Filter by Owner
+## Import Planning and Import
-```python
-# Get objects for specific user
-user_id = 5
-datasets = conn.getObjects("Dataset", opts={'owner': user_id})
+The OMERO importer can scan without a running server:
-for dataset in datasets:
- print(f"Dataset: {dataset.getName()}")
+```bash
+omero import -f ./explicit-input
+omero import --depth 4 -f ./explicit-directory
```
-## Advanced Queries
+`-f` lists files that would be imported, grouped into filesets, then exits.
+This is the correct first pass; it is not a remote import.
-### Pagination
+The bundled local planner is even more conservative and does not invoke OMERO:
-```python
-# Paginate through large result sets
-page_size = 50
-offset = 0
-
-while True:
- images = list(conn.getObjects("Image", opts={
- 'limit': page_size,
- 'offset': offset,
- 'order_by': 'obj.id'
- }))
-
- if not images:
- break
-
- for image in images:
- print(f"Image: {image.getName()}")
-
- offset += page_size
+```bash
+python -B scripts/plan_transfer.py import \
+ --target Dataset:id:42 \
+ --max-files 100 \
+ ./explicit-input
```
-### Sorting Results
+After review and a prompted `omero login`, an actual scoped import is:
-```python
-# Sort by name (case-insensitive)
-projects = conn.getObjects("Project", opts={
- 'order_by': 'lower(obj.name)'
-})
-
-# Sort by ID (ascending)
-datasets = conn.getObjects("Dataset", opts={
- 'order_by': 'obj.id'
-})
-
-# Sort by name (descending)
-images = conn.getObjects("Image", opts={
- 'order_by': 'lower(obj.name) desc'
-})
+```bash
+omero import -T Dataset:id:42 ./explicit-input
```
-### Combining Filters
+Important:
-```python
-# Complex query with multiple filters
-my_exp_id = conn.getUser().getId()
-default_group_id = conn.getEventContext().groupId
-
-images = conn.getObjects("Image", opts={
- 'owner': my_exp_id,
- 'group': default_group_id,
- 'dataset': dataset_id,
- 'order_by': 'lower(obj.name)',
- 'limit': 100,
- 'offset': 0
-})
-```
-
-## Counting Objects
+- The target must be in the current session group.
+- Import needs compatible importer Java libraries; set `OMERODIR` to the
+ matching extracted server distribution.
+- `--parallel-fileset` and `--parallel-upload` are documented as experimental;
+ high values can crash the client or make the server unresponsive.
+- `--report --upload` can send broken source files and logs to the OME team.
+ Never use it without explicit authorization to disclose that data.
+- In-place imports change repository assumptions and are administrator
+ workflows, not a routine client optimization.
-### Count Children
+## OME-TIFF and XML Export
-```python
-# Count images in dataset
-dataset = conn.getObject("Dataset", dataset_id)
-image_count = dataset.countChildren()
-print(f"Dataset contains {image_count} images")
+The documented `omero export` command currently supports:
-# Count datasets in project
-project = conn.getObject("Project", project_id)
-dataset_count = project.countChildren()
-print(f"Project contains {dataset_count} datasets")
+```bash
+omero export --file ./image-123.ome.tiff Image:123
+omero export --file ./image-123.ome.xml --type XML Image:123
```
-### Count Annotations
+This is not the same as downloading original files:
-```python
-# Count annotations on object
-image = conn.getObject("Image", image_id)
-annotation_count = image.countAnnotations()
-print(f"Image has {annotation_count} annotations")
-```
-
-## Orphaned Objects
+- export serializes an OMERO image as OME-TIFF or its metadata as XML;
+- download retrieves original files associated with an OriginalFile,
+ FileAnnotation, Image, or Fileset.
-### Find Orphaned Datasets
+Dataset iteration exists only as an experimental export mode. Do not use it
+for broad exports by default. Plan explicit image IDs instead:
-```python
-# Datasets not linked to any project
-orphaned_datasets = conn.getObjects("Dataset", opts={'orphaned': True})
-
-print("Orphaned Datasets:")
-for dataset in orphaned_datasets:
- print(f" {dataset.getName()} (ID: {dataset.getId()})")
- print(f" Owner: {dataset.getDetails().getOwner().getOmeName()}")
- print(f" Images: {dataset.countChildren()}")
+```bash
+python -B scripts/plan_transfer.py export \
+ --format ome-tiff \
+ --output-dir ./reviewed-output \
+ Image:123 Image:124
```
-### Find Orphaned Images
+The planner does not connect or export. Review file collisions, image count,
+and available storage before running each proposed command.
-```python
-# Images not in any dataset
-orphaned_images = conn.getObjects("Image", opts={'orphaned': True})
+## Transfer Checklist
-print("Orphaned Images:")
-for image in orphaned_images:
- print(f" {image.getName()} (ID: {image.getId()})")
-```
-
-### Find Orphaned Plates
-
-```python
-# Plates not in any screen
-orphaned_plates = conn.getObjects("Plate", opts={'orphaned': True})
-
-for plate in orphaned_plates:
- print(f"Orphaned Plate: {plate.getName()}")
-```
-
-## Complete Example
-
-```python
-from omero.gateway import BlitzGateway
-
-# Connection details
-HOST = 'omero.example.com'
-PORT = 4064
-USERNAME = 'user'
-PASSWORD = 'pass'
-
-# Connect and query data
-with BlitzGateway(USERNAME, PASSWORD, host=HOST, port=PORT) as conn:
- # Get user context
- user = conn.getUser()
- group = conn.getGroupFromContext()
-
- print(f"Connected as {user.getName()} in group {group.getName()}")
- print()
-
- # List projects with datasets and images
- for project in conn.getObjects("Project", opts={'limit': 5}):
- print(f"Project: {project.getName()} (ID: {project.getId()})")
-
- for dataset in project.listChildren():
- image_count = dataset.countChildren()
- print(f" Dataset: {dataset.getName()} ({image_count} images)")
-
- # Show first 3 images
- for idx, image in enumerate(dataset.listChildren()):
- if idx >= 3:
- print(f" ... and {image_count - 3} more")
- break
- print(f" Image: {image.getName()}")
- print(f" Size: {image.getSizeX()}x{image.getSizeY()}")
- print(f" Channels: {image.getSizeC()}, Z: {image.getSizeZ()}")
-
- print()
-```
+Before any import, export, or download:
-## Best Practices
-
-1. **Use Context Managers**: Always use `with` statements for automatic connection cleanup
-2. **Limit Results**: Use `limit` and `offset` for large datasets
-3. **Filter Early**: Apply filters to reduce data transfer
-4. **Check for None**: Always check if `getObject()` returns None before using
-5. **Efficient Traversal**: Use `listChildren()` instead of querying separately
-6. **Count Before Loading**: Use `countChildren()` to decide whether to load data
-7. **Group Context**: Set appropriate group context before cross-group queries
-8. **Pagination**: Implement pagination for large result sets
-9. **Object Reuse**: Cache frequently accessed objects to reduce queries
-10. **Error Handling**: Wrap queries in try-except blocks for robustness
+1. Confirm current session group.
+2. Confirm explicit source paths or object IDs.
+3. Cap file/object count and directory scan depth.
+4. Distinguish derived OME-TIFF/XML export from original-file download.
+5. Estimate bytes and review data-sharing authorization.
+6. Use a dedicated existing output directory with no symlinks/collisions.
+7. Never use credential flags.
+8. Do not upload diagnostics or broken files without separate consent.
diff --git a/skills/omero-integration/references/image_processing.md b/skills/omero-integration/references/image_processing.md
index dd36bd14..85225521 100644
--- a/skills/omero-integration/references/image_processing.md
+++ b/skills/omero-integration/references/image_processing.md
@@ -1,665 +1,286 @@
-# Image Processing & Rendering
+# Pixels, Rendering, and Derived Images
-This reference covers accessing raw pixel data, image rendering, and creating new images in OMERO.
+Pixel planes, thumbnails, rendered images, channel labels, and physical sizes
+are data exports. Set explicit image IDs, coordinates, byte/memory caps, and
+output paths before retrieval.
-## Accessing Raw Pixel Data
+## Dimensions Before Data
-### Get Single Plane
+Inspect dimensions without loading a plane:
```python
-# Get image
image = conn.getObject("Image", image_id)
-
-# Get dimensions
-size_z = image.getSizeZ()
-size_c = image.getSizeC()
-size_t = image.getSizeT()
-
-# Get pixels object
-pixels = image.getPrimaryPixels()
-
-# Get single plane (returns NumPy array)
-z, c, t = 0, 0, 0 # First Z-section, channel, and timepoint
-plane = pixels.getPlane(z, c, t)
-
-print(f"Shape: {plane.shape}")
-print(f"Data type: {plane.dtype.name}")
-print(f"Min: {plane.min()}, Max: {plane.max()}")
-```
-
-### Get Multiple Planes
-
-```python
-import numpy as np
-
-# Get Z-stack for specific channel and timepoint
-pixels = image.getPrimaryPixels()
-c, t = 0, 0 # First channel and timepoint
-
-# Build list of (z, c, t) coordinates
-zct_list = [(z, c, t) for z in range(size_z)]
-
-# Get all planes at once
-planes = pixels.getPlanes(zct_list)
-
-# Stack into 3D array
-z_stack = np.array([p for p in planes])
-print(f"Z-stack shape: {z_stack.shape}")
-```
-
-### Get Hypercube (Subset of 5D Data)
-
-```python
-# Get subset of 5D data (Z, C, T)
-zct_list = []
-for z in range(size_z // 2, size_z): # Second half of Z
- for c in range(size_c): # All channels
- for t in range(size_t): # All timepoints
- zct_list.append((z, c, t))
-
-# Get planes
-planes = pixels.getPlanes(zct_list)
-
-# Process each plane
-for i, plane in enumerate(planes):
- z, c, t = zct_list[i]
- print(f"Plane Z={z}, C={c}, T={t}: Min={plane.min()}, Max={plane.max()}")
-```
-
-### Get Tile (Region of Interest)
-
-```python
-# Define tile coordinates
-x, y = 50, 50 # Top-left corner
-width, height = 100, 100 # Tile size
-tile = (x, y, width, height)
-
-# Get tile for specific Z, C, T
-z, c, t = 0, 0, 0
-zct_list = [(z, c, t, tile)]
-
-tiles = pixels.getTiles(zct_list)
-tile_data = tiles[0]
-
-print(f"Tile shape: {tile_data.shape}") # Should be (height, width)
+if image is None:
+ raise LookupError("Image unavailable")
+
+dimensions = {
+ "size_x": image.getSizeX(),
+ "size_y": image.getSizeY(),
+ "size_z": image.getSizeZ(),
+ "size_c": image.getSizeC(),
+ "size_t": image.getSizeT(),
+ "pixels_type": image.getPixelsType(),
+}
```
-### Get Multiple Tiles
+Estimate element count and memory before a read. A single `uint16` plane uses
+roughly `size_x * size_y * 2` bytes before NumPy/container overhead. Do not
+retrieve a full 5D image by default.
-```python
-# Get tiles from Z-stack
-c, t = 0, 0
-tile = (50, 50, 100, 100) # x, y, width, height
-
-# Build list with tiles
-zct_list = [(z, c, t, tile) for z in range(size_z)]
-
-tiles = pixels.getTiles(zct_list)
-
-for i, tile_data in enumerate(tiles):
- print(f"Tile Z={i}: {tile_data.shape}, Min={tile_data.min()}")
-```
+## One Raw Plane
-## Image Histograms
-
-### Get Histogram
+Raw pixel access is zero-based in Z, C, and T:
```python
-# Get histogram for first channel
-channel_index = 0
-num_bins = 256
-z, t = 0, 0
-
-histogram = image.getHistogram([channel_index], num_bins, False, z, t)
-print(f"Histogram bins: {len(histogram)}")
-print(f"First 10 bins: {histogram[:10]}")
-```
+z = 0
+c = 0
+t = 0
-### Multi-Channel Histogram
+if not 0 <= z < image.getSizeZ():
+ raise ValueError("Z out of range")
+if not 0 <= c < image.getSizeC():
+ raise ValueError("C out of range")
+if not 0 <= t < image.getSizeT():
+ raise ValueError("T out of range")
-```python
-# Get histograms for all channels
-channels = list(range(image.getSizeC()))
-histograms = image.getHistogram(channels, 256, False, 0, 0)
+max_pixels = 16_000_000
+if image.getSizeX() * image.getSizeY() > max_pixels:
+ raise ValueError("Plane exceeds approved pixel count; use tiles")
-for c, hist in enumerate(histograms):
- print(f"Channel {c}: Total pixels = {sum(hist)}")
+pixels = image.getPrimaryPixels()
+plane = pixels.getPlane(z, c, t)
+print(plane.shape, plane.dtype)
```
-## Image Rendering
-
-### Render Image with Current Settings
-
-```python
-from PIL import Image
-from io import BytesIO
-
-# Get image
-image = conn.getObject("Image", image_id)
-
-# Render at specific Z and T
-z = image.getSizeZ() // 2 # Middle Z-section
-t = 0
+Do not print arrays. Summaries such as min/max may still reveal signal
+distribution and should be included only when requested.
-rendered_image = image.renderImage(z, t)
-# rendered_image is a PIL Image object
-rendered_image.save("rendered_image.jpg")
-```
+## Several Explicit Planes
-### Get Thumbnail
+`getPlanes()` accepts a list of `(z, c, t)` tuples and returns an iterator.
+Bound the coordinate list and process incrementally:
```python
-from PIL import Image
-from io import BytesIO
+coordinates = [(0, 0, 0), (1, 0, 0), (2, 0, 0)]
+if len(coordinates) > 20:
+ raise ValueError("Too many planes")
-# Get thumbnail (uses current rendering settings)
-thumbnail_data = image.getThumbnail()
-
-# Convert to PIL Image
-thumbnail = Image.open(BytesIO(thumbnail_data))
-thumbnail.save("thumbnail.jpg")
-
-# Get specific thumbnail size
-thumbnail_data = image.getThumbnail(size=(96, 96))
-thumbnail = Image.open(BytesIO(thumbnail_data))
+for (z, c, t), plane in zip(coordinates, pixels.getPlanes(coordinates)):
+ print({"z": z, "c": c, "t": t, "shape": plane.shape})
```
-## Rendering Settings
+Do not create a coordinate list from all dimensions until the resulting count
+has been checked.
-### View Current Settings
+## Tiles for Large Images
-```python
-# Display rendering settings
-print("Current Rendering Settings:")
-print(f"Grayscale mode: {image.isGreyscaleRenderingModel()}")
-print(f"Default Z: {image.getDefaultZ()}")
-print(f"Default T: {image.getDefaultT()}")
-print()
-
-# Channel settings
-print("Channel Settings:")
-for idx, channel in enumerate(image.getChannels()):
- print(f"Channel {idx + 1}:")
- print(f" Label: {channel.getLabel()}")
- print(f" Color: {channel.getColor().getHtml()}")
- print(f" Active: {channel.isActive()}")
- print(f" Window: {channel.getWindowStart()} - {channel.getWindowEnd()}")
- print(f" Min/Max: {channel.getWindowMin()} - {channel.getWindowMax()}")
-```
-
-### Set Rendering Model
+`getTiles()` accepts `(z, c, t, (x, y, width, height))` tuples:
```python
-# Switch to grayscale rendering
-image.setGreyscaleRenderingModel()
+x = 0
+y = 0
+width = 512
+height = 512
+z = 0
+c = 0
+t = 0
-# Switch to color rendering
-image.setColorRenderingModel()
+if width <= 0 or height <= 0:
+ raise ValueError("Tile dimensions must be positive")
+if x < 0 or y < 0:
+ raise ValueError("Tile origin must be non-negative")
+if x + width > image.getSizeX() or y + height > image.getSizeY():
+ raise ValueError("Tile exceeds image bounds")
+if width * height > 1_048_576:
+ raise ValueError("Tile exceeds approved pixel count")
+
+request = [(z, c, t, (x, y, width, height))]
+tile = next(pixels.getTiles(request))
```
-### Set Active Channels
+For a tiled scan, cap:
-```python
-# Activate specific channels (1-indexed)
-image.setActiveChannels([1, 3]) # Channels 1 and 3 only
+- number of tiles;
+- pixels per tile;
+- total pixels;
+- channels/Z/T;
+- memory retained at once.
-# Activate all channels
-all_channels = list(range(1, image.getSizeC() + 1))
-image.setActiveChannels(all_channels)
+Do not infer that a rectangular tile is equivalent to a nonrectangular ROI.
-# Activate single channel
-image.setActiveChannels([2])
-```
+## Channel Metadata
-### Set Channel Colors
+Channel metadata may include sensitive labels:
```python
-# Set channel colors (hex format)
-channels = [1, 2, 3]
-colors = ['FF0000', '00FF00', '0000FF'] # Red, Green, Blue
-
-image.setActiveChannels(channels, colors=colors)
-
-# Use None to keep existing color
-colors = ['FF0000', None, '0000FF'] # Keep channel 2's color
-image.setActiveChannels(channels, colors=colors)
+max_channels = min(image.getSizeC(), 16)
+for index, channel in enumerate(image.getChannels()):
+ if index >= max_channels:
+ break
+ print(
+ {
+ "index": index,
+ "label_redacted": True,
+ "color": channel.getColor().getRGB(),
+ "lut": channel.getLut(),
+ "reverse_intensity": channel.isReverseIntensity(),
+ }
+ )
```
-### Set Channel Window (Intensity Range)
+Raw pixel channel indices are zero-based. BlitzGateway rendering channel
+selectors are one-based. Keep this conversion explicit.
-```python
-# Set intensity windows for channels
-channels = [1, 2]
-windows = [
- [100.0, 500.0], # Channel 1: 100-500
- [50.0, 300.0] # Channel 2: 50-300
-]
-
-image.setActiveChannels(channels, windows=windows)
-
-# Use None to keep existing window
-windows = [[100.0, 500.0], [None, None]]
-image.setActiveChannels(channels, windows=windows)
-```
+## Physical Dimensions
-### Set Default Z and T
+Physical sizes can be absent:
```python
-# Set default Z-section and timepoint
-image.setDefaultZ(5)
-image.setDefaultT(0)
-
-# Render using defaults
-rendered_image = image.renderImage(z=None, t=None)
-rendered_image.save("default_rendering.jpg")
+for axis, value in (
+ ("x", image.getPixelSizeX(units=True)),
+ ("y", image.getPixelSizeY(units=True)),
+ ("z", image.getPixelSizeZ(units=True)),
+):
+ if value is not None:
+ print(axis, value.getValue(), value.getSymbol())
```
-## Render Individual Channels
-
-### Render Each Channel Separately
-
-```python
-# Set grayscale mode
-image.setGreyscaleRenderingModel()
+Preserve the unit. Do not assume an unwrapped numeric value has the unit needed
+by downstream analysis.
-z = image.getSizeZ() // 2
-t = 0
+Changing pixel sizes mutates the server model and must be a separately
+reviewed write. Do not “correct” missing metadata automatically.
-# Render each channel
-for c in range(1, image.getSizeC() + 1):
- image.setActiveChannels([c])
- rendered = image.renderImage(z, t)
- rendered.save(f"channel_{c}.jpg")
-```
+## Thumbnail Bytes
-### Render Multi-Channel Composites
+`getThumbnail()` returns encoded image bytes using current rendering settings:
```python
-# Color composite of first 3 channels
-image.setColorRenderingModel()
-channels = [1, 2, 3]
-colors = ['FF0000', '00FF00', '0000FF'] # RGB
+from io import BytesIO
+from PIL import Image
-image.setActiveChannels(channels, colors=colors)
-rendered = image.renderImage(z, t)
-rendered.save("rgb_composite.jpg")
+thumbnail_bytes = image.getThumbnail(size=(96, 96))
+thumbnail = Image.open(BytesIO(thumbnail_bytes))
+thumbnail.load()
+print(thumbnail.size)
```
-## Image Projections
-
-### Maximum Intensity Projection
+To save, use a caller-selected filename and refuse collisions/symlinks:
```python
-# Set projection type
-image.setProjection('intmax')
-
-# Render (projects across all Z)
-z, t = 0, 0 # Z is ignored for projections
-rendered = image.renderImage(z, t)
-rendered.save("max_projection.jpg")
+from pathlib import Path
-# Reset to normal rendering
-image.setProjection('normal')
-```
-
-### Mean Intensity Projection
-
-```python
-image.setProjection('intmean')
-rendered = image.renderImage(z, t)
-rendered.save("mean_projection.jpg")
-image.setProjection('normal')
+destination = Path("./image-123-thumbnail.png")
+if destination.exists() or destination.is_symlink():
+ raise FileExistsError(destination)
+thumbnail.save(destination, format="PNG")
```
-### Available Projection Types
-
-- `'normal'`: No projection (default)
-- `'intmax'`: Maximum intensity projection
-- `'intmean'`: Mean intensity projection
-- `'intmin'`: Minimum intensity projection (if supported)
+Do not derive `destination` from `image.getName()`.
-## Save and Reset Rendering Settings
+## Rendering
-### Save Current Settings as Default
+`renderImage(z, t, compression=0.9)` returns a Pillow image:
```python
-# Modify rendering settings
-image.setActiveChannels([1, 2])
-image.setDefaultZ(5)
-
-# Save as new default
-image.saveDefaults()
-```
-
-### Reset to Import Settings
-
-```python
-# Reset to original import settings
-image.resetDefaults(save=True)
+z = image.getSizeZ() // 2
+t = 0
+rendered = image.renderImage(z, t, compression=0.9)
```
-## Create Images from NumPy Arrays
+The rendered result reflects the current rendering model, active channels,
+colors, windows, LUTs, and defaults. Record those settings when a reproducible
+figure depends on them.
-### Create Simple Image
+Current official examples set active rendering channels with one-based
+indices:
```python
-import numpy as np
-
-# Create sample data
-size_x, size_y = 512, 512
-size_z, size_c, size_t = 10, 2, 1
-
-# Generate planes
-def plane_generator():
- """Generator that yields planes"""
- for z in range(size_z):
- for c in range(size_c):
- for t in range(size_t):
- # Create synthetic data
- plane = np.random.randint(0, 255, (size_y, size_x), dtype=np.uint8)
- yield plane
-
-# Create image
-image = conn.createImageFromNumpySeq(
- plane_generator(),
- "Test Image",
- size_z, size_c, size_t,
- description="Image created from NumPy arrays",
- dataset=None
+image.setActiveChannels(
+ [1, 2],
+ [[20.0, 300.0], [50.0, 500.0]],
+ ["00FF00", "FF0000"],
)
-
-print(f"Created image ID: {image.getId()}")
+rendered = image.renderImage(z, t)
```
-### Create Image from Hard-Coded Arrays
+This initializes a stateful rendering engine. Keep the rendering scope short.
+Closing the BlitzGateway closes its tracked services; if using low-level
+stateful services directly, close each in `finally`. Do not depend on private
+attributes such as `image._re` in durable code.
-```python
-from numpy import array, int8
-
-# Define dimensions
-size_x, size_y = 5, 4
-size_z, size_c, size_t = 1, 2, 1
-
-# Create planes
-plane1 = array(
- [[0, 1, 2, 3, 4],
- [5, 6, 7, 8, 9],
- [0, 1, 2, 3, 4],
- [5, 6, 7, 8, 9]],
- dtype=int8
-)
+`saveDefaults()` or other persistence calls change server rendering settings.
+Do not call them in a read/render helper. Rendering locally does not authorize
+persisting new defaults.
-plane2 = array(
- [[5, 6, 7, 8, 9],
- [0, 1, 2, 3, 4],
- [5, 6, 7, 8, 9],
- [0, 1, 2, 3, 4]],
- dtype=int8
-)
+## Histograms and Statistics
-planes = [plane1, plane2]
+Histograms and min/max statistics can be large or expensive across many
+channels/planes. Restrict:
-def plane_gen():
- for p in planes:
- yield p
+- one explicit image;
+- an allowlisted channel list;
+- bin count;
+- Z/T;
+- number of returned arrays.
-# Create image
-desc = "Image created from hard-coded arrays"
-image = conn.createImageFromNumpySeq(
- plane_gen(),
- "numpy_image",
- size_z, size_c, size_t,
- description=desc,
- dataset=None
-)
+Do not use whole-dataset histograms as a connectivity test.
-print(f"Created image: {image.getName()} (ID: {image.getId()})")
-```
+## Derived Images Are Writes
-### Create Image in Dataset
+`BlitzGateway.createImageFromNumpySeq(...)` creates a server image:
```python
-# Get target dataset
-dataset = conn.getObject("Dataset", dataset_id)
-
-# Create image
-image = conn.createImageFromNumpySeq(
- plane_generator(),
- "New Analysis Result",
- size_z, size_c, size_t,
- description="Result from analysis pipeline",
- dataset=dataset # Add to dataset
+result = conn.createImageFromNumpySeq(
+ plane_iterator,
+ "reviewed-derived-image",
+ sizeZ=1,
+ sizeC=source.getSizeC(),
+ sizeT=source.getSizeT(),
+ description="Method and source IDs recorded separately",
+ dataset=target_dataset,
+ sourceImageId=source.getId(),
)
```
-### Create Derived Image
-
-```python
-# Get source image
-source = conn.getObject("Image", source_image_id)
-size_z = source.getSizeZ()
-size_c = source.getSizeC()
-size_t = source.getSizeT()
-dataset = source.getParent()
-
-pixels = source.getPrimaryPixels()
-new_size_c = 1 # Average channels
-
-def plane_gen():
- """Average channels together"""
- for z in range(size_z):
- for c in range(new_size_c):
- for t in range(size_t):
- # Get multiple channels
- channel0 = pixels.getPlane(z, 0, t)
- channel1 = pixels.getPlane(z, 1, t)
-
- # Combine
- new_plane = (channel0.astype(float) + channel1.astype(float)) / 2
- new_plane = new_plane.astype(channel0.dtype)
-
- yield new_plane
-
-# Create new image
-desc = "Averaged channels from source image"
-derived = conn.createImageFromNumpySeq(
- plane_gen(),
- f"{source.getName()}_averaged",
- size_z, new_size_c, size_t,
- description=desc,
- dataset=dataset
-)
-
-print(f"Created derived image: {derived.getId()}")
-```
-
-## Set Physical Dimensions
-
-### Set Pixel Sizes with Units
-
-```python
-from omero.model.enums import UnitsLength
-import omero.model
-
-# Get image
-image = conn.getObject("Image", image_id)
-
-# Create unit objects
-pixel_size_x = omero.model.LengthI(0.325, UnitsLength.MICROMETER)
-pixel_size_y = omero.model.LengthI(0.325, UnitsLength.MICROMETER)
-pixel_size_z = omero.model.LengthI(1.0, UnitsLength.MICROMETER)
-
-# Get pixels object
-pixels = image.getPrimaryPixels()._obj
-
-# Set physical sizes
-pixels.setPhysicalSizeX(pixel_size_x)
-pixels.setPhysicalSizeY(pixel_size_y)
-pixels.setPhysicalSizeZ(pixel_size_z)
-
-# Save changes
-conn.getUpdateService().saveObject(pixels)
-
-print("Updated pixel dimensions")
-```
-
-### Available Length Units
+Before execution:
-From `omero.model.enums.UnitsLength`:
-- `ANGSTROM`
-- `NANOMETER`
-- `MICROMETER`
-- `MILLIMETER`
-- `CENTIMETER`
-- `METER`
-- `PIXEL`
+1. validate iterator plane order and exact expected plane count;
+2. validate each shape and dtype;
+3. cap source planes and memory;
+4. confirm target dataset and group;
+5. confirm output name/description contains no secrets;
+6. decide cleanup for a partial write;
+7. copy physical dimensions only when semantically valid.
-### Set Pixel Size on New Image
+For a maximum-intensity projection, the derived image has one Z plane.
+Do not copy a source Z spacing that no longer describes the data.
-```python
-from omero.model.enums import UnitsLength
-import omero.model
-
-# Create image
-image = conn.createImageFromNumpySeq(
- plane_generator(),
- "New Image with Dimensions",
- size_z, size_c, size_t
-)
+## Dtype Handling
-# Set pixel sizes
-pixel_size = omero.model.LengthI(0.5, UnitsLength.MICROMETER)
-pixels = image.getPrimaryPixels()._obj
-pixels.setPhysicalSizeX(pixel_size)
-pixels.setPhysicalSizeY(pixel_size)
-
-z_size = omero.model.LengthI(2.0, UnitsLength.MICROMETER)
-pixels.setPhysicalSizeZ(z_size)
-
-conn.getUpdateService().saveObject(pixels)
-```
-
-## Complete Example: Image Processing Pipeline
+Keep the source dtype unless the algorithm requires conversion:
```python
-from omero.gateway import BlitzGateway
import numpy as np
-HOST = 'omero.example.com'
-PORT = 4064
-USERNAME = 'user'
-PASSWORD = 'pass'
-
-with BlitzGateway(USERNAME, PASSWORD, host=HOST, port=PORT) as conn:
- # Get source image
- source = conn.getObject("Image", source_image_id)
- print(f"Processing: {source.getName()}")
-
- # Get dimensions
- size_x = source.getSizeX()
- size_y = source.getSizeY()
- size_z = source.getSizeZ()
- size_c = source.getSizeC()
- size_t = source.getSizeT()
-
- pixels = source.getPrimaryPixels()
-
- # Process: Maximum intensity projection over Z
- def plane_gen():
- for c in range(size_c):
- for t in range(size_t):
- # Get all Z planes for this C, T
- z_stack = []
- for z in range(size_z):
- plane = pixels.getPlane(z, c, t)
- z_stack.append(plane)
-
- # Maximum projection
- max_proj = np.max(z_stack, axis=0)
- yield max_proj
-
- # Create result image (single Z-section)
- result = conn.createImageFromNumpySeq(
- plane_gen(),
- f"{source.getName()}_MIP",
- 1, size_c, size_t, # Z=1 for projection
- description="Maximum intensity projection",
- dataset=source.getParent()
- )
-
- print(f"Created MIP image: {result.getId()}")
-
- # Copy pixel sizes (X and Y only, no Z for projection)
- from omero.model.enums import UnitsLength
- import omero.model
-
- source_pixels = source.getPrimaryPixels()._obj
- result_pixels = result.getPrimaryPixels()._obj
-
- result_pixels.setPhysicalSizeX(source_pixels.getPhysicalSizeX())
- result_pixels.setPhysicalSizeY(source_pixels.getPhysicalSizeY())
-
- conn.getUpdateService().saveObject(result_pixels)
-
- print("Processing complete")
-```
-
-## Working with Different Data Types
-
-### Handle Various Pixel Types
-
-```python
-# Get pixel type
-pixel_type = image.getPixelsType()
-print(f"Pixel type: {pixel_type}")
-
-# Common types: uint8, uint16, uint32, int8, int16, int32, float, double
-
-# Get plane with correct dtype
-plane = pixels.getPlane(z, c, t)
-print(f"NumPy dtype: {plane.dtype}")
-
-# Convert if needed for processing
-if plane.dtype == np.uint16:
- # Convert to float for processing
- plane_float = plane.astype(np.float32)
- # Process...
- # Convert back
- result = plane_float.astype(np.uint16)
-```
-
-### Handle Large Images
-
-```python
-# Process large images in tiles to save memory
-tile_size = 512
-size_x = image.getSizeX()
-size_y = image.getSizeY()
-
-for y in range(0, size_y, tile_size):
- for x in range(0, size_x, tile_size):
- # Get tile dimensions
- w = min(tile_size, size_x - x)
- h = min(tile_size, size_y - y)
- tile = (x, y, w, h)
-
- # Get tile data
- zct_list = [(z, c, t, tile)]
- tile_data = pixels.getTiles(zct_list)[0]
-
- # Process tile
- # ...
+plane_float = plane.astype(np.float32)
+# Perform reviewed numerical processing.
+result = np.clip(plane_float, 0, np.iinfo(np.uint16).max).astype(np.uint16)
```
-## Best Practices
-
-1. **Use Generators**: For creating images, use generators to avoid loading all data in memory
-2. **Specify Data Types**: Match NumPy dtypes to OMERO pixel types
-3. **Set Physical Dimensions**: Always set pixel sizes for new images
-4. **Tile Large Images**: Process large images in tiles to manage memory
-5. **Close Connections**: Always close connections when done
-6. **Rendering Efficiency**: Cache rendering settings when rendering multiple images
-7. **Channel Indexing**: Remember channels are 1-indexed for rendering, 0-indexed for pixel access
-8. **Save Settings**: Save rendering settings if they should be permanent
-9. **Compression**: Use compression parameter in renderImage() for faster transfers
-10. **Error Handling**: Check for None returns and handle exceptions
+Document clipping, scaling, normalization, and rounding. Never cast a float
+array to an integer type without checking range and non-finite values.
+
+## Rendering and Pixel Checklist
+
+- Explicit image ID and group
+- Dimensions inspected before retrieval
+- Z/C/T and coordinates range-checked
+- Plane/tile count and total pixels bounded
+- Raw channel indexing distinguished from rendering indexing
+- Labels and pixel-derived values classified for export
+- Caller-selected non-symlink output with collision refusal
+- Rendering services short-lived
+- No rendering-default save in read-only workflows
+- Derived-image creation separately approved
+- Connection and stateful services closed
diff --git a/skills/omero-integration/references/metadata.md b/skills/omero-integration/references/metadata.md
index 4083f089..93f2d64f 100644
--- a/skills/omero-integration/references/metadata.md
+++ b/skills/omero-integration/references/metadata.md
@@ -1,688 +1,313 @@
-# Metadata & Annotations
+# Metadata and Annotations
-This reference covers creating and managing annotations in OMERO, including tags, key-value pairs, file attachments, and comments.
+Annotations may contain participant identifiers, sample names, unpublished
+results, free text, remote filenames, or attached files. Read and export the
+minimum fields needed.
-## Annotation Types
+## Current Annotation Types
-OMERO supports several annotation types:
+The OMERO structured annotation model includes:
-- **TagAnnotation**: Text labels for categorization
-- **MapAnnotation**: Key-value pairs for structured metadata
-- **FileAnnotation**: File attachments (PDFs, CSVs, analysis results, etc.)
-- **CommentAnnotation**: Free-text comments
-- **LongAnnotation**: Integer values
-- **DoubleAnnotation**: Floating-point values
-- **BooleanAnnotation**: Boolean values
-- **TimestampAnnotation**: Date/time stamps
-- **TermAnnotation**: Ontology terms
+- `TagAnnotation`
+- `MapAnnotation`
+- `FileAnnotation`
+- `CommentAnnotation`
+- `BooleanAnnotation`
+- `LongAnnotation`
+- `DoubleAnnotation`
+- `TimestampAnnotation`
+- `TermAnnotation`
+- `XmlAnnotation`
+- annotation hierarchies through annotation-to-annotation links
-## Tag Annotations
+Current `omero.gateway` exports corresponding wrappers, including
+`TagAnnotationWrapper`, `MapAnnotationWrapper`,
+`FileAnnotationWrapper`, and `CommentAnnotationWrapper`. Do not import a
+historical `BaseAnnotationWrapper`; the current public wrapper is
+`AnnotationWrapper`.
-### Create and Link Tag
+Annotations can be linked to multiple objects. Their ownership and the
+ownership of each link may differ. Deleting an annotation is not the same as
+deleting one link.
-```python
-import omero.gateway
-
-# Create new tag
-tag_ann = omero.gateway.TagAnnotationWrapper(conn)
-tag_ann.setValue("Experiment 2024")
-tag_ann.setDescription("Optional description of this tag")
-tag_ann.save()
-
-# Link tag to an object
-project = conn.getObject("Project", project_id)
-project.linkAnnotation(tag_ann)
-```
+## Bounded Read
-### Create Tag with Namespace
+`listAnnotations()` supports a namespace filter but not a page-size argument.
+Cap client iteration and report truncation:
```python
-# Create tag with custom namespace
-tag_ann = omero.gateway.TagAnnotationWrapper(conn)
-tag_ann.setValue("Quality Control")
-tag_ann.setNs("mylab.qc.tags")
-tag_ann.save()
+from itertools import islice
-# Link to image
image = conn.getObject("Image", image_id)
-image.linkAnnotation(tag_ann)
-```
-
-### Reuse Existing Tag
-
-```python
-# Find existing tag
-tag_id = 123
-tag_ann = conn.getObject("TagAnnotation", tag_id)
+if image is None:
+ raise LookupError("Image unavailable")
-# Link to multiple images
-for image in conn.getObjects("Image", [img1, img2, img3]):
- image.linkAnnotation(tag_ann)
-```
+max_annotations = 100
+items = list(islice(image.listAnnotations(), max_annotations + 1))
+truncated = len(items) > max_annotations
-### Create Tag Set (Tag with Children)
+for annotation in items[:max_annotations]:
+ print(annotation.getId(), annotation.OMERO_CLASS, annotation.getNs())
-```python
-# Create tag set (parent tag)
-tag_set = omero.gateway.TagAnnotationWrapper(conn)
-tag_set.setValue("Cell Types")
-tag_set.save()
-
-# Create child tags
-tags = ["HeLa", "U2OS", "HEK293"]
-for tag_value in tags:
- tag = omero.gateway.TagAnnotationWrapper(conn)
- tag.setValue(tag_value)
- tag.save()
-
- # Link child to parent
- tag_set.linkAnnotation(tag)
+print({"truncated": truncated})
```
-## Map Annotations (Key-Value Pairs)
+Do not call `getValue()` when values are outside the approved export scope.
+Merely avoiding printing after retrieval is weaker than not retrieving.
-### Create Map Annotation
+For explicit parent IDs, annotation links can be queried:
```python
-import omero.gateway
-import omero.constants.metadata
-
-# Prepare key-value data
-key_value_data = [
- ["Drug Name", "Monastrol"],
- ["Concentration", "5 mg/ml"],
- ["Treatment Time", "24 hours"],
- ["Temperature", "37C"]
-]
-
-# Create map annotation
-map_ann = omero.gateway.MapAnnotationWrapper(conn)
-
-# Use standard client namespace
-namespace = omero.constants.metadata.NSCLIENTMAPANNOTATION
-map_ann.setNs(namespace)
-
-# Set data
-map_ann.setValue(key_value_data)
-map_ann.save()
-
-# Link to dataset
-dataset = conn.getObject("Dataset", dataset_id)
-dataset.linkAnnotation(map_ann)
+image_ids = [101, 102]
+for link in islice(
+ conn.getAnnotationLinks("Image", parent_ids=image_ids),
+ 200,
+):
+ print(link.getParent().getId(), link.getChild().getId())
```
-### Custom Namespace for Map Annotations
-
-```python
-# Use custom namespace for organization-specific metadata
-key_value_data = [
- ["Microscope", "Zeiss LSM 880"],
- ["Objective", "63x Oil"],
- ["Laser Power", "10%"]
-]
-
-map_ann = omero.gateway.MapAnnotationWrapper(conn)
-map_ann.setNs("mylab.microscopy.settings")
-map_ann.setValue(key_value_data)
-map_ann.save()
+Keep both the parent-ID list and returned-link count bounded.
-image = conn.getObject("Image", image_id)
-image.linkAnnotation(map_ann)
-```
+## Redacted Inventory
-### Read Map Annotation
+A safe default record contains identifiers and type, not values:
```python
-# Get map annotation
-image = conn.getObject("Image", image_id)
-
-for ann in image.listAnnotations():
- if isinstance(ann, omero.gateway.MapAnnotationWrapper):
- print(f"Map Annotation (ID: {ann.getId()}):")
- print(f"Namespace: {ann.getNs()}")
-
- # Get key-value pairs
- for key, value in ann.getValue():
- print(f" {key}: {value}")
+def annotation_summary(annotation):
+ details = annotation.getDetails()
+ owner = details.getOwner() if details is not None else None
+ return {
+ "id": annotation.getId(),
+ "type": annotation.OMERO_CLASS,
+ "namespace": annotation.getNs(),
+ "owner_id": owner.getId() if owner is not None else None,
+ "value_redacted": True,
+ }
```
-## File Annotations
-
-### Upload and Attach File
-
-```python
-import os
+Owner names, annotation values, file names, descriptions, and link-owner names
+require separate inclusion decisions.
-# Prepare file
-file_path = "analysis_results.csv"
+The bundled exporter defaults to redaction:
-# Create file annotation
-namespace = "mylab.analysis.results"
-file_ann = conn.createFileAnnfromLocalFile(
- file_path,
- mimetype="text/csv",
- ns=namespace,
- desc="Cell segmentation results"
-)
+```bash
+python -B scripts/export_image_metadata.py \
+ --image-id 101 \
+ --max-annotations-per-image 100 \
+ --max-rois-per-image 100 \
+ --output ./image-101-metadata.json
-# Link to dataset
-dataset = conn.getObject("Dataset", dataset_id)
-dataset.linkAnnotation(file_ann)
+# Review, then connect. Add inclusion flags only when approved.
+python -B scripts/export_image_metadata.py \
+ --image-id 101 \
+ --max-annotations-per-image 100 \
+ --max-rois-per-image 100 \
+ --execute \
+ --output ./image-101-metadata.json
```
-### Supported MIME Types
+It never downloads FileAnnotation bytes or pixel data.
-Common MIME types:
-- Text: `"text/plain"`, `"text/csv"`, `"text/tab-separated-values"`
-- Documents: `"application/pdf"`, `"application/vnd.ms-excel"`
-- Images: `"image/png"`, `"image/jpeg"`
-- Data: `"application/json"`, `"application/xml"`
-- Archives: `"application/zip"`, `"application/gzip"`
+## Namespaces
-### Upload Multiple Files
+Namespaces let tools assign semantics:
```python
-files = ["figure1.pdf", "figure2.pdf", "table1.csv"]
-namespace = "publication.supplementary"
-
-dataset = conn.getObject("Dataset", dataset_id)
-
-for file_path in files:
- file_ann = conn.createFileAnnfromLocalFile(
- file_path,
- mimetype="application/octet-stream",
- ns=namespace,
- desc=f"Supplementary file: {os.path.basename(file_path)}"
- )
- dataset.linkAnnotation(file_ann)
+for annotation in image.listAnnotations(ns="org.example.analysis.v1"):
+ print(annotation.getId())
```
-### Download File Annotation
-
-```python
-import os
-
-# Get object with file annotation
-image = conn.getObject("Image", image_id)
-
-# Download directory
-download_path = "./downloads"
-os.makedirs(download_path, exist_ok=True)
-
-# Filter by namespace
-namespace = "mylab.analysis.results"
-
-for ann in image.listAnnotations(ns=namespace):
- if isinstance(ann, omero.gateway.FileAnnotationWrapper):
- file_name = ann.getFile().getName()
- file_path = os.path.join(download_path, file_name)
-
- print(f"Downloading: {file_name}")
+Use an organization-controlled URI or reverse-domain pattern and document its
+schema/version. Do not claim a custom namespace is an OME standard.
- # Download file in chunks
- with open(file_path, 'wb') as f:
- for chunk in ann.getFileInChunks():
- f.write(chunk)
-
- print(f"Saved to: {file_path}")
-```
-
-### Get File Annotation Metadata
+The current client constant for client map annotations is:
```python
-for ann in dataset.listAnnotations():
- if isinstance(ann, omero.gateway.FileAnnotationWrapper):
- orig_file = ann.getFile()
-
- print(f"File Annotation ID: {ann.getId()}")
- print(f" File Name: {orig_file.getName()}")
- print(f" File Size: {orig_file.getSize()} bytes")
- print(f" MIME Type: {orig_file.getMimetype()}")
- print(f" Namespace: {ann.getNs()}")
- print(f" Description: {ann.getDescription()}")
+from omero.constants.metadata import NSCLIENTMAPANNOTATION
```
-## Comment Annotations
-
-### Add Comment
+OME's Python example warns that a client map annotation should be linked to
+only one object. Create a separate map annotation for each target when using
+that namespace.
-```python
-# Create comment
-comment = omero.gateway.CommentAnnotationWrapper(conn)
-comment.setValue("This image shows excellent staining quality")
-comment.save()
-
-# Link to image
-image = conn.getObject("Image", image_id)
-image.linkAnnotation(comment)
-```
+## Map Annotations
-### Add Comment with Namespace
+Read key/value pairs only when approved:
```python
-comment = omero.gateway.CommentAnnotationWrapper(conn)
-comment.setValue("Approved for publication")
-comment.setNs("mylab.publication.status")
-comment.save()
+from omero.gateway import MapAnnotationWrapper
-dataset = conn.getObject("Dataset", dataset_id)
-dataset.linkAnnotation(comment)
+for annotation in image.listAnnotations(ns="org.example.analysis.v1"):
+ if isinstance(annotation, MapAnnotationWrapper):
+ pairs = annotation.getValue()
+ for key, value in pairs[:50]:
+ print(key, value)
```
-## Numeric Annotations
+Apply independent limits to annotation count, pair count, key length, and
+value length. Keys can be sensitive too; a “values redacted” export that leaves
+participant IDs in keys is not redacted.
-### Long Annotation (Integer)
+Creating and linking is a write:
```python
-# Create long annotation
-long_ann = omero.gateway.LongAnnotationWrapper(conn)
-long_ann.setValue(42)
-long_ann.setNs("mylab.cell.count")
-long_ann.save()
+from omero.constants.metadata import NSCLIENTMAPANNOTATION
+from omero.gateway import MapAnnotationWrapper
image = conn.getObject("Image", image_id)
-image.linkAnnotation(long_ann)
-```
-
-### Double Annotation (Float)
-
-```python
-# Create double annotation
-double_ann = omero.gateway.DoubleAnnotationWrapper(conn)
-double_ann.setValue(3.14159)
-double_ann.setNs("mylab.fluorescence.intensity")
-double_ann.save()
-
-image = conn.getObject("Image", image_id)
-image.linkAnnotation(double_ann)
-```
-
-## Listing Annotations
+if image is None:
+ raise LookupError("Image unavailable")
-### List All Annotations on Object
-
-```python
-import omero.model
-
-# Get object
-project = conn.getObject("Project", project_id)
-
-# List all annotations
-for ann in project.listAnnotations():
- print(f"Annotation ID: {ann.getId()}")
- print(f" Type: {ann.OMERO_TYPE}")
- print(f" Added by: {ann.link.getDetails().getOwner().getOmeName()}")
-
- # Type-specific handling
- if ann.OMERO_TYPE == omero.model.TagAnnotationI:
- print(f" Tag value: {ann.getTextValue()}")
-
- elif isinstance(ann, omero.gateway.MapAnnotationWrapper):
- print(f" Map data: {ann.getValue()}")
-
- elif isinstance(ann, omero.gateway.FileAnnotationWrapper):
- print(f" File: {ann.getFile().getName()}")
-
- elif isinstance(ann, omero.gateway.CommentAnnotationWrapper):
- print(f" Comment: {ann.getValue()}")
-
- print()
+pairs = [["Analysis version", "2.1"], ["Status", "reviewed"]]
+annotation = MapAnnotationWrapper(conn)
+annotation.setNs(NSCLIENTMAPANNOTATION)
+annotation.setValue(pairs)
+annotation.save()
+image.linkAnnotation(annotation)
```
-### Filter Annotations by Namespace
-
-```python
-# Get annotations with specific namespace
-namespace = "mylab.qc.tags"
-
-for ann in image.listAnnotations(ns=namespace):
- print(f"Found annotation: {ann.getId()}")
+Before running this:
- if isinstance(ann, omero.gateway.MapAnnotationWrapper):
- for key, value in ann.getValue():
- print(f" {key}: {value}")
-```
-
-### Get First Annotation with Namespace
+- confirm image ID and group;
+- confirm write permission and namespace;
+- validate pair count and string lengths;
+- decide rollback behavior if save succeeds but link creation fails;
+- never create duplicate metadata merely because an earlier query was scoped
+ to the wrong group.
-```python
-# Get single annotation by namespace
-namespace = "mylab.analysis.results"
-ann = dataset.getAnnotation(namespace)
-
-if ann:
- print(f"Found annotation with namespace: {ann.getNs()}")
-else:
- print("No annotation found with that namespace")
-```
+## Tags and Comments
-### Query Annotations Across Multiple Objects
+Tag creation and linking are separate writes:
```python
-# Get all tag annotations linked to image IDs
-image_ids = [1, 2, 3, 4, 5]
+from omero.gateway import TagAnnotationWrapper
-for link in conn.getAnnotationLinks('Image', parent_ids=image_ids):
- ann = link.getChild()
-
- if isinstance(ann._obj, omero.model.TagAnnotationI):
- print(f"Image {link.getParent().getId()}: Tag '{ann.getTextValue()}'")
-```
-
-## Counting Annotations
-
-```python
-# Count annotations on project
-project_id = 123
-count = conn.countAnnotations('Project', [project_id])
-print(f"Project has {count[project_id]} annotations")
-
-# Count annotations on multiple images
-image_ids = [1, 2, 3]
-counts = conn.countAnnotations('Image', image_ids)
-
-for image_id, count in counts.items():
- print(f"Image {image_id}: {count} annotations")
-```
-
-## Annotation Links
-
-### Create Annotation Link Manually
-
-```python
-# Get annotation and image
-tag = conn.getObject("TagAnnotation", tag_id)
-image = conn.getObject("Image", image_id)
-
-# Create link
-link = omero.model.ImageAnnotationLinkI()
-link.setParent(omero.model.ImageI(image.getId(), False))
-link.setChild(omero.model.TagAnnotationI(tag.getId(), False))
-
-# Save link
-conn.getUpdateService().saveAndReturnObject(link)
-```
-
-### Update Annotation Links
-
-```python
-# Get existing links
-annotation_ids = [1, 2, 3]
-new_tag_id = 5
-
-for link in conn.getAnnotationLinks('Image', ann_ids=annotation_ids):
- print(f"Image ID: {link.getParent().id}")
-
- # Change linked annotation
- link._obj.child = omero.model.TagAnnotationI(new_tag_id, False)
- link.save()
-```
-
-## Removing Annotations
-
-### Delete Annotations
+tag = TagAnnotationWrapper(conn)
+tag.setValue("Reviewed")
+tag.setDescription("Reviewed under protocol v2")
+tag.save()
-```python
-# Get image
image = conn.getObject("Image", image_id)
-
-# Collect annotation IDs to delete
-to_delete = []
-namespace = "mylab.temp.annotations"
-
-for ann in image.listAnnotations(ns=namespace):
- to_delete.append(ann.getId())
-
-# Delete annotations
-if to_delete:
- conn.deleteObjects('Annotation', to_delete, wait=True)
- print(f"Deleted {len(to_delete)} annotations")
+if image is None:
+ raise LookupError("Image unavailable")
+image.linkAnnotation(tag)
```
-### Unlink Annotations (Keep Annotation, Remove Link)
-
-```python
-# Get image
-image = conn.getObject("Image", image_id)
+Query for an existing controlled tag before creating another. Check group and
+owner semantics; do not reuse a same-named tag from an unintended group.
-# Collect link IDs to delete
-to_delete = []
+Comments are free text and often the most sensitive annotation type. Do not
+include them in a general inventory. Never pass untrusted comments into shell,
+HTML, SQL/HQL, filenames, or dynamic code.
-for ann in image.listAnnotations():
- if isinstance(ann, omero.gateway.TagAnnotationWrapper):
- to_delete.append(ann.link.getId())
-
-# Delete links (annotations remain in database)
-if to_delete:
- conn.deleteObjects("ImageAnnotationLink", to_delete, wait=True)
- print(f"Unlinked {len(to_delete)} annotations")
-```
+## File Annotations
-### Delete Specific Annotation Types
+Inspect metadata without downloading bytes:
```python
-import omero.gateway
-
-# Delete only map annotations
-image = conn.getObject("Image", image_id)
-to_delete = []
-
-for ann in image.listAnnotations():
- if isinstance(ann, omero.gateway.MapAnnotationWrapper):
- to_delete.append(ann.getId())
+from omero.gateway import FileAnnotationWrapper
-conn.deleteObjects('Annotation', to_delete, wait=True)
+for annotation in image.listAnnotations():
+ if isinstance(annotation, FileAnnotationWrapper):
+ original = annotation.getFile()
+ print(
+ {
+ "annotation_id": annotation.getId(),
+ "original_file_id": original.getId(),
+ "size": original.getSize(),
+ "mimetype": original.getMimetype(),
+ "name_redacted": True,
+ }
+ )
```
-## Annotation Ownership
+Remote filenames are untrusted input. Never join them directly to an output
+directory.
-### Set Annotation Owner (Admin Only)
+For one explicitly approved file, check size and use a caller-chosen path:
```python
-import omero.model
+from pathlib import Path
-# Create tag with specific owner
-tag_ann = omero.gateway.TagAnnotationWrapper(conn)
-tag_ann.setValue("Admin Tag")
-
-# Set owner (requires admin privileges)
-user_id = 5
-tag_ann._obj.details.owner = omero.model.ExperimenterI(user_id, False)
-tag_ann.save()
-```
+max_bytes = 50 * 1024 * 1024
+destination = Path("./approved-result.bin")
-### Create Annotation as Another User (Admin Only)
+original = file_annotation.getFile()
+if original.getSize() > max_bytes:
+ raise ValueError("File exceeds approved byte limit")
+if destination.exists() or destination.is_symlink():
+ raise FileExistsError(destination)
-```python
-# Admin connection
-admin_conn = BlitzGateway(admin_user, admin_pass, host=host, port=4064)
-admin_conn.connect()
-
-# Get target user
-user_id = 10
-user = admin_conn.getObject("Experimenter", user_id).getName()
-
-# Create connection as user
-user_conn = admin_conn.suConn(user)
-
-# Create annotation as that user
-map_ann = omero.gateway.MapAnnotationWrapper(user_conn)
-map_ann.setNs("mylab.metadata")
-map_ann.setValue([["key", "value"]])
-map_ann.save()
-
-# Link to project
-project = admin_conn.getObject("Project", project_id)
-project.linkAnnotation(map_ann)
-
-# Close connections
-user_conn.close()
-admin_conn.close()
+written = 0
+with destination.open("xb") as handle:
+ for chunk in file_annotation.getFileInChunks():
+ written += len(chunk)
+ if written > max_bytes:
+ raise ValueError("Received more than approved byte limit")
+ handle.write(chunk)
```
-## Bulk Annotation Operations
+On failure, delete the partial local file if policy permits. Do not download
+all file annotations attached to a project/dataset without an explicit list.
-### Tag Multiple Images
+Uploading is a mutation:
```python
-# Create or get tag
-tag = omero.gateway.TagAnnotationWrapper(conn)
-tag.setValue("Validated")
-tag.save()
-
-# Get images to tag
-dataset = conn.getObject("Dataset", dataset_id)
-
-# Tag all images in dataset
-for image in dataset.listChildren():
- image.linkAnnotation(tag)
- print(f"Tagged image: {image.getName()}")
+source = "./approved-analysis.csv"
+annotation = conn.createFileAnnfromLocalFile(
+ source,
+ mimetype="text/csv",
+ ns="org.example.analysis.v1",
+ desc="Reviewed analysis results",
+)
+dataset.linkAnnotation(annotation)
```
-### Batch Add Map Annotations
+Check local file size, type, content classification, target dataset ID/group,
+and whether upload is permitted before execution.
-```python
-# Prepare metadata for multiple images
-image_metadata = {
- 101: [["Quality", "Good"], ["Reviewed", "Yes"]],
- 102: [["Quality", "Excellent"], ["Reviewed", "Yes"]],
- 103: [["Quality", "Poor"], ["Reviewed", "No"]]
-}
-
-# Add annotations
-for image_id, kv_data in image_metadata.items():
- image = conn.getObject("Image", image_id)
-
- if image:
- map_ann = omero.gateway.MapAnnotationWrapper(conn)
- map_ann.setNs("mylab.qc")
- map_ann.setValue(kv_data)
- map_ann.save()
-
- image.linkAnnotation(map_ann)
- print(f"Annotated image {image_id}")
-```
+## Numeric and Boolean Values
-## Namespaces
-
-### Standard OMERO Namespaces
+Wrapper examples:
```python
-import omero.constants.metadata as omero_ns
-
-# Client map annotation namespace
-omero_ns.NSCLIENTMAPANNOTATION
-# "openmicroscopy.org/omero/client/mapAnnotation"
-
-# Bulk annotations namespace
-omero_ns.NSBULKANNOTATIONS
-# "openmicroscopy.org/omero/bulk_annotations"
+from omero.gateway import (
+ BooleanAnnotationWrapper,
+ DoubleAnnotationWrapper,
+ LongAnnotationWrapper,
+)
```
-### Custom Namespaces
+Numeric values still need units and semantics in the namespace/schema.
+Do not infer that `DoubleAnnotation` values are in micrometers or that a
+`LongAnnotation` is a count.
-Best practices for custom namespaces:
-- Use reverse domain notation: `"org.mylab.category.subcategory"`
-- Be specific: `"com.company.project.analysis.v1"`
-- Include version if schema may change: `"mylab.metadata.v2"`
+## Unlink Versus Delete
-```python
-# Define namespaces
-NS_QC = "org.mylab.quality_control"
-NS_ANALYSIS = "org.mylab.image_analysis.v1"
-NS_PUBLICATION = "org.mylab.publication.2024"
+- **Unlink** deletes an object-annotation link but keeps the annotation and
+ other links.
+- **Delete annotation** deletes the annotation and may affect every linked
+ object.
-# Use in annotations
-map_ann.setNs(NS_ANALYSIS)
-```
+Before either operation:
-## Load All Annotations by Type
+1. retrieve and display exact link/annotation IDs;
+2. count other links;
+3. verify ownership and permission;
+4. obtain explicit approval for the exact operation;
+5. do not use a namespace-only bulk delete without an ID review;
+6. wait for and check command completion.
-### Load All File Annotations
+Read-only export utilities must not include delete/unlink modes.
-```python
-# Define namespaces to include/exclude
-ns_to_include = ["mylab.analysis.results"]
-ns_to_exclude = []
-
-# Get metadata service
-metadataService = conn.getMetadataService()
-
-# Load all file annotations with namespace
-annotations = metadataService.loadSpecifiedAnnotations(
- 'omero.model.FileAnnotation',
- ns_to_include,
- ns_to_exclude,
- None
-)
-
-for ann in annotations:
- print(f"File Annotation ID: {ann.getId().getValue()}")
- print(f" File: {ann.getFile().getName().getValue()}")
- print(f" Size: {ann.getFile().getSize().getValue()} bytes")
-```
-
-## Complete Example
-
-```python
-from omero.gateway import BlitzGateway
-import omero.gateway
-import omero.constants.metadata
-
-HOST = 'omero.example.com'
-PORT = 4064
-USERNAME = 'user'
-PASSWORD = 'pass'
-
-with BlitzGateway(USERNAME, PASSWORD, host=HOST, port=PORT) as conn:
- # Get dataset
- dataset = conn.getObject("Dataset", dataset_id)
-
- # Add tag
- tag = omero.gateway.TagAnnotationWrapper(conn)
- tag.setValue("Analysis Complete")
- tag.save()
- dataset.linkAnnotation(tag)
-
- # Add map annotation with metadata
- metadata = [
- ["Analysis Date", "2024-10-20"],
- ["Software", "CellProfiler 4.2"],
- ["Pipeline", "cell_segmentation_v3"]
- ]
- map_ann = omero.gateway.MapAnnotationWrapper(conn)
- map_ann.setNs(omero.constants.metadata.NSCLIENTMAPANNOTATION)
- map_ann.setValue(metadata)
- map_ann.save()
- dataset.linkAnnotation(map_ann)
-
- # Add file annotation
- file_ann = conn.createFileAnnfromLocalFile(
- "analysis_summary.pdf",
- mimetype="application/pdf",
- ns="mylab.reports",
- desc="Analysis summary report"
- )
- dataset.linkAnnotation(file_ann)
-
- # Add comment
- comment = omero.gateway.CommentAnnotationWrapper(conn)
- comment.setValue("Dataset ready for review")
- comment.save()
- dataset.linkAnnotation(comment)
-
- print(f"Added 4 annotations to dataset {dataset.getName()}")
-```
+## Metadata Export Checklist
-## Best Practices
-
-1. **Use Namespaces**: Always use namespaces to organize annotations
-2. **Descriptive Tags**: Use clear, consistent tag names
-3. **Structured Metadata**: Prefer map annotations over comments for structured data
-4. **File Organization**: Use descriptive filenames and MIME types
-5. **Link Reuse**: Reuse existing tags instead of creating duplicates
-6. **Batch Operations**: Process multiple objects in loops for efficiency
-7. **Error Handling**: Check for successful saves before linking
-8. **Cleanup**: Remove temporary annotations when no longer needed
-9. **Documentation**: Document custom namespace meanings
-10. **Permissions**: Consider annotation ownership for collaborative workflows
+- Explicit object type and IDs
+- One group context
+- Maximum objects, annotations, links, pairs, and string length
+- Values redacted by default
+- File names and owner names separately gated
+- No attachment bytes unless one file and byte cap are approved
+- Output path chosen by caller; no remote-derived path
+- Atomic write with owner-only permissions
+- Connection closed in `finally`
diff --git a/skills/omero-integration/references/rois.md b/skills/omero-integration/references/rois.md
index 7146b76b..5ccca17d 100644
--- a/skills/omero-integration/references/rois.md
+++ b/skills/omero-integration/references/rois.md
@@ -1,648 +1,291 @@
# Regions of Interest (ROIs)
-This reference covers creating, retrieving, and analyzing ROIs in OMERO.
+ROIs and shape labels may encode phenotypes, diagnoses, sample identifiers, or
+analysis decisions. Export geometry and labels only within an explicit scope.
-## ROI Overview
+## Model Semantics
-ROIs (Regions of Interest) in OMERO are containers for geometric shapes that mark specific regions on images. Each ROI can contain multiple shapes, and shapes can be specific to Z-sections and timepoints.
+The OMERO 5.6 line uses the June 2016 OME schema. The OME ROI model defines
+eight concrete 2D shape types:
-### Supported Shape Types
+- Ellipse
+- Label
+- Line
+- Mask
+- Point
+- Polygon
+- Polyline
+- Rectangle
-- **Rectangle**: Rectangular regions
-- **Ellipse**: Circular and elliptical regions
-- **Line**: Line segments
-- **Point**: Single points
-- **Polygon**: Multi-point polygons
-- **Mask**: Pixel-based masks
-- **Polyline**: Multi-segment lines
+Plane selectors are optional:
-## Creating ROIs
+- `TheZ`: z-section; absent means all z-sections
+- `TheT`: timepoint; absent means all timepoints
+- `TheC`: channel; absent means all channels
-### Helper Functions
+Do not coerce absent values to zero. A 3D ROI is represented as a union of 2D
+shapes across planes; it is not a native volumetric mesh.
-```python
-from omero.rtypes import rdouble, rint, rstring
-import omero.model
-
-def create_roi(conn, image, shapes):
- """
- Create an ROI and link it to shapes.
-
- Args:
- conn: BlitzGateway connection
- image: Image object
- shapes: List of shape objects
-
- Returns:
- Saved ROI object
- """
- roi = omero.model.RoiI()
- roi.setImage(image._obj)
-
- for shape in shapes:
- roi.addShape(shape)
-
- updateService = conn.getUpdateService()
- return updateService.saveAndReturnObject(roi)
-
-def rgba_to_int(red, green, blue, alpha=255):
- """
- Convert RGBA values (0-255) to integer encoding for OMERO.
-
- Args:
- red, green, blue, alpha: Color values (0-255)
+Display fields include RGBA fill/stroke colors, stroke width, fill rule, dash
+array, text label, and font properties. Geometry and display metadata are
+distinct.
- Returns:
- Integer color value
- """
- return int.from_bytes([red, green, blue, alpha],
- byteorder='big', signed=True)
-```
+## Current Service Status
-### Rectangle ROI
+The current Python examples still retrieve ROIs with:
```python
-from omero.rtypes import rdouble, rint, rstring
-import omero.model
-
-# Get image
-image = conn.getObject("Image", image_id)
-
-# Define position and size
-x, y = 50, 100
-width, height = 200, 150
-z, t = 0, 0 # Z-section and timepoint
-
-# Create rectangle
-rect = omero.model.RectangleI()
-rect.x = rdouble(x)
-rect.y = rdouble(y)
-rect.width = rdouble(width)
-rect.height = rdouble(height)
-rect.theZ = rint(z)
-rect.theT = rint(t)
-
-# Set label and colors
-rect.textValue = rstring("Cell Region")
-rect.fillColor = rint(rgba_to_int(255, 0, 0, 50)) # Red, semi-transparent
-rect.strokeColor = rint(rgba_to_int(255, 255, 0, 255)) # Yellow border
-
-# Create ROI
-roi = create_roi(conn, image, [rect])
-print(f"Created ROI ID: {roi.getId().getValue()}")
-```
-
-### Ellipse ROI
-
-```python
-# Center position and radii
-center_x, center_y = 250, 250
-radius_x, radius_y = 100, 75
-z, t = 0, 0
-
-# Create ellipse
-ellipse = omero.model.EllipseI()
-ellipse.x = rdouble(center_x)
-ellipse.y = rdouble(center_y)
-ellipse.radiusX = rdouble(radius_x)
-ellipse.radiusY = rdouble(radius_y)
-ellipse.theZ = rint(z)
-ellipse.theT = rint(t)
-ellipse.textValue = rstring("Nucleus")
-ellipse.fillColor = rint(rgba_to_int(0, 255, 0, 50))
-
-# Create ROI
-roi = create_roi(conn, image, [ellipse])
-```
-
-### Line ROI
-
-```python
-# Line endpoints
-x1, y1 = 100, 100
-x2, y2 = 300, 200
-z, t = 0, 0
-
-# Create line
-line = omero.model.LineI()
-line.x1 = rdouble(x1)
-line.y1 = rdouble(y1)
-line.x2 = rdouble(x2)
-line.y2 = rdouble(y2)
-line.theZ = rint(z)
-line.theT = rint(t)
-line.textValue = rstring("Measurement Line")
-line.strokeColor = rint(rgba_to_int(0, 0, 255, 255))
-
-# Create ROI
-roi = create_roi(conn, image, [line])
+roi_service = conn.getRoiService()
+result = roi_service.findByImage(image_id, None)
```
-### Point ROI
+However, the current OMERO Blitz API marks the `IRoi` interface deprecated.
+That means “still available but at removal risk,” not “already removed.” OME
+does not document a general replacement for every `IRoi` method in the pages
+reviewed for this snapshot.
-```python
-# Point position
-x, y = 150, 150
-z, t = 0, 0
-
-# Create point
-point = omero.model.PointI()
-point.x = rdouble(x)
-point.y = rdouble(y)
-point.theZ = rint(z)
-point.theT = rint(t)
-point.textValue = rstring("Feature Point")
-
-# Create ROI
-roi = create_roi(conn, image, [point])
-```
+Therefore:
-### Polygon ROI
+- isolate `IRoi` use behind a small function;
+- do not build new broad workflows around legacy measurement-table helpers;
+- verify the target server's generated API before relying on it;
+- record this dependency in long-lived integrations.
-```python
-from omero.model.enums import UnitsLength
-
-# Define vertices as string "x1,y1 x2,y2 x3,y3 ..."
-vertices = "10,20 50,150 200,200 250,75"
-z, t = 0, 0
-
-# Create polygon
-polygon = omero.model.PolygonI()
-polygon.points = rstring(vertices)
-polygon.theZ = rint(z)
-polygon.theT = rint(t)
-polygon.textValue = rstring("Cell Outline")
-
-# Set colors and stroke width
-polygon.fillColor = rint(rgba_to_int(255, 0, 255, 50))
-polygon.strokeColor = rint(rgba_to_int(255, 255, 0, 255))
-polygon.strokeWidth = omero.model.LengthI(2, UnitsLength.PIXEL)
-
-# Create ROI
-roi = create_roi(conn, image, [polygon])
-```
+The official OMERO.web JSON API also documents paginated ROI listing by image:
+`/api/v0/m/rois/?image=<id>&limit=<n>&offset=<n>`. Use it only when the site
+exposes the documented `api` app over HTTPS and its authentication model is
+appropriate.
-### Mask ROI
+## Bounded ROI Read
-```python
-import numpy as np
-import struct
-import math
-
-def create_mask_bytes(mask_array, bytes_per_pixel=1):
- """
- Convert binary mask array to bit-packed bytes for OMERO.
-
- Args:
- mask_array: Binary numpy array (0s and 1s)
- bytes_per_pixel: 1 or 2
-
- Returns:
- Byte array for OMERO mask
- """
- if bytes_per_pixel == 2:
- divider = 16.0
- format_string = "H"
- byte_factor = 0.5
- elif bytes_per_pixel == 1:
- divider = 8.0
- format_string = "B"
- byte_factor = 1
- else:
- raise ValueError("bytes_per_pixel must be 1 or 2")
-
- mask_bytes = mask_array.astype(np.uint8).tobytes()
- steps = math.ceil(len(mask_bytes) / divider)
- packed_mask = []
-
- for i in range(int(steps)):
- binary = mask_bytes[i * int(divider):
- i * int(divider) + int(divider)]
- format_str = str(int(byte_factor * len(binary))) + format_string
- binary = struct.unpack(format_str, binary)
- s = "".join(str(bit) for bit in binary)
- packed_mask.append(int(s, 2))
-
- return bytearray(packed_mask)
-
-# Create binary mask (1s and 0s)
-mask_w, mask_h = 100, 100
-mask_array = np.fromfunction(
- lambda x, y: ((x - 50)**2 + (y - 50)**2) < 40**2, # Circle
- (mask_w, mask_h)
-)
-
-# Pack mask
-mask_packed = create_mask_bytes(mask_array, bytes_per_pixel=1)
-
-# Mask position
-mask_x, mask_y = 50, 50
-z, t, c = 0, 0, 0
-
-# Create mask
-mask = omero.model.MaskI()
-mask.setX(rdouble(mask_x))
-mask.setY(rdouble(mask_y))
-mask.setWidth(rdouble(mask_w))
-mask.setHeight(rdouble(mask_h))
-mask.setTheZ(rint(z))
-mask.setTheT(rint(t))
-mask.setTheC(rint(c))
-mask.setBytes(mask_packed)
-mask.textValue = rstring("Segmentation Mask")
-
-# Set color
-from omero.gateway import ColorHolder
-mask_color = ColorHolder()
-mask_color.setRed(255)
-mask_color.setGreen(0)
-mask_color.setBlue(0)
-mask_color.setAlpha(100)
-mask.setFillColor(rint(mask_color.getInt()))
-
-# Create ROI
-roi = create_roi(conn, image, [mask])
-```
-
-## Multiple Shapes in One ROI
+`findByImage()` does not expose page arguments. Apply explicit image, ROI, and
+shape caps and report truncation:
```python
-# Create multiple shapes for the same ROI
-shapes = []
-
-# Rectangle
-rect = omero.model.RectangleI()
-rect.x = rdouble(100)
-rect.y = rdouble(100)
-rect.width = rdouble(50)
-rect.height = rdouble(50)
-rect.theZ = rint(0)
-rect.theT = rint(0)
-shapes.append(rect)
-
-# Ellipse
-ellipse = omero.model.EllipseI()
-ellipse.x = rdouble(125)
-ellipse.y = rdouble(125)
-ellipse.radiusX = rdouble(20)
-ellipse.radiusY = rdouble(20)
-ellipse.theZ = rint(0)
-ellipse.theT = rint(0)
-shapes.append(ellipse)
-
-# Create single ROI with both shapes
-roi = create_roi(conn, image, shapes)
-```
-
-## Retrieving ROIs
+image_id = 123
+max_rois = 100
+max_shapes_per_roi = 500
-### Get All ROIs for Image
-
-```python
-# Get ROI service
roi_service = conn.getRoiService()
-
-# Find all ROIs for image
result = roi_service.findByImage(image_id, None)
-
-print(f"Found {len(result.rois)} ROIs")
-
-for roi in result.rois:
- print(f"ROI ID: {roi.getId().getValue()}")
- print(f" Number of shapes: {len(roi.copyShapes())}")
+rois = list(result.rois)
+
+roi_truncated = len(rois) > max_rois
+for roi in rois[:max_rois]:
+ shapes = list(roi.copyShapes())
+ print(
+ {
+ "roi_id": roi.getId().getValue(),
+ "shape_count_returned": min(len(shapes), max_shapes_per_roi),
+ "shape_truncated": len(shapes) > max_shapes_per_roi,
+ }
+ )
```
-### Parse ROI Shapes
-
-```python
-import omero.model
+The cap limits client processing/output, not necessarily server work:
+`findByImage()` may already have assembled all matching ROIs. For a known very
+large image, do not call it casually; consider the documented paginated JSON
+API or a site-reviewed query.
-result = roi_service.findByImage(image_id, None)
+The bundled exporter requires explicit image IDs and uses redaction defaults:
-for roi in result.rois:
- roi_id = roi.getId().getValue()
- print(f"ROI ID: {roi_id}")
-
- for shape in roi.copyShapes():
- shape_id = shape.getId().getValue()
- z = shape.getTheZ().getValue() if shape.getTheZ() else None
- t = shape.getTheT().getValue() if shape.getTheT() else None
-
- # Get label
- label = ""
- if shape.getTextValue():
- label = shape.getTextValue().getValue()
-
- print(f" Shape ID: {shape_id}, Z: {z}, T: {t}, Label: {label}")
-
- # Type-specific parsing
- if isinstance(shape, omero.model.RectangleI):
- x = shape.getX().getValue()
- y = shape.getY().getValue()
- width = shape.getWidth().getValue()
- height = shape.getHeight().getValue()
- print(f" Rectangle: ({x}, {y}) {width}x{height}")
-
- elif isinstance(shape, omero.model.EllipseI):
- x = shape.getX().getValue()
- y = shape.getY().getValue()
- rx = shape.getRadiusX().getValue()
- ry = shape.getRadiusY().getValue()
- print(f" Ellipse: center ({x}, {y}), radii ({rx}, {ry})")
-
- elif isinstance(shape, omero.model.PointI):
- x = shape.getX().getValue()
- y = shape.getY().getValue()
- print(f" Point: ({x}, {y})")
-
- elif isinstance(shape, omero.model.LineI):
- x1 = shape.getX1().getValue()
- y1 = shape.getY1().getValue()
- x2 = shape.getX2().getValue()
- y2 = shape.getY2().getValue()
- print(f" Line: ({x1}, {y1}) to ({x2}, {y2})")
-
- elif isinstance(shape, omero.model.PolygonI):
- points = shape.getPoints().getValue()
- print(f" Polygon: {points}")
-
- elif isinstance(shape, omero.model.MaskI):
- x = shape.getX().getValue()
- y = shape.getY().getValue()
- width = shape.getWidth().getValue()
- height = shape.getHeight().getValue()
- print(f" Mask: ({x}, {y}) {width}x{height}")
+```bash
+python -B scripts/export_image_metadata.py \
+ --image-id 123 \
+ --max-rois-per-image 100 \
+ --max-shapes-per-roi 500 \
+ --output ./image-123-metadata.json
```
-## Analyzing ROI Intensities
+Review the dry run, then add `--execute`. ROI labels remain redacted unless
+`--include-roi-labels` is specified.
-### Get Statistics for ROI Shapes
+## Reading Shape Fields
-```python
-# Get all shapes from ROIs
-roi_service = conn.getRoiService()
-result = roi_service.findByImage(image_id, None)
+Generated model values are usually wrapped in OMERO rtypes. Preserve `None`:
-shape_ids = []
-for roi in result.rois:
- for shape in roi.copyShapes():
- shape_ids.append(shape.id.val)
-
-# Define position
-z, t = 0, 0
-channel_index = 0
-
-# Get statistics
-stats = roi_service.getShapeStatsRestricted(
- shape_ids, z, t, [channel_index]
-)
-
-# Display statistics
-for i, stat in enumerate(stats):
- shape_id = shape_ids[i]
- print(f"Shape {shape_id} statistics:")
- print(f" Points Count: {stat.pointsCount[channel_index]}")
- print(f" Min: {stat.min[channel_index]}")
- print(f" Mean: {stat.mean[channel_index]}")
- print(f" Max: {stat.max[channel_index]}")
- print(f" Sum: {stat.sum[channel_index]}")
- print(f" Std Dev: {stat.stdDev[channel_index]}")
+```python
+def unwrap(value):
+ if value is None:
+ return None
+ getter = getattr(value, "getValue", None)
+ return getter() if callable(getter) else value
+
+
+for roi in result.rois[:max_rois]:
+ for shape in list(roi.copyShapes())[:max_shapes_per_roi]:
+ record = {
+ "id": unwrap(shape.getId()),
+ "the_z": unwrap(shape.getTheZ()),
+ "the_t": unwrap(shape.getTheT()),
+ "the_c": unwrap(shape.getTheC()),
+ "label_redacted": True,
+ }
+ print(record)
```
-### Extract Pixel Values Within ROI
+Use type checks before geometry access:
```python
-import numpy as np
-
-# Get image and ROI
-image = conn.getObject("Image", image_id)
-result = roi_service.findByImage(image_id, None)
-
-# Get first rectangle shape
-roi = result.rois[0]
-rect = roi.copyShapes()[0]
-
-# Get rectangle bounds
-x = int(rect.getX().getValue())
-y = int(rect.getY().getValue())
-width = int(rect.getWidth().getValue())
-height = int(rect.getHeight().getValue())
-z = rect.getTheZ().getValue()
-t = rect.getTheT().getValue()
-
-# Get pixel data
-pixels = image.getPrimaryPixels()
-
-# Extract region for each channel
-for c in range(image.getSizeC()):
- # Get plane
- plane = pixels.getPlane(z, c, t)
-
- # Extract ROI region
- roi_region = plane[y:y+height, x:x+width]
+import omero.model
- print(f"Channel {c}:")
- print(f" Mean intensity: {np.mean(roi_region)}")
- print(f" Max intensity: {np.max(roi_region)}")
+if isinstance(shape, omero.model.RectangleI):
+ geometry = {
+ "x": unwrap(shape.getX()),
+ "y": unwrap(shape.getY()),
+ "width": unwrap(shape.getWidth()),
+ "height": unwrap(shape.getHeight()),
+ }
+elif isinstance(shape, omero.model.EllipseI):
+ geometry = {
+ "x": unwrap(shape.getX()),
+ "y": unwrap(shape.getY()),
+ "radius_x": unwrap(shape.getRadiusX()),
+ "radius_y": unwrap(shape.getRadiusY()),
+ }
+elif isinstance(shape, omero.model.LineI):
+ geometry = {
+ "x1": unwrap(shape.getX1()),
+ "y1": unwrap(shape.getY1()),
+ "x2": unwrap(shape.getX2()),
+ "y2": unwrap(shape.getY2()),
+ }
+elif isinstance(shape, (omero.model.PolygonI, omero.model.PolylineI)):
+ geometry = {"points": unwrap(shape.getPoints())}
```
-## Modifying ROIs
+Validate coordinates against image dimensions. Preserve floating-point
+coordinates; do not truncate them to integers merely for JSON.
-### Update Shape Properties
+For masks:
-```python
-# Get ROI and shape
-result = roi_service.findByImage(image_id, None)
-roi = result.rois[0]
-shape = roi.copyShapes()[0]
+- export position, dimensions, plane selectors, and byte count only by default;
+- do not serialize mask bytes into broad JSON;
+- treat decoded masks as pixel-derived data;
+- validate width/height and bit packing against the current model before
+ reconstructing.
-# Modify shape (example: change rectangle size)
-if isinstance(shape, omero.model.RectangleI):
- shape.setWidth(rdouble(150))
- shape.setHeight(rdouble(100))
- shape.setTextValue(rstring("Updated Rectangle"))
-
-# Save changes
-updateService = conn.getUpdateService()
-updated_roi = updateService.saveAndReturnObject(roi._obj)
-```
+## Creating an ROI Is a Write
-### Remove Shape from ROI
+Current core-model pattern:
```python
-result = roi_service.findByImage(image_id, None)
-
-for roi in result.rois:
- for shape in roi.copyShapes():
- # Check condition (e.g., remove by label)
- if (shape.getTextValue() and
- shape.getTextValue().getValue() == "test-Ellipse"):
-
- print(f"Removing shape {shape.getId().getValue()}")
- roi.removeShape(shape)
+import omero.model
+from omero.rtypes import rdouble, rint, rstring
- # Save modified ROI
- updateService = conn.getUpdateService()
- roi = updateService.saveAndReturnObject(roi)
+image = conn.getObject("Image", image_id)
+if image is None:
+ raise LookupError("Image unavailable")
+
+x = 50.0
+y = 100.0
+width = 200.0
+height = 150.0
+z = 0
+t = 0
+
+if x < 0 or y < 0 or x + width > image.getSizeX() or y + height > image.getSizeY():
+ raise ValueError("Rectangle is outside image bounds")
+if not 0 <= z < image.getSizeZ() or not 0 <= t < image.getSizeT():
+ raise ValueError("Plane index is outside image bounds")
+
+rectangle = omero.model.RectangleI()
+rectangle.setX(rdouble(x))
+rectangle.setY(rdouble(y))
+rectangle.setWidth(rdouble(width))
+rectangle.setHeight(rdouble(height))
+rectangle.setTheZ(rint(z))
+rectangle.setTheT(rint(t))
+rectangle.setTextValue(rstring("reviewed-region"))
+
+roi = omero.model.RoiI()
+roi.setImage(image._obj)
+roi.addShape(rectangle)
+
+saved = conn.getUpdateService().saveAndReturnObject(roi)
+print(saved.getId().getValue())
```
-## Deleting ROIs
+Before execution, confirm:
-### Delete Single ROI
+- image ID, group, and dimensions;
+- shape count and coordinate system;
+- Z/T/C semantics;
+- label sensitivity;
+- write permission;
+- whether an existing ROI should be updated rather than duplicated.
-```python
-# Delete ROI by ID
-roi_id = 123
-conn.deleteObjects("Roi", [roi_id], wait=True)
-print(f"Deleted ROI {roi_id}")
-```
+## RGBA Encoding
-### Delete All ROIs for Image
+The official Python example encodes color bytes as a signed 32-bit integer:
```python
-# Get all ROI IDs for image
-result = roi_service.findByImage(image_id, None)
-roi_ids = [roi.getId().getValue() for roi in result.rois]
-
-# Delete all
-if roi_ids:
- conn.deleteObjects("Roi", roi_ids, wait=True)
- print(f"Deleted {len(roi_ids)} ROIs")
+def rgba_to_int(red, green, blue, alpha=255):
+ channels = (red, green, blue, alpha)
+ if any(not 0 <= value <= 255 for value in channels):
+ raise ValueError("RGBA channels must be in 0..255")
+ return int.from_bytes(channels, byteorder="big", signed=True)
```
-## Batch ROI Creation
+Use `rint(rgba_to_int(...))` for generated shape color fields. Do not swap RGBA
+order or assume an unsigned representation.
-### Create ROIs for Multiple Images
+## Intensity Measurements
-```python
-# Get images
-dataset = conn.getObject("Dataset", dataset_id)
-
-for image in dataset.listChildren():
- # Create rectangle at center of each image
- x = image.getSizeX() // 2 - 50
- y = image.getSizeY() // 2 - 50
-
- rect = omero.model.RectangleI()
- rect.x = rdouble(x)
- rect.y = rdouble(y)
- rect.width = rdouble(100)
- rect.height = rdouble(100)
- rect.theZ = rint(0)
- rect.theT = rint(0)
- rect.textValue = rstring("Auto ROI")
-
- roi = create_roi(conn, image, [rect])
- print(f"Created ROI for image {image.getName()}")
-```
-
-### Create ROIs Across Z-Stack
+The historical Python example uses
+`IRoi.getShapeStatsRestricted(shape_ids, z, t, channel_indices)`. Since
+`IRoi` is deprecated:
-```python
-image = conn.getObject("Image", image_id)
-size_z = image.getSizeZ()
-
-# Create rectangle on each Z-section
-shapes = []
-for z in range(size_z):
- rect = omero.model.RectangleI()
- rect.x = rdouble(100)
- rect.y = rdouble(100)
- rect.width = rdouble(50)
- rect.height = rdouble(50)
- rect.theZ = rint(z)
- rect.theT = rint(0)
- shapes.append(rect)
-
-# Single ROI with shapes across Z
-roi = create_roi(conn, image, shapes)
-```
+1. verify the method in the target server's generated API;
+2. cap shape and channel counts;
+3. preserve channel indexing (pixel channels are zero-based);
+4. record the exact server/client versions;
+5. do not describe the result as a replacement for a validated analysis
+ pipeline.
-## Complete Example
+For simple rectangular reads, a bounded pixel tile may be clearer:
```python
-from omero.gateway import BlitzGateway
-from omero.rtypes import rdouble, rint, rstring
-import omero.model
-
-HOST = 'omero.example.com'
-PORT = 4064
-USERNAME = 'user'
-PASSWORD = 'pass'
-
-def rgba_to_int(r, g, b, a=255):
- return int.from_bytes([r, g, b, a], byteorder='big', signed=True)
-
-with BlitzGateway(USERNAME, PASSWORD, host=HOST, port=PORT) as conn:
- # Get image
- image = conn.getObject("Image", image_id)
- print(f"Processing: {image.getName()}")
-
- # Create multiple ROIs
- updateService = conn.getUpdateService()
-
- # ROI 1: Rectangle
- roi1 = omero.model.RoiI()
- roi1.setImage(image._obj)
-
- rect = omero.model.RectangleI()
- rect.x = rdouble(50)
- rect.y = rdouble(50)
- rect.width = rdouble(100)
- rect.height = rdouble(100)
- rect.theZ = rint(0)
- rect.theT = rint(0)
- rect.textValue = rstring("Cell 1")
- rect.strokeColor = rint(rgba_to_int(255, 0, 0, 255))
-
- roi1.addShape(rect)
- roi1 = updateService.saveAndReturnObject(roi1)
- print(f"Created ROI 1: {roi1.getId().getValue()}")
-
- # ROI 2: Ellipse
- roi2 = omero.model.RoiI()
- roi2.setImage(image._obj)
-
- ellipse = omero.model.EllipseI()
- ellipse.x = rdouble(200)
- ellipse.y = rdouble(150)
- ellipse.radiusX = rdouble(40)
- ellipse.radiusY = rdouble(30)
- ellipse.theZ = rint(0)
- ellipse.theT = rint(0)
- ellipse.textValue = rstring("Cell 2")
- ellipse.strokeColor = rint(rgba_to_int(0, 255, 0, 255))
-
- roi2.addShape(ellipse)
- roi2 = updateService.saveAndReturnObject(roi2)
- print(f"Created ROI 2: {roi2.getId().getValue()}")
-
- # Retrieve and analyze
- roi_service = conn.getRoiService()
- result = roi_service.findByImage(image_id, None)
-
- shape_ids = []
- for roi in result.rois:
- for shape in roi.copyShapes():
- shape_ids.append(shape.id.val)
-
- # Get statistics
- stats = roi_service.getShapeStatsRestricted(shape_ids, 0, 0, [0])
-
- for i, stat in enumerate(stats):
- print(f"Shape {shape_ids[i]}:")
- print(f" Mean intensity: {stat.mean[0]:.2f}")
+pixels = image.getPrimaryPixels()
+z = 0
+c = 0
+t = 0
+x = 10
+y = 20
+width = 100
+height = 80
+
+tile = next(pixels.getTiles([(z, c, t, (x, y, width, height))]))
```
-## Best Practices
-
-1. **Organize Shapes**: Group related shapes in single ROIs
-2. **Label Shapes**: Use textValue for identification
-3. **Set Z and T**: Always specify Z-section and timepoint
-4. **Color Coding**: Use consistent colors for shape types
-5. **Validate Coordinates**: Ensure shapes are within image bounds
-6. **Batch Creation**: Create multiple ROIs in single transaction when possible
-7. **Delete Unused**: Remove temporary or test ROIs
-8. **Export Data**: Store ROI statistics in tables for later analysis
-9. **Version Control**: Document ROI creation methods in annotations
-10. **Performance**: Use shape statistics service instead of manual pixel extraction
+Confirm the current API's tile generator behavior and cap tile area. Polygon,
+polyline, ellipse, and mask measurements require a correctly defined raster
+mask; a bounding box alone is not the ROI.
+
+## Updates and Deletion
+
+Updating a shape and saving an ROI is a write that can affect downstream
+measurements. Deleting an ROI removes its shapes. Never add delete support to a
+read-only export script.
+
+Before update/delete:
+
+- show image, ROI, and shape IDs;
+- retrieve current values;
+- check permissions and group context;
+- obtain approval for the exact IDs;
+- avoid namespace/label-based bulk selection;
+- wait for command completion and verify the result.
+
+## ROI Export Checklist
+
+- Explicit image IDs only
+- One group context
+- Maximum images, ROIs per image, and shapes per ROI
+- Labels redacted by default
+- Mask bytes omitted
+- No pixel values unless separately requested
+- Plane selectors preserve `None`
+- Geometry strings have a length cap
+- `IRoi` deprecation recorded
+- Connection closed in `finally`
diff --git a/skills/omero-integration/references/scripts.md b/skills/omero-integration/references/scripts.md
index cddb73fa..afcd9122 100644
--- a/skills/omero-integration/references/scripts.md
+++ b/skills/omero-integration/references/scripts.md
@@ -1,637 +1,304 @@
-# Scripts & Batch Operations
+# Bundled Helpers and OMERO.server Scripts
-This reference covers creating OMERO.scripts for server-side processing and batch operations.
+The local files in this skill's `scripts/` directory are client-side safety
+helpers. They are not OMERO.server scripts and are never uploaded
+automatically.
-## OMERO.scripts Overview
+## Shared Safety Model
-OMERO.scripts are Python scripts that run on the OMERO server and can be called from OMERO clients (web, insight, CLI). They function as plugins that extend OMERO functionality.
+Every bundled executable:
-### Key Features
+- uses `argparse`;
+- supports `--help` without OMERO installed;
+- imports `omero` only after argument parsing and only for `--execute`;
+- reads only named `OMERO_*` variables;
+- never loads `.env`;
+- never accepts or prints a password/session key;
+- defaults to local validation or dry-run output;
+- applies hard limits;
+- refuses unsafe output collisions/symlinks;
+- closes remote connections in `finally`.
-- **Server-Side Execution**: Scripts run on the server, avoiding data transfer
-- **Client Integration**: Callable from any OMERO client with auto-generated UI
-- **Parameter Handling**: Define input parameters with validation
-- **Result Reporting**: Return images, files, or messages to clients
-- **Batch Processing**: Process multiple images or datasets efficiently
+Remote helpers require `--execute`. That flag authorizes a read-only
+connection, not broader scope or mutation.
-## Basic Script Structure
+## Local Endpoint Validation
-### Minimal Script Template
-
-```python
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
+```bash
+python -B scripts/validate_config.py
+python -B scripts/validate_config.py --require-auth --json
+```
-import omero
-from omero.gateway import BlitzGateway
-import omero.scripts as scripts
-from omero.rtypes import rlong, rstring, robject
+By default it performs only local syntax checks. `--resolve-host` performs DNS
+resolution but does not connect to an OMERO port.
-def run_script():
- """
- Main script function.
- """
- # Script definition
- client = scripts.client(
- 'Script_Name.py',
- """
- Description of what this script does.
- """,
+Output reports which named variables are present and the authentication mode.
+It never displays credential values.
- # Input parameters
- scripts.String("Data_Type", optional=False, grouping="1",
- description="Choose source of images",
- values=[rstring('Dataset'), rstring('Image')],
- default=rstring('Dataset')),
+Examples of failures:
- scripts.Long("IDs", optional=False, grouping="2",
- description="Dataset or Image ID(s)").ofType(rlong(0)),
+- host contains `http://`, a path, whitespace, or shell syntax;
+- port is not in `1..65535`;
+- `OMERO_SECURE` is not a recognized boolean;
+- only one of `OMERO_USER`/`OMERO_PASSWORD` is present;
+- `--require-auth` is used without either a session key or complete password
+ authentication.
- # Outputs
- namespaces=[omero.constants.namespaces.NSDYNAMIC],
- version="1.0"
- )
+## Read-Only Inventory
- try:
- # Get connection
- conn = BlitzGateway(client_obj=client)
+Dry run:
- # Get script parameters
- script_params = client.getInputs(unwrap=True)
- data_type = script_params["Data_Type"]
- ids = script_params["IDs"]
+```bash
+python -B scripts/inventory.py \
+ --object-type Image \
+ --limit 50 \
+ --page-size 25
+```
- # Process data
- message = process_data(conn, data_type, ids)
+Execute after reviewing endpoint/group/scope:
- # Return results
- client.setOutput("Message", rstring(message))
+```bash
+python -B scripts/inventory.py \
+ --object-type Image \
+ --limit 50 \
+ --page-size 25 \
+ --group-id 42 \
+ --execute \
+ --output ./image-inventory.json
+```
- finally:
- client.closeSession()
+Properties:
-def process_data(conn, data_type, ids):
- """
- Process images based on parameters.
- """
- # Implementation here
- return "Processing complete"
+- allowlisted object types only;
+- overall cap at 1000 and page cap at 200;
+- stable `obj.id` ordering request;
+- one optional explicit group, never cross-group `-1`;
+- object names redacted unless `--include-names`;
+- JSON output written atomically with owner-only permissions;
+- existing output refused unless `--overwrite`.
-if __name__ == "__main__":
- run_script()
-```
+`limit_reached` means the requested cap was filled; it does not assert that
+more server rows exist.
-## Script Parameters
+## Annotation and ROI Export
-### Parameter Types
+Dry run:
-```python
-# String parameter
-scripts.String("Name", optional=False,
- description="Enter a name")
-
-# String with choices
-scripts.String("Mode", optional=False,
- values=[rstring('Fast'), rstring('Accurate')],
- default=rstring('Fast'))
-
-# Integer parameter
-scripts.Long("ImageID", optional=False,
- description="Image to process").ofType(rlong(0))
-
-# List of integers
-scripts.List("ImageIDs", optional=False,
- description="Multiple images").ofType(rlong(0))
-
-# Float parameter
-scripts.Float("Threshold", optional=True,
- description="Threshold value",
- min=0.0, max=1.0, default=0.5)
-
-# Boolean parameter
-scripts.Bool("SaveResults", optional=True,
- description="Save results to OMERO",
- default=True)
+```bash
+python -B scripts/export_image_metadata.py \
+ --image-id 101 \
+ --image-id 102 \
+ --max-annotations-per-image 100 \
+ --max-rois-per-image 100 \
+ --max-shapes-per-roi 500 \
+ --output ./selected-image-metadata.json
```
-### Parameter Grouping
-
-```python
-# Group related parameters
-scripts.String("Data_Type", grouping="1",
- description="Source type",
- values=[rstring('Dataset'), rstring('Image')])
-
-scripts.Long("Dataset_ID", grouping="1.1",
- description="Dataset ID").ofType(rlong(0))
+Execute:
-scripts.List("Image_IDs", grouping="1.2",
- description="Image IDs").ofType(rlong(0))
+```bash
+python -B scripts/export_image_metadata.py \
+ --image-id 101 \
+ --image-id 102 \
+ --group-id 42 \
+ --execute \
+ --output ./selected-image-metadata.json
```
-## Accessing Input Data
+Default redactions:
-### Get Script Parameters
+- annotation values
+- owner names
+- FileAnnotation filenames
+- ROI/shape labels
+- mask bytes
-```python
-# Inside run_script()
-client = scripts.client(...)
+Optional inclusion flags are independent. The helper never retrieves pixels or
+FileAnnotation bytes. It uses the currently documented `IRoi.findByImage`
+pattern and records that `IRoi` is deprecated.
-# Get parameters as Python objects
-script_params = client.getInputs(unwrap=True)
+Because `findByImage` has no page argument, the ROI caps bound serialization
+but may not bound server-side assembly. Do not run it on a known extreme image
+without reviewing the ROI count or using a site-approved paginated API.
-# Access individual parameters
-data_type = script_params.get("Data_Type", "Image")
-image_ids = script_params.get("Image_IDs", [])
-threshold = script_params.get("Threshold", 0.5)
-save_results = script_params.get("SaveResults", True)
-```
+## Import/Export Planner
-### Get Images from Parameters
+The planner is always local and has no `--execute`.
-```python
-def get_images_from_params(conn, script_params):
- """
- Get image objects based on script parameters.
- """
- images = []
-
- data_type = script_params["Data_Type"]
-
- if data_type == "Dataset":
- dataset_id = script_params["Dataset_ID"]
- dataset = conn.getObject("Dataset", dataset_id)
- if dataset:
- images = list(dataset.listChildren())
-
- elif data_type == "Image":
- image_ids = script_params["Image_IDs"]
- for image_id in image_ids:
- image = conn.getObject("Image", image_id)
- if image:
- images.append(image)
+Import scan plan:
- return images
+```bash
+python -B scripts/plan_transfer.py import \
+ --target Dataset:id:42 \
+ --max-files 100 \
+ --scan-depth 4 \
+ ./explicit-input
```
-## Processing Images
+It walks only explicit paths, does not follow directory symlinks, caps depth
+and file count, and proposes `omero import -f` plus a future scoped import
+command. It does not invoke either.
-### Batch Image Processing
+Per-image export plan:
-```python
-def process_images(conn, images, threshold):
- """
- Process multiple images.
- """
- results = []
-
- for image in images:
- print(f"Processing: {image.getName()}")
-
- # Get pixel data
- pixels = image.getPrimaryPixels()
- size_z = image.getSizeZ()
- size_c = image.getSizeC()
- size_t = image.getSizeT()
-
- # Process each plane
- for z in range(size_z):
- for c in range(size_c):
- for t in range(size_t):
- plane = pixels.getPlane(z, c, t)
-
- # Apply threshold
- binary = (plane > threshold).astype(np.uint8)
-
- # Count features
- feature_count = count_features(binary)
-
- results.append({
- 'image_id': image.getId(),
- 'image_name': image.getName(),
- 'z': z, 'c': c, 't': t,
- 'feature_count': feature_count
- })
-
- return results
+```bash
+python -B scripts/plan_transfer.py export \
+ --format ome-tiff \
+ --output-dir ./reviewed-existing-directory \
+ Image:101 Image:102
```
-## Generating Outputs
+It accepts explicit `Image:<id>` selectors only, proposes one output per image,
+and reports collisions. Dataset iteration is intentionally excluded because
+the official export mode is experimental and too easy to broaden.
-### Return Messages
+Global `--output` and `--overwrite` arguments must precede the subcommand:
-```python
-# Simple message
-message = "Processed 10 images successfully"
-client.setOutput("Message", rstring(message))
-
-# Detailed message
-message = "Results:\n"
-for result in results:
- message += f"Image {result['image_id']}: {result['count']} cells\n"
-client.setOutput("Message", rstring(message))
+```bash
+python -B scripts/plan_transfer.py \
+ --output ./transfer-plan.json \
+ import ./explicit-input
```
-### Return Images
+No proposed command includes `-w`, `--password`, `-k`, or a session value.
-```python
-# Return newly created image
-new_image = conn.createImageFromNumpySeq(...)
-client.setOutput("New_Image", robject(new_image._obj))
-```
+## Running Local Tests
-### Return Files
+No real OMERO server is needed:
-```python
-# Create and return file annotation
-file_ann = conn.createFileAnnfromLocalFile(
- output_file_path,
- mimetype="text/csv",
- ns="analysis.results"
-)
-
-client.setOutput("Result_File", robject(file_ann._obj))
+```bash
+PYTHONDONTWRITEBYTECODE=1 \
+ python -B -m unittest discover \
+ -s skills/omero-integration/tests \
+ -p "test_*.py"
```
-### Return Tables
+The tests use temporary directories and fake gateway objects.
-```python
-# Create OMERO table and return
-resources = conn.c.sf.sharedResources()
-table = create_results_table(resources, results)
-orig_file = table.getOriginalFile()
-table.close()
-
-# Create file annotation
-file_ann = omero.model.FileAnnotationI()
-file_ann.setFile(orig_file)
-file_ann = conn.getUpdateService().saveAndReturnObject(file_ann)
-
-client.setOutput("Results_Table", robject(file_ann._obj))
-```
+## OMERO.server Script Model
-## Complete Example Scripts
+OMERO.server scripts are Python plugins registered with the Script Service.
+Clients can launch them and receive typed outputs. Inputs often include an
+explicit data type, object IDs, thresholds, or options.
-### Example 1: Maximum Intensity Projection
+A minimal structure:
```python
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-
import omero
-from omero.gateway import BlitzGateway
import omero.scripts as scripts
-from omero.rtypes import rlong, rstring, robject
-import numpy as np
-
-def run_script():
- client = scripts.client(
- 'Maximum_Intensity_Projection.py',
- """
- Creates maximum intensity projection from Z-stack images.
- """,
-
- scripts.String("Data_Type", optional=False, grouping="1",
- description="Process images from",
- values=[rstring('Dataset'), rstring('Image')],
- default=rstring('Image')),
-
- scripts.List("IDs", optional=False, grouping="2",
- description="Dataset or Image ID(s)").ofType(rlong(0)),
-
- scripts.Bool("Link_to_Source", optional=True, grouping="3",
- description="Link results to source dataset",
- default=True),
-
- version="1.0"
- )
-
- try:
- conn = BlitzGateway(client_obj=client)
- script_params = client.getInputs(unwrap=True)
-
- # Get images
- images = get_images(conn, script_params)
- created_images = []
-
- for image in images:
- print(f"Processing: {image.getName()}")
-
- # Create MIP
- mip_image = create_mip(conn, image)
- if mip_image:
- created_images.append(mip_image)
-
- # Report results
- if created_images:
- message = f"Created {len(created_images)} MIP images"
- # Return first image for display
- client.setOutput("Message", rstring(message))
- client.setOutput("Result", robject(created_images[0]._obj))
- else:
- client.setOutput("Message", rstring("No images created"))
-
- finally:
- client.closeSession()
-
-def get_images(conn, script_params):
- """Get images from script parameters."""
- images = []
- data_type = script_params["Data_Type"]
- ids = script_params["IDs"]
-
- if data_type == "Dataset":
- for dataset_id in ids:
- dataset = conn.getObject("Dataset", dataset_id)
- if dataset:
- images.extend(list(dataset.listChildren()))
- else:
- for image_id in ids:
- image = conn.getObject("Image", image_id)
- if image:
- images.append(image)
-
- return images
-
-def create_mip(conn, source_image):
- """Create maximum intensity projection."""
- pixels = source_image.getPrimaryPixels()
- size_z = source_image.getSizeZ()
- size_c = source_image.getSizeC()
- size_t = source_image.getSizeT()
-
- if size_z == 1:
- print(" Skipping (single Z-section)")
- return None
-
- def plane_gen():
- for c in range(size_c):
- for t in range(size_t):
- # Get Z-stack
- z_stack = []
- for z in range(size_z):
- plane = pixels.getPlane(z, c, t)
- z_stack.append(plane)
-
- # Maximum projection
- max_proj = np.max(z_stack, axis=0)
- yield max_proj
-
- # Create new image
- new_image = conn.createImageFromNumpySeq(
- plane_gen(),
- f"{source_image.getName()}_MIP",
- 1, size_c, size_t,
- description="Maximum intensity projection",
- dataset=source_image.getParent()
- )
-
- return new_image
-
-if __name__ == "__main__":
- run_script()
-```
-
-### Example 2: Batch ROI Analysis
-
-```python
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-
-import omero
from omero.gateway import BlitzGateway
-import omero.scripts as scripts
-from omero.rtypes import rlong, rstring, robject
-import omero.grid
-
-def run_script():
- client = scripts.client(
- 'Batch_ROI_Analysis.py',
- """
- Analyzes ROIs across multiple images and creates results table.
- """,
+from omero.rtypes import rlong, rstring
- scripts.Long("Dataset_ID", optional=False,
- description="Dataset with images and ROIs").ofType(rlong(0)),
- scripts.Long("Channel_Index", optional=True,
- description="Channel to analyze (0-indexed)",
- default=0, min=0),
-
- version="1.0"
+def main():
+ client = scripts.client(
+ "Bounded_Image_Summary.py",
+ "Returns IDs for an explicit bounded image list.",
+ scripts.List(
+ "Image_IDs",
+ optional=False,
+ description="Explicit image IDs (maximum enforced by script)",
+ ).ofType(rlong(0)),
+ namespaces=[omero.constants.namespaces.NSDYNAMIC],
+ version="1.0",
)
try:
- conn = BlitzGateway(client_obj=client)
- script_params = client.getInputs(unwrap=True)
-
- dataset_id = script_params["Dataset_ID"]
- channel_index = script_params["Channel_Index"]
-
- # Get dataset
- dataset = conn.getObject("Dataset", dataset_id)
- if not dataset:
- client.setOutput("Message", rstring("Dataset not found"))
- return
-
- # Analyze ROIs
- results = analyze_rois(conn, dataset, channel_index)
+ inputs = client.getInputs(unwrap=True)
+ image_ids = list(inputs["Image_IDs"])
+ if not 1 <= len(image_ids) <= 25:
+ raise ValueError("Image_IDs must contain 1..25 IDs")
- # Create table
- table_file = create_results_table(conn, dataset, results)
-
- # Report
- message = f"Analyzed {len(results)} ROIs from {dataset.getName()}"
- client.setOutput("Message", rstring(message))
- client.setOutput("Results_Table", robject(table_file._obj))
+ conn = BlitzGateway(client_obj=client)
+ found = []
+ for image_id in image_ids:
+ image = conn.getObject("Image", image_id)
+ if image is not None:
+ found.append(image.getId())
+ client.setOutput("Message", rstring(f"Found {len(found)} images"))
finally:
client.closeSession()
-def analyze_rois(conn, dataset, channel_index):
- """Analyze all ROIs in dataset images."""
- roi_service = conn.getRoiService()
- results = []
-
- for image in dataset.listChildren():
- result = roi_service.findByImage(image.getId(), None)
-
- if not result.rois:
- continue
-
- # Get shape IDs
- shape_ids = []
- for roi in result.rois:
- for shape in roi.copyShapes():
- shape_ids.append(shape.id.val)
-
- # Get statistics
- stats = roi_service.getShapeStatsRestricted(
- shape_ids, 0, 0, [channel_index]
- )
-
- # Store results
- for i, stat in enumerate(stats):
- results.append({
- 'image_id': image.getId(),
- 'image_name': image.getName(),
- 'shape_id': shape_ids[i],
- 'mean': stat.mean[channel_index],
- 'min': stat.min[channel_index],
- 'max': stat.max[channel_index],
- 'sum': stat.sum[channel_index],
- 'area': stat.pointsCount[channel_index]
- })
-
- return results
-
-def create_results_table(conn, dataset, results):
- """Create OMERO table from results."""
- # Prepare data
- image_ids = [r['image_id'] for r in results]
- shape_ids = [r['shape_id'] for r in results]
- means = [r['mean'] for r in results]
- mins = [r['min'] for r in results]
- maxs = [r['max'] for r in results]
- sums = [r['sum'] for r in results]
- areas = [r['area'] for r in results]
-
- # Create table
- resources = conn.c.sf.sharedResources()
- repository_id = resources.repositories().descriptions[0].getId().getValue()
- table = resources.newTable(repository_id, f"ROI_Analysis_{dataset.getId()}")
-
- # Define columns
- columns = [
- omero.grid.ImageColumn('Image', 'Source image', []),
- omero.grid.LongColumn('ShapeID', 'ROI shape ID', []),
- omero.grid.DoubleColumn('Mean', 'Mean intensity', []),
- omero.grid.DoubleColumn('Min', 'Min intensity', []),
- omero.grid.DoubleColumn('Max', 'Max intensity', []),
- omero.grid.DoubleColumn('Sum', 'Integrated density', []),
- omero.grid.LongColumn('Area', 'Area in pixels', [])
- ]
- table.initialize(columns)
-
- # Add data
- data = [
- omero.grid.ImageColumn('Image', 'Source image', image_ids),
- omero.grid.LongColumn('ShapeID', 'ROI shape ID', shape_ids),
- omero.grid.DoubleColumn('Mean', 'Mean intensity', means),
- omero.grid.DoubleColumn('Min', 'Min intensity', mins),
- omero.grid.DoubleColumn('Max', 'Max intensity', maxs),
- omero.grid.DoubleColumn('Sum', 'Integrated density', sums),
- omero.grid.LongColumn('Area', 'Area in pixels', areas)
- ]
- table.addData(data)
-
- orig_file = table.getOriginalFile()
- table.close()
-
- # Link to dataset
- file_ann = omero.model.FileAnnotationI()
- file_ann.setFile(orig_file)
- file_ann = conn.getUpdateService().saveAndReturnObject(file_ann)
-
- link = omero.model.DatasetAnnotationLinkI()
- link.setParent(dataset._obj)
- link.setChild(file_ann)
- conn.getUpdateService().saveAndReturnObject(link)
-
- return file_ann
if __name__ == "__main__":
- run_script()
+ main()
```
-## Script Deployment
+The script session is supplied by OMERO. Do not read a password or create a
+second login inside a server script.
-### Installation Location
+## Server-Script Safety
-Scripts should be placed in the OMERO server scripts directory:
-```
-OMERO_DIR/lib/scripts/
-```
+Even a server script that only reads can be expensive. It must enforce:
-### Recommended Structure
+- maximum ID count;
+- per-container child cap;
+- plane/tile/byte limits;
+- fixed group context;
+- no cross-group fallback;
+- no user-controlled HQL/code strings;
+- bounded output size;
+- `client.closeSession()` in `finally`.
-```
-lib/scripts/
-├── analysis/
-│ ├── Cell_Counter.py
-│ └── ROI_Analyzer.py
-├── export/
-│ ├── Export_Images.py
-│ └── Export_ROIs.py
-└── util/
- └── Helper_Functions.py
-```
+For writes, additionally require an explicit “save” input or other reviewed
+gate and document every created/linked object. A client-side confirmation is
+not enough if the server script itself accepts unbounded inputs.
-### Testing Scripts
+Do not use Python `eval()` or `exec()` for parameters. Do not interpolate
+parameter text into HQL, filesystem paths, commands, or table conditions.
-```bash
-# Test script syntax
-python Script_Name.py
+## Upload and Launch
-# Upload to OMERO
-omero script upload Script_Name.py
+Uploading registers executable code and is a mutation:
-# List scripts
+```bash
+omero script upload ./Bounded_Image_Summary.py
omero script list
-
-# Run script from CLI
-omero script launch Script_ID Dataset_ID=123
```
-## Best Practices
-
-1. **Error Handling**: Always use try-finally to close session
-2. **Progress Updates**: Print status messages for long operations
-3. **Parameter Validation**: Check parameters before processing
-4. **Memory Management**: Process large datasets in batches
-5. **Documentation**: Include clear description and parameter docs
-6. **Versioning**: Include version number in script
-7. **Namespaces**: Use appropriate namespaces for outputs
-8. **Return Objects**: Return created objects for client display
-9. **Logging**: Use print() for server logs
-10. **Testing**: Test with various input combinations
-
-## Common Patterns
+Before upload:
-### Progress Reporting
-
-```python
-total = len(images)
-for idx, image in enumerate(images):
- print(f"Processing {idx + 1}/{total}: {image.getName()}")
- # Process image
-```
+1. review source and dependencies;
+2. validate against the target OMERO.py/server pairing;
+3. confirm destination script path/category;
+4. confirm administrator authorization;
+5. record returned script ID/version.
-### Error Collection
+Launching is also a remote operation:
-```python
-errors = []
-for image in images:
- try:
- process_image(image)
- except Exception as e:
- errors.append(f"{image.getName()}: {str(e)}")
-
-if errors:
- message = "Completed with errors:\n" + "\n".join(errors)
-else:
- message = "All images processed successfully"
+```bash
+omero script launch <SCRIPT_ID> Image_IDs=101,102
```
-### Resource Cleanup
-
-```python
-try:
- # Script processing
- pass
-finally:
- # Clean up temporary files
- if os.path.exists(temp_file):
- os.remove(temp_file)
- client.closeSession()
-```
+Use an already prompted session. Confirm the exact script ID, version, group,
+input IDs, expected writes, and resource limits. Never launch based only on a
+script display name.
+
+## Outputs and Temporary Files
+
+Server scripts may return strings, objects, images, or FileAnnotations. For a
+file output:
+
+- use a server-side temporary directory designed for scripts;
+- generate a safe filename independent of user text;
+- cap bytes;
+- classify content before attaching;
+- remove local temporary files in `finally`;
+- close any table or raw store before closing the script session.
+
+Do not place server paths, credentials, session IDs, or stack traces in client
+outputs.
+
+## Script Review Checklist
+
+- Client helper or server plugin clearly identified
+- Dry run and execution separated
+- Credentials absent from arguments/output
+- Object/group/file scope explicit
+- Hard bounds at every expansion
+- Output path safe and collision-aware
+- Lazy optional imports for local helpers
+- Stateful resources closed
+- `IRoi`/other deprecated service dependencies documented
+- No real-server test performed without explicit authorization
diff --git a/skills/omero-integration/references/sources.md b/skills/omero-integration/references/sources.md
new file mode 100644
index 00000000..74181336
--- /dev/null
+++ b/skills/omero-integration/references/sources.md
@@ -0,0 +1,194 @@
+# Official Sources and Version Snapshot
+
+Research date: **2026-07-23**
+
+This file records the authoritative basis for skill version 1.2. The snapshot
+must not replace checking the target server's own version and discovery
+endpoints.
+
+## Current Versions
+
+- **OMERO.server 5.6.18** — May 2026 bug-fix release.
+- **OMERO.py / `omero-py` 5.22.1** — released 2026-03-25.
+- **OMERO.web 5.31.0** — the version tested with OMERO.server 5.6.18.
+- **Bio-Formats 8.5.0** — bundled by OMERO.server 5.6.18.
+- **ZeroC IcePy 3.6.5** — exact client binding version in current official
+ installation examples and OMERO-linked wheel matrix.
+
+The OMERO.server history explicitly says 5.6.18 was tested with OMERO.py
+5.22.1 and OMERO.web 5.31.0. That tested pairing is stronger evidence than
+assuming compatibility from package version numbers.
+
+## Release and Package Metadata
+
+- OMERO version history
+ https://omero.readthedocs.io/en/stable/users/history.html
+ Basis for server 5.6.18, tested client/web pairing, and Bio-Formats 8.5.0.
+
+- `omero-py` on PyPI
+ https://pypi.org/project/omero-py/
+ Basis for 5.22.1, 2026-03-25 release date, Python `>=3.10`, IcePy 3.6,
+ NumPy/Pillow requirements, OMERODIR notes, and GPL-2.0-or-later package
+ license.
+
+- Official OME `omero-py` repository and changelog
+ https://github.com/ome/omero-py
+ https://github.com/ome/omero-py/blob/v5.22.1/CHANGELOG.md
+ Basis for recent Python/NumPy compatibility and historical deprecations.
+
+- Official OME OMERO.server component releases
+ https://github.com/ome/omero-server/releases
+ Cross-check for current server component releases.
+
+## Installation and Compatibility
+
+- OMERO Python language bindings
+ https://omero.readthedocs.io/en/stable/developers/Python.html
+ Basis for the current `omero-py==5.22.1` examples, IcePy 3.6.5 ordering,
+ BlitzGateway patterns, objects, annotations, tables, ROIs, pixels, and
+ rendering.
+
+- OMERO version requirements
+ https://omero.readthedocs.io/en/stable/sysadmins/version-requirements.html
+ Basis for Python 3.10/3.11 support, Python 3.12 recommendation,
+ Python 3.13/3.14 “upcoming” status, Ice 3.6 recommendation, Ice 3.7
+ unsupported status, and server platform/runtime matrix.
+
+- OMERO-linked Glencoe Ice binary matrix
+ https://www.glencoesoftware.com/blog/2023/12/08/ice-binaries-for-omero.html
+ Basis for exact prebuilt IcePy 3.6.5 wheel coverage through Python 3.12.
+ Glencoe is identified in OME's Python installation page as its commercial
+ partner. Select the exact wheel from the linked release repositories.
+
+- OMERO CLI installation
+ https://omero.readthedocs.io/en/stable/users/cli/installation.html
+ Basis for client installation and import/admin prerequisites.
+
+## Connection and Security
+
+- BlitzGateway documentation
+ https://omero.readthedocs.io/en/stable/developers/PythonBlitzGateway.html
+ Basis for context-manager closure, wrappers/lazy loading, stateless versus
+ stateful service reuse, and stale stateful proxies after reconnection.
+
+- Server security and firewalls
+ https://omero.readthedocs.io/en/stable/sysadmins/server-security.html
+ Basis for login encryption, optional full transport encryption, session-ID
+ exposure on insecure post-login traffic, and default router ports 4063/4064.
+
+- Client/server SSL verification
+ https://omero.readthedocs.io/en/stable/sysadmins/client-server-ssl.html
+ Basis for the warning that standard clients do not automatically verify the
+ host and for the documented IceSSL verification properties.
+
+- CLI session management
+ https://omero.readthedocs.io/en/stable/users/cli/sessions.html
+ Basis for prompted login, session files, `omero sessions`, group switching,
+ `-k` session reuse, and logout.
+
+## Data, Metadata, ROIs, and Tables
+
+- OMERO Python examples
+ https://omero.readthedocs.io/en/stable/developers/Python.html
+ Primary current examples for bounded `getObjects`, annotations, pixels,
+ rendering, tables, and ROI model operations.
+
+- OMERO.tables
+ https://omero.readthedocs.io/en/stable/developers/Tables.html
+ Basis for current column signatures, reads, queries, paging, global locking,
+ and HDF implementation details.
+
+- Structured annotations
+ https://omero.readthedocs.io/en/stable/developers/Model/StructuredAnnotations.html
+ Basis for annotation type hierarchy, namespaces, and link semantics.
+
+- OME ROI model 5.6.3
+ https://docs.openmicroscopy.org/ome-model/5.6.3/developers/roi.html
+ Basis for the eight shape types, optional TheZ/TheT/TheC, RGBA fields, and
+ union-of-2D-shapes representation. The page itself was last updated in 2018
+ but documents the June 2016 schema still used by OMERO 5.6.
+
+- Current generated `IRoi` API
+ https://docs.openmicroscopy.org/omero-blitz/5.8.5/slice2html/omero/api/IRoi.html
+ Basis for the explicit `IRoi` deprecation warning.
+
+- OMERO application services
+ https://omero.readthedocs.io/en/stable/developers/Modules/Api.html
+ Basis for service categories and current `IRoi`/`IShare` deprecation status.
+
+## CLI Import, Export, and Download
+
+- Import images
+ https://omero.readthedocs.io/en/stable/users/cli/import.html
+ Basis for `omero import`, `-f` serverless scanning, target syntax,
+ depth/output options, experimental parallelism warning, and diagnostic
+ upload disclosure.
+
+- Import targets
+ https://omero.readthedocs.io/en/stable/users/cli/import-target.html
+ Basis for current-group target behavior and target syntax.
+
+- Export images
+ https://omero.readthedocs.io/en/stable/users/cli/export.html
+ Basis for OME-TIFF/XML-only export and experimental Dataset iteration.
+
+- Current `omero-py==5.22.1` CLI help (`omero download -h`)
+ Verified in an isolated environment on 2026-07-23. Basis for explicit
+ OriginalFile, FileAnnotation, Image, and Fileset download forms. This was
+ cross-checked against the official `ome/omero-py` package.
+
+## OMERO.web and Public Data
+
+- OMERO.web framework
+ https://omero.readthedocs.io/en/stable/developers/Web.html
+ Basis for treating only `api` and `webgateway` as stable public APIs and
+ treating other app URLs as internal.
+
+- OMERO JSON API
+ https://omero.readthedocs.io/en/stable/developers/json-api.html
+ Basis for version discovery, API version headers, CSRF/login behavior,
+ pagination/maxLimit, ROI endpoints, and limited create/update object types.
+
+- Publishing data using OMERO.web
+ https://omero.readthedocs.io/en/stable/sysadmins/public.html
+ Basis for dedicated read-only public groups/users, GET-only default, URL
+ filters, and publication URL examples.
+
+- OMERO configuration properties
+ https://omero.readthedocs.io/en/stable/sysadmins/config.html
+ Basis for public-user defaults (`enabled=false`, `get_only=true`, and a
+ URL filter that allows nothing until configured).
+
+## Research Method
+
+The refresh used focused `parallel-cli search` queries restricted primarily to:
+
+- `omero.readthedocs.io`
+- `docs.openmicroscopy.org`
+- `ome-model.readthedocs.io`
+- `openmicroscopy.org`
+- `pypi.org`
+- official `github.com/ome/*` repositories
+
+Canonical pages above were then fetched with `parallel-cli extract` using
+objectives specific to versions, Python/Ice compatibility, connection
+security, BlitzGateway APIs, CLI behavior, tables, ROIs/annotations,
+rendering, and OMERO.web/public APIs.
+
+No Parallel JSON research artifacts were written into the repository.
+
+## Known Documentation Tensions
+
+- PyPI declares Python `>=3.10` without an upper bound, while the OMERO support
+ matrix currently supports through 3.12 and marks 3.13/3.14 upcoming.
+ Installation is also constrained by matching IcePy wheels. This skill uses
+ Python 3.12 as the reproducible recommendation.
+- Current Python docs still demonstrate `IRoi` while the generated API marks
+ the interface deprecated. The skill documents and isolates this dependency
+ rather than pretending a replacement is official.
+- OMERO.web documents webclient publication links, while separately stating
+ that webclient is not a stable public API. Durable publication links should
+ use administrator-managed redirects/DOIs.
+- `secure=True` encrypts traffic but standard clients do not automatically
+ provide full hostname verification. High-assurance deployments need the
+ administrator-provided IceSSL trust/name configuration.
diff --git a/skills/omero-integration/references/tables.md b/skills/omero-integration/references/tables.md
index 3d84c90c..63f34257 100644
--- a/skills/omero-integration/references/tables.md
+++ b/skills/omero-integration/references/tables.md
@@ -1,532 +1,269 @@
-# OMERO Tables
+# OMERO.tables
-This reference covers creating and managing structured tabular data in OMERO using OMERO.tables.
+OMERO.tables stores columnar analysis data as an `OriginalFile` backed by an
+HDF table. Treat table reads as data exports and table creation/update as
+server writes.
-## OMERO.tables Overview
+## Compatibility and Scope
-OMERO.tables provides a way to store structured tabular data associated with OMERO objects. Tables are stored as HDF5 files and can be queried efficiently. Common use cases include:
+The current stable OMERO.tables definition is part of `omero-blitz` 5.8.5 in
+the OMERO.server 5.6.18 documentation. OMERO.server 5.6.12 specifically
+required OMERO.py 5.19.4 for the Tables service to start correctly, which
+illustrates why client/server pairing matters.
-- Storing quantitative measurements from images
-- Recording analysis results
-- Tracking experimental metadata
-- Linking measurements to specific images or ROIs
+Before using tables:
-## Column Types
-
-OMERO.tables supports various column types:
-
-- **LongColumn**: Integer values (64-bit)
-- **DoubleColumn**: Floating-point values
-- **StringColumn**: Text data (fixed max length)
-- **BoolColumn**: Boolean values
-- **LongArrayColumn**: Arrays of integers
-- **DoubleArrayColumn**: Arrays of floats
-- **FileColumn**: References to OMERO files
-- **ImageColumn**: References to OMERO images
-- **RoiColumn**: References to OMERO ROIs
-- **WellColumn**: References to OMERO wells
-
-## Creating Tables
-
-### Basic Table Creation
-
-```python
-from random import random
-import omero.grid
-
-# Create unique table name
-table_name = f"MyAnalysisTable_{random()}"
-
-# Define columns (empty data for initialization)
-col1 = omero.grid.LongColumn('ImageID', 'Image identifier', [])
-col2 = omero.grid.DoubleColumn('MeanIntensity', 'Mean pixel intensity', [])
-col3 = omero.grid.StringColumn('Category', 'Classification', 64, [])
-
-columns = [col1, col2, col3]
-
-# Get resources and create table
-resources = conn.c.sf.sharedResources()
-repository_id = resources.repositories().descriptions[0].getId().getValue()
-table = resources.newTable(repository_id, table_name)
-
-# Initialize table with column definitions
-table.initialize(columns)
-```
-
-### Add Data to Table
-
-```python
-# Prepare data
-image_ids = [1, 2, 3, 4, 5]
-intensities = [123.4, 145.2, 98.7, 156.3, 132.8]
-categories = ["Good", "Good", "Poor", "Excellent", "Good"]
-
-# Create data columns
-data_col1 = omero.grid.LongColumn('ImageID', 'Image identifier', image_ids)
-data_col2 = omero.grid.DoubleColumn('MeanIntensity', 'Mean pixel intensity', intensities)
-data_col3 = omero.grid.StringColumn('Category', 'Classification', 64, categories)
-
-data = [data_col1, data_col2, data_col3]
-
-# Add data to table
-table.addData(data)
-
-# Get file reference
-orig_file = table.getOriginalFile()
-table.close() # Always close table when done
-```
-
-### Link Table to Dataset
-
-```python
-# Create file annotation from table
-orig_file_id = orig_file.id.val
-file_ann = omero.model.FileAnnotationI()
-file_ann.setFile(omero.model.OriginalFileI(orig_file_id, False))
-file_ann = conn.getUpdateService().saveAndReturnObject(file_ann)
-
-# Link to dataset
-link = omero.model.DatasetAnnotationLinkI()
-link.setParent(omero.model.DatasetI(dataset_id, False))
-link.setChild(omero.model.FileAnnotationI(file_ann.getId().getValue(), False))
-conn.getUpdateService().saveAndReturnObject(link)
-
-print(f"Linked table to dataset {dataset_id}")
-```
-
-## Column Types in Detail
+- confirm the server's tested OMERO.py version;
+- confirm the Tables service is active;
+- select one group and one table/attached object;
+- cap columns and rows;
+- plan handle closure even after read/query failure.
-### Long Column (Integers)
+## Column Types
-```python
-# Column for integer values
-image_ids = [101, 102, 103, 104, 105]
-col = omero.grid.LongColumn('ImageID', 'Image identifier', image_ids)
-```
+Current scalar columns:
-### Double Column (Floats)
+- `FileColumn`, `ImageColumn`, `RoiColumn`, `WellColumn`, `PlateColumn`
+- `BoolColumn`
+- `LongColumn` (signed 64-bit)
+- `DoubleColumn` (64-bit)
+- `StringColumn(name, description, size, values)`
-```python
-# Column for floating-point values
-measurements = [12.34, 56.78, 90.12, 34.56, 78.90]
-col = omero.grid.DoubleColumn('Measurement', 'Value in microns', measurements)
-```
+Current fixed-width array columns include:
-### String Column (Text)
+- `FloatArrayColumn(name, description, size, values)`
+- `DoubleArrayColumn(name, description, size, values)`
+- `LongArrayColumn(name, description, size, values)`
-```python
-# Column for text (max length required)
-labels = ["Control", "Treatment A", "Treatment B", "Control", "Treatment A"]
-col = omero.grid.StringColumn('Condition', 'Experimental condition', 64, labels)
-```
+The array `size` argument is required. Older examples that omit it are stale.
+All columns added in one operation must contain the same number of rows.
+Column names are unique; names beginning with double underscore are reserved.
-### Boolean Column
+The service performs limited validation of string and array lengths. Validate
+every value against the initialized schema before writing.
-```python
-# Column for boolean values
-flags = [True, False, True, True, False]
-col = omero.grid.BoolColumn('QualityPass', 'Passes quality control', flags)
-```
+## Read-Only Table Inspection
-### Image Column (References to Images)
+Start from one explicit `OriginalFile` ID, not a filename search:
```python
-# Column linking to OMERO images
-image_ids = [101, 102, 103, 104, 105]
-col = omero.grid.ImageColumn('Image', 'Source image', image_ids)
-```
+original_file_id = 123
+max_rows = 100
+max_columns = 20
-### ROI Column (References to ROIs)
+original = conn.getObject("OriginalFile", original_file_id)
+if original is None:
+ raise LookupError("Table OriginalFile unavailable")
-```python
-# Column linking to OMERO ROIs
-roi_ids = [201, 202, 203, 204, 205]
-col = omero.grid.RoiColumn('ROI', 'Associated ROI', roi_ids)
-```
-
-### Array Columns
-
-```python
-# Column for arrays of doubles
-histogram_data = [
- [10, 20, 30, 40],
- [15, 25, 35, 45],
- [12, 22, 32, 42]
-]
-col = omero.grid.DoubleArrayColumn('Histogram', 'Intensity histogram', histogram_data)
-
-# Column for arrays of longs
-bin_counts = [[5, 10, 15], [8, 12, 16], [6, 11, 14]]
-col = omero.grid.LongArrayColumn('Bins', 'Histogram bins', bin_counts)
-```
-
-## Reading Table Data
-
-### Open Existing Table
-
-```python
-# Get table file by name
-orig_table_file = conn.getObject("OriginalFile",
- attributes={'name': table_name})
-
-# Open table
resources = conn.c.sf.sharedResources()
-table = resources.openTable(orig_table_file._obj)
-
-print(f"Opened table: {table.getOriginalFile().getName().getValue()}")
-print(f"Number of rows: {table.getNumberOfRows()}")
+table = resources.openTable(original._obj)
+try:
+ headers = list(table.getHeaders())
+ if len(headers) > max_columns:
+ raise ValueError("Table has more columns than approved")
+
+ row_count = table.getNumberOfRows()
+ stop = min(row_count, max_rows)
+ column_indices = list(range(len(headers)))
+ data = table.read(column_indices, 0, stop)
+
+ print(
+ {
+ "original_file_id": original_file_id,
+ "total_rows": row_count,
+ "returned_rows": stop,
+ "truncated": row_count > stop,
+ "columns": [column.name for column in headers],
+ }
+ )
+finally:
+ table.close()
```
-### Read All Data
+`read(colNumbers, start, stop)` uses a stop-exclusive row range, except the
+current docs note that `start=0, stop=0` returns the first row. Avoid that edge
+case: do not call `read` when the approved row count is zero.
-```python
-# Get column headers
-print("Columns:")
-for col in table.getHeaders():
- print(f" {col.name}: {col.description}")
+Other current read methods:
-# Read all data
-row_count = table.getNumberOfRows()
-data = table.readCoordinates(range(row_count))
+- `readCoordinates(rowNumbers)`: complete rows at explicit indices
+- `slice(colNumbers, rowNumbers)`: selected columns and rows
+- `getWhereList(condition, variables, start, stop, step)`: matching row
+ indices, which can then be passed to `readCoordinates`
-# Display data
-for col in data.columns:
- print(f"\nColumn: {col.name}")
- for value in col.values:
- print(f" {value}")
+An empty column or row selection in `slice` may mean “all,” so never use empty
+lists as a safety limit.
-table.close()
-```
+## Paged Read
-### Read Specific Rows
+Read consecutive chunks instead of every row:
```python
-# Read rows 10-20
-start = 10
-stop = 20
-data = table.read(list(range(table.getHeaders().__len__())), start, stop)
-
-for col in data.columns:
- print(f"Column: {col.name}")
- for value in col.values:
- print(f" {value}")
+def iter_table_pages(table, column_indices, *, limit=1000, page_size=100):
+ if not 1 <= limit <= 10_000:
+ raise ValueError("limit out of range")
+ if not 1 <= page_size <= min(limit, 500):
+ raise ValueError("page_size out of range")
+
+ total = min(table.getNumberOfRows(), limit)
+ start = 0
+ while start < total:
+ stop = min(start + page_size, total)
+ yield table.read(column_indices, start, stop)
+ start = stop
```
-### Read Specific Columns
+Do not accumulate all pages unless the total cap and memory cost were reviewed.
+Large string/array columns can make a small row count expensive.
-```python
-# Read only columns 0 and 2
-column_indices = [0, 2]
-start = 0
-stop = table.getNumberOfRows()
-
-data = table.read(column_indices, start, stop)
-
-for col in data.columns:
- print(f"Column: {col.name}")
- print(f"Values: {col.values}")
-```
+## Fixed Queries and Bound Variables
-## Querying Tables
-
-### Query with Conditions
+OMERO.tables uses PyTables condition syntax. Keep the condition code fixed and
+bind user values:
```python
-# Query rows where MeanIntensity > 100
-row_count = table.getNumberOfRows()
+from omero.rtypes import rint
-query_rows = table.getWhereList(
- "(MeanIntensity > 100)",
- variables={},
+row_count = table.getNumberOfRows()
+max_rows_considered = min(row_count, 1000)
+matches = table.getWhereList(
+ condition="(Image > minimum_id)",
+ variables={"minimum_id": rint(100)},
start=0,
- stop=row_count,
- step=0
+ stop=max_rows_considered,
+ step=0,
)
-
-print(f"Found {len(query_rows)} matching rows")
-
-# Read matching rows
-data = table.readCoordinates(query_rows)
-
-for col in data.columns:
- print(f"\n{col.name}:")
- for value in col.values:
- print(f" {value}")
+matches = list(matches[:100])
+data = table.readCoordinates(matches)
```
-### Complex Queries
+Never concatenate user text into a condition. Validate column names against
+`getHeaders()` and map requested operations to a fixed allowlist.
-```python
-# Multiple conditions with AND
-query_rows = table.getWhereList(
- "(MeanIntensity > 100) & (MeanIntensity < 150)",
- variables={},
- start=0,
- stop=row_count,
- step=0
-)
+The documented condition language includes logical, comparison, arithmetic,
+and selected mathematical operations. Treat it as a query language, not as
+arbitrary Python. Do not use Python `eval()` or `exec()` around it.
-# Multiple conditions with OR
-query_rows = table.getWhereList(
- "(Category == 'Good') | (Category == 'Excellent')",
- variables={},
- start=0,
- stop=row_count,
- step=0
-)
+## Creating a Table
-# String matching
-query_rows = table.getWhereList(
- "(Category == 'Good')",
- variables={},
- start=0,
- stop=row_count,
- step=0
-)
-```
-
-## Complete Example: Image Analysis Results
+Creation is a write. Use a unique, caller-reviewed name and one selected
+repository:
```python
-from omero.gateway import BlitzGateway
-import omero.grid
-import omero.model
-import numpy as np
-
-HOST = 'omero.example.com'
-PORT = 4064
-USERNAME = 'user'
-PASSWORD = 'pass'
-
-with BlitzGateway(USERNAME, PASSWORD, host=HOST, port=PORT) as conn:
- # Get dataset
- dataset = conn.getObject("Dataset", dataset_id)
- print(f"Analyzing dataset: {dataset.getName()}")
-
- # Collect measurements from images
- image_ids = []
- mean_intensities = []
- max_intensities = []
- cell_counts = []
-
- for image in dataset.listChildren():
- image_ids.append(image.getId())
-
- # Get pixel data
- pixels = image.getPrimaryPixels()
- plane = pixels.getPlane(0, 0, 0) # Z=0, C=0, T=0
-
- # Calculate statistics
- mean_intensities.append(float(np.mean(plane)))
- max_intensities.append(float(np.max(plane)))
-
- # Simulate cell count (would be from actual analysis)
- cell_counts.append(np.random.randint(50, 200))
-
- # Create table
- table_name = f"Analysis_Results_{dataset.getId()}"
-
- # Define columns
- col1 = omero.grid.ImageColumn('Image', 'Source image', [])
- col2 = omero.grid.DoubleColumn('MeanIntensity', 'Mean pixel value', [])
- col3 = omero.grid.DoubleColumn('MaxIntensity', 'Maximum pixel value', [])
- col4 = omero.grid.LongColumn('CellCount', 'Number of cells detected', [])
-
- # Initialize table
- resources = conn.c.sf.sharedResources()
- repository_id = resources.repositories().descriptions[0].getId().getValue()
- table = resources.newTable(repository_id, table_name)
- table.initialize([col1, col2, col3, col4])
-
- # Add data
- data_col1 = omero.grid.ImageColumn('Image', 'Source image', image_ids)
- data_col2 = omero.grid.DoubleColumn('MeanIntensity', 'Mean pixel value',
- mean_intensities)
- data_col3 = omero.grid.DoubleColumn('MaxIntensity', 'Maximum pixel value',
- max_intensities)
- data_col4 = omero.grid.LongColumn('CellCount', 'Number of cells detected',
- cell_counts)
-
- table.addData([data_col1, data_col2, data_col3, data_col4])
-
- # Get file and close table
- orig_file = table.getOriginalFile()
- table.close()
-
- # Link to dataset
- orig_file_id = orig_file.id.val
- file_ann = omero.model.FileAnnotationI()
- file_ann.setFile(omero.model.OriginalFileI(orig_file_id, False))
- file_ann = conn.getUpdateService().saveAndReturnObject(file_ann)
-
- link = omero.model.DatasetAnnotationLinkI()
- link.setParent(omero.model.DatasetI(dataset_id, False))
- link.setChild(omero.model.FileAnnotationI(file_ann.getId().getValue(), False))
- conn.getUpdateService().saveAndReturnObject(link)
+from omero.grid import DoubleColumn, ImageColumn, StringColumn
- print(f"Created and linked table with {len(image_ids)} rows")
-
- # Query results
- table = resources.openTable(orig_file)
+columns = [
+ ImageColumn("Image", "Source image", []),
+ DoubleColumn("MeanIntensity", "Mean raw value", []),
+ StringColumn("Status", "Review status", 32, []),
+]
- high_cell_count_rows = table.getWhereList(
- "(CellCount > 100)",
- variables={},
- start=0,
- stop=table.getNumberOfRows(),
- step=0
+resources = conn.c.sf.sharedResources()
+repositories = resources.repositories().descriptions
+if not repositories:
+ raise RuntimeError("No table repository is available")
+
+repository_id = repositories[0].getId().getValue()
+table = resources.newTable(repository_id, "analysis-v2-explicit-name")
+try:
+ table.initialize(columns)
+ table.addData(
+ [
+ ImageColumn("Image", "Source image", [101, 102]),
+ DoubleColumn("MeanIntensity", "Mean raw value", [12.5, 14.0]),
+ StringColumn("Status", "Review status", 32, ["reviewed", "reviewed"]),
+ ]
)
-
- print(f"Images with >100 cells: {len(high_cell_count_rows)}")
-
- # Read those rows
- data = table.readCoordinates(high_cell_count_rows)
- for i in range(len(high_cell_count_rows)):
- img_id = data.columns[0].values[i]
- count = data.columns[3].values[i]
- print(f" Image {img_id}: {count} cells")
-
+ table_file_id = table.getOriginalFile().getId().getValue()
+finally:
table.close()
```
-## Retrieve Tables from Objects
+Before execution:
-### Find Tables Attached to Dataset
+- verify repository selection with the administrator;
+- validate every referenced object ID in the same intended group;
+- validate all row counts, numeric ranges, strings, and array sizes;
+- cap rows per `addData` batch;
+- decide recovery if initialization succeeds but data upload fails.
-```python
-# Get dataset
-dataset = conn.getObject("Dataset", dataset_id)
-
-# List file annotations
-for ann in dataset.listAnnotations():
- if isinstance(ann, omero.gateway.FileAnnotationWrapper):
- file_obj = ann.getFile()
- file_name = file_obj.getName()
-
- # Check if it's a table (might have specific naming pattern)
- if "Table" in file_name or file_name.endswith(".h5"):
- print(f"Found table: {file_name} (ID: {file_obj.getId()})")
-
- # Open and inspect
- resources = conn.c.sf.sharedResources()
- table = resources.openTable(file_obj._obj)
-
- print(f" Rows: {table.getNumberOfRows()}")
- print(f" Columns:")
- for col in table.getHeaders():
- print(f" {col.name}")
-
- table.close()
-```
-
-## Updating Tables
+## Linking a Table
-### Append Rows
+The table `OriginalFile` becomes discoverable through a `FileAnnotation` and an
+object-annotation link:
```python
-# Open existing table
-resources = conn.c.sf.sharedResources()
-table = resources.openTable(orig_file._obj)
-
-# Prepare new data
-new_image_ids = [106, 107]
-new_intensities = [88.9, 92.3]
-new_categories = ["Good", "Excellent"]
-
-# Create data columns
-data_col1 = omero.grid.LongColumn('ImageID', '', new_image_ids)
-data_col2 = omero.grid.DoubleColumn('MeanIntensity', '', new_intensities)
-data_col3 = omero.grid.StringColumn('Category', '', 64, new_categories)
+from omero.model import (
+ DatasetAnnotationLinkI,
+ DatasetI,
+ FileAnnotationI,
+ OriginalFileI,
+)
-# Append data
-table.addData([data_col1, data_col2, data_col3])
+file_annotation = FileAnnotationI()
+file_annotation.setFile(OriginalFileI(table_file_id, False))
+file_annotation = conn.getUpdateService().saveAndReturnObject(file_annotation)
-print(f"New row count: {table.getNumberOfRows()}")
-table.close()
+link = DatasetAnnotationLinkI()
+link.setParent(DatasetI(dataset_id, False))
+link.setChild(FileAnnotationI(file_annotation.getId().getValue(), False))
+conn.getUpdateService().saveAndReturnObject(link)
```
-## Deleting Tables
+This is a second write after table creation. If link creation fails, the table
+and file annotation may remain orphaned. Record IDs after every successful
+step and define cleanup before starting.
-### Delete Table File
+OMERO.web table viewing expects conventions such as a column named `Image`
+with a supported ID/numeric column type. A custom column called something else
+may store valid data but not receive the same UI behavior.
-```python
-# Get file object
-orig_file = conn.getObject("OriginalFile", file_id)
+## Concurrency and Lifecycle
-# Delete file (also deletes table)
-conn.deleteObjects("OriginalFile", [file_id], wait=True)
-print(f"Deleted table file {file_id}")
-```
-
-### Unlink Table from Object
+Each OMERO table is backed by one HDF table. PyTables/HDF does not support
+general concurrent access, so OMERO.tables adds global locking. Keep table
+handles short-lived:
```python
-# Find annotation links
-dataset = conn.getObject("Dataset", dataset_id)
-
-for ann in dataset.listAnnotations():
- if isinstance(ann, omero.gateway.FileAnnotationWrapper):
- if "Table" in ann.getFile().getName():
- # Delete link (keeps table, removes association)
- conn.deleteObjects("DatasetAnnotationLink",
- [ann.link.getId()],
- wait=True)
- print(f"Unlinked table from dataset")
+table = resources.openTable(original._obj)
+try:
+ # One bounded operation.
+ ...
+finally:
+ table.close()
```
-## Best Practices
+Do not hold a handle across:
-1. **Descriptive Names**: Use meaningful table and column names
-2. **Close Tables**: Always close tables after use
-3. **String Length**: Set appropriate max length for string columns
-4. **Link to Objects**: Attach tables to relevant datasets or projects
-5. **Use References**: Use ImageColumn, RoiColumn for object references
-6. **Query Efficiently**: Use getWhereList() instead of reading all data
-7. **Document**: Add descriptions to columns
-8. **Version Control**: Include version info in table name or metadata
-9. **Batch Operations**: Add data in batches for better performance
-10. **Error Handling**: Check for None returns and handle exceptions
+- user interaction;
+- network retries/reconnection;
+- long pixel analysis;
+- another process's expected write window.
-## Common Patterns
+If BlitzGateway reconnects, discard any old table proxy and open a fresh one.
-### ROI Measurements Table
+## Updating or Deleting
-```python
-# Table structure for ROI measurements
-columns = [
- omero.grid.ImageColumn('Image', 'Source image', []),
- omero.grid.RoiColumn('ROI', 'Measured ROI', []),
- omero.grid.LongColumn('ChannelIndex', 'Channel number', []),
- omero.grid.DoubleColumn('Area', 'ROI area in pixels', []),
- omero.grid.DoubleColumn('MeanIntensity', 'Mean intensity', []),
- omero.grid.DoubleColumn('IntegratedDensity', 'Sum of intensities', []),
- omero.grid.StringColumn('CellType', 'Cell classification', 32, [])
-]
-```
+`addData()` and `update()` mutate table content. Deleting the backing
+`OriginalFile` may remove the table; deleting one annotation link may merely
+detach it from one object. These require separate impact review.
-### Time Series Data Table
+Never:
-```python
-# Table structure for time series measurements
-columns = [
- omero.grid.ImageColumn('Image', 'Time series image', []),
- omero.grid.LongColumn('Timepoint', 'Time index', []),
- omero.grid.DoubleColumn('Timestamp', 'Time in seconds', []),
- omero.grid.DoubleColumn('Value', 'Measured value', []),
- omero.grid.StringColumn('Measurement', 'Type of measurement', 64, [])
-]
-```
+- update rows selected by a dynamically constructed condition;
+- append an unbounded result set;
+- delete a table based only on filename;
+- overwrite an existing table as a retry strategy;
+- leave a handle open after an exception.
-### Screening Results Table
+## Table Checklist
-```python
-# Table structure for screening plate analysis
-columns = [
- omero.grid.WellColumn('Well', 'Plate well', []),
- omero.grid.LongColumn('FieldIndex', 'Field number', []),
- omero.grid.DoubleColumn('CellCount', 'Number of cells', []),
- omero.grid.DoubleColumn('Viability', 'Percent viable', []),
- omero.grid.StringColumn('Phenotype', 'Observed phenotype', 128, []),
- omero.grid.BoolColumn('Hit', 'Hit in screen', [])
-]
-```
+- Explicit `OriginalFile` ID and selected group
+- Server/client pairing verified
+- Column count, row limit, page size, string size, and array width bounded
+- Fixed conditions with bound variables
+- No empty selection that means “all”
+- Handle closed in `finally`
+- Writes and links reviewed separately
+- Partial-create IDs recorded for recovery
+- Export classification reviewed before JSON/CSV output
diff --git a/skills/omero-integration/scripts/export_image_metadata.py b/skills/omero-integration/scripts/export_image_metadata.py
new file mode 100644
index 00000000..76e60220
--- /dev/null
+++ b/skills/omero-integration/scripts/export_image_metadata.py
@@ -0,0 +1,560 @@
+#!/usr/bin/env python3
+"""Export bounded annotations and ROI geometry for explicit image IDs."""
+
+from __future__ import annotations
+
+import argparse
+import json
+import sys
+from datetime import datetime, timezone
+from typing import Any
+
+from omero_common import (
+ ConfigError,
+ DependencyError,
+ OutputPathError,
+ bounded_int,
+ config_summary,
+ emit_json,
+ gateway_session,
+ json_safe,
+ load_connection_config,
+ scrubbed_error,
+ take_bounded,
+ unwrap_omero,
+)
+
+
+SHAPE_GEOMETRY = {
+ "EllipseI": ("X", "Y", "RadiusX", "RadiusY"),
+ "LabelI": ("X", "Y"),
+ "LineI": ("X1", "Y1", "X2", "Y2"),
+ "MaskI": ("X", "Y", "Width", "Height"),
+ "PointI": ("X", "Y"),
+ "PolygonI": ("Points",),
+ "PolylineI": ("Points",),
+ "RectangleI": ("X", "Y", "Width", "Height"),
+}
+
+
+def positive_argument(value: str) -> int:
+ try:
+ parsed = int(value, 10)
+ except ValueError as exc:
+ raise argparse.ArgumentTypeError("expected an integer") from exc
+ if parsed <= 0:
+ raise argparse.ArgumentTypeError("expected a positive integer")
+ return parsed
+
+
+def build_parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser(
+ description=(
+ "Plan or execute a read-only JSON export of annotations and ROI "
+ "geometry for explicit image IDs. No pixels or attachment bytes "
+ "are retrieved."
+ )
+ )
+ parser.add_argument(
+ "--image-id",
+ action="append",
+ required=True,
+ type=positive_argument,
+ help="Explicit image ID; repeat for additional images.",
+ )
+ parser.add_argument(
+ "--group-id",
+ type=positive_argument,
+ help="Optional explicit group ID; cross-group -1 is not supported.",
+ )
+ parser.add_argument(
+ "--max-images",
+ type=positive_argument,
+ default=25,
+ help="Maximum explicit images, 1..100 (default: 25).",
+ )
+ parser.add_argument(
+ "--max-annotations-per-image",
+ type=positive_argument,
+ default=100,
+ help="Per-image annotation cap, 1..1000 (default: 100).",
+ )
+ parser.add_argument(
+ "--max-rois-per-image",
+ type=positive_argument,
+ default=100,
+ help="Per-image ROI serialization cap, 1..1000 (default: 100).",
+ )
+ parser.add_argument(
+ "--max-shapes-per-roi",
+ type=positive_argument,
+ default=500,
+ help="Per-ROI shape cap, 1..5000 (default: 500).",
+ )
+ parser.add_argument(
+ "--max-string-length",
+ type=positive_argument,
+ default=512,
+ help="Maximum exported string length, 32..4096.",
+ )
+ parser.add_argument(
+ "--max-value-items",
+ type=positive_argument,
+ default=100,
+ help="Maximum items in an included annotation value, 1..1000.",
+ )
+ parser.add_argument(
+ "--include-annotation-values",
+ action="store_true",
+ help="Include bounded annotation values; redacted by default.",
+ )
+ parser.add_argument(
+ "--include-owner-names",
+ action="store_true",
+ help="Include annotation owner usernames; IDs only by default.",
+ )
+ parser.add_argument(
+ "--include-file-names",
+ action="store_true",
+ help="Include FileAnnotation filenames; redacted by default.",
+ )
+ parser.add_argument(
+ "--include-roi-labels",
+ action="store_true",
+ help="Include shape text labels; redacted by default.",
+ )
+ parser.add_argument(
+ "--output",
+ required=True,
+ help="Required .json destination in an existing directory.",
+ )
+ parser.add_argument(
+ "--overwrite",
+ action="store_true",
+ help="Replace an existing regular output file, never a symlink.",
+ )
+ parser.add_argument(
+ "--execute",
+ action="store_true",
+ help="Connect and perform the read-only export.",
+ )
+ parser.add_argument(
+ "--allow-insecure-transport",
+ action="store_true",
+ help=(
+ "Permit OMERO_SECURE=false after explicit policy review. "
+ "Encrypted transport remains the default."
+ ),
+ )
+ return parser
+
+
+def call_or_none(obj: Any, method: str) -> Any:
+ function = getattr(obj, method, None)
+ if not callable(function):
+ return None
+ return function()
+
+
+def normalized(
+ value: Any,
+ *,
+ max_string_length: int,
+ max_value_items: int,
+) -> Any:
+ return json_safe(
+ unwrap_omero(value),
+ max_string_length=max_string_length,
+ max_collection_length=max_value_items,
+ )
+
+
+def owner_record(
+ obj: Any,
+ *,
+ include_owner_names: bool,
+ max_string_length: int,
+) -> dict[str, Any]:
+ details = call_or_none(obj, "getDetails")
+ owner = call_or_none(details, "getOwner") if details is not None else None
+ record = {
+ "owner_id": normalized(
+ call_or_none(owner, "getId"),
+ max_string_length=max_string_length,
+ max_value_items=1,
+ )
+ }
+ if include_owner_names:
+ record["owner_username"] = normalized(
+ call_or_none(owner, "getOmeName"),
+ max_string_length=max_string_length,
+ max_value_items=1,
+ )
+ else:
+ record["owner_name_redacted"] = True
+ return record
+
+
+def annotation_record(
+ annotation: Any,
+ *,
+ include_values: bool,
+ include_owner_names: bool,
+ include_file_names: bool,
+ max_string_length: int,
+ max_value_items: int,
+) -> dict[str, Any]:
+ kind = getattr(
+ annotation,
+ "OMERO_CLASS",
+ type(annotation).__name__.removesuffix("Wrapper"),
+ )
+ record: dict[str, Any] = {
+ "id": call_or_none(annotation, "getId"),
+ "type": kind,
+ "namespace": normalized(
+ call_or_none(annotation, "getNs"),
+ max_string_length=max_string_length,
+ max_value_items=1,
+ ),
+ **owner_record(
+ annotation,
+ include_owner_names=include_owner_names,
+ max_string_length=max_string_length,
+ ),
+ }
+
+ if include_values:
+ record["value"] = normalized(
+ call_or_none(annotation, "getValue"),
+ max_string_length=max_string_length,
+ max_value_items=max_value_items,
+ )
+ else:
+ record["value_redacted"] = True
+
+ if kind == "FileAnnotation" or type(annotation).__name__ == (
+ "FileAnnotationWrapper"
+ ):
+ original = call_or_none(annotation, "getFile")
+ file_record = {
+ "original_file_id": call_or_none(original, "getId"),
+ "size_bytes": call_or_none(original, "getSize"),
+ "mimetype": normalized(
+ call_or_none(original, "getMimetype"),
+ max_string_length=128,
+ max_value_items=1,
+ ),
+ "bytes_downloaded": False,
+ }
+ if include_file_names:
+ file_record["name"] = normalized(
+ call_or_none(original, "getName"),
+ max_string_length=max_string_length,
+ max_value_items=1,
+ )
+ else:
+ file_record["name_redacted"] = True
+ record["file"] = file_record
+ return record
+
+
+def shape_record(
+ shape: Any,
+ *,
+ include_labels: bool,
+ max_string_length: int,
+) -> dict[str, Any]:
+ model_name = type(shape).__name__
+ shape_type = model_name.removesuffix("I")
+ record: dict[str, Any] = {
+ "id": normalized(
+ call_or_none(shape, "getId"),
+ max_string_length=max_string_length,
+ max_value_items=1,
+ ),
+ "type": shape_type,
+ "the_z": normalized(
+ call_or_none(shape, "getTheZ"),
+ max_string_length=max_string_length,
+ max_value_items=1,
+ ),
+ "the_t": normalized(
+ call_or_none(shape, "getTheT"),
+ max_string_length=max_string_length,
+ max_value_items=1,
+ ),
+ "the_c": normalized(
+ call_or_none(shape, "getTheC"),
+ max_string_length=max_string_length,
+ max_value_items=1,
+ ),
+ }
+ if include_labels:
+ record["label"] = normalized(
+ call_or_none(shape, "getTextValue"),
+ max_string_length=max_string_length,
+ max_value_items=1,
+ )
+ else:
+ record["label_redacted"] = True
+
+ geometry: dict[str, Any] = {}
+ for field in SHAPE_GEOMETRY.get(model_name, ()):
+ geometry[field[0].lower() + field[1:]] = normalized(
+ call_or_none(shape, f"get{field}"),
+ max_string_length=max_string_length,
+ max_value_items=1,
+ )
+ record["geometry"] = geometry
+ if model_name == "MaskI":
+ record["mask_bytes_omitted"] = True
+ return record
+
+
+def roi_record(
+ roi: Any,
+ *,
+ max_shapes: int,
+ include_labels: bool,
+ max_string_length: int,
+) -> dict[str, Any]:
+ shapes = take_bounded(roi.copyShapes(), max_shapes)
+ return {
+ "id": normalized(
+ call_or_none(roi, "getId"),
+ max_string_length=max_string_length,
+ max_value_items=1,
+ ),
+ "shapes": [
+ shape_record(
+ shape,
+ include_labels=include_labels,
+ max_string_length=max_string_length,
+ )
+ for shape in shapes.items
+ ],
+ "returned_shapes": len(shapes.items),
+ "shapes_truncated": shapes.truncated,
+ }
+
+
+def export_one_image(
+ connection: Any,
+ roi_service: Any,
+ image_id: int,
+ args: argparse.Namespace,
+) -> dict[str, Any]:
+ image = connection.getObject("Image", image_id)
+ if image is None:
+ return {"id": image_id, "accessible": False}
+
+ annotation_result = take_bounded(
+ image.listAnnotations(),
+ args.max_annotations_per_image,
+ )
+ roi_result = roi_service.findByImage(image_id, None)
+ roi_items = take_bounded(
+ roi_result.rois,
+ args.max_rois_per_image,
+ )
+
+ details = call_or_none(image, "getDetails")
+ group = call_or_none(details, "getGroup") if details is not None else None
+ owner = call_or_none(details, "getOwner") if details is not None else None
+ return {
+ "id": image_id,
+ "accessible": True,
+ "name_redacted": True,
+ "group_id": call_or_none(group, "getId"),
+ "owner_id": call_or_none(owner, "getId"),
+ "dimensions": {
+ "x": call_or_none(image, "getSizeX"),
+ "y": call_or_none(image, "getSizeY"),
+ "z": call_or_none(image, "getSizeZ"),
+ "c": call_or_none(image, "getSizeC"),
+ "t": call_or_none(image, "getSizeT"),
+ },
+ "annotations": [
+ annotation_record(
+ annotation,
+ include_values=args.include_annotation_values,
+ include_owner_names=args.include_owner_names,
+ include_file_names=args.include_file_names,
+ max_string_length=args.max_string_length,
+ max_value_items=args.max_value_items,
+ )
+ for annotation in annotation_result.items
+ ],
+ "returned_annotations": len(annotation_result.items),
+ "annotations_truncated": annotation_result.truncated,
+ "rois": [
+ roi_record(
+ roi,
+ max_shapes=args.max_shapes_per_roi,
+ include_labels=args.include_roi_labels,
+ max_string_length=args.max_string_length,
+ )
+ for roi in roi_items.items
+ ],
+ "returned_rois": len(roi_items.items),
+ "rois_truncated": roi_items.truncated,
+ }
+
+
+def scope_payload(
+ args: argparse.Namespace,
+ image_ids: list[int],
+) -> dict[str, Any]:
+ return {
+ "image_ids": image_ids,
+ "group_id": args.group_id,
+ "cross_group": False,
+ "max_images": args.max_images,
+ "max_annotations_per_image": args.max_annotations_per_image,
+ "max_rois_per_image": args.max_rois_per_image,
+ "max_shapes_per_roi": args.max_shapes_per_roi,
+ "max_string_length": args.max_string_length,
+ "max_value_items": args.max_value_items,
+ }
+
+
+def redaction_payload(args: argparse.Namespace) -> dict[str, bool]:
+ return {
+ "annotation_values_included": args.include_annotation_values,
+ "owner_names_included": args.include_owner_names,
+ "file_names_included": args.include_file_names,
+ "roi_labels_included": args.include_roi_labels,
+ "file_bytes_included": False,
+ "pixel_data_included": False,
+ "mask_bytes_included": False,
+ }
+
+
+def main(argv: list[str] | None = None) -> int:
+ parser = build_parser()
+ args = parser.parse_args(argv)
+ try:
+ bounded_int(
+ args.max_images,
+ name="max-images",
+ minimum=1,
+ maximum=100,
+ )
+ bounded_int(
+ args.max_annotations_per_image,
+ name="max-annotations-per-image",
+ minimum=1,
+ maximum=1000,
+ )
+ bounded_int(
+ args.max_rois_per_image,
+ name="max-rois-per-image",
+ minimum=1,
+ maximum=1000,
+ )
+ bounded_int(
+ args.max_shapes_per_roi,
+ name="max-shapes-per-roi",
+ minimum=1,
+ maximum=5000,
+ )
+ bounded_int(
+ args.max_string_length,
+ name="max-string-length",
+ minimum=32,
+ maximum=4096,
+ )
+ bounded_int(
+ args.max_value_items,
+ name="max-value-items",
+ minimum=1,
+ maximum=1000,
+ )
+
+ image_ids = list(dict.fromkeys(args.image_id))
+ if len(image_ids) != len(args.image_id):
+ raise ValueError("duplicate --image-id values are not allowed")
+ if len(image_ids) > args.max_images:
+ raise ValueError("explicit image count exceeds --max-images")
+
+ config = load_connection_config(require_auth=args.execute)
+ if not args.execute:
+ print(
+ json.dumps(
+ {
+ "mode": "dry-run",
+ "server_contacted": False,
+ "output_not_written": True,
+ "requested_output": args.output,
+ "configuration": config_summary(config),
+ "scope": scope_payload(args, image_ids),
+ "redaction": redaction_payload(args),
+ "next_step": (
+ "Review scope/redaction, then add --execute."
+ ),
+ },
+ indent=2,
+ sort_keys=True,
+ )
+ )
+ return 0
+
+ with gateway_session(
+ config,
+ allow_insecure_transport=args.allow_insecure_transport,
+ ) as connection:
+ if args.group_id is not None:
+ connection.SERVICE_OPTS.setOmeroGroup(str(args.group_id))
+ roi_service = connection.getRoiService()
+ images = [
+ export_one_image(
+ connection,
+ roi_service,
+ image_id,
+ args,
+ )
+ for image_id in image_ids
+ ]
+
+ payload = {
+ "mode": "executed-read-only",
+ "generated_at": datetime.now(timezone.utc).isoformat(),
+ "configuration": config_summary(config),
+ "scope": scope_payload(args, image_ids),
+ "redaction": redaction_payload(args),
+ "api_notes": [
+ (
+ "IRoi.findByImage is used by current official Python "
+ "examples but IRoi is deprecated."
+ ),
+ (
+ "ROI limits bound serialization; findByImage itself "
+ "does not expose pagination."
+ ),
+ ],
+ "images": images,
+ }
+ emit_json(
+ payload,
+ output=args.output,
+ overwrite=args.overwrite,
+ )
+ return 0
+ except (
+ ConfigError,
+ DependencyError,
+ OutputPathError,
+ FileExistsError,
+ ValueError,
+ RuntimeError,
+ ) as error:
+ print(scrubbed_error(error), file=sys.stderr)
+ return 2
+ except Exception as error:
+ print(scrubbed_error(error), file=sys.stderr)
+ return 1
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/skills/omero-integration/scripts/inventory.py b/skills/omero-integration/scripts/inventory.py
new file mode 100644
index 00000000..bf253e1d
--- /dev/null
+++ b/skills/omero-integration/scripts/inventory.py
@@ -0,0 +1,302 @@
+#!/usr/bin/env python3
+"""Produce a bounded, read-only OMERO object inventory."""
+
+from __future__ import annotations
+
+import argparse
+import sys
+from datetime import datetime, timezone
+from typing import Any
+
+from omero_common import (
+ ConfigError,
+ DependencyError,
+ OutputPathError,
+ bounded_int,
+ config_summary,
+ emit_json,
+ gateway_session,
+ json_safe,
+ load_connection_config,
+ scrubbed_error,
+)
+
+
+OBJECT_TYPES = (
+ "Project",
+ "Dataset",
+ "Image",
+ "Screen",
+ "Plate",
+ "Well",
+ "Fileset",
+ "OriginalFile",
+)
+
+
+def positive_argument(value: str) -> int:
+ try:
+ parsed = int(value, 10)
+ except ValueError as exc:
+ raise argparse.ArgumentTypeError("expected an integer") from exc
+ if parsed <= 0:
+ raise argparse.ArgumentTypeError("expected a positive integer")
+ return parsed
+
+
+def build_parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser(
+ description=(
+ "Plan or execute a bounded read-only OMERO object inventory. "
+ "Without --execute, no server connection is made."
+ )
+ )
+ parser.add_argument(
+ "--object-type",
+ choices=OBJECT_TYPES,
+ default="Image",
+ help="Allowlisted OMERO object type (default: Image).",
+ )
+ parser.add_argument(
+ "--limit",
+ type=positive_argument,
+ default=100,
+ help="Overall object cap, 1..1000 (default: 100).",
+ )
+ parser.add_argument(
+ "--page-size",
+ type=positive_argument,
+ default=50,
+ help="Server page size, 1..200 and no greater than limit.",
+ )
+ parser.add_argument(
+ "--group-id",
+ type=positive_argument,
+ help="Optional explicit group ID; cross-group -1 is not supported.",
+ )
+ parser.add_argument(
+ "--include-names",
+ action="store_true",
+ help="Include object names; names are redacted by default.",
+ )
+ parser.add_argument(
+ "--output",
+ help="Optional .json output in an existing directory.",
+ )
+ parser.add_argument(
+ "--overwrite",
+ action="store_true",
+ help="Replace an existing regular output file, never a symlink.",
+ )
+ parser.add_argument(
+ "--execute",
+ action="store_true",
+ help="Connect and perform the read-only inventory.",
+ )
+ parser.add_argument(
+ "--allow-insecure-transport",
+ action="store_true",
+ help=(
+ "Permit OMERO_SECURE=false after explicit policy review. "
+ "Encrypted transport remains the default."
+ ),
+ )
+ return parser
+
+
+def call_or_none(obj: Any, method: str) -> Any:
+ function = getattr(obj, method, None)
+ if not callable(function):
+ return None
+ return function()
+
+
+def object_record(
+ obj: Any,
+ *,
+ requested_type: str,
+ include_names: bool,
+) -> dict[str, Any]:
+ """Serialize only a small allowlisted metadata subset."""
+
+ record: dict[str, Any] = {
+ "type": getattr(obj, "OMERO_CLASS", requested_type),
+ "id": call_or_none(obj, "getId"),
+ }
+ if include_names:
+ record["name"] = json_safe(
+ call_or_none(obj, "getName"),
+ max_string_length=512,
+ )
+ else:
+ record["name_redacted"] = True
+
+ details = call_or_none(obj, "getDetails")
+ owner = call_or_none(details, "getOwner") if details is not None else None
+ group = call_or_none(details, "getGroup") if details is not None else None
+ record["owner_id"] = call_or_none(owner, "getId")
+ record["group_id"] = call_or_none(group, "getId")
+
+ if requested_type == "Image":
+ record["dimensions"] = {
+ "x": call_or_none(obj, "getSizeX"),
+ "y": call_or_none(obj, "getSizeY"),
+ "z": call_or_none(obj, "getSizeZ"),
+ "c": call_or_none(obj, "getSizeC"),
+ "t": call_or_none(obj, "getSizeT"),
+ }
+ record["pixels_type"] = call_or_none(obj, "getPixelsType")
+ elif requested_type == "OriginalFile":
+ record["size_bytes"] = call_or_none(obj, "getSize")
+ record["mimetype"] = json_safe(
+ call_or_none(obj, "getMimetype"),
+ max_string_length=128,
+ )
+ return record
+
+
+def collect_inventory(
+ connection: Any,
+ *,
+ object_type: str,
+ limit: int,
+ page_size: int,
+ include_names: bool,
+) -> dict[str, Any]:
+ """Collect records with explicit server and client limits."""
+
+ records: list[dict[str, Any]] = []
+ offset = 0
+ exhausted = False
+
+ while len(records) < limit:
+ requested = min(page_size, limit - len(records))
+ page = list(
+ connection.getObjects(
+ object_type,
+ opts={
+ "limit": requested,
+ "offset": offset,
+ "order_by": "obj.id",
+ },
+ )
+ )
+ if not page:
+ exhausted = True
+ break
+
+ records.extend(
+ object_record(
+ obj,
+ requested_type=object_type,
+ include_names=include_names,
+ )
+ for obj in page[:requested]
+ )
+ if len(page) < requested:
+ exhausted = True
+ break
+ offset += len(page)
+
+ return {
+ "records": records,
+ "returned": len(records),
+ "limit_reached": len(records) == limit,
+ "server_result_exhausted": exhausted,
+ }
+
+
+def dry_run_payload(
+ args: argparse.Namespace,
+ config: Any,
+) -> dict[str, Any]:
+ return {
+ "mode": "dry-run",
+ "server_contacted": False,
+ "configuration": config_summary(config),
+ "scope": {
+ "object_type": args.object_type,
+ "group_id": args.group_id,
+ "limit": args.limit,
+ "page_size": args.page_size,
+ "include_names": args.include_names,
+ "cross_group": False,
+ },
+ "next_step": "Review scope, then add --execute for a read-only query.",
+ }
+
+
+def main(argv: list[str] | None = None) -> int:
+ parser = build_parser()
+ args = parser.parse_args(argv)
+ try:
+ bounded_int(args.limit, name="limit", minimum=1, maximum=1000)
+ bounded_int(
+ args.page_size,
+ name="page-size",
+ minimum=1,
+ maximum=200,
+ )
+ if args.page_size > args.limit:
+ raise ValueError("page-size must not exceed limit")
+
+ config = load_connection_config(require_auth=args.execute)
+ if not args.execute:
+ emit_json(
+ dry_run_payload(args, config),
+ output=args.output,
+ overwrite=args.overwrite,
+ )
+ return 0
+
+ with gateway_session(
+ config,
+ allow_insecure_transport=args.allow_insecure_transport,
+ ) as connection:
+ if args.group_id is not None:
+ connection.SERVICE_OPTS.setOmeroGroup(str(args.group_id))
+ result = collect_inventory(
+ connection,
+ object_type=args.object_type,
+ limit=args.limit,
+ page_size=args.page_size,
+ include_names=args.include_names,
+ )
+
+ payload = {
+ "mode": "executed-read-only",
+ "generated_at": datetime.now(timezone.utc).isoformat(),
+ "configuration": config_summary(config),
+ "scope": {
+ "object_type": args.object_type,
+ "group_id": args.group_id,
+ "limit": args.limit,
+ "page_size": args.page_size,
+ "include_names": args.include_names,
+ "cross_group": False,
+ },
+ **result,
+ }
+ emit_json(
+ payload,
+ output=args.output,
+ overwrite=args.overwrite,
+ )
+ return 0
+ except (
+ ConfigError,
+ DependencyError,
+ OutputPathError,
+ FileExistsError,
+ ValueError,
+ RuntimeError,
+ ) as error:
+ print(scrubbed_error(error), file=sys.stderr)
+ return 2
+ except Exception as error:
+ print(scrubbed_error(error), file=sys.stderr)
+ return 1
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/skills/omero-integration/scripts/omero_common.py b/skills/omero-integration/scripts/omero_common.py
new file mode 100644
index 00000000..523e5eda
--- /dev/null
+++ b/skills/omero-integration/scripts/omero_common.py
@@ -0,0 +1,490 @@
+#!/usr/bin/env python3
+"""Shared safety utilities for the bundled OMERO client helpers."""
+
+from __future__ import annotations
+
+import argparse
+import contextlib
+import json
+import math
+import os
+import tempfile
+from collections.abc import Iterable, Iterator, Mapping
+from dataclasses import dataclass
+from datetime import date, datetime
+from itertools import islice
+from pathlib import Path
+from typing import Any
+
+
+NAMED_ENV_VARS = (
+ "OMERO_HOST",
+ "OMERO_PORT",
+ "OMERO_USER",
+ "OMERO_PASSWORD",
+ "OMERO_SESSION_KEY",
+ "OMERO_SECURE",
+)
+
+TRUE_VALUES = frozenset({"1", "true", "yes", "on"})
+FALSE_VALUES = frozenset({"0", "false", "no", "off"})
+
+
+class ConfigError(ValueError):
+ """Raised when named OMERO configuration is invalid."""
+
+
+class OutputPathError(ValueError):
+ """Raised when an output path is unsafe or ambiguous."""
+
+
+class DependencyError(RuntimeError):
+ """Raised when an optional runtime dependency is unavailable."""
+
+
+@dataclass(frozen=True)
+class ConnectionConfig:
+ """Validated connection material. Never serialize this dataclass."""
+
+ host: str
+ port: int
+ secure: bool
+ username: str | None
+ password: str | None
+ session_key: str | None
+
+ @property
+ def authentication_mode(self) -> str:
+ if self.session_key:
+ return "session_key"
+ if self.username and self.password:
+ return "username_password"
+ return "missing"
+
+
+@dataclass(frozen=True)
+class BoundedResult:
+ """A bounded materialization with explicit truncation state."""
+
+ items: list[Any]
+ truncated: bool
+
+
+def parse_bool(value: str, *, variable: str) -> bool:
+ """Parse a strict environment boolean."""
+
+ normalized = value.strip().lower()
+ if normalized in TRUE_VALUES:
+ return True
+ if normalized in FALSE_VALUES:
+ return False
+ allowed = ", ".join(sorted(TRUE_VALUES | FALSE_VALUES))
+ raise ConfigError(f"{variable} must be one of: {allowed}")
+
+
+def validate_host(value: str) -> str:
+ """Validate a hostname without resolving or connecting."""
+
+ host = value.strip()
+ if not host:
+ raise ConfigError("OMERO_HOST is required")
+ if "\x00" in host:
+ raise ConfigError("OMERO_HOST contains a NUL byte")
+ if any(character.isspace() for character in host):
+ raise ConfigError("OMERO_HOST must not contain whitespace")
+ if "://" in host:
+ raise ConfigError("OMERO_HOST must be a hostname, not a URL")
+ if "/" in host or "\\" in host:
+ raise ConfigError("OMERO_HOST must not contain a path")
+ if host.startswith("-"):
+ raise ConfigError("OMERO_HOST must not begin with '-'")
+ if len(host) > 255:
+ raise ConfigError("OMERO_HOST is too long")
+ return host
+
+
+def parse_port(value: str | None) -> int:
+ """Parse OMERO_PORT with the documented SSL-router default."""
+
+ raw = "4064" if value is None or not value.strip() else value.strip()
+ try:
+ port = int(raw, 10)
+ except ValueError as exc:
+ raise ConfigError("OMERO_PORT must be an integer") from exc
+ if not 1 <= port <= 65535:
+ raise ConfigError("OMERO_PORT must be between 1 and 65535")
+ return port
+
+
+def load_connection_config(
+ *,
+ require_auth: bool,
+ environ: Mapping[str, str] | None = None,
+) -> ConnectionConfig:
+ """Read only the named OMERO_* variables and validate them."""
+
+ source = os.environ if environ is None else environ
+ values = {name: source.get(name) for name in NAMED_ENV_VARS}
+
+ host = validate_host(values["OMERO_HOST"] or "")
+ port = parse_port(values["OMERO_PORT"])
+ secure_raw = values["OMERO_SECURE"]
+ secure = True if secure_raw is None else parse_bool(
+ secure_raw,
+ variable="OMERO_SECURE",
+ )
+
+ username = (values["OMERO_USER"] or "").strip() or None
+ password = values["OMERO_PASSWORD"]
+ if password == "":
+ password = None
+ session_key = (values["OMERO_SESSION_KEY"] or "").strip() or None
+
+ # An explicit session is the sole credential in use. Stale password
+ # variables are deliberately ignored and never surfaced.
+ if session_key:
+ username = None
+ password = None
+ elif bool(username) != bool(password):
+ raise ConfigError(
+ "OMERO_USER and OMERO_PASSWORD must be set together, "
+ "or use OMERO_SESSION_KEY"
+ )
+
+ config = ConnectionConfig(
+ host=host,
+ port=port,
+ secure=secure,
+ username=username,
+ password=password,
+ session_key=session_key,
+ )
+ if require_auth and config.authentication_mode == "missing":
+ raise ConfigError(
+ "Authentication requires OMERO_SESSION_KEY or both "
+ "OMERO_USER and OMERO_PASSWORD"
+ )
+ return config
+
+
+def config_summary(
+ config: ConnectionConfig,
+ *,
+ environ: Mapping[str, str] | None = None,
+) -> dict[str, Any]:
+ """Return a credential-safe configuration summary."""
+
+ source = os.environ if environ is None else environ
+ return {
+ "endpoint": {
+ "host": config.host,
+ "port": config.port,
+ "secure_transport": config.secure,
+ },
+ "authentication_mode": config.authentication_mode,
+ "named_variables_present": {
+ name: bool(source.get(name))
+ for name in NAMED_ENV_VARS
+ },
+ "credential_values_included": False,
+ }
+
+
+def require_secure_transport(
+ config: ConnectionConfig,
+ *,
+ allow_insecure_transport: bool,
+) -> None:
+ """Refuse post-login cleartext unless explicitly overridden."""
+
+ if not config.secure and not allow_insecure_transport:
+ raise ConfigError(
+ "OMERO_SECURE is false; pass --allow-insecure-transport only "
+ "after reviewing the server transport policy"
+ )
+
+
+def gateway_session(
+ config: ConnectionConfig,
+ *,
+ allow_insecure_transport: bool,
+) -> Iterator[Any]:
+ """Open and always close a BlitzGateway connection."""
+
+ require_secure_transport(
+ config,
+ allow_insecure_transport=allow_insecure_transport,
+ )
+ if config.authentication_mode == "missing":
+ raise ConfigError("Remote execution requires authentication")
+
+ try:
+ from omero.gateway import BlitzGateway
+ except ImportError as exc:
+ raise DependencyError(
+ "omero-py and a matching ZeroC IcePy wheel are required "
+ "for --execute"
+ ) from exc
+
+ connection = None
+ try:
+ if config.session_key:
+ connection = BlitzGateway(
+ host=config.host,
+ port=config.port,
+ secure=config.secure,
+ )
+ connected = connection.connect(sUuid=config.session_key)
+ else:
+ connection = BlitzGateway(
+ config.username,
+ config.password,
+ host=config.host,
+ port=config.port,
+ secure=config.secure,
+ )
+ connected = connection.connect()
+
+ if not connected:
+ raise RuntimeError("OMERO connection failed")
+ yield connection
+ finally:
+ if connection is not None:
+ with contextlib.suppress(Exception):
+ connection.close()
+
+
+def take_bounded(iterable: Iterable[Any], limit: int) -> BoundedResult:
+ """Materialize at most limit values and detect one additional value."""
+
+ if limit < 0:
+ raise ValueError("limit must be non-negative")
+ items = list(islice(iterable, limit + 1))
+ return BoundedResult(items=items[:limit], truncated=len(items) > limit)
+
+
+def unwrap_omero(value: Any) -> Any:
+ """Unwrap a generated OMERO rtype when possible."""
+
+ if value is None:
+ return None
+ getter = getattr(value, "getValue", None)
+ if callable(getter):
+ return getter()
+ if hasattr(value, "val"):
+ return value.val
+ return value
+
+
+def json_safe(
+ value: Any,
+ *,
+ max_string_length: int = 512,
+ max_collection_length: int = 1000,
+ _depth: int = 0,
+) -> Any:
+ """Convert known values to bounded JSON without unsafe repr output."""
+
+ if _depth > 8:
+ return {"omitted": "maximum nesting depth exceeded"}
+ if value is None or isinstance(value, (bool, int)):
+ return value
+ if isinstance(value, float):
+ if math.isfinite(value):
+ return value
+ return {"non_finite_float": str(value)}
+ if isinstance(value, str):
+ if len(value) <= max_string_length:
+ return value
+ return value[:max_string_length] + "…[truncated]"
+ if isinstance(value, bytes):
+ return {"bytes_omitted": len(value)}
+ if isinstance(value, (date, datetime)):
+ return value.isoformat()
+
+ unwrapped = unwrap_omero(value)
+ if unwrapped is not value:
+ return json_safe(
+ unwrapped,
+ max_string_length=max_string_length,
+ max_collection_length=max_collection_length,
+ _depth=_depth + 1,
+ )
+ if isinstance(value, Mapping):
+ total_items = len(value)
+ converted = {
+ str(key)[:max_string_length]: json_safe(
+ item,
+ max_string_length=max_string_length,
+ max_collection_length=max_collection_length,
+ _depth=_depth + 1,
+ )
+ for key, item in islice(
+ value.items(),
+ max_collection_length,
+ )
+ }
+ if total_items > max_collection_length:
+ converted["__truncated_items__"] = (
+ total_items - max_collection_length
+ )
+ return converted
+ if isinstance(value, (list, tuple)):
+ converted = [
+ json_safe(
+ item,
+ max_string_length=max_string_length,
+ max_collection_length=max_collection_length,
+ _depth=_depth + 1,
+ )
+ for item in value[:max_collection_length]
+ ]
+ if len(value) > max_collection_length:
+ converted.append(
+ {
+ "truncated_items": (
+ len(value) - max_collection_length
+ )
+ }
+ )
+ return converted
+ return {"unsupported_type": type(value).__name__}
+
+
+def positive_int(value: str) -> int:
+ """Argparse-compatible positive integer parser."""
+
+ try:
+ parsed = int(value, 10)
+ except ValueError as exc:
+ raise ValueError("expected an integer") from exc
+ if parsed <= 0:
+ raise ValueError("expected a positive integer")
+ return parsed
+
+
+def bounded_int(
+ value: int,
+ *,
+ name: str,
+ minimum: int,
+ maximum: int,
+) -> int:
+ """Validate an integer bound with a stable message."""
+
+ if not minimum <= value <= maximum:
+ raise ValueError(
+ f"{name} must be between {minimum} and {maximum}"
+ )
+ return value
+
+
+def atomic_write_json(
+ output: str | os.PathLike[str],
+ payload: Any,
+ *,
+ overwrite: bool,
+) -> Path:
+ """Atomically write JSON to an existing directory with mode 0600."""
+
+ requested = Path(output).expanduser()
+ if requested.name in {"", ".", ".."}:
+ raise OutputPathError("output must name a JSON file")
+ if requested.suffix.lower() != ".json":
+ raise OutputPathError("output filename must end in .json")
+ if requested.is_symlink():
+ raise OutputPathError("refusing to write through an output symlink")
+
+ try:
+ parent = requested.parent.resolve(strict=True)
+ except FileNotFoundError as exc:
+ raise OutputPathError("output parent directory does not exist") from exc
+ if not parent.is_dir():
+ raise OutputPathError("output parent is not a directory")
+
+ target = parent / requested.name
+ if target.is_symlink():
+ raise OutputPathError("refusing to replace an output symlink")
+ if target.exists():
+ if not target.is_file():
+ raise OutputPathError("output exists and is not a regular file")
+ if not overwrite:
+ raise FileExistsError(f"output already exists: {target}")
+
+ descriptor, temporary_name = tempfile.mkstemp(
+ prefix=f".{target.name}.",
+ suffix=".tmp",
+ dir=parent,
+ )
+ temporary = Path(temporary_name)
+ try:
+ os.fchmod(descriptor, 0o600)
+ with os.fdopen(descriptor, "w", encoding="utf-8") as handle:
+ descriptor = -1
+ json.dump(
+ payload,
+ handle,
+ indent=2,
+ sort_keys=True,
+ ensure_ascii=False,
+ )
+ handle.write("\n")
+ handle.flush()
+ os.fsync(handle.fileno())
+ os.replace(temporary, target)
+ os.chmod(target, 0o600)
+ except Exception:
+ if descriptor >= 0:
+ os.close(descriptor)
+ with contextlib.suppress(FileNotFoundError):
+ temporary.unlink()
+ raise
+ return target
+
+
+def emit_json(
+ payload: Any,
+ *,
+ output: str | os.PathLike[str] | None,
+ overwrite: bool,
+) -> Path | None:
+ """Write to a safe file or emit bounded JSON to stdout."""
+
+ if output is None:
+ print(
+ json.dumps(
+ payload,
+ indent=2,
+ sort_keys=True,
+ ensure_ascii=False,
+ )
+ )
+ return None
+ return atomic_write_json(output, payload, overwrite=overwrite)
+
+
+def scrubbed_error(error: BaseException) -> str:
+ """Describe an error without serializing its potentially sensitive text."""
+
+ return (
+ f"{type(error).__name__}: operation failed; "
+ "credential values were not logged"
+ )
+
+
+def main(argv: list[str] | None = None) -> int:
+ """Expose module documentation without loading optional OMERO packages."""
+
+ parser = argparse.ArgumentParser(
+ description=(
+ "Shared local safety utilities for the bundled OMERO helpers. "
+ "This module does not connect to OMERO when invoked directly."
+ )
+ )
+ parser.parse_args(argv)
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/skills/omero-integration/scripts/plan_transfer.py b/skills/omero-integration/scripts/plan_transfer.py
new file mode 100644
index 00000000..b7a9eddb
--- /dev/null
+++ b/skills/omero-integration/scripts/plan_transfer.py
@@ -0,0 +1,393 @@
+#!/usr/bin/env python3
+"""Build a local-only, bounded OMERO import or export plan."""
+
+from __future__ import annotations
+
+import argparse
+import os
+import re
+import sys
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Any
+
+from omero_common import (
+ OutputPathError,
+ bounded_int,
+ emit_json,
+ scrubbed_error,
+)
+
+
+TARGET_PATTERN = re.compile(r"^(Dataset|Screen):id:([1-9][0-9]*)$")
+IMAGE_PATTERN = re.compile(r"^Image:([1-9][0-9]*)$")
+
+
+def positive_argument(value: str) -> int:
+ try:
+ parsed = int(value, 10)
+ except ValueError as exc:
+ raise argparse.ArgumentTypeError("expected an integer") from exc
+ if parsed <= 0:
+ raise argparse.ArgumentTypeError("expected a positive integer")
+ return parsed
+
+
+def import_target(value: str) -> str:
+ if not TARGET_PATTERN.fullmatch(value):
+ raise argparse.ArgumentTypeError(
+ "target must be Dataset:id:<positive-id> or "
+ "Screen:id:<positive-id>"
+ )
+ return value
+
+
+def image_selector(value: str) -> str:
+ if not IMAGE_PATTERN.fullmatch(value):
+ raise argparse.ArgumentTypeError(
+ "selector must be Image:<positive-id>"
+ )
+ return value
+
+
+def build_parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser(
+ description=(
+ "Create a bounded local OMERO import/export plan. This command "
+ "never imports omero, connects to a server, or executes a plan."
+ )
+ )
+ parser.add_argument(
+ "--output",
+ help="Optional .json plan in an existing directory.",
+ )
+ parser.add_argument(
+ "--overwrite",
+ action="store_true",
+ help="Replace an existing regular plan file, never a symlink.",
+ )
+
+ subparsers = parser.add_subparsers(dest="operation", required=True)
+
+ import_parser = subparsers.add_parser(
+ "import",
+ help="Scan explicit local paths and propose importer commands.",
+ )
+ import_parser.add_argument(
+ "paths",
+ nargs="+",
+ help="Explicit existing files/directories; symlinks are refused.",
+ )
+ import_parser.add_argument(
+ "--target",
+ type=import_target,
+ help="Optional numeric Dataset:id:<id> or Screen:id:<id> target.",
+ )
+ import_parser.add_argument(
+ "--max-paths",
+ type=positive_argument,
+ default=25,
+ help="Maximum explicit top-level paths, 1..100.",
+ )
+ import_parser.add_argument(
+ "--max-files",
+ type=positive_argument,
+ default=100,
+ help="Maximum discovered regular files, 1..10000.",
+ )
+ import_parser.add_argument(
+ "--scan-depth",
+ type=positive_argument,
+ default=4,
+ help="Maximum directory depth, 1..20 (default: 4).",
+ )
+
+ export_parser = subparsers.add_parser(
+ "export",
+ help="Propose one documented OMERO export command per image.",
+ )
+ export_parser.add_argument(
+ "selectors",
+ nargs="+",
+ type=image_selector,
+ help="Explicit Image:<positive-id> selectors.",
+ )
+ export_parser.add_argument(
+ "--format",
+ choices=("ome-tiff", "xml"),
+ default="ome-tiff",
+ help="Documented export format (default: ome-tiff).",
+ )
+ export_parser.add_argument(
+ "--output-dir",
+ required=True,
+ help="Existing non-symlink directory for future exports.",
+ )
+ export_parser.add_argument(
+ "--max-images",
+ type=positive_argument,
+ default=25,
+ help="Maximum image selectors, 1..100.",
+ )
+ return parser
+
+
+def path_depth(root: Path, current: Path) -> int:
+ relative = current.relative_to(root)
+ return 0 if relative == Path(".") else len(relative.parts)
+
+
+def scan_import_path(
+ raw_path: str,
+ *,
+ max_files_remaining: int,
+ scan_depth: int,
+) -> dict[str, Any]:
+ """Scan metadata only; never read file contents or follow symlinks."""
+
+ requested = Path(raw_path).expanduser()
+ if requested.is_symlink():
+ raise ValueError("top-level import paths must not be symlinks")
+ try:
+ resolved = requested.resolve(strict=True)
+ except FileNotFoundError as exc:
+ raise ValueError("an explicit import path does not exist") from exc
+
+ if resolved.is_file():
+ if max_files_remaining < 1:
+ raise ValueError("discovered file count exceeds --max-files")
+ return {
+ "path": str(resolved),
+ "kind": "file",
+ "regular_files": 1,
+ "depth_limit_reached": False,
+ }
+ if not resolved.is_dir():
+ raise ValueError("import paths must be regular files or directories")
+
+ regular_files = 0
+ skipped_symlinks = 0
+ depth_limit_reached = False
+ for root_text, directories, files in os.walk(
+ resolved,
+ topdown=True,
+ followlinks=False,
+ ):
+ root = Path(root_text)
+ depth = path_depth(resolved, root)
+
+ kept_directories = []
+ for directory in directories:
+ candidate = root / directory
+ if candidate.is_symlink():
+ skipped_symlinks += 1
+ else:
+ kept_directories.append(directory)
+ directories[:] = kept_directories
+
+ if depth >= scan_depth:
+ if directories:
+ depth_limit_reached = True
+ directories[:] = []
+
+ for filename in files:
+ candidate = root / filename
+ if candidate.is_symlink():
+ skipped_symlinks += 1
+ continue
+ if candidate.is_file():
+ regular_files += 1
+ if regular_files > max_files_remaining:
+ raise ValueError(
+ "discovered file count exceeds --max-files"
+ )
+
+ return {
+ "path": str(resolved),
+ "kind": "directory",
+ "regular_files": regular_files,
+ "skipped_symlinks": skipped_symlinks,
+ "depth_limit_reached": depth_limit_reached,
+ }
+
+
+def plan_import(args: argparse.Namespace) -> dict[str, Any]:
+ bounded_int(
+ args.max_paths,
+ name="max-paths",
+ minimum=1,
+ maximum=100,
+ )
+ bounded_int(
+ args.max_files,
+ name="max-files",
+ minimum=1,
+ maximum=10_000,
+ )
+ bounded_int(
+ args.scan_depth,
+ name="scan-depth",
+ minimum=1,
+ maximum=20,
+ )
+ if len(args.paths) > args.max_paths:
+ raise ValueError("explicit path count exceeds --max-paths")
+
+ entries: list[dict[str, Any]] = []
+ total_files = 0
+ for raw_path in args.paths:
+ entry = scan_import_path(
+ raw_path,
+ max_files_remaining=args.max_files - total_files,
+ scan_depth=args.scan_depth,
+ )
+ total_files += entry["regular_files"]
+ scan_command = ["omero", "import", "-f", entry["path"]]
+ import_command = ["omero", "import"]
+ if args.target:
+ import_command.extend(["-T", args.target])
+ import_command.append(entry["path"])
+ entry["local_omero_scan_command"] = scan_command
+ entry["future_remote_import_command"] = import_command
+ entries.append(entry)
+
+ depth_limited = any(
+ entry["depth_limit_reached"]
+ for entry in entries
+ if entry["kind"] == "directory"
+ )
+ return {
+ "operation": "import",
+ "mode": "local-dry-run",
+ "server_contacted": False,
+ "commands_executed": False,
+ "credential_flags_included": False,
+ "target": args.target,
+ "limits": {
+ "max_paths": args.max_paths,
+ "max_files": args.max_files,
+ "scan_depth": args.scan_depth,
+ },
+ "total_regular_files": total_files,
+ "depth_limit_reached": depth_limited,
+ "ready_for_remote_import_review": not depth_limited,
+ "entries": entries,
+ "notes": [
+ "Run each local 'omero import -f' scan before any remote import.",
+ "Use a separately prompted 'omero login'; do not add -w or -k.",
+ "Importer grouping/file-format support is determined by Bio-Formats.",
+ ],
+ }
+
+
+def validated_output_directory(raw_path: str) -> Path:
+ requested = Path(raw_path).expanduser()
+ if requested.is_symlink():
+ raise ValueError("output directory must not be a symlink")
+ try:
+ resolved = requested.resolve(strict=True)
+ except FileNotFoundError as exc:
+ raise ValueError("output directory does not exist") from exc
+ if not resolved.is_dir():
+ raise ValueError("output directory is not a directory")
+ return resolved
+
+
+def plan_export(args: argparse.Namespace) -> dict[str, Any]:
+ bounded_int(
+ args.max_images,
+ name="max-images",
+ minimum=1,
+ maximum=100,
+ )
+ if len(args.selectors) > args.max_images:
+ raise ValueError("selector count exceeds --max-images")
+ if len(set(args.selectors)) != len(args.selectors):
+ raise ValueError("duplicate image selectors are not allowed")
+
+ output_directory = validated_output_directory(args.output_dir)
+ entries = []
+ for selector in args.selectors:
+ match = IMAGE_PATTERN.fullmatch(selector)
+ if match is None:
+ raise ValueError("invalid image selector")
+ image_id = int(match.group(1))
+ if args.format == "xml":
+ destination = output_directory / f"image-{image_id}.ome.xml"
+ command = [
+ "omero",
+ "export",
+ "--file",
+ str(destination),
+ "--type",
+ "XML",
+ selector,
+ ]
+ else:
+ destination = output_directory / f"image-{image_id}.ome.tiff"
+ command = [
+ "omero",
+ "export",
+ "--file",
+ str(destination),
+ selector,
+ ]
+ entries.append(
+ {
+ "selector": selector,
+ "destination": str(destination),
+ "collision": destination.exists()
+ or destination.is_symlink(),
+ "future_remote_export_command": command,
+ }
+ )
+
+ collisions = sum(bool(entry["collision"]) for entry in entries)
+ return {
+ "operation": "export",
+ "mode": "local-dry-run",
+ "server_contacted": False,
+ "commands_executed": False,
+ "credential_flags_included": False,
+ "format": args.format,
+ "output_directory": str(output_directory),
+ "limits": {"max_images": args.max_images},
+ "image_count": len(entries),
+ "collisions": collisions,
+ "ready_for_remote_export_review": collisions == 0,
+ "entries": entries,
+ "notes": [
+ "The documented export formats are OME-TIFF and XML.",
+ "This plan intentionally excludes experimental Dataset iteration.",
+ "Use a separately prompted 'omero login'; do not add -w or -k.",
+ ],
+ }
+
+
+def main(argv: list[str] | None = None) -> int:
+ parser = build_parser()
+ args = parser.parse_args(argv)
+ try:
+ if args.operation == "import":
+ payload = plan_import(args)
+ else:
+ payload = plan_export(args)
+ payload["generated_at"] = datetime.now(timezone.utc).isoformat()
+ emit_json(
+ payload,
+ output=args.output,
+ overwrite=args.overwrite,
+ )
+ return 0
+ except (
+ OutputPathError,
+ FileExistsError,
+ ValueError,
+ OSError,
+ ) as error:
+ print(scrubbed_error(error), file=sys.stderr)
+ return 2
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/skills/omero-integration/scripts/validate_config.py b/skills/omero-integration/scripts/validate_config.py
new file mode 100644
index 00000000..86400946
--- /dev/null
+++ b/skills/omero-integration/scripts/validate_config.py
@@ -0,0 +1,140 @@
+#!/usr/bin/env python3
+"""Validate named OMERO endpoint/auth variables without contacting OMERO."""
+
+from __future__ import annotations
+
+import argparse
+import json
+import socket
+import sys
+from typing import Any
+
+from omero_common import (
+ ConfigError,
+ config_summary,
+ load_connection_config,
+ scrubbed_error,
+)
+
+
+def build_parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser(
+ description=(
+ "Validate only named OMERO_* variables locally. By default this "
+ "does not resolve DNS and never contacts an OMERO server."
+ )
+ )
+ parser.add_argument(
+ "--require-auth",
+ action="store_true",
+ help=(
+ "Require OMERO_SESSION_KEY or both OMERO_USER and "
+ "OMERO_PASSWORD."
+ ),
+ )
+ parser.add_argument(
+ "--resolve-host",
+ action="store_true",
+ help=(
+ "Resolve OMERO_HOST through DNS without opening an OMERO "
+ "connection."
+ ),
+ )
+ parser.add_argument(
+ "--json",
+ action="store_true",
+ help="Emit machine-readable JSON instead of a concise text summary.",
+ )
+ return parser
+
+
+def resolve_host(host: str, port: int, *, limit: int = 10) -> list[str]:
+ """Resolve a bounded set of unique numeric addresses."""
+
+ addresses: list[str] = []
+ seen: set[str] = set()
+ for result in socket.getaddrinfo(
+ host,
+ port,
+ type=socket.SOCK_STREAM,
+ ):
+ address = result[4][0]
+ if address not in seen:
+ seen.add(address)
+ addresses.append(address)
+ if len(addresses) >= limit:
+ break
+ return addresses
+
+
+def format_text(payload: dict[str, Any]) -> str:
+ endpoint = payload["endpoint"]
+ lines = [
+ "OMERO configuration is valid.",
+ f"Endpoint: {endpoint['host']}:{endpoint['port']}",
+ f"Secure transport requested: {endpoint['secure_transport']}",
+ f"Authentication mode: {payload['authentication_mode']}",
+ "Credential values included: false",
+ ]
+ if "resolved_addresses" in payload:
+ lines.append(
+ "Resolved addresses: "
+ + ", ".join(payload["resolved_addresses"])
+ )
+ for warning in payload.get("warnings", []):
+ lines.append(f"Warning: {warning}")
+ return "\n".join(lines)
+
+
+def main(argv: list[str] | None = None) -> int:
+ args = build_parser().parse_args(argv)
+ try:
+ config = load_connection_config(require_auth=args.require_auth)
+ payload = config_summary(config)
+ payload["status"] = "valid"
+ payload["server_contacted"] = False
+ payload["warnings"] = []
+ if not config.secure:
+ payload["warnings"].append(
+ "OMERO_SECURE is false; post-login traffic may be unencrypted"
+ )
+ if config.authentication_mode == "missing":
+ payload["warnings"].append(
+ "No complete authentication credential is configured"
+ )
+ if args.resolve_host:
+ payload["resolved_addresses"] = resolve_host(
+ config.host,
+ config.port,
+ )
+ payload["dns_resolution_performed"] = True
+ else:
+ payload["dns_resolution_performed"] = False
+
+ if args.json:
+ print(json.dumps(payload, indent=2, sort_keys=True))
+ else:
+ print(format_text(payload))
+ return 0
+ except (ConfigError, socket.gaierror, OSError) as error:
+ if args.json:
+ print(
+ json.dumps(
+ {
+ "status": "invalid",
+ "server_contacted": False,
+ "error": scrubbed_error(error),
+ "credential_values_included": False,
+ },
+ indent=2,
+ sort_keys=True,
+ ),
+ file=sys.stderr,
+ )
+ else:
+ print(scrubbed_error(error), file=sys.stderr)
+ return 2
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/skills/omero-integration/tests/test_scripts.py b/skills/omero-integration/tests/test_scripts.py
new file mode 100644
index 00000000..c9d0b1ff
--- /dev/null
+++ b/skills/omero-integration/tests/test_scripts.py
@@ -0,0 +1,341 @@
+"""Synthetic tests for the OMERO helper scripts; no server is contacted."""
+
+from __future__ import annotations
+
+import argparse
+import json
+import os
+import stat
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+
+
+SKILL_ROOT = Path(__file__).resolve().parents[1]
+SCRIPTS = SKILL_ROOT / "scripts"
+sys.path.insert(0, str(SCRIPTS))
+
+import export_image_metadata # noqa: E402
+import inventory # noqa: E402
+import plan_transfer # noqa: E402
+from omero_common import ( # noqa: E402
+ ConfigError,
+ atomic_write_json,
+ config_summary,
+ json_safe,
+ load_connection_config,
+ take_bounded,
+)
+
+
+class FakeParty:
+ def __init__(self, identifier: int, username: str = "private-user"):
+ self.identifier = identifier
+ self.username = username
+
+ def getId(self) -> int:
+ return self.identifier
+
+ def getOmeName(self) -> str:
+ return self.username
+
+
+class FakeDetails:
+ def __init__(self):
+ self.owner = FakeParty(7)
+ self.group = FakeParty(8)
+
+ def getOwner(self) -> FakeParty:
+ return self.owner
+
+ def getGroup(self) -> FakeParty:
+ return self.group
+
+
+class FakeImage:
+ OMERO_CLASS = "Image"
+
+ def __init__(self, identifier: int):
+ self.identifier = identifier
+
+ def getId(self) -> int:
+ return self.identifier
+
+ def getName(self) -> str:
+ return f"sensitive-{self.identifier}"
+
+ def getDetails(self) -> FakeDetails:
+ return FakeDetails()
+
+ def getSizeX(self) -> int:
+ return 10
+
+ def getSizeY(self) -> int:
+ return 20
+
+ def getSizeZ(self) -> int:
+ return 2
+
+ def getSizeC(self) -> int:
+ return 3
+
+ def getSizeT(self) -> int:
+ return 4
+
+ def getPixelsType(self) -> str:
+ return "uint16"
+
+
+class FakeConnection:
+ def __init__(self, count: int):
+ self.objects = [FakeImage(index + 1) for index in range(count)]
+ self.requests: list[dict[str, int | str]] = []
+
+ def getObjects(self, object_type: str, opts: dict):
+ self.requests.append(dict(opts))
+ start = int(opts["offset"])
+ stop = start + int(opts["limit"])
+ return iter(self.objects[start:stop])
+
+
+class FakeFile:
+ def getId(self) -> int:
+ return 77
+
+ def getSize(self) -> int:
+ return 1234
+
+ def getMimetype(self) -> str:
+ return "text/plain"
+
+ def getName(self) -> str:
+ return "sensitive-name.txt"
+
+
+class FakeAnnotation:
+ OMERO_CLASS = "FileAnnotation"
+
+ def __init__(self):
+ self.value_read = False
+
+ def getId(self) -> int:
+ return 11
+
+ def getNs(self) -> str:
+ return "org.example"
+
+ def getDetails(self) -> FakeDetails:
+ return FakeDetails()
+
+ def getValue(self) -> str:
+ self.value_read = True
+ return "sensitive-value"
+
+ def getFile(self) -> FakeFile:
+ return FakeFile()
+
+
+class ConfigTests(unittest.TestCase):
+ def test_defaults_and_no_auth(self):
+ config = load_connection_config(
+ require_auth=False,
+ environ={"OMERO_HOST": "omero.example.org"},
+ )
+ self.assertEqual(config.port, 4064)
+ self.assertTrue(config.secure)
+ self.assertEqual(config.authentication_mode, "missing")
+
+ def test_session_key_takes_precedence_without_leaking(self):
+ environment = {
+ "OMERO_HOST": "omero.example.org",
+ "OMERO_USER": "secret-user",
+ "OMERO_PASSWORD": "secret-password",
+ "OMERO_SESSION_KEY": "secret-session",
+ }
+ config = load_connection_config(
+ require_auth=True,
+ environ=environment,
+ )
+ self.assertEqual(config.authentication_mode, "session_key")
+ serialized = json.dumps(
+ config_summary(config, environ=environment)
+ )
+ self.assertNotIn("secret-user", serialized)
+ self.assertNotIn("secret-password", serialized)
+ self.assertNotIn("secret-session", serialized)
+
+ def test_partial_password_auth_is_rejected(self):
+ with self.assertRaises(ConfigError):
+ load_connection_config(
+ require_auth=False,
+ environ={
+ "OMERO_HOST": "omero.example.org",
+ "OMERO_USER": "user-only",
+ },
+ )
+
+ def test_url_is_not_a_host(self):
+ with self.assertRaises(ConfigError):
+ load_connection_config(
+ require_auth=False,
+ environ={"OMERO_HOST": "https://omero.example.org"},
+ )
+
+
+class OutputTests(unittest.TestCase):
+ def test_atomic_json_refuses_overwrite_and_uses_private_mode(self):
+ with tempfile.TemporaryDirectory() as directory:
+ output = Path(directory) / "result.json"
+ written = atomic_write_json(
+ output,
+ {"ok": True},
+ overwrite=False,
+ )
+ self.assertEqual(json.loads(written.read_text()), {"ok": True})
+ mode = stat.S_IMODE(written.stat().st_mode)
+ self.assertEqual(mode, 0o600)
+ with self.assertRaises(FileExistsError):
+ atomic_write_json(
+ output,
+ {"ok": False},
+ overwrite=False,
+ )
+
+ def test_atomic_json_refuses_symlink(self):
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ real = root / "real.json"
+ real.write_text("{}")
+ link = root / "link.json"
+ try:
+ link.symlink_to(real)
+ except OSError:
+ self.skipTest("symlinks unavailable")
+ with self.assertRaises(ValueError):
+ atomic_write_json(link, {"ok": True}, overwrite=True)
+
+
+class BoundTests(unittest.TestCase):
+ def test_take_bounded_detects_extra_item(self):
+ result = take_bounded(range(5), 3)
+ self.assertEqual(result.items, [0, 1, 2])
+ self.assertTrue(result.truncated)
+
+ def test_json_safe_bounds_nested_values(self):
+ result = json_safe(
+ ["abcdef", "ghijkl", "mnopqr"],
+ max_string_length=3,
+ max_collection_length=2,
+ )
+ self.assertEqual(len(result), 3)
+ self.assertIn("truncated", result[0])
+ self.assertEqual(result[-1], {"truncated_items": 1})
+
+
+class InventoryTests(unittest.TestCase):
+ def test_inventory_pages_and_redacts_names(self):
+ connection = FakeConnection(7)
+ result = inventory.collect_inventory(
+ connection,
+ object_type="Image",
+ limit=5,
+ page_size=2,
+ include_names=False,
+ )
+ self.assertEqual(result["returned"], 5)
+ self.assertTrue(result["limit_reached"])
+ self.assertEqual(
+ [request["offset"] for request in connection.requests],
+ [0, 2, 4],
+ )
+ self.assertTrue(
+ all(record["name_redacted"] for record in result["records"])
+ )
+ self.assertNotIn(
+ "sensitive",
+ json.dumps(result),
+ )
+
+
+class RedactionTests(unittest.TestCase):
+ def test_annotation_value_and_filename_not_read_when_redacted(self):
+ annotation = FakeAnnotation()
+ record = export_image_metadata.annotation_record(
+ annotation,
+ include_values=False,
+ include_owner_names=False,
+ include_file_names=False,
+ max_string_length=128,
+ max_value_items=10,
+ )
+ self.assertFalse(annotation.value_read)
+ self.assertTrue(record["value_redacted"])
+ self.assertTrue(record["file"]["name_redacted"])
+ self.assertNotIn("sensitive", json.dumps(record))
+
+
+class TransferPlannerTests(unittest.TestCase):
+ def test_import_plan_is_bounded_and_contains_no_credentials(self):
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ (root / "a.tif").write_bytes(b"a")
+ (root / "b.tif").write_bytes(b"b")
+ args = argparse.Namespace(
+ paths=[str(root)],
+ target="Dataset:id:42",
+ max_paths=2,
+ max_files=2,
+ scan_depth=4,
+ )
+ plan = plan_transfer.plan_import(args)
+ self.assertEqual(plan["total_regular_files"], 2)
+ commands = [
+ command
+ for entry in plan["entries"]
+ for command in (
+ entry["local_omero_scan_command"],
+ entry["future_remote_import_command"],
+ )
+ ]
+ for command in commands:
+ self.assertNotIn("--password", command)
+ self.assertNotIn("-w", command)
+ self.assertNotIn("-k", command)
+ self.assertFalse(plan["commands_executed"])
+
+ def test_export_plan_reports_collision(self):
+ with tempfile.TemporaryDirectory() as directory:
+ output = Path(directory)
+ (output / "image-5.ome.xml").write_text("existing")
+ args = argparse.Namespace(
+ selectors=["Image:5"],
+ format="xml",
+ output_dir=str(output),
+ max_images=1,
+ )
+ plan = plan_transfer.plan_export(args)
+ self.assertEqual(plan["collisions"], 1)
+ self.assertFalse(plan["ready_for_remote_export_review"])
+ self.assertFalse(plan["commands_executed"])
+
+ def test_import_plan_caps_multiple_top_level_files(self):
+ with tempfile.TemporaryDirectory() as directory:
+ root = Path(directory)
+ first = root / "a.tif"
+ second = root / "b.tif"
+ first.write_bytes(b"a")
+ second.write_bytes(b"b")
+ args = argparse.Namespace(
+ paths=[str(first), str(second)],
+ target=None,
+ max_paths=2,
+ max_files=1,
+ scan_depth=4,
+ )
+ with self.assertRaises(ValueError):
+ plan_transfer.plan_import(args)
+
+
+if __name__ == "__main__":
+ unittest.main()