#!/usr/bin/env python3 """Local-only, RGB-only three-camera preview. No recording or robot/CAN imports. Latest JPEG only in memory; no frame history, image or video files. Browser UI has a stop button. A bounded runtime and browser heartbeat release devices. """ from __future__ import annotations import argparse from collections import deque from dataclasses import asdict, replace from datetime import datetime from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer import json from pathlib import Path import secrets import signal import sys import threading import time import cv2 ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "intent_rack_demo")) from src.camera.recording import load_camera_specs, load_yaml, prepare_camera, read_camera, stop_camera def crop_bounds(width, height, fraction, anchor="center"): """ROI retains a fraction of each dimension; coordinates are half-open.""" if not 0.1 <= fraction <= 1: raise ValueError("crop fraction must be 0.1..1") if anchor not in ("center", "top-left"): raise ValueError("unknown crop anchor") crop_w, crop_h = max(1, round(width*fraction)), max(1, round(height*fraction)) x, y = ((width-crop_w)//2, (height-crop_h)//2) if anchor == "center" else (0, 0) return x, y, crop_w, crop_h def crop_frame(frame, fraction, anchor="center"): """Crop pixels without resizing or mirroring.""" height, width = frame.shape[:2] x, y, crop_w, crop_h = crop_bounds(width, height, fraction, anchor) return frame[y:y+crop_h, x:x+crop_w] def center_crop(frame, fraction): return crop_frame(frame, fraction, "center") def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--seconds", type=int, default=900) parser.add_argument("--roles", nargs="+", choices=("top", "front", "wrist"), default=["top", "front", "wrist"]) parser.add_argument("--top-center-fraction", "--top-crop-fraction", type=float, default=None, help="override saved Top preview fraction of width AND height") parser.add_argument("--top-crop-anchor", choices=("center", "top-left"), default=None, help="override saved Top preview crop anchor") args = parser.parse_args() config_path = ROOT / "intent_rack_demo/configs/cameras.yaml" saved_crop = load_yaml(config_path)["cameras"]["top"].get("preview_crop", {}) if args.top_center_fraction is None: args.top_center_fraction = float(saved_crop.get("fraction_per_dimension", 1)) if args.top_crop_anchor is None: args.top_crop_anchor = saved_crop.get("anchor", "center") if not 30 <= args.seconds <= 1800: parser.error("preview lifetime must be 30..1800 seconds") if not 0.1 <= args.top_center_fraction <= 1: parser.error("Top crop fraction must be 0.1..1") if args.top_crop_anchor not in ("center", "top-left"): parser.error("invalid saved Top preview crop anchor") cv2.setNumThreads(1) specs = [replace(s, width=1280, height=720, fps=30) for s in load_camera_specs(config_path) if s.role in args.roles] specs.sort(key=lambda s: ("top", "front", "wrist").index(s.role)) condition = threading.Condition() stop = threading.Event() started = time.monotonic() activity = {"heartbeat": started, "browser_seen": False} cameras = {s.role: {"spec": asdict(s), "error": None, "jpeg": None, "count": 0, "last_ns": 0, "times": deque(maxlen=90)} for s in specs} token = secrets.token_urlsafe(24) prefix = "/" + token html = Path(__file__).with_name("three_camera_preview.html").read_text(encoding="utf-8") html = html.replace("__PREFIX__", prefix).replace("__TOKEN__", token) html = html.replace("__CONFIG__", json.dumps({"roles": [s.role for s in specs], "top_center_fraction": args.top_center_fraction, "top_crop_anchor": args.top_crop_anchor})) workers = [] def status(): now = time.monotonic_ns() with condition: result = {} for role, entry in cameras.items(): times = entry["times"] fps = (len(times)-1)*1e9/(times[-1]-times[0]) if len(times)>1 else 0 age = (now-entry["last_ns"])/1e9 if entry["last_ns"] else None result[role] = {"spec": entry["spec"], "frames_received": entry["count"], "fps": fps, "age_sec": age, "error": entry["error"], "live": not stop.is_set() and age is not None and age < 2 and entry["error"] is None} fraction = args.top_center_fraction if role == "top" else 1 width, height = entry["spec"]["width"], entry["spec"]["height"] anchor = args.top_crop_anchor if role == "top" else "center" x, y, cw, ch = crop_bounds(width, height, fraction, anchor) result[role]["preview_crop"] = {"fraction_per_dimension": fraction, "anchor": anchor, "x": x, "y": y, "width": cw, "height": ch} return {"cameras": result, "stopped": stop.is_set(), "recording": False, "remaining_sec": max(0, args.seconds-(time.monotonic()-started))} def worker(spec): handle = None entry = cameras[spec.role] last_index = None last_received = time.monotonic() try: handle = prepare_camera(spec) while not stop.is_set(): result = read_camera(handle, 500) if result is None: if time.monotonic()-last_received > 5: raise RuntimeError("No fresh camera frame for 5 seconds") continue frame, metadata = result if metadata["camera_frame_index"] == last_index: if time.monotonic()-last_received > 5: raise RuntimeError("Camera frame index stopped advancing") continue last_index = metadata["camera_frame_index"] last_received = time.monotonic() host_ns = time.monotonic_ns() if spec.role == "top" and args.top_center_fraction != 1: frame = crop_frame(frame, args.top_center_fraction, args.top_crop_anchor) ok, encoded = cv2.imencode(".jpg", frame, [cv2.IMWRITE_JPEG_QUALITY, 80]) if not ok: raise RuntimeError("JPEG preview encoding failed") with condition: entry["jpeg"] = encoded.tobytes() entry["count"] += 1 entry["last_ns"] = host_ns entry["times"].append(host_ns) condition.notify_all() except Exception as exc: with condition: entry["error"] = f"{type(exc).__name__}: {exc}" condition.notify_all() print(f"CAMERA ERROR {spec.role}: {exc}", flush=True) finally: if handle is not None: stop_camera(handle) class Handler(BaseHTTPRequestHandler): def log_message(self, *args): pass def send(self, data, mime="application/json", code=200): self.send_response(code) self.send_header("Content-Type", mime) self.send_header("Content-Length", str(len(data))) self.send_header("Cache-Control", "no-store, max-age=0") self.send_header("X-Content-Type-Options", "nosniff") self.send_header("Referrer-Policy", "no-referrer") self.end_headers() self.wfile.write(data) def do_GET(self): path = self.path.split("?", 1)[0] try: if path == prefix + "/": self.send(html.encode(), "text/html; charset=utf-8") elif path == prefix + "/status": self.send(json.dumps(status()).encode()) elif path.startswith(prefix + "/stream/"): role = path.removeprefix(prefix + "/stream/") if role not in cameras: self.send(b"not found", "text/plain", 404) return self.connection.settimeout(5) self.send_response(200) self.send_header("Content-Type", "multipart/x-mixed-replace; boundary=frame") self.send_header("Cache-Control", "no-store") self.end_headers() last = 0 while not stop.is_set(): with condition: condition.wait_for(lambda: stop.is_set() or cameras[role]["count"] != last, timeout=1) entry = cameras[role] if stop.is_set(): break if entry["jpeg"] is None or entry["count"] == last: continue frame, last = entry["jpeg"], entry["count"] self.wfile.write(b"--frame\r\nContent-Type: image/jpeg\r\nContent-Length: " + str(len(frame)).encode() + b"\r\n\r\n" + frame + b"\r\n") self.wfile.flush() else: self.send(b"not found", "text/plain", 404) except (BrokenPipeError, ConnectionResetError, TimeoutError): pass def do_POST(self): if self.headers.get("X-Preview-Token") != token: self.send(b"forbidden", "text/plain", 403) return if self.path == prefix + "/heartbeat": activity.update(heartbeat=time.monotonic(), browser_seen=True) self.send(b"{}") elif self.path == prefix + "/stop": self.send(b'{"stopping":true}') stop.set() with condition: condition.notify_all() else: self.send(b"not found", "text/plain", 404) server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) server.daemon_threads = True url = f"http://127.0.0.1:{server.server_port}{prefix}/" run = ROOT / "reports/live_previews" / datetime.now().astimezone().strftime("%Y%m%dT%H%M%S_%f%z") run.mkdir(parents=True, exist_ok=False) (run / "session.json").write_text(json.dumps({"url": url, "max_seconds": args.seconds, "frames_saved": False, "robot_access": False, "camera_specs": [asdict(s) for s in specs], "top_center_fraction": args.top_center_fraction, "top_crop_anchor": args.top_crop_anchor, "crop_applies_to": "preview JPEG only"}, indent=2)+"\n") signal.signal(signal.SIGTERM, lambda *_: stop.set()) signal.signal(signal.SIGINT, lambda *_: stop.set()) serving = threading.Thread(target=server.serve_forever, daemon=True) serving.start() try: for spec in specs: thread = threading.Thread(target=worker, args=(spec,), name=f"preview-{spec.role}") workers.append(thread) thread.start() print(f"PREVIEW_URL={url}\nSESSION_DIR={run}", flush=True) last_ready = None while not stop.wait(0.5): now = time.monotonic() if now-started >= args.seconds: print("STOP: preview lifetime reached", flush=True) break if now-activity["heartbeat"] > (45 if activity["browser_seen"] else 120): print("STOP: no browser heartbeat", flush=True) break current = status() ready = tuple(role for role, entry in current["cameras"].items() if entry["live"]) if ready != last_ready: print("LIVE_CAMERAS=" + json.dumps(ready), flush=True) last_ready = ready finally: stop.set() with condition: condition.notify_all() for thread in workers: thread.join() (run / "final_status.json").write_text(json.dumps(status(), indent=2)+"\n") server.shutdown() server.server_close() print("STOPPED: all camera pipelines released; no video/image files recorded", flush=True) if __name__ == "__main__": main()