"""Pinned urban surface inference; potential crossings grant no driving authority.""" import hashlib import json from http.server import BaseHTTPRequestHandler, HTTPServer from pathlib import Path import numpy as np import torch from PIL import Image from transformers import AutoImageProcessor, Mask2FormerForUniversalSegmentation def main(): descriptor = json.loads(Path(__file__).with_name("model.json").read_text()) for name, expected in descriptor["files"].items(): digest = hashlib.sha256() with (Path("/assets") / name).open("rb") as stream: for chunk in iter(lambda: stream.read(1024 * 1024), b""): digest.update(chunk) if digest.hexdigest() != expected: raise RuntimeError("Mapillary asset identity changed: " + name) processor = AutoImageProcessor.from_pretrained("/assets", local_files_only=True) model = Mask2FormerForUniversalSegmentation.from_pretrained("/assets", local_files_only=True).cuda().eval() torch.set_num_threads(3) def infer(rgb): # Preserve the existing central-square pixel geometry. 768 is an # explicitly qualified processor override, not a checkpoint default. image = Image.fromarray(rgb).crop((100, 0, 700, 600)) inputs = processor(images=image, return_tensors="pt", size={"height": 768, "width": 768}).to("cuda") with torch.inference_mode(): output = model(**inputs) masks = torch.nn.functional.interpolate(output.masks_queries_logits, size=(512, 512), mode="bilinear", align_corners=False).sigmoid() classes = output.class_queries_logits.softmax(-1)[..., :-1] scores = torch.einsum("bqc,bqhw->bchw", classes, masks) score, labels = scores.max(1) # Query-aggregated scores are not calibrated class probabilities. # Require both absolute evidence and dominance over other classes. known = (score >= .55) & (score / scores.sum(1).clamp_min(1e-8) >= .55) labels = labels[0].cpu().numpy().astype(np.uint8) known = known[0].cpu().numpy() candidate = np.isin(labels, (7, 8, 9, 10, 11, 13, 14, 15, 23)) & known return labels.tobytes() + candidate.astype(np.uint8).tobytes() + known.astype(np.uint8).tobytes() infer(np.zeros((600, 800, 3), dtype=np.uint8)) class Handler(BaseHTTPRequestHandler): def setup(self): super().setup() self.connection.settimeout(10) def reply(self, status, body): self.send_response(status) self.send_header("Content-Type", "application/octet-stream") self.send_header("Content-Length", str(len(body))) self.end_headers() self.wfile.write(body) def do_GET(self): self.reply(200 if self.path == "/ready" else 404, b'{"model":"mask2former-mapillary65"}') def do_POST(self): if self.path != "/infer" or self.headers.get("Content-Length") != "1440000": self.reply(400, b"Expected 800x600 raw RGB uint8") return try: raw = self.rfile.read(1440000) if len(raw) != 1440000: raise ValueError("Incomplete camera frame") self.reply(200, infer(np.frombuffer(raw, np.uint8).reshape(600, 800, 3))) except (TimeoutError, ValueError, RuntimeError): self.reply(500, b"Surface inference failed") def log_message(self, *_): pass HTTPServer(("0.0.0.0", 8010), Handler).serve_forever() if __name__ == "__main__": main()