"""Offline, artifact-scoped Gaussian → urban observations. Never commands a rover.""" import argparse import hashlib import json import math import time from datetime import datetime, timezone from pathlib import Path import numpy as np from PIL import Image from validation import validate_job, fingerprint, phase_inputs CLASSES = { 2: ('curb', [245, 130, 48]), 6: ('wall', [128, 100, 70]), 7: ('bike_lane', [150, 110, 220]), 8: ('crosswalk_area', [255, 225, 35]), 9: ('curb_cut', [255, 150, 80]), 10: ('parking', [140, 140, 150]), 11: ('pedestrian_area', [60, 220, 200]), 13: ('carriageway', [90, 130, 200]), 14: ('service_lane', [110, 150, 210]), 15: ('sidewalk', [60, 220, 200]), 17: ('building', [200, 120, 100]), 23: ('crosswalk_marking', [255, 225, 35]), 24: ('road_marking', [245, 245, 245]), 33: ('bench', [220, 70, 160]), 44: ('street_light', [200, 80, 220]), 45: ('pole', [180, 70, 230]), 48: ('traffic_light', [255, 80, 70]), 50: ('traffic_sign', [255, 100, 70]), } def digest(path): with Path(path).open('rb') as stream: return hashlib.file_digest(stream, 'sha256').hexdigest() def write_json(path, value): temporary = path.with_suffix(path.suffix + '.tmp') temporary.write_text(json.dumps(value, ensure_ascii=False, allow_nan=False, indent=2)) temporary.replace(path) def view_matrix(eye, target, up): eye, target, up = map(lambda p: np.asarray(p, dtype=np.float64), (eye, target, up)) forward = target - eye if np.linalg.norm(forward) < 1e-9 or np.linalg.norm(np.cross(forward, up)) < 1e-9: raise ValueError('Degenerate camera orientation') forward /= np.linalg.norm(forward) right = np.cross(forward, up) right /= np.linalg.norm(right) down = np.cross(forward, right) view = np.eye(4) view[:3, :3] = [right, down, forward] view[:3, 3] = -view[:3, :3] @ eye return view def camera(spec): w, h = spec['size'] view = view_matrix(spec['eye'], spec['target'], spec.get('up', [0, 0, 1])) model = spec.get('projection', 'pinhole') focal = w / spec['width_m'] if model == 'ortho' else w / (2 * math.tan(math.radians(spec['fov_degrees']) / 2)) return view, np.array([[focal, 0, w / 2], [0, focal, h / 2], [0, 0, 1]], dtype=np.float32) def unproject(pixels, depth, view, intrinsics, projection): """OpenCV pixels + camera-Z depth to scene-local XYZ in metres.""" uv = np.asarray(pixels, dtype=np.float64) xy = (uv + 0.5 - intrinsics[:2, 2]) / np.diag(intrinsics)[:2] if projection == 'pinhole': xy *= np.asarray(depth)[:, None] local = np.column_stack([xy, depth, np.ones(len(uv))]) return (local @ np.linalg.inv(view).T)[:, :3] def render(job, output): import torch from gsplat import rasterization from plyfile import PlyData source = Path('/input') / job['source']['ply'] if digest(source) != job['source']['sha256']: raise ValueError('Gaussian source checksum mismatch') transform = np.asarray(job['source']['source_to_world'], dtype=np.float64) if (transform.shape != (4, 4) or not np.isfinite(transform).all() or not np.allclose(transform[3], [0, 0, 0, 1]) or not np.allclose(transform[:3, :3].T @ transform[:3, :3], np.eye(3), atol=1e-5) or not np.isclose(np.linalg.det(transform[:3, :3]), 1)): raise ValueError('Only rigid source transforms are supported; bake scale into the source') data = PlyData.read(source, mmap='r')['vertex'].data rows = [] bounds = np.asarray(job['bounds_xy'], dtype=float) # Chunk filtering bounds RAM while retaining every source splat in the requested tile + halo. for start in range(0, len(data), 250000): d = data[start:start + 250000] xyz = np.column_stack([d[n] for n in ['x', 'y', 'z']]) world = xyz @ transform[:3, :3].T + transform[:3, 3] mask = ((world[:, :2] >= bounds[0] - job.get('halo_m', 15)) & (world[:, :2] <= bounds[1] + job.get('halo_m', 15))).all(axis=1) rows.append(d[mask].copy()) d = np.concatenate(rows) del rows if not len(d): raise ValueError('No Gaussians in the requested tile') def tensor(names): return torch.tensor(np.column_stack([d[n] for n in names]), device='cuda', dtype=torch.float32) means = tensor(['x', 'y', 'z']) quats = tensor([f'rot_{i}' for i in range(4)]) scales = tensor([f'scale_{i}' for i in range(3)]).exp() opacity = tensor(['opacity']).squeeze(-1).sigmoid() dc = tensor([f'f_dc_{i}' for i in range(3)])[:, None, :] rest_names = sorted((n for n in d.dtype.names if n.startswith('f_rest_')), key=lambda n: int(n.split('_')[-1])) sh = torch.cat([dc, tensor(rest_names).reshape(len(d), 3, -1).transpose(1, 2)], dim=1) if rest_names else dc degree = int(math.sqrt(sh.shape[1])) - 1 print(json.dumps({'stage': 'render', 'source_splats': len(data), 'tile_splats': len(d), 'sh_degree': degree}), flush=True) for spec in job['views']: view, k = camera(spec) w, h = spec['size'] with torch.inference_mode(): rgbd, alpha, _ = rasterization(means, quats, scales, opacity, sh, torch.tensor(view @ transform, device='cuda', dtype=torch.float32)[None], torch.tensor(k, device='cuda')[None], w, h, sh_degree=degree, camera_model=spec.get('projection', 'pinhole'), render_mode='RGB+ED', packed=True) rgbd, alpha = rgbd[0].cpu().numpy(), alpha[0, :, :, 0].cpu().numpy() rgbd[:, :, :3] += (1 - alpha[:, :, None]) Image.fromarray(np.uint8(np.clip(rgbd[:, :, :3], 0, 1) * 255)).save(output / (spec['id'] + '.png')) np.savez_compressed(output / (spec['id'] + '.geometry.npz'), depth=rgbd[:, :, 3], alpha=alpha, view=view, intrinsics=k) write_json(output / (spec['id'] + '.render.json'), {'inputs': phase_inputs(job, spec), 'files': {spec['id'] + ext: digest(output / (spec['id'] + ext)) for ext in ['.png', '.geometry.npz']}}) print(json.dumps({'view': spec['id'], 'opaque_fraction': float(np.mean(alpha >= .95))}), flush=True) def infer(job, output): import torch from transformers import AutoImageProcessor, Mask2FormerForUniversalSegmentation model_path = Path('/model') for name, expected in job['model']['files'].items(): if digest(model_path / name) != expected: raise ValueError('Model asset checksum mismatch: ' + name) processor = AutoImageProcessor.from_pretrained(model_path, local_files_only=True) model = Mask2FormerForUniversalSegmentation.from_pretrained(model_path, local_files_only=True).cuda().eval() for spec in job['views']: if spec.get('projection', 'pinhole') != 'pinhole': continue # Mapillary is a street-view model; orthographic views are review only. verify_phase(output, spec['id'] + '.render.json', phase_inputs(job, spec)) image = Image.open(output / (spec['id'] + '.png')).convert('RGB') inputs = processor(images=image, return_tensors='pt').to('cuda') with torch.inference_mode(): result = model(**inputs) # Same query aggregation as the upstream semantic postprocessor; retain a confidence plane. classes = result.class_queries_logits.softmax(-1)[..., :-1] masks = torch.nn.functional.interpolate(result.masks_queries_logits, size=(image.height, image.width), mode='bilinear', align_corners=False).sigmoid() scores = torch.einsum('bqc,bqhw->bchw', classes, masks)[0] value, labels = scores.max(0) confidence = value / scores.sum(0).clamp_min(1e-6) labels, confidence = labels.byte().cpu().numpy(), confidence.cpu().numpy() geometry = np.load(output / (spec['id'] + '.geometry.npz')) valid = (geometry['alpha'] >= .95) & np.isfinite(geometry['depth']) & (geometry['depth'] > 0) labels[(confidence < job.get('min_confidence', .65)) | ~valid] = 255 Image.fromarray(labels).save(output / (spec['id'] + '.labels.png')) np.save(output / (spec['id'] + '.confidence.npy'), confidence) base = np.asarray(image).copy() overlay = base.copy() for cls, (name, color) in CLASSES.items(): overlay[labels == cls] = np.uint8(.45 * base[labels == cls] + .55 * np.array(color)) Image.fromarray(overlay).save(output / (spec['id'] + '.overlay.png')) write_json(output / (spec['id'] + '.inference.json'), {'inputs': inference_inputs(job, spec), 'files': {spec['id'] + ext: digest(output / (spec['id'] + ext)) for ext in ['.labels.png', '.confidence.npy']}}) print(json.dumps({'view': spec['id'], 'stage': 'inference', 'pixels': {CLASSES[c][0]: int((labels == c).sum()) for c in CLASSES if np.any(labels == c)}, 'unknown': int((labels == 255).sum())}), flush=True) def inference_inputs(job, spec): return fingerprint({'render': phase_inputs(job, spec), 'model': job['model'], 'confidence': job.get('min_confidence', .65)}) def verify_phase(output, manifest, expected): receipt = json.loads((output / manifest).read_text()) if receipt['inputs'] != expected or any(digest(output / name) != sha for name, sha in receipt['files'].items()): raise ValueError('Stale or changed phase input: ' + manifest) def main(): parser = argparse.ArgumentParser() parser.add_argument('--job', type=Path, required=True) parser.add_argument('--output', type=Path, required=True) parser.add_argument('--stage', choices=['render', 'infer', 'atlas', 'all'], default='all') args = parser.parse_args() job = validate_job(json.loads(args.job.read_text())) args.output.mkdir(parents=True, exist_ok=True) started = time.monotonic() from atlas import fuse def atlas(job, output): for spec in job['views']: verify_phase(output, spec['id'] + '.render.json', phase_inputs(job, spec)) if spec.get('projection', 'pinhole') == 'pinhole': verify_phase(output, spec['id'] + '.inference.json', inference_inputs(job, spec)) document = fuse(job, output, unproject, CLASSES, write_json) print(json.dumps({'stage': 'atlas', 'features': len(document['features']), 'coverage': document['coverage']}), flush=True) for name, fn in [('render', render), ('infer', infer), ('atlas', atlas)]: if args.stage in ['all', name]: fn(job, args.output) write_json(args.output / ('receipt-' + args.stage + '.json'), { 'schema_version': 'missioncore.urban-mapping-receipt/v1', 'utc': datetime.now(timezone.utc).isoformat(), 'elapsed_s': time.monotonic() - started, 'job_sha256': digest(args.job), 'stage': args.stage, 'implementation': {p.name: digest(p) for p in Path(__file__).parent.glob('*.py')}, 'files': {p.name: digest(p) for p in args.output.iterdir() if p.is_file() and not p.name.startswith('receipt-')}, }) if __name__ == '__main__': main()