CONOPS imaging application source
Generated from docs/examples/conops-imaging/conops_imaging.py. Do not edit directly.
"""CONOPS imaging: plan a pass, image the target, segment it, analyse it, save the results.
One module, one Job. The driver runs seven phases, each announced with a `phase=` line:
0 plan ask orbit-service when each of ~76 ground targets next passes, and ask
camera-service for them soonest first until one is admitted
1 commit wait for satellite-manager to commit the capture to a pass window
2 capture wait for the exposure and for camera-service to deliver the product
3 fetch fetch the product and verify its size and checksum
4 segment MobileSAM on the GPU, plus the structured facts about what it found
5 characterise write the target, its coordinates, and the capture window
6 analyse a short description of the captured image from the platform's vLLM endpoint
Phase 0 is what makes this runnable at any time. camera-service owns the orbital maths: it
searches for the next pass itself and refuses a target it cannot image in time, so this
driver never carries a TLE. Pinning one target with TARGET_LAT/TARGET_LON is still possible;
it is simply a one-entry catalog.
Every wait has a deadline derived from that plan. A wait that expires says what it was
waiting for, how long it waited, and what it last saw: the retired version of this demo
looped forever on a `while True` and its only symptom was silence.
The Job mounts the tenant `default` PVC at /data for its durable artifacts.
The Job runs as a generated Workload Pod, so Customer Controller injects
OMNISAT_TOKEN_URL / OMNISAT_CLIENT_ID / OMNISAT_CLIENT_SECRET, the Default Workload
Machine Account. Every call to the first-party APIs carries a token minted from those.
"""
import base64
import hashlib
import json
import mimetypes
import os
import signal
import sys
import time
from datetime import UTC, datetime, timedelta
from importlib import import_module
from pathlib import Path
from typing import Any
from urllib.error import HTTPError
from urllib.parse import urlencode
from urllib.request import Request, urlopen
GATEWAY = "https://api.dphi.space"
CAMERA_API = os.getenv("CAMERA_API_URL", f"{GATEWAY}/camera/api/v1")
# orbit-service predicts passes over ground points from the mission clock; a Tenant needs
# `orbit.passes.read`. Phase 0 asks it only which target to ASK camera-service for first --
# camera-service picks the pass itself either way, and refuses what it cannot image.
ORBIT_API = os.getenv("ORBIT_API_URL", f"{GATEWAY}/orbit/api/v1")
# LLM inference is exposed through the same public gateway as the other customer APIs.
# The URL and model remain overridable so the example can follow the live model catalog.
# Phase 6 sends the captured image, so the model has to be a vision model.
VLLM_URL = os.getenv("VLLM_URL", f"{GATEWAY}/vllm/v1/chat/completions")
VLLM_MODEL = os.getenv("VLLM_MODEL", "qwen2.5-vl-3b-instruct")
# Runtime state lives OUTSIDE the Image Build context directory (`conops-imaging/`), so a
# run never adds files to what the next build would package.
RUN_DIRECTORY = Path(os.getenv("CONOPS_RUN_DIRECTORY", "/data/conops-imaging-run"))
SAM_WEIGHTS = Path(os.getenv("SAM_WEIGHTS", "/app/mobile_sam.pt"))
POLL_SECONDS = float(os.getenv("POLL_SECONDS", "5"))
REQUEST_TIMEOUT_SECONDS = 30
VLLM_TIMEOUT_SECONDS = float(os.getenv("VLLM_TIMEOUT_SECONDS", "120"))
VISION_IMAGE_LONG_EDGE = 1024
# How far ahead, in mission seconds, a capture may be scheduled. camera-service never
# searches more than two hours ahead, so a larger value only lengthens the deadline.
ACCESS_HORIZON_SECONDS = float(os.getenv("ACCESS_HORIZON_SECONDS", "7200"))
# The capture's `duration_s`: how long the camera images (line time). The reserved pointing
# window is longer: camera-service adds ~2 s pointing/command margin (plus any band stagger).
# High-resolution caps at 5 s; MultiScape200 passes at the 30 deg off-nadir limit last about
# 90 s at most, so a value near that is refused as `unsatisfiable_geometry` for every target.
MIN_WINDOW_SECONDS = float(os.getenv("MIN_WINDOW_SECONDS", "2"))
# satellite-manager commits an admitted capture to its window within seconds; this only
# bounds a scheduler that never answers.
COMMIT_DEADLINE_SECONDS = 300.0
# The delivery deadline is `mission seconds until the committed window ends x WAIT_SLACK +
# WAIT_MARGIN_SECONDS`, and it is spent in WALL seconds. The two are not the same clock: the
# simulator can run mission time faster than real time, which only ever makes the window
# arrive early, but a slower-than-real-time clock would make a tight budget expire before a
# window that is still coming. The slack is what covers that, and the margin is what covers
# the readout and product processing after it.
WAIT_SLACK = float(os.getenv("WAIT_SLACK", "2.0"))
WAIT_MARGIN_SECONDS = float(os.getenv("WAIT_MARGIN_SECONDS", "900"))
RANKED_TARGETS_LOGGED = 8
# A capture's status only moves forward through these; the rest are terminal failures.
CAPTURE_PROGRESS = ("queued", "committed", "executing", "processing", "delivered")
CAPTURE_FAILED = ("failed", "expired", "cancelled", "rejected")
# The 422 reasons that mean "not this target, not within the horizon". Every other refusal
# (admission closed, stale observation, ...) would refuse the next target too.
NO_PASS_REASONS = ("no_qualifying_pass", "unsatisfiable_geometry")
# camera-service's 30 deg off-nadir imaging limit, expressed as the elevation orbit-service
# searches by at the ~540 km orbit. Measured: camera-service's committed windows started
# within 1 s of orbit-service's >=57 deg edge.
MIN_ELEVATION_DEG = 57
# The most targets one orbit-service pass search accepts.
ORBIT_TARGETS_PER_REQUEST = 100
_token = {"value": None, "expires_at": 0.0}
class ConopsAborted(RuntimeError):
"""This Run cannot proceed, and says why rather than continuing to wait."""
class CaptureRejected(ConopsAborted):
"""satellite-manager could not schedule the capture; another target may still fit."""
# ---------------------------------------------------------------------------
# The tasking catalog
# ---------------------------------------------------------------------------
# Well-spread land targets, drawn from Softsat's demo imaging catalog. The size and the
# spread are the point: with this many candidates some target is almost always inside the
# two-hour horizon, and the demo never has to be started at a particular moment. The remote
# entries are not decoration -- they cover the Pacific, where a continents-only catalog
# leaves gaps hours long.
TARGET_CATALOG = {
"London": (51.5074, -0.1276),
"Paris": (48.8566, 2.3522),
"Berlin": (52.5200, 13.4050),
"Madrid": (40.4168, -3.7038),
"Rome": (41.9028, 12.4964),
"Venice": (45.4408, 12.3155),
"Amsterdam": (52.3676, 4.9041),
"Vienna": (48.2082, 16.3738),
"Warsaw": (52.2297, 21.0122),
"Stockholm": (59.3293, 18.0686),
"Lisbon": (38.7223, -9.1393),
"Athens": (37.9838, 23.7275),
"Istanbul": (41.0082, 28.9784),
"Moscow": (55.7558, 37.6173),
"Reykjavik": (64.1466, -21.9426),
"Casablanca": (33.5731, -7.5898),
"Algiers": (36.7538, 3.0588),
"Cairo": (30.0444, 31.2357),
"Dakar": (14.7167, -17.4677),
"Lagos": (6.5244, 3.3792),
"Addis Ababa": (9.0300, 38.7400),
"Nairobi": (-1.2921, 36.8219),
"Kinshasa": (-4.4419, 15.2663),
"Johannesburg": (-26.2041, 28.0473),
"Cape Town": (-33.9249, 18.4241),
"Riyadh": (24.7136, 46.6753),
"Dubai": (25.2048, 55.2708),
"Tehran": (35.6892, 51.3890),
"Baghdad": (33.3152, 44.3661),
"Tashkent": (41.2995, 69.2401),
"Almaty": (43.2220, 76.8512),
"Karachi": (24.8607, 67.0011),
"Delhi": (28.7041, 77.1025),
"Mumbai": (19.0760, 72.8777),
"Dhaka": (23.8103, 90.4125),
"Colombo": (6.9271, 79.8612),
"Beijing": (39.9042, 116.4074),
"Shanghai": (31.2304, 121.4737),
"Tokyo": (35.6895, 139.6917),
"Seoul": (37.5665, 126.9780),
"Taipei": (25.0330, 121.5654),
"Bangkok": (13.7563, 100.5018),
"Singapore": (1.3521, 103.8198),
"Jakarta": (-6.2088, 106.8456),
"Manila": (14.5995, 120.9842),
"Guam": (13.4443, 144.7937),
"Port Moresby": (-9.4438, 147.1803),
"Darwin": (-12.4634, 130.8456),
"Perth": (-31.9505, 115.8605),
"Sydney": (-33.8688, 151.2093),
"Melbourne": (-37.8136, 144.9631),
"Noumea": (-22.2758, 166.4580),
"Suva": (-18.1248, 178.4501),
"Auckland": (-36.8485, 174.7633),
"Christchurch": (-43.5321, 172.6362),
"Papeete": (-17.5516, -149.5585),
"Honolulu": (21.3069, -157.8583),
"Anchorage": (61.2181, -149.9003),
"Nuuk": (64.1836, -51.7214),
"Vancouver": (49.2827, -123.1216),
"Los Angeles": (34.0522, -118.2437),
"Chicago": (41.8781, -87.6298),
"New York": (40.7128, -74.0060),
"Toronto": (43.6532, -79.3832),
"Mexico City": (19.4326, -99.1332),
"Panama City": (8.9824, -79.5199),
"Caracas": (10.4806, -66.9036),
"Bogota": (4.7110, -74.0721),
"Manaus": (-3.1190, -60.0217),
"Recife": (-8.0476, -34.8770),
"Lima": (-12.0464, -77.0428),
"Santiago": (-33.4489, -70.6693),
"Buenos Aires": (-34.6037, -58.3816),
"Sao Paulo": (-23.5505, -46.6333),
"Rio de Janeiro": (-22.9068, -43.1729),
"Ushuaia": (-54.8019, -68.3030),
}
def requested_catalog() -> Any:
"""The catalog to plan over: the whole thing, or the one target the env pins."""
latitude = os.getenv("TARGET_LAT")
longitude = os.getenv("TARGET_LON")
if bool(latitude) != bool(longitude):
raise ConopsAborted("TARGET_LAT and TARGET_LON must be set together")
if latitude and longitude:
return {
os.getenv("TARGET_NAME", "pinned-target"): (
float(latitude),
float(longitude),
)
}
return TARGET_CATALOG
# ---------------------------------------------------------------------------
# Phase 0: order the catalog, and let camera-service choose
# ---------------------------------------------------------------------------
def first_passes(http: Any, orbit_api: str, catalog: Any, *, log: Any = print) -> Any:
"""Mission "now" and the mission seconds until each target's first pass, or None.
One orbit-service search per ORBIT_TARGETS_PER_REQUEST targets. Without `from` and
`to`, orbit-service searches the next 24 hours from the mission clock's "now", and
answers that "now" as `from`. A target with no pass in those 24 hours maps to None.
"""
names = list(catalog)
mission_time = None
estimates = {}
try:
for offset in range(0, len(names), ORBIT_TARGETS_PER_REQUEST):
chunk = names[offset : offset + ORBIT_TARGETS_PER_REQUEST]
answer = http(
"POST",
f"{orbit_api}/passes/search",
{
"targets": [
{
"id": name,
"latitude_deg": catalog[name][0],
"longitude_deg": catalog[name][1],
}
for name in chunk
],
"min_elevation_deg": MIN_ELEVATION_DEG,
"limit_per_target": 1,
},
)
if mission_time is None:
mission_time = _aware(answer["from"])
for name, target in zip(chunk, answer["targets"], strict=True):
if target["id"] != name:
raise ValueError(f"expected {name!r}, got {target['id']!r}")
passes = target["passes"]
estimates[name] = (
(_aware(passes[0]["start"]) - mission_time).total_seconds()
if passes
else None
)
except HTTPError as error:
detail = error_detail(error)
if error.code == 403:
detail = (
f"{detail} -- grant the Tenant `orbit.passes.read` to order the catalog"
)
log(
f"[plan] orbit-service refused the pass search ({error.code}): {detail}",
flush=True,
)
except (OSError, ValueError, LookupError, TypeError) as error:
log(f"[plan] no passes from orbit-service ({error!r})", flush=True)
else:
return mission_time, estimates
return None
def _aware(text: str) -> datetime:
moment = datetime.fromisoformat(text)
if moment.tzinfo is None:
raise ValueError(f"{text!r} has no timezone")
return moment
def plan_capture(
http: Any,
camera_api: str,
orbit_api: str,
catalog: Any,
**options: Any,
) -> Any:
"""Phase 0: offer camera-service the catalog soonest pass first, until one is admitted.
orbit-service only orders the attempts. camera-service picks the pass itself and
answers 422 for a target it cannot image within the deadline -- so a wrong or missing
prediction costs a few refused requests, never a wrong capture. Without orbit-service
the catalog is offered in its own order and camera-service defaults the deadline to
two hours of its mission time.
"""
image_name = options["image_name"]
horizon_s = options.get("horizon_s", ACCESS_HORIZON_SECONDS)
min_window_s = options.get("min_window_s", MIN_WINDOW_SECONDS)
monotonic = options.get("monotonic", time.monotonic)
log = options.get("log", print)
skip = options.get("skip", ())
passes = first_passes(http, orbit_api, catalog, log=log)
planned_at = monotonic()
if passes is None:
log("[plan] offering the catalog in its own order", flush=True)
mission_time = None
estimates = dict.fromkeys(catalog)
else:
mission_time, estimates = passes
log(
f"[plan] orbit-service passes from mission time {_iso(mission_time)}, "
f"horizon {clock(horizon_s)}, {len(catalog)} targets",
flush=True,
)
ranked = sorted(
catalog, key=lambda name: (estimates[name] is None, estimates[name] or 0.0)
)
for rank, name in enumerate(ranked[:RANKED_TARGETS_LOGGED], start=1):
estimate = estimates[name]
log(
f"[plan] {rank:>2}. {name:<16} "
+ ("no estimate" if estimate is None else f"visible in ~{clock(estimate)}"),
flush=True,
)
expire_at = (
None if mission_time is None else mission_time + timedelta(seconds=horizon_s)
)
for name in ranked:
if name in skip:
continue
latitude, longitude = catalog[name]
try:
created = http(
"POST",
f"{camera_api}/capture/create",
{
"target": {"type": "point", "coordinates": [longitude, latitude]},
# The only profile camera-service accepts today.
"imaging": {"resolution": "high", "bands": ["PAN"]},
"timing": {"kind": "asap"},
"delivery": "offline",
"deadline": {
"kind": "expire_at",
"expire_at": None if expire_at is None else _iso(expire_at),
},
"duration_s": min_window_s,
},
headers={"Idempotency-Key": f"{image_name}-{name}"},
)
except HTTPError as error:
detail = error_detail(error)
if error.code == 422 and detail in NO_PASS_REASONS:
log(f"[plan] {name}: {detail}", flush=True)
continue
raise ConopsAborted(
f"camera-service refused the capture of {name} ({error.code}): {detail}"
) from None
estimate = estimates[name]
return {
"name": name,
"lat": latitude,
"lon": longitude,
"capture_id": created["capture_id"],
"duration_s": min_window_s,
"mission_time": mission_time,
"planned_at": planned_at,
"estimated_at": (
None
if estimate is None
else _iso(mission_time + timedelta(seconds=estimate))
),
}
raise ConopsAborted(
f"camera-service found no pass for any of the {len(catalog)} targets within "
f"{clock(horizon_s)}. Widen the catalog, or check the scenario TLE."
)
# ---------------------------------------------------------------------------
# Phases 1-2: the bounded waits on camera-service
# ---------------------------------------------------------------------------
def follow_capture(http: Any, camera_api: str, plan: Any, **options: Any) -> Any:
"""Phases 1-2: wait for the commit, then for delivery. Returns the delivered status.
Any abort before delivery withdraws the capture, so a Run that gave up does not leave
the spacecraft imaging for nobody.
"""
monotonic = options.get("monotonic", time.monotonic)
log = options.get("log", print)
capture_id = plan["capture_id"]
try:
phase(1, "commit", f"capture {capture_id} of {plan['name']}")
committed = wait_for_capture(
http,
camera_api,
capture_id,
reached="committed",
deadline_seconds=COMMIT_DEADLINE_SECONDS,
**options,
)
window = committed.get("window") or {}
log(
f"[commit] window {window.get('start')} -> {window.get('end')}; "
f"orbit-service predicted the first pass at {plan['estimated_at'] or 'unknown'}",
flush=True,
)
phase(2, "capture", "waiting for the exposure and the product")
if plan["mission_time"] is None or not window:
# camera-service never commits a pass beyond its own horizon.
until_end = ACCESS_HORIZON_SECONDS
else:
end = datetime.fromisoformat(window["end"])
until_end = max(0.0, (end - plan["mission_time"]).total_seconds())
deadline = until_end * WAIT_SLACK + WAIT_MARGIN_SECONDS
deadline -= monotonic() - plan["planned_at"]
started = monotonic()
wait_for_capture(
http,
camera_api,
capture_id,
reached="executing",
deadline_seconds=deadline,
**options,
)
delivered = wait_for_capture(
http,
camera_api,
capture_id,
reached="delivered",
deadline_seconds=deadline - (monotonic() - started),
**options,
)
except CaptureRejected:
raise
except BaseException:
cancel_capture(http, camera_api, capture_id, log=log)
raise
return delivered
def wait_for_capture(
http: Any,
camera_api: str,
capture_id: str,
**options: Any,
) -> Any:
"""Poll the capture's status until it has `reached` a stage, and return that status.
A terminal failure ends the Run with camera-service's reason. A failing status read is
logged and retried; it decides nothing. This component holds a GPU, so a capture that
is never coming has to end the Run rather than be waited on.
"""
reached = CAPTURE_PROGRESS[CAPTURE_PROGRESS.index(options["reached"]) :]
deadline_seconds = options["deadline_seconds"]
poll_seconds = options.get("poll_seconds", POLL_SECONDS)
sleep = options.get("sleep", time.sleep)
log = options.get("log", print)
monotonic = options.get("monotonic", time.monotonic)
url = f"{camera_api}/capture/status?{urlencode({'capture_id': capture_id})}"
started = monotonic()
last_seen = "nothing yet"
while True:
try:
status = http("GET", url)
except OSError as error:
log(f"[capture] status unavailable: {error}", flush=True)
else:
seen = (
f"status={status.get('status')} "
f"activity_state={status.get('activity_state')}"
)
if seen != last_seen:
log(f"[capture] {seen}", flush=True)
last_seen = seen
if status.get("status") in reached:
return status
if status.get("status") in CAPTURE_FAILED:
failure = (
CaptureRejected if status["status"] == "rejected" else ConopsAborted
)
raise failure(
f"capture {capture_id} is {status['status']}: "
f"reason_code={status.get('reason_code')} "
f"activity_reason={status.get('activity_reason')}"
)
waited = monotonic() - started
if waited >= deadline_seconds:
raise ConopsAborted(
f"capture {capture_id} had not reached {reached[0]} after {clock(waited)} "
f"(budget {clock(deadline_seconds)}); camera-service last reported "
f"{last_seen}"
)
sleep(poll_seconds)
def cancel_capture(
http: Any, camera_api: str, capture_id: str, *, log: Any = print
) -> None:
"""Best effort, and never raises: the abort that led here is the error to report."""
try:
response = http(
"POST",
f"{camera_api}/capture/cancel",
{"capture_id": capture_id},
headers={"Idempotency-Key": f"cancel-{capture_id}"},
)
log(f"[cancel] {response}", flush=True)
except OSError as error:
log(
f"[cancel] capture {capture_id} was not cancelled: {error_detail(error) or error}",
flush=True,
)
def error_detail(error: Any) -> Any:
"""The `detail` an HTTPError carries, or its reason when there is no JSON body."""
try:
return json.loads(error.read())["detail"]
except (ValueError, KeyError, OSError, AttributeError, TypeError):
return getattr(error, "reason", "") or ""
def clock(seconds: float) -> str:
"""Seconds as `07m18s` / `2h04m18s`, for lines a human reads while waiting."""
seconds = round(seconds)
sign = "-" if seconds < 0 else ""
hours, remainder = divmod(abs(seconds), 3600)
minutes, whole_seconds = divmod(remainder, 60)
if hours:
return f"{sign}{hours}h{minutes:02d}m{whole_seconds:02d}s"
return f"{sign}{minutes:02d}m{whole_seconds:02d}s"
def _iso(moment: datetime) -> str:
return moment.astimezone(UTC).isoformat().replace("+00:00", "Z")
def access_token() -> Any:
"""A client_credentials token for the Default Workload Machine Account, cached."""
value, expires_at = _token["value"], _token["expires_at"]
if value and expires_at is not None and time.monotonic() < expires_at:
return value
request = Request(
os.environ["OMNISAT_TOKEN_URL"],
data=urlencode(
{
"grant_type": "client_credentials",
"client_id": os.environ["OMNISAT_CLIENT_ID"],
"client_secret": os.environ["OMNISAT_CLIENT_SECRET"],
}
).encode(),
headers={"Content-Type": "application/x-www-form-urlencoded"},
method="POST",
)
with urlopen(request, timeout=REQUEST_TIMEOUT_SECONDS) as response:
body = json.load(response)
_token["value"] = body["access_token"]
_token["expires_at"] = time.monotonic() + float(body.get("expires_in", 300)) - 30
return _token["value"]
def http_json(
method: str,
url: str,
body: Any = None,
timeout: float = REQUEST_TIMEOUT_SECONDS,
*,
headers: Any = None,
raw: bool = False,
) -> Any:
"""One authenticated request, JSON unless `raw`. This is the callable every phase is given."""
request = Request(
url,
data=None if body is None else json.dumps(body).encode(),
headers={
"Content-Type": "application/json",
"Authorization": f"Bearer {access_token()}",
**(headers or {}),
},
method=method,
)
with urlopen(request, timeout=timeout) as response:
return response.read() if raw else json.load(response)
# ---------------------------------------------------------------------------
# Role: conops-driver (mode: job, gpuRequest: true)
# ---------------------------------------------------------------------------
def write_file(path: Path, content: bytes) -> None:
"""Publish a durable artifact, visible only once it is complete."""
path.parent.mkdir(parents=True, exist_ok=True)
partial = path.with_name(f".{path.name}.partial")
partial.write_bytes(content)
partial.replace(path)
def fetch_product(
http: Any, camera_api: str, product_id: str, directory: Path, image_name: str
) -> Any:
"""Phase 3: fetch the product, verify it against its metadata, and save it.
The metadata `url` (often `memory://…`) is not fetchable from a Workload; the bytes
come from the same endpoint with `download=true`. Products are 16-bit TIFF
(`image/tiff`). Returns `(path, metadata)`.
"""
url = f"{camera_api}/asset/read?{urlencode({'product_id': product_id})}"
metadata = http("GET", url)
content = http("GET", f"{url}&download=true", raw=True)
checksum = f"sha256:{hashlib.sha256(content).hexdigest()}"
if len(content) != metadata["byte_size"] or checksum != metadata["checksum"]:
raise ConopsAborted(
f"product {product_id} arrived as {len(content)} bytes {checksum}, but "
f"camera-service catalogued {metadata['byte_size']} bytes {metadata['checksum']}"
)
# Prefer .tif for image/tiff; guess_extension can return .tiff depending on Python.
content_type = metadata["content_type"]
if content_type == "image/tiff":
suffix = ".tif"
else:
suffix = mimetypes.guess_extension(content_type) or ".bin"
path = directory / f"{image_name}{suffix}"
write_file(path, content)
return path, metadata
def as_eight_bit_png(image_path: Path) -> Path:
"""Turn a single-band TIFF capture into an 8-bit RGB PNG for SAM and the LLM.
Softsat products arrive as 16-bit single-band TIFFs whose DN values sit far below
the full uint16 range. OpenCV's default 8-bit load truncates them to near-black, and
the vision endpoint's Pillow decoder rejects the raw TIFF outright. Stretch the band
to uint8, expand to RGB, and write a PNG next to the original. Non-TIFF inputs are
left alone.
"""
if image_path.suffix.lower() not in {".tif", ".tiff"}:
return image_path
cv2 = import_module("cv2")
numpy = import_module("numpy")
band = cv2.imread(str(image_path), cv2.IMREAD_UNCHANGED)
if band is None:
raise ConopsAborted(
f"could not read the capture at {image_path} as a TIFF"
)
# One band: a 2-D array, or a trailing singleton channel from some writers.
if band.ndim == 3:
band = band[:, :, 0]
if band.ndim != 2:
raise ConopsAborted(
f"expected a single-band TIFF at {image_path}, got shape {band.shape}"
)
if band.dtype == numpy.uint8:
scaled = band
else:
pixels = band.astype(numpy.float32)
low, high = numpy.percentile(pixels, (2.0, 98.0))
if not high > low:
low, high = float(pixels.min()), float(pixels.max())
if not high > low:
scaled = numpy.zeros(band.shape, dtype=numpy.uint8)
else:
scaled = numpy.clip(
(pixels - low) * (255.0 / (high - low)), 0, 255
).astype(numpy.uint8)
png_path = image_path.with_suffix(".png")
rgb = cv2.cvtColor(scaled, cv2.COLOR_GRAY2BGR)
if not cv2.imwrite(str(png_path), rgb):
raise ConopsAborted(f"could not write the 8-bit PNG at {png_path}")
print(
f"wrote 8-bit PNG {png_path} from single-band {image_path.name} "
f"({band.dtype}, {band.shape[1]}x{band.shape[0]})",
flush=True,
)
return png_path
def segment(image_path: Path, output_path: Path) -> Any:
"""Phase 4: run MobileSAM over the capture, and report what it found.
Returns `(path, facts)`. torch and ultralytics are imported HERE, not at module scope, so
the module stays importable wherever the GPU stack is not installed, and the unit tests
import the module directly. Any heavy import added later belongs here too.
"""
torch = import_module("torch")
SAM = import_module("ultralytics").SAM
if not SAM_WEIGHTS.is_file():
raise ConopsAborted(f"SAM weights not found: {SAM_WEIGHTS}")
sam_input = as_eight_bit_png(image_path)
device = "cuda" if torch.cuda.is_available() else "cpu"
print(f"segmenting {sam_input} on {device}", flush=True)
predictions = SAM(str(SAM_WEIGHTS)).predict(
str(sam_input), imgsz=640, device=device, verbose=True
)
size = sam_input.stat().st_size if sam_input.is_file() else 0
if not predictions:
raise ConopsAborted(
f"the capture at {sam_input} ({size} bytes) is not an image the segmenter "
"could read"
)
results = predictions[0]
if results.masks is None:
raise ConopsAborted(
f"MobileSAM found no masks in {sam_input} ({size} bytes); a frame without "
"scene content, such as an all-black simulated capture, has nothing to segment"
)
masks = results.masks.data # (N, H, W)
height, width = masks.shape[1], masks.shape[2]
area = masks.sum(dim=(1, 2))
# Drop the frame-sized masks and the specks; what is left is the scene content.
keep = (area < 0.75 * height * width) & (area > 0.005 * height * width)
results.masks.data = masks[keep]
if results.boxes is not None:
results.boxes = results.boxes[keep]
kept_area = area[keep]
facts = {
"mask_count": int(kept_area.numel()),
"largest_mask_coverage": (
round(float(kept_area.max()) / (height * width), 4)
if kept_area.numel()
else 0.0
),
"width": int(width),
"height": int(height),
}
results.save(filename=str(output_path), boxes=True)
return output_path, facts
def characterise(image_name: str, plan: dict[str, Any], status: dict[str, Any]) -> Path:
"""Phase 5: write the target and the capture window camera-service reported.
The start and end come from the delivered capture status. `duration_s` is the imaging
duration that was requested for that capture.
"""
phase(5, "characterise", f"capture window for {plan['name']}")
window = status.get("window") or {}
start_at, end_at = window.get("start"), window.get("end")
if not start_at or not end_at:
raise ConopsAborted(
f"capture {plan['capture_id']} was delivered without a window start and end"
)
record = {
"target": plan["name"],
"coordinates": {
"latitude_deg": plan["lat"],
"longitude_deg": plan["lon"],
},
"start": start_at,
"end": end_at,
"duration_s": plan["duration_s"],
}
pass_path = RUN_DIRECTORY / f"{image_name}-pass.json"
write_file(pass_path, (json.dumps(record, indent=2) + "\n").encode())
print(f"[pass] {json.dumps(record)}", flush=True)
return pass_path
def vision_image_payload(image_path: Path) -> tuple[str, bytes]:
"""Bound the vision prompt's image tokens while preserving the saved artifact."""
image_path = as_eight_bit_png(image_path)
cv2 = import_module("cv2")
image = cv2.imread(str(image_path))
if image is None:
raise ValueError(f"could not read vision input {image_path}")
height, width = image.shape[:2]
long_edge = max(height, width)
if long_edge <= VISION_IMAGE_LONG_EDGE:
mime = mimetypes.guess_type(image_path.name)[0] or "application/octet-stream"
return mime, image_path.read_bytes()
scale = VISION_IMAGE_LONG_EDGE / long_edge
dimensions = (max(1, round(width * scale)), max(1, round(height * scale)))
resized = cv2.resize(image, dimensions, interpolation=cv2.INTER_AREA)
written, encoded = cv2.imencode(".png", resized)
if not written:
raise ValueError(f"could not encode resized vision input {image_path}")
return "image/png", encoded.tobytes()
def analyse(
http: Any,
image_path: Path,
target_name: str,
*,
url: str = VLLM_URL,
model: str = VLLM_MODEL,
log: Any = print,
) -> str:
"""Phase 6: ask for a short description of the captured image.
The request carries the image and the target location's name. Single-band TIFFs are
converted to an 8-bit PNG first: the vision endpoint's decoder rejects the raw
product the same way MobileSAM's loader does. A model that is unreachable,
unauthorised or slow must not discard the captured results: the failure is logged
and a placeholder report is saved instead.
"""
prompt = (
f"The target location is {target_name}. "
"Describe this image in at most five sentences."
)
try:
mime, image_bytes = vision_image_payload(image_path)
encoded = base64.b64encode(image_bytes).decode("ascii")
body = http(
"POST",
url,
{
"model": model,
"messages": [
{
"role": "user",
"content": [
{"type": "text", "text": prompt},
{
"type": "image_url",
"image_url": {"url": f"data:{mime};base64,{encoded}"},
},
],
}
],
"max_tokens": 300,
"temperature": 0.2,
},
VLLM_TIMEOUT_SECONDS,
)
report: str = body["choices"][0]["message"]["content"].strip()
if not report:
raise ValueError("empty completion")
except (OSError, ValueError, KeyError, IndexError, TypeError) as error:
log(
f"[analyse] {model} unavailable ({error!r}); carrying a placeholder report",
flush=True,
)
return (
f"The analysis model {model} could not describe the image of {target_name}: "
f"{error!r}\n"
)
return report
def phase(number: int, name: str, detail: str = "") -> None:
print(f"phase={name} ({number}/6) {detail}".rstrip(), flush=True)
def capture_name() -> str:
"""Give each Job's artifacts and capture requests a distinct name, across reruns too."""
prefix = os.getenv("IMAGE_NAME", "conops_capture")
pod_name = os.getenv("HOSTNAME", "local")
return f"{prefix}-{pod_name}"
def run_driver() -> None:
image_name = capture_name()
RUN_DIRECTORY.mkdir(parents=True, exist_ok=True)
print(f"gateway {GATEWAY}", flush=True)
catalog = requested_catalog()
# camera-service admits any pass it can see, but satellite-manager also needs time to
# prepare inside the pass and can still reject it; the next target may fit.
rejected = set()
while True:
phase(0, "plan", f"ordering {len(catalog)} targets by their next pass")
plan = plan_capture(
http_json,
CAMERA_API,
ORBIT_API,
catalog,
image_name=image_name,
skip=rejected,
)
print(
f"[plan] camera-service admitted {plan['name']} ({plan['lat']}, {plan['lon']}) "
f"as capture {plan['capture_id']}",
flush=True,
)
try:
delivered = follow_capture(http_json, CAMERA_API, plan)
break
except CaptureRejected as rejection:
print(f"[plan] {rejection}; trying the next target", flush=True)
rejected.add(plan["name"])
phase(3, "fetch", f"product {delivered['assets'][0]}")
image_path, product = fetch_product(
http_json, CAMERA_API, delivered["assets"][0], RUN_DIRECTORY, image_name
)
print(f"[fetch] saved {image_path} ({product['byte_size']} bytes)", flush=True)
# Softsat TIFFs need an 8-bit PNG before both MobileSAM and the image-capable LLM.
viewable_path = as_eight_bit_png(image_path)
phase(4, "segment", "MobileSAM over the capture")
segmented_path, facts = segment(
viewable_path, RUN_DIRECTORY / f"{image_name}-segmented.png"
)
print(f"[segment] saved {segmented_path}: {json.dumps(facts)}", flush=True)
pass_path = characterise(image_name, plan, delivered)
phase(6, "analyse", f"{VLLM_MODEL} describing the capture of {plan['name']}")
report = analyse(http_json, viewable_path, plan["name"])
report_path = RUN_DIRECTORY / f"{image_name}-report.txt"
report_path.write_text(report + "\n")
print(f"[analyse] {report}", flush=True)
print(f"phase=done {plan['name']} results saved in {RUN_DIRECTORY}", flush=True)
def main(argv: list[str]) -> None:
if len(argv) != 1:
raise SystemExit("usage: conops_imaging.py")
# Cancelling the Run sends SIGTERM. Exit through Python so an admitted capture is
# withdrawn on the way out instead of being left committed on the spacecraft.
signal.signal(signal.SIGTERM, lambda *_: sys.exit(143))
try:
run_driver()
except ConopsAborted as aborted:
# A demo that fails should say what it was waiting for on its last line, not print
# a traceback whose most useful frame is a sleep.
raise SystemExit(f"conops imaging aborted: {aborted}") from None
if __name__ == "__main__":
main(sys.argv)