Files
NODEDC_MISSION_CORE/simulation/ai-polygon/qualify_surface_sequence.py
T
DCCONSTRUCTIONS d0e5f90952 Preserve installed operator workspace before consolidation
Local preservation snapshot, not a new deployment or simulation acceptance.
2026-10-08 09:59:51 +03:00

154 lines
6.4 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Replay identical archived JPEGs in either installed surface-provider image.
No runtime, network or motion authority. Keep the reference model, decoder and
preprocessing unchanged; retain per-frame labels and identities for comparison
with the original ADE output and separately authored image annotations.
"""
import argparse
import csv
import hashlib
import importlib.util
import json
import time
from datetime import datetime, timezone
from pathlib import Path
import numpy as np
from PIL import Image
def sha256(path):
return hashlib.sha256(path.read_bytes()).hexdigest()
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--camera", required=True, type=Path)
parser.add_argument("--output", required=True, type=Path)
parser.add_argument("--frames", required=True, help="Comma-separated immutable frame IDs")
parser.add_argument("--provider", choices=("goose", "ade"), default="goose")
args = parser.parse_args()
frames = sorted(set(int(value) for value in args.frames.split(",")))
if not frames or len(frames) > 512 or min(frames) < 1:
raise ValueError("Expected 1–512 positive frame IDs")
if args.output.exists():
raise ValueError("Replay output must be a new evidence directory")
runner = Path("/assets/ddrnet-goose-runner.py")
checkpoint = Path("/assets/ddrnet-checkpoint.pth")
mapping = Path("/assets/ddrnet-goose-mapping.csv")
expected = {
runner: "b18ad60f277eea69a240a28f290611b94627fb9707faf1bb3e6e22102dad67c1",
checkpoint: "b99c2838051bcd7b092fd3970aa62a77d5c0bbb809c9b9afb2ff4b0ebdaa4ee6",
mapping: "88ae319ba5a3877dd3ae0773f693a6a5fdc283934140de9dfaff029108aefd7f",
}
if args.provider == "ade":
expected = {
Path(
"/assets/config.json"
): "ee7400840fdb1e5045f0b2eba78bf053df8e33a309c4acec31705a48c8cc5c00",
Path(
"/assets/preprocessor_config.json"
): "8039d1d210abaa7117ad78e58cdfd6141a2ec72c03dae891b3cd76737e422c6c",
Path(
"/assets/pytorch_model.bin"
): "187ca07bea003a5717c63d04ea90b07f33cd033c0ebf44b4b89fce5070d6c8f3",
}
for path, digest in expected.items():
if sha256(path) != digest:
raise ValueError("Pinned asset changed: " + path.name)
images = [args.camera / f"{frame:08d}.jpg" for frame in frames]
if not all(image.is_file() for image in images):
raise ValueError("Requested source frame is missing")
if args.provider == "goose":
spec = importlib.util.spec_from_file_location("pinned_goose", runner)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
model, _, _ = module.load_model("ddrnet", checkpoint)
with mapping.open() as stream:
names = {int(row["label_key"]): row["class_name"] for row in csv.DictReader(stream)}
def infer(original):
tensor, _ = module.preprocess(original)
labels, elapsed = module.infer(model, tensor)
return labels, None, elapsed
else:
import torch
from transformers import SegformerForSemanticSegmentation, SegformerImageProcessor
processor = SegformerImageProcessor.from_pretrained("/assets", local_files_only=True)
model = (
SegformerForSemanticSegmentation.from_pretrained("/assets", local_files_only=True)
.cuda()
.eval()
)
torch.set_num_threads(2)
names = {int(k): v for k, v in model.config.id2label.items()}
def infer(original):
started = time.monotonic()
tensor = processor(images=original.crop((100, 0, 700, 600)), return_tensors="pt")[
"pixel_values"
].cuda()
with torch.inference_mode():
logits = model(tensor).logits
logits = torch.nn.functional.interpolate(
logits, size=(512, 512), mode="bilinear", align_corners=False
)
confidence, labels = logits.softmax(1).max(1)
labels = labels[0].cpu().numpy().astype(np.uint8)
candidate = np.isin(labels, (3, 6, 9, 11, 13, 29, 34, 46, 52, 91)) & (
confidence[0].cpu().numpy() >= 0.55
)
return labels, candidate, (time.monotonic() - started) * 1000
args.output.mkdir(parents=True)
report = {
"schema_version": "missioncore.surface-sequence-replay/v1",
"utc": datetime.now(timezone.utc).isoformat(), # noqa: UP017 (pinned Python 3.9 image)
"monotonic_ns": time.monotonic_ns(),
"authority": "offline-no-motion",
"provider": args.provider,
"assets": {path.name: digest for path, digest in expected.items()},
"frames": [],
}
for image in images:
with Image.open(image) as original:
if original.size != (800, 600):
raise ValueError("Expected simulation RGB dimensions")
labels, candidate, elapsed_ms = infer(original.convert("RGB"))
if labels.shape != (512, 512) or not np.isin(labels, list(names)).all():
raise ValueError("Surface output contract changed")
destination = args.output / (image.stem + ".labels.png")
Image.fromarray(labels.astype(np.uint8)).save(destination)
surface = args.output / (image.stem + ".surface.png")
if candidate is not None:
Image.fromarray(candidate.astype(np.uint8) * 255).save(surface)
ids, counts = np.unique(labels, return_counts=True)
report["frames"].append(
{
"frame_id": int(image.stem),
"source_sha256": sha256(image),
"labels_sha256": sha256(destination),
"surface_sha256": sha256(surface) if candidate is not None else None,
"inference_ms": elapsed_ms,
"classes": {names[int(i)]: int(counts[n]) for n, i in enumerate(ids)},
}
)
report["completed_utc"] = datetime.now(timezone.utc).isoformat() # noqa: UP017
report["completed_monotonic_ns"] = time.monotonic_ns()
(args.output / "report.json").write_text(json.dumps(report, indent=2), encoding="utf-8")
print(
json.dumps(
{
"frames": len(frames),
"output": str(args.output),
"report_sha256": sha256(args.output / "report.json"),
}
)
)
if __name__ == "__main__":
main()