Local preservation snapshot, not a new deployment or simulation acceptance.
200 lines
7.2 KiB
Python
200 lines
7.2 KiB
Python
"""Bounded, read-only operator views selected from the executed composition ports.
|
|
|
|
Register a port renderer here when a provider adds an observable output. The UI
|
|
uses descriptors, not model names. No preview is ever fed back into inference.
|
|
"""
|
|
|
|
import base64
|
|
import io
|
|
import time
|
|
from dataclasses import dataclass
|
|
|
|
import numpy as np
|
|
from local_state import write_json
|
|
from PIL import Image, ImageDraw
|
|
|
|
|
|
def jpeg(image, size=(400, 300)):
|
|
output = io.BytesIO()
|
|
image.resize(size, Image.Resampling.BILINEAR).save(output, "JPEG", quality=72)
|
|
raw = base64.b64encode(output.getvalue()).decode()
|
|
if len(raw) > 100000:
|
|
raise ValueError("Preview exceeds budget")
|
|
return raw
|
|
|
|
|
|
def overlay(original, colors):
|
|
image = original.copy()
|
|
crop = Image.fromarray(colors).resize((600, 600), Image.Resampling.NEAREST)
|
|
image.paste(Image.blend(original.crop((100, 0, 700, 600)), crop, 0.6), (100, 0))
|
|
return image
|
|
|
|
|
|
def segmentation(original, values, names):
|
|
labels = values["segmentation.labels"].astype(np.uint16)
|
|
colors = np.stack(
|
|
((labels * 67 + 41) % 255, (labels * 131 + 97) % 255, (labels * 47 + 173) % 255), axis=-1
|
|
).astype(np.uint8)
|
|
ids, counts = np.unique(labels, return_counts=True)
|
|
legend = [
|
|
{
|
|
"class_id": int(i),
|
|
"label": names.get(int(i), f"Класс {i}"),
|
|
"color": "#"
|
|
+ "".join(
|
|
f"{int(c):02x}"
|
|
for c in ((i * 67 + 41) % 255, (i * 131 + 97) % 255, (i * 47 + 173) % 255)
|
|
),
|
|
}
|
|
for i in ids[np.argsort(counts)[::-1][:8]]
|
|
]
|
|
return {"kind": "image", "jpeg": jpeg(overlay(original, colors)), "legend": legend}
|
|
|
|
|
|
def surface(original, values, names):
|
|
colors = np.zeros((512, 512, 3), dtype=np.uint8)
|
|
colors[:] = [215, 60, 55]
|
|
colors[values["navigation.surface"]] = [140, 220, 80]
|
|
return {
|
|
"kind": "image",
|
|
"jpeg": jpeg(overlay(original, colors)),
|
|
"legend": [
|
|
{"class_id": 1, "label": "Разрешённое покрытие", "color": "#8cdc50"},
|
|
{"class_id": 0, "label": "Не разрешено", "color": "#d73c37"},
|
|
],
|
|
}
|
|
|
|
|
|
def detection(original, values, names):
|
|
image = original.copy()
|
|
draw = ImageDraw.Draw(image)
|
|
for x1, y1, x2, y2 in values["detection.boxes"]:
|
|
draw.rectangle((x1 * 800, y1 * 600, x2 * 800, y2 * 600), outline=(255, 200, 70), width=3)
|
|
return {"kind": "image", "jpeg": jpeg(image)}
|
|
|
|
|
|
def lidar(original, values, names):
|
|
points = np.asarray(values["source.lidar"], dtype=float).reshape(-1, 3)
|
|
points = points[np.isfinite(points).all(axis=1)]
|
|
pose = np.asarray(values["source.pose"], dtype=float)
|
|
x, y, z, w = pose[3:] / np.linalg.norm(pose[3:])
|
|
rotation = np.array(
|
|
[
|
|
[1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w)],
|
|
[2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w)],
|
|
[2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y)],
|
|
]
|
|
)
|
|
count = len(points)
|
|
# Display sampling only. Inference retains the complete original returns.
|
|
points = points[:: max(1, int(np.ceil(count / 2048)))]
|
|
points = (points - pose[:3]) @ rotation
|
|
return {
|
|
"kind": "points3d",
|
|
"points": np.round(points, 4).tolist(),
|
|
"source_count": count,
|
|
"frame": "body-x-forward-y-left-z-up",
|
|
}
|
|
|
|
|
|
def camera_layers(observation):
|
|
"""Read-only views of the same timestamped sensor packet used for fusion."""
|
|
layers = []
|
|
names = (
|
|
("insta360_panorama", "Insta360 · панорама", (640, 320)),
|
|
("insta360_left", "Insta360 · левая линза", (320, 320)),
|
|
("insta360_right", "Insta360 · правая линза", (320, 320)),
|
|
("realsense_rgb", "RealSense · изображение", (400, 300)),
|
|
)
|
|
for key, label, size in names:
|
|
if key not in observation.get("camera_sources", {}):
|
|
continue
|
|
layers.append(
|
|
{
|
|
"id": key.replace("_", "-"),
|
|
"label": label,
|
|
"kind": "image",
|
|
"ports": ["source.camera." + key],
|
|
"image_size": list(size),
|
|
"jpeg": jpeg(Image.fromarray(observation["camera_sources"][key]), size),
|
|
}
|
|
)
|
|
if "realsense_depth" in observation:
|
|
depth = np.asarray(observation["realsense_depth"])
|
|
valid = np.isfinite(depth) & (depth >= 0.52) & (depth <= 6.0)
|
|
gray = np.zeros(depth.shape, dtype=np.uint8)
|
|
gray[valid] = np.round(32 + 223 * (6.0 - depth[valid]) / (6.0 - 0.52)).astype(np.uint8)
|
|
layers.append(
|
|
{
|
|
"id": "realsense-depth",
|
|
"label": "RealSense · глубина",
|
|
"kind": "image",
|
|
"ports": ["source.realsense.depth"],
|
|
"image_size": [400, 300],
|
|
"jpeg": jpeg(Image.fromarray(gray)),
|
|
"legend": [
|
|
{"class_id": 0, "label": "Нет измерения", "color": "#000000"},
|
|
{"class_id": 1, "label": "0,52 м", "color": "#ffffff"},
|
|
{"class_id": 2, "label": "6 м", "color": "#202020"},
|
|
],
|
|
}
|
|
)
|
|
return layers
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class PortView:
|
|
id: str
|
|
label: str
|
|
ports: tuple[str, ...]
|
|
render: object
|
|
|
|
|
|
PORT_VIEWS = (
|
|
PortView("segmentation", "Сегментация", ("segmentation.labels",), segmentation),
|
|
PortView("surface", "Проходимость", ("navigation.surface",), surface),
|
|
PortView("detection", "Детекция", ("detection.boxes",), detection),
|
|
PortView("lidar", "LiDAR", ("source.lidar", "source.pose"), lidar),
|
|
)
|
|
|
|
|
|
class InferencePreview:
|
|
def __init__(self, directory, graph, environment, names=None):
|
|
self.path = directory.parent / "inference-preview.json"
|
|
self.graph, self.environment = graph, environment
|
|
self.last = 0.0
|
|
self.names = names or {}
|
|
# A source existing in the observation does not imply this composition
|
|
# consumes it. Admit only outputs/inputs of the resolved graph.
|
|
ports = {port for node in graph.nodes for port in node.module.provides}
|
|
ports.update(port for node in graph.nodes for port, _ in node.inputs)
|
|
self.views = [view for view in PORT_VIEWS if set(view.ports) <= ports]
|
|
|
|
def publish(self, rgb, values, observation, frame_id):
|
|
now = time.monotonic()
|
|
if now - self.last < 0.5:
|
|
return
|
|
self.last = now
|
|
original = Image.fromarray(rgb)
|
|
layers = [
|
|
{
|
|
"id": view.id,
|
|
"label": view.label,
|
|
"ports": list(view.ports),
|
|
**view.render(original, values, self.names),
|
|
}
|
|
for view in self.views
|
|
if all(port in values for port in view.ports)
|
|
]
|
|
layers.extend(camera_layers(observation))
|
|
write_json(
|
|
self.path,
|
|
{
|
|
"frame_id": frame_id,
|
|
"simulation_time_ns": observation["simulation_time_ns"],
|
|
"composition_sha256": self.graph.sha256,
|
|
"environment": self.environment,
|
|
"layers": layers,
|
|
},
|
|
)
|