Files
parking_solution/poc/zone-anpr/zone_anpr.py
T
julian 980a3e5178 poc(zone-anpr): live picture, H.264 metrics, one decode thread
- /live/<camera>.mjpg: the newest decoded frame with the vehicle boxes,
  re-encoded once for all viewers; idle while nobody watches
- the page shows that stream instead of polling a still every 700 ms
- metrics: stream codec, seconds to the first picture, viewers, live
  frames a second, network in
- config: decode_threads (CAP_PROP_N_THREADS; 1 removes the frames the
  H.264 decoder holds back per extra thread), live_quality

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RZgP5oZdzvo92Eouc9eRv5
2026-11-23 12:02:18 +01:00

1594 lines
88 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.
#!/usr/bin/env python3
"""Zone ANPR proof of concept — vendor-neutral, NVR-style (no recording).
Each camera is a plain RTSP URL (any vendor). Per camera:
grabber thread decodes the stream continuously, keeps only the newest frame
worker thread DETECT_FPS times a second: vehicle detector (YOLOX) on the zone's
bounding box. A visit starts when a car has zone_overlap of its box in
the drawn polygon; the car is then followed frame to frame. The plate
reader (fast-alpr) runs on the stream frames while the car approaches
(and on a hi-res still, if configured, as a second source) until a
consensus. Nothing is decided while the
zone is busy. When it is free, the LAST crossing of the barrier line
decides: A → B = passed, anything else = abandoned → the close relay.
Outputs (in OUT_DIR):
saves/<UTC>_<camera>_<plate>.jpg full frame, zone + vehicle + plate boxes drawn
reads.jsonl one line per saved read
visits.jsonl one line per visit: verdict, plate, path over the line
metrics.jsonl every METRICS_S: process CPU/RSS, host load, per-camera
decode fps, detector / reader runs and timings
A small web page (HTTP_PORT) shows each camera live with its zone; click to draw a new
polygon and save it into the config file.
Config: JSON file (see config.example.json). ${VAR} in URLs is expanded from the
environment, so credentials never sit in the file.
Usage: zone_anpr.py <config.json>
"""
from __future__ import annotations
import hashlib
import json
import os
import queue
import select
import socket
import struct
import urllib.parse
import urllib.request
import re
import sys
import threading
import time
from datetime import datetime, timezone
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
os.environ.setdefault("OPENCV_FFMPEG_CAPTURE_OPTIONS", "rtsp_transport;tcp")
import cv2 # noqa: E402
import numpy as np # noqa: E402
import onnxruntime as ort # noqa: E402
COCO_VEHICLES = {2: "car", 3: "motorcycle", 5: "bus", 7: "truck"}
CLK = os.sysconf("SC_CLK_TCK")
NCPU = os.cpu_count() or 1
# ORT_DEVICE=GPU runs the models on the Intel iGPU through OpenVINO (needs onnxruntime-openvino
# and /dev/dri); anything else = CPU.
DEVICE = os.environ.get("ORT_DEVICE", "CPU").upper()
def providers():
if DEVICE == "CPU":
return ["CPUExecutionProvider"]
return [("OpenVINOExecutionProvider", {"device_type": DEVICE, "cache_dir": os.environ.get("OV_CACHE", "ov-cache")}),
"CPUExecutionProvider"]
SPIN = os.environ.get("ORT_SPIN", "1") == "1"
def log(*a):
print(datetime.now().strftime("%H:%M:%S"), *a, flush=True)
# --------------------------------------------------------------------------- RFC 2435 (RTP/JPEG) headers
# --- RFC 2435 JPEG header reconstruction -------------------------------------------------
def zz_tables(q):
jl=[16,11,10,16,24,40,51,61,12,12,14,19,26,58,60,55,14,13,16,24,40,57,69,56,14,17,22,29,51,87,80,62,18,22,37,56,68,109,103,77,24,35,55,64,81,104,113,92,49,64,78,87,103,121,120,101,72,92,95,98,112,100,103,99]
jc=[17,18,24,47,99,99,99,99,18,21,26,66,99,99,99,99,24,26,56,99,99,99,99,99,47,66,99,99,99,99,99,99]+[99]*32
f = 5000//q if q<50 else 200-q*2
mk=lambda t: bytes(max(1,min(255,(x*f+50)//100)) for x in t)
zz=[0,1,8,16,9,2,3,10,17,24,32,25,18,11,4,5,12,19,26,33,40,48,41,34,27,20,13,6,7,14,21,28,35,42,49,56,57,50,43,36,29,22,15,23,30,37,44,51,58,59,52,45,38,31,39,46,53,60,61,54,47,55,62,63]
L,C=mk(jl),mk(jc); return bytes(L[i] for i in zz)+bytes(C[i] for i in zz)
def huff(cls,id_,bits,vals): return b"\xff\xc4"+struct.pack(">H",3+len(bits)+len(vals))+bytes([(cls<<4)|id_])+bytes(bits)+bytes(vals)
DC_L_B=[0,1,5,1,1,1,1,1,1,0,0,0,0,0,0,0];DC_L_V=list(range(12))
DC_C_B=[0,3,1,1,1,1,1,1,1,1,1,0,0,0,0,0];DC_C_V=list(range(12))
AC_L_B=[0,2,1,3,3,2,4,3,5,5,4,4,0,0,1,0x7d]
AC_L_V=bytes.fromhex("01020300041105122131410613516107227114328191a1082342b1c11552d1f02433627282090a161718191a25262728292a3435363738393a434445464748494a535455565758595a636465666768696a737475767778797a838485868788898a92939495969798999aa2a3a4a5a6a7a8a9aab2b3b4b5b6b7b8b9bac2c3c4c5c6c7c8c9cad2d3d4d5d6d7d8d9dae1e2e3e4e5e6e7e8e9eaf1f2f3f4f5f6f7f8f9fa")
AC_C_B=[0,2,1,2,4,4,3,4,7,5,4,4,0,1,2,0x77]
AC_C_V=bytes.fromhex("000102031104052131061241510761711322328108144291a1b1c109233352f0156272d10a162434e125f11718191a262728292a35363738393a434445464748494a535455565758595a636465666768696a737475767778797a82838485868788898a92939495969798999aa2a3a4a5a6a7a8a9aab2b3b4b5b6b7b8b9bac2c3c4c5c6c7c8c9cad2d3d4d5d6d7d8d9dae2e3e4e5e6e7e8e9eaf2f3f4f5f6f7f8f9fa")
def jpeg_header(typ,w,h,qt,dri):
o=b"\xff\xd8"
nt=len(qt)//64
for i in range(nt): o+=b"\xff\xdb"+struct.pack(">H",67)+bytes([i])+qt[i*64:(i+1)*64]
if dri: o+=b"\xff\xdd\x00\x04"+struct.pack(">H",dri)
hs=0x21 if (typ&0x3f)==0 else 0x22
o+=b"\xff\xc0"+struct.pack(">HBHHB",17,8,h,w,3)+bytes([1,hs,0,2,0x11,1 if nt>1 else 0,3,0x11,1 if nt>1 else 0])
o+=huff(0,0,DC_L_B,DC_L_V)+huff(1,0,AC_L_B,AC_L_V)+huff(0,1,DC_C_B,DC_C_V)+huff(1,1,AC_C_B,AC_C_V)
o+=b"\xff\xda\x00\x0c\x03\x01\x00\x02\x11\x03\x11\x00\x3f\x00"; return o
# --------------------------------------------------------------------------- vehicle detector
class Yolox:
def __init__(self, path: str, size: int, threads: int, min_conf: float):
o = ort.SessionOptions()
o.intra_op_num_threads = threads
o.inter_op_num_threads = 1
if not SPIN: # idle worker threads sleep instead of busy-waiting between checks
o.add_session_config_entry("session.intra_op.allow_spinning", "0")
self.s = ort.InferenceSession(path, sess_options=o, providers=providers())
log("vehicle detector on", self.s.get_providers()[0], DEVICE)
i = self.s.get_inputs()[0]
self.inp = i.name
if isinstance(i.shape[-1], int): # a static graph dictates its input size
size = i.shape[-1]
self.size, self.min_conf = size, min_conf
self.lock = threading.Lock()
n = size
grids, strides = [], []
for st in (8, 16, 32):
g = n // st
yv, xv = np.meshgrid(np.arange(g), np.arange(g), indexing="ij")
grids.append(np.stack((xv, yv), 2).reshape(-1, 2))
strides.append(np.full((g * g, 1), st))
self.grid = np.concatenate(grids).astype(np.float32)
self.stride = np.concatenate(strides).astype(np.float32)
def detect(self, img):
"""Vehicle boxes [(x1,y1,x2,y2,score,cls)] in img pixels."""
h, w = img.shape[:2]
r = min(self.size / h, self.size / w)
pad = np.full((self.size, self.size, 3), 114, np.uint8)
pad[: int(h * r), : int(w * r)] = cv2.resize(img, (int(w * r), int(h * r)))
t = pad.transpose(2, 0, 1)[None].astype(np.float32)
with self.lock:
out = self.s.run(None, {self.inp: t})[0][0]
xy = (out[:, :2] + self.grid) * self.stride
wh = np.exp(out[:, 2:4]) * self.stride
cls = out[:, 5:].argmax(1)
score = out[:, 4] * out[np.arange(len(out)), 5 + cls]
keep = (score >= self.min_conf) & np.isin(cls, list(COCO_VEHICLES))
if not keep.any():
return []
xy, wh, score, cls = xy[keep], wh[keep], score[keep], cls[keep]
b = np.concatenate([xy - wh / 2, xy + wh / 2], 1) / r
idx = cv2.dnn.NMSBoxes(
[[float(x1), float(y1), float(x2 - x1), float(y2 - y1)] for x1, y1, x2, y2 in b],
score.tolist(), self.min_conf, 0.45,
)
return [(*b[i].tolist(), float(score[i]), int(cls[i])) for i in np.array(idx).flatten()]
# --------------------------------------------------------------------------- plate reader
class Reader:
def __init__(self, detector_model: str, ocr_model: str, threads: int):
from fast_alpr import ALPR
def opts():
o = ort.SessionOptions()
o.intra_op_num_threads = threads
o.inter_op_num_threads = 1
if not SPIN:
o.add_session_config_entry("session.intra_op.allow_spinning", "0")
return o
self.alpr = ALPR(
detector_model=detector_model, ocr_model=ocr_model,
# The plate models stay on the CPU: the plate detector does not compile on the
# Intel iGPU (OpenVINO reshape error), and they only run while a car is present.
detector_providers=["CPUExecutionProvider"], detector_sess_options=opts(),
ocr_providers=["CPUExecutionProvider"], ocr_sess_options=opts(),
)
self.lock = threading.Lock()
def read(self, img):
"""Best (plate, confidence, box) or None. Box in img pixels."""
with self.lock:
res = self.alpr.predict(img)
best = None
for r in res:
if not r.ocr or not r.ocr.text:
continue
# Score = the WEAKEST real character. The model pads every read to 10 slots and
# the pads score ~1.0, so the plain average makes a misread look ~0.96 sure.
raw = r.ocr.text.upper()
text = re.sub(r"[^A-Z0-9]", "", raw)
cc = np.array(r.ocr.confidence, dtype=float).ravel()
real = [cc[i] for i, ch in enumerate(raw[: len(cc)]) if ch.isalnum()]
c = float(min(real)) if real else 0.0
bb = r.detection.bounding_box
if text and (best is None or c > best[1]):
best = (text, c, (bb.x1, bb.y1, bb.x2, bb.y2))
return best
# --------------------------------------------------------------------------- per camera
def http_opener(url):
"""(url without credentials, opener doing digest or basic auth with them)."""
u = urllib.parse.urlsplit(url)
clean = urllib.parse.urlunsplit((u.scheme, u.hostname + (f":{u.port}" if u.port else ""), u.path, u.query, ""))
pm = urllib.request.HTTPPasswordMgrWithDefaultRealm()
pm.add_password(None, clean, urllib.parse.unquote(u.username or ""), urllib.parse.unquote(u.password or ""))
return clean, urllib.request.build_opener(urllib.request.HTTPDigestAuthHandler(pm), urllib.request.HTTPBasicAuthHandler(pm))
def inside(poly, x, y):
n, ok = len(poly), False
for i in range(n):
(x1, y1), (x2, y2) = poly[i], poly[(i + 1) % n]
if (y1 > y) != (y2 > y) and x < x1 + (y - y1) * (x2 - x1) / (y2 - y1):
ok = not ok
return ok
def iou(a, b):
ix = max(0.0, min(a[2], b[2]) - max(a[0], b[0]))
iy = max(0.0, min(a[3], b[3]) - max(a[1], b[1]))
i = ix * iy
u = (a[2] - a[0]) * (a[3] - a[1]) + (b[2] - b[0]) * (b[3] - b[1]) - i
return i / u if u > 0 else 0.0
def parse_line(v):
"""The app's CrossingLine shape: {p1:{x,y}, p2:{x,y}, direction}. Side A is the screen-left of
p1→p2 (packages/shared crossingSide). Returns None when absent or invalid."""
try:
p1, p2 = (float(v["p1"]["x"]), float(v["p1"]["y"])), (float(v["p2"]["x"]), float(v["p2"]["y"]))
d = v.get("direction", "a-to-b")
if d not in ("a-to-b", "b-to-a", "both") or ((p2[0] - p1[0]) ** 2 + (p2[1] - p1[1]) ** 2) ** 0.5 < 0.03:
return None
return dict(p1=dict(x=p1[0], y=p1[1]), p2=dict(x=p2[0], y=p2[1]), direction=d)
except (TypeError, KeyError, ValueError):
return None
def line_side(line, x, y):
"""'a' | 'b' for a normalised point (same formula as the app's crossingSide)."""
p1, p2 = line["p1"], line["p2"]
cross = (p2["x"] - p1["x"]) * (y - p1["y"]) - (p2["y"] - p1["y"]) * (x - p1["x"])
return "a" if cross < 0 else "b"
# The car's ground footprint, approximated as the lowest FOOT share of its box. The car is
# "on side X" only when all four corners of that footprint are on X: its rear included, not
# only its nose. Anything else = on the line.
FOOT = 0.35
def car_state(line, box, W, H):
x1, y1, x2, y2 = box[:4]
yt = y2 - FOOT * (y2 - y1)
sides = {line_side(line, x / W, y / H) for x, y in ((x1, yt), (x2, yt), (x1, y2), (x2, y2))}
return sides.pop() if len(sides) == 1 else "line"
def edge_side(line, box, W, H, near=0.05):
"""The side of the line where the car's box touches the left or right frame edge: where a
car on the line came INTO view from, or LEFT the view to (its rear is out of the picture,
so the camera can't see it clear the line). None otherwise. The bottom edge is ignored: a
near car always touches it."""
x1, y1, x2, y2 = box[:4]
cy = (y1 + y2) / 2
pts = []
if x1 <= near * W:
pts.append((0.0, cy / H))
if x2 >= (1 - near) * W:
pts.append((1.0, cy / H))
sides = {line_side(line, x, y) for x, y in pts}
return sides.pop() if len(sides) == 1 else None
def plate_glare(img, box):
"""How much of the picture right beside the plate is burnt out: the share of pixels with
every channel >= 250 in the strip just left and the strip just right of the plate box (each
a quarter of the plate wide, as high as the plate); the larger of the two.
A headlight flare that reaches the plate hides characters at that end, and the reader then
returns a shorter text, sure of itself: on the wet night of 2026-11-22 'AA927AU' was read
as 'A927AU' three stills in a row. On the 20 kept stills with a read, the four with the
flare on the plate scored 0.18-0.43 here, the other sixteen 0.00."""
x1, y1, x2, y2 = (int(v) for v in box)
w = max(4, (x2 - x1) // 4)
worst = 0.0
for strip in (img[max(0, y1):y2, max(0, x1 - w):max(0, x1)], img[max(0, y1):y2, x2:x2 + w]):
if strip.size:
worst = max(worst, float((strip.min(axis=2) >= 250).mean()))
return worst
def decide(last_crossing, end, close_on_lost=False):
"""The user's flow (2026-11-22), called only once the zone is FREE. A → B is IN, B → A is
OUT, and only the LAST crossing counts:
last crossing A → B → passed (nothing to do)
last crossing B → A, or none → abandoned (the open was not used → close)
`end` says HOW the zone became free: 'left_zone' (the car was seen outside the zone),
'left_view' (it stopped being detected with its box at the picture's edge) or 'lost' (it
stopped being detected inside the zone). Only a car SEEN OUTSIDE the zone proves the zone
free: the other two give 'unclear', never a close, unless close_on_lost is set."""
if last_crossing == "a-to-b":
return "passed"
if end != "left_zone" and not close_on_lost:
return "unclear"
return "abandoned"
class Camera:
def __init__(self, cfg: dict, app: "App"):
self.name = cfg["name"]
self.url = re.sub(r"\$\{(\w+)\}", lambda m: os.environ.get(m.group(1), ""), cfg["url"])
self.zone = cfg.get("zone") or [] # [[x,y], ...] normalised 0..1
self.line = parse_line(cfg.get("line")) # the barrier line, the app's CrossingLine shape
if self.line and self.line["direction"] != "a-to-b":
log(self.name, f"line direction '{self.line['direction']}' is IGNORED: A → B is in, B → A is out. Swap A/B on the page if needed.")
# Relay channels this camera may pulse (0 = none): open on a car in the zone; close when
# the car leaves the zone back on the start side without crossing.
self.relay_open = int(cfg.get("relay_open", 0))
self.relay_close = int(cfg.get("relay_close", 0))
self.zone_mask = None # (shape, zone) -> uint8 mask, for the overlap rule
self.track = None # the one car this visit follows (box, sides path, last frame)
self.zone_busy = False # any vehicle in the zone on the last processed frame
self.checked_t = 0.0 # wall clock of that frame: a close needs a FRESH look at the zone
self.app = app
exp = lambda v: re.sub(r"\$\{(\w+)\}", lambda m: os.environ.get(m.group(1), ""), v)
# stream = decode every frame of the RTSP video (any codec) [default]
# mjpeg = RTSP MJPEG, receive every frame, decode only the ones checked
# snapshot = HTTP GET a still picture snapshot_fps times a second
self.mode = cfg.get("mode", "stream")
self.snapshot_url = exp(cfg.get("snapshot_url", ""))
# Optional: a full-resolution still fetched ONLY while a vehicle is in the zone; the
# plate is read from it instead of from the (low-res) watch frame.
self.plate_snap_url = exp(cfg["plate_snapshot_url"]) if cfg.get("plate_snapshot_url") else None
self.snapshot_fps = cfg.get("snapshot_fps", app.cfg.get("detect_fps", 5))
self.frame = None # decoded BGR (stream mode, or cached decode of jpeg)
self.jpeg = None # newest undecoded JPEG (mjpeg / snapshot modes)
self.decoded_no = -1
self.frame_t = 0.0
self.frame_no = 0
self.cond = threading.Condition()
self.status = "starting"
self.stats = dict(decoded=0, received=0, snap_ms=0.0, hires=0, hires_ms=0.0, det_runs=0, det_ms=0.0, read_runs=0, read_ms=0.0, saves=0, verdicts=0, live=0)
# The live picture for the page: every decoded frame re-encoded as JPEG, ONCE per frame
# for all viewers, and only while somebody watches (2026-11-23, the H.264 test).
self.live_viewers, self.live_jpeg, self.live_no = 0, None, 0
self.live_cond = threading.Condition()
self.codec, self.first_frame_s = None, None # what the camera sends; connect -> first picture
self.present = False
# One lane, two cameras (entry and exit watch the same lane from both ends): only one
# camera may hold a visit at a time. The other YIELDS, and stays yielded until its own
# zone has been empty for a frame, so the car the owner just handled cannot start a
# second visit (and a second open) on this camera when the owner lets go.
self.yielded = False
# The plate is read from two sources, each in its own background job, one at a time:
# stream = the watch frame itself, every processed frame: no camera load, no delay;
# still = a hi-res still fetched from the camera (optional), paced: the second source.
self.read_busy, self.still_busy = False, False
self.visit_id, self.read_lock = 0, threading.Lock()
self.read_fails, self.read_pause_until, self.still_t = 0, 0.0, 0.0
self.visit_t0, self.decided_s = 0.0, None # when the visit started; seconds until the plate was decided
self.visit_src = {"stream": [0, 0, 0], "still": [0, 0, 0]} # per source: tries, reads, votes
self.visit_done = False # one save per visit
self.visit_votes: dict[str, int] = {} # qualifying reads this visit, per text
self.still_votes: dict[str, int] = {} # the same, hi-res stills only
self.visit_best: dict[str, tuple] = {} # text -> best (conf, frame, t, veh, pbox, poly)
self.visit_reads = 0 # all reads this visit
self.visit_plate = (None, None) # (text, decided|undecided) for the verdict record
self.last_seen = 0.0
self.last_vehicles: list = []
self.last_read = None
def safe_url(self, u=None):
return re.sub(r"//[^@/]*@", "//***@", u or self.url)
def latest(self):
"""(frame, t, no) — decodes the newest JPEG only when someone asks for it."""
with self.cond:
jpeg, f, t, no = self.jpeg, self.frame, self.frame_t, self.frame_no
if jpeg is not None and self.decoded_no != no:
f = cv2.imdecode(np.frombuffer(jpeg, np.uint8), cv2.IMREAD_COLOR)
self.stats["decoded"] += 1
self.frame, self.decoded_no = f, no
return f, t, no
def publish(self, frame=None, jpeg=None):
with self.cond:
if frame is not None:
self.frame = frame
self.stats["decoded"] += 1
self.jpeg = jpeg
self.frame_t = time.time()
self.frame_no += 1
self.stats["received"] += 1
self.cond.notify_all()
def grab(self):
g = {"stream": self.grab_stream, "mjpeg": self.grab_mjpeg, "snapshot": self.grab_snapshot}[self.mode]
while True:
try:
g()
except Exception as e: # noqa: BLE001 - reconnect on anything
self.status = "error"
log(self.name, f"{self.mode} error: {e!r}; retrying")
time.sleep(2)
# --- snapshot mode: GET a still picture N times a second (digest or basic auth)
def grab_snapshot(self):
clean, op = http_opener(self.snapshot_url)
period = 1.0 / self.snapshot_fps
log(self.name, "snapshot mode", self.safe_url(clean), f"{self.snapshot_fps}/s")
while True:
t0 = time.time()
body = op.open(clean, timeout=5).read()
self.stats["snap_ms"] += (time.time() - t0) * 1000
if body[:2] != b"\xff\xd8":
raise ValueError(f"not a JPEG ({len(body)} bytes)")
self.status = "live"
self.publish(jpeg=body)
time.sleep(max(0.0, period - (time.time() - t0)))
# --- mjpeg mode: own RTSP client, RTP/JPEG (RFC 2435) reassembly, no decode here
def grab_mjpeg(self):
u = urllib.parse.urlsplit(self.url)
user, pw = urllib.parse.unquote(u.username or ""), urllib.parse.unquote(u.password or "")
host, port = u.hostname, u.port or 554
base = urllib.parse.urlunsplit(("rtsp", f"{host}:{port}", u.path, u.query, ""))
s = socket.create_connection((host, port), timeout=10)
st = {"cseq": 0, "auth": None}
def send(method, url, extra=""):
st["cseq"] += 1
a = ""
if st["auth"]:
realm, nonce = st["auth"]
ha1 = hashlib.md5(f"{user}:{realm}:{pw}".encode()).hexdigest()
ha2 = hashlib.md5(f"{method}:{url}".encode()).hexdigest()
r = hashlib.md5(f"{ha1}:{nonce}:{ha2}".encode()).hexdigest()
a = (f'Authorization: Digest username="{user}", realm="{realm}", nonce="{nonce}", '
f'uri="{url}", response="{r}"\r\n')
s.sendall(f"{method} {url} RTSP/1.0\r\nCSeq: {st['cseq']}\r\n{extra}{a}\r\n".encode())
d = b""
while b"\r\n\r\n" not in d:
c = s.recv(4096)
if not c:
raise ConnectionError("closed during handshake")
d += c
h, _, b = d.partition(b"\r\n\r\n")
h = h.decode(errors="replace")
m = re.search(r"Content-Length:\s*(\d+)", h, re.I)
n = int(m.group(1)) if m else 0
while len(b) < n:
b += s.recv(4096)
return h, b[:n], b[n:]
h, _, _ = send("DESCRIBE", base, "Accept: application/sdp\r\n")
if " 401 " in h.splitlines()[0]:
st["auth"] = (re.search(r'realm="([^"]+)"', h).group(1), re.search(r'nonce="([^"]+)"', h).group(1))
h, _, _ = send("DESCRIBE", base, "Accept: application/sdp\r\n")
h, sdp, _ = send("DESCRIBE", base, "Accept: application/sdp\r\n")
if " 200 " not in h.splitlines()[0]:
raise ConnectionError(h.splitlines()[0])
sdp = sdp.decode(errors="replace")
video = sdp[sdp.index("m=video"):]
if "JPEG" not in video and not re.search(r"m=video \d+ \S+ 26\b", video):
raise ValueError("stream is not MJPEG — set the camera's stream to MJPEG or use mode=stream")
ctrl = re.search(r"a=control:(\S+)", video).group(1)
track = ctrl if ctrl.startswith("rtsp://") else base.rstrip("/") + "/" + ctrl
h, _, _ = send("SETUP", track, "Transport: RTP/AVP/TCP;unicast;interleaved=0-1\r\n")
sess = re.search(r"Session:\s*([^;\r\n]+)", h).group(1)
h, _, buf = send("PLAY", base + "/", f"Session: {sess}\r\nRange: npt=0.000-\r\n")
self.status = "live"
log(self.name, "mjpeg stream open", self.safe_url())
s.settimeout(None)
last_ka, cur = time.time(), b""
def fill(n):
nonlocal buf
while len(buf) < n:
r, _, _ = select.select([s], [], [], 10)
if not r:
raise TimeoutError("no data for 10 s")
c = s.recv(262144)
if not c:
raise ConnectionError("closed by camera")
buf += c
while True:
if time.time() - last_ka > 25:
st["cseq"] += 1
s.sendall(f"GET_PARAMETER {base}/ RTSP/1.0\r\nCSeq: {st['cseq']}\r\nSession: {sess}\r\n\r\n".encode())
last_ka = time.time()
fill(4)
if buf[0] != 0x24: # an interleaved RTSP reply — skip to the next '$'
i = buf.find(b"$", 1)
buf = buf[i:] if i > 0 else b""
continue
ch, ln = buf[1], int.from_bytes(buf[2:4], "big")
fill(4 + ln)
p, buf = buf[4:4 + ln], buf[4 + ln:]
if ch != 0:
continue
hl = 12 + 4 * (p[0] & 0x0F)
marker, pl = p[1] & 0x80, p[hl:]
if p[0] & 0x20:
pl = pl[: len(pl) - p[-1]]
off = int.from_bytes(pl[1:4], "big")
typ, q, w, hh = pl[4], pl[5], pl[6] * 8, pl[7] * 8
k, dri = 8, 0
if typ >= 64:
dri, k = int.from_bytes(pl[8:10], "big"), 12
if off == 0:
if q >= 128:
qlen = int.from_bytes(pl[k + 2:k + 4], "big")
qt, k = pl[k + 4:k + 4 + qlen], k + 4 + qlen
else:
qt = zz_tables(q)
cur = jpeg_header(typ, w, hh, qt, dri)
elif not cur:
continue # joined mid-frame
cur += pl[k:]
if marker:
self.publish(jpeg=cur if cur.endswith(b"\xff\xd9") else cur + b"\xff\xd9")
cur = b""
# --- stream mode: decode everything, keep the newest
def grab_stream(self):
if True:
t0 = time.time()
# FFmpeg decodes H.264 on several threads by default, and each extra thread holds one
# more frame back: 5 frames on the 6-core booth PC, 0.4 s at 12.5 fps (measured
# 2026-11-23). decode_threads: 1 gives each frame out as soon as it is decoded.
n = self.app.cfg.get("decode_threads")
cap = (cv2.VideoCapture(self.url, cv2.CAP_FFMPEG, [cv2.CAP_PROP_N_THREADS, int(n)]) if n
else cv2.VideoCapture(self.url, cv2.CAP_FFMPEG))
if not cap.isOpened():
raise ConnectionError("cannot open stream")
self.status = "live"
fcc = int(cap.get(cv2.CAP_PROP_FOURCC))
self.codec = "".join(chr((fcc >> 8 * i) & 0xFF) for i in range(4)).strip("\x00 ") or "?"
log(self.name, "stream open", self.safe_url(), self.codec,
int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)), "x", int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)))
first = True
while True:
ok, f = cap.read()
if not ok:
self.status = "stream lost"
log(self.name, "stream lost, reconnecting")
break
if first:
first, self.first_frame_s = False, round(time.time() - t0, 2)
log(self.name, f"first picture {self.first_frame_s} s after connecting")
self.publish(frame=f)
cap.release()
# --- live picture: one JPEG per decoded frame, shared by all viewers, idle with none
def live_loop(self):
seen = 0
q = int(self.app.cfg.get("live_quality", 75))
while True:
with self.live_cond:
self.live_cond.wait_for(lambda: self.live_viewers > 0)
with self.cond:
self.cond.wait_for(lambda: self.frame_no != seen, timeout=2)
if self.frame_no == seen:
continue
f, _, seen = self.latest()
if f is None:
continue
img = f.copy() # the boxes must not land on the frame the detector and the clip use
for x1, y1, x2, y2, *_ in list(self.last_vehicles):
cv2.rectangle(img, (int(x1), int(y1)), (int(x2), int(y2)), (0, 255, 0), 2)
jpeg = cv2.imencode(".jpg", img, [cv2.IMWRITE_JPEG_QUALITY, q])[1].tobytes()
self.stats["live"] += 1
with self.live_cond:
self.live_jpeg, self.live_no = jpeg, self.live_no + 1
self.live_cond.notify_all()
# --- worker: presence in zone → plate
def work(self):
period = 1.0 / self.app.cfg["detect_fps"]
seen_no = 0
while True:
t0 = time.time()
with self.cond:
self.cond.wait_for(lambda: self.frame_no != seen_no, timeout=5)
if self.frame_no == seen_no or len(self.zone) < 3:
continue
f, ft, seen_no = self.latest()
try:
self.step(f, ft)
except Exception as e: # noqa: BLE001 - a PoC keeps going
log(self.name, "step failed:", repr(e))
time.sleep(max(0.0, period - (time.time() - t0)))
def step(self, f, ft):
H, W = f.shape[:2]
cfg = self.app.cfg
poly = [(x * W, y * H) for x, y in self.zone]
xs, ys = [p[0] for p in poly], [p[1] for p in poly]
if self.line: # the line must be watched too, even where it leaves the zone
xs += [self.line["p1"]["x"] * W, self.line["p2"]["x"] * W]
ys += [self.line["p1"]["y"] * H, self.line["p2"]["y"] * H]
# The WHOLE frame: a crop around the zone cut a close car in half (exit camera, night,
# 2026-11-21) and the detector no longer saw a car at all. It costs nothing: the
# detector resizes to its input size either way.
bx1, by1, bx2, by2 = 0, 0, W, H
t = time.perf_counter()
dets = self.app.yolox.detect(f[by1:by2, bx1:bx2])
self.stats["det_runs"] += 1
self.stats["det_ms"] += (time.perf_counter() - t) * 1000
dets = [(x1 + bx1, y1 + by1, x2 + bx1, y2 + by1, s, c) for x1, y1, x2, y2, s, c in dets]
if self.zone_mask is None or self.zone_mask[0] != (H, W, str(self.zone)):
mk = np.zeros((H, W), np.uint8)
cv2.fillPoly(mk, [np.array(poly, np.int32)], 1)
self.zone_mask = ((H, W, str(self.zone)), mk)
mk = self.zone_mask[1]
def overlap(v): # share of the car's box inside the zone
a = mk[int(max(0, v[1])):int(v[3]), int(max(0, v[0])):int(v[2])]
return float(a.mean()) if a.size else 0.0
now = time.time()
# ZONE BUSY = any vehicle in the zone, not only the tracked one (the detector already
# runs at keep_conf). Nothing is decided while it is busy.
in_zone = [v for v in dets if overlap(v) >= cfg["zone_overlap"]]
self.zone_busy, self.checked_t = bool(in_zone), now
free_n = cfg.get("zone_free_s", 1) * cfg["detect_fps"]
# One visit = one busy period of the zone. It STARTS when a car has >= zone_overlap of
# its box in the zone (a car stopping on the zone's edge counts). That car is FOLLOWED by
# box overlap frame to frame, wherever it goes, and its side changes are the crossings.
# It ENDS, and is decided, only when the zone is FREE.
tr = self.track
if tr is None:
# A visit STARTS on a sure detection (start_conf); once started, the car is KEPT on
# weaker ones (the detector runs at keep_conf). A car standing in headlight glare
# scored ~0.4-0.5 and flickered: each 3 s loss ended the visit and the next frame
# opened the barrier again for the same car.
cands = [v for v in in_zone if v[4] >= cfg.get("start_conf", 0.4)]
self.last_vehicles = cands
if not cands:
if self.yielded:
log(self.name, "zone clear, lane free for this camera again")
self.yielded = False
return
car = max(cands, key=lambda v: (v[2] - v[0]) * (v[3] - v[1]))
with self.app.lane_lock:
owner = next((c for c in self.app.cams if c is not self and c.track is not None), None)
if owner or self.yielded:
if not self.yielded:
log(self.name, f"car in zone IGNORED: lane busy with {owner.name}")
self.yielded = True
return
tr = self.track = dict(box=car, t0=now, path=[], frame=None, frame_t=ft,
entry_side=edge_side(self.line, car, W, H) if self.line else None,
side=None, cross=None, crossings=[], miss=0, outz=0, free=0, closed=False)
self.present, self.visit_t0 = True, ft
log(self.name, "vehicle in zone")
if self.relay_open:
tr["opened"] = True
self.app.relays.pulse("open", self.relay_open, f"{self.name}: car in zone",
valid=lambda: self.track is tr) # still this busy period
else:
# Consecutive processed frames with NO vehicle in the zone. Counted in frames, not
# wall-clock: a stream stall or a slow still fetch must not free the zone by itself.
tr["free"] = 0 if in_zone else tr["free"] + 1
self.last_vehicles = in_zone
best = max(dets, key=lambda v: iou(v, tr["box"]), default=None)
if best is None or iou(best, tr["box"]) < 0.15:
# The followed car is not seen. The zone is FREE when it has been gone for
# visit_gap_s AND no other vehicle is in the zone either.
tr["miss"] += 1
gap_n = cfg["visit_gap_s"] * cfg["detect_fps"]
if tr["miss"] >= gap_n and tr["free"] >= free_n:
# HOW it went: seen outside the zone before it was lost = it left the zone.
# Otherwise it vanished inside the zone, at the picture's edge or not.
# "Seen outside" needs side_hold looks in a row, and the edge is judged on
# the last box that agreed with the car's side: ONE stray box at the very
# end must not decide (2026-11-22 night: a blurred last box on side A turned
# a crossing into 'abandoned' and R2 fired behind the car).
eb = self.leaving_box(tr, W, H)[0]
at_edge = eb[0] <= 0.05 * W or eb[2] >= 0.95 * W
self.end_visit("left_zone" if tr["outz"] >= cfg.get("side_hold", 2) else "left_view" if at_edge else "lost")
elif tr["miss"] >= gap_n and tr["miss"] % (10 * cfg["detect_fps"]) == 0:
log(self.name, f"followed car gone, but the zone is still busy ({len(in_zone)} vehicle(s) in it): no decision yet")
return
car = best
tr["box"], tr["miss"] = car, 0
if car not in in_zone:
self.last_vehicles = in_zone + [car]
# Zone FREE = the car is out of the zone (still in view or not) and no other vehicle
# is in it, for zone_free_s. Then the visit is decided at once: passed, or abandoned
# → R2. How long the car stood in the lane before does not matter.
tr["outz"] = tr["outz"] + 1 if overlap(car) < cfg["zone_overlap"] else 0
if tr["outz"] >= free_n and tr["free"] >= free_n:
self.end_visit("left_zone")
return
self.last_seen = now
tr["frame"], tr["frame_t"] = f, ft
self.clip_frame(tr, f, ft, car)
if self.line:
st = car_state(self.line, car, W, H)
if not tr["path"]:
pend = (st, cfg.get("side_hold", 2), ft) # the first look of a visit counts at once
elif tr["path"][-1][0] == st:
pend, tr["agree_box"] = None, car # still where it was: the box the leaving edge is judged on
else:
# A NEW side counts only once it has been seen side_hold looks in a row.
was = tr.get("pend")
pend = (st, was[1] + 1, was[2]) if was and was[0] == st else (st, 1, ft)
tr["pend"], tr["pend_box"] = pend, car
if pend and pend[1] >= cfg.get("side_hold", 2):
st, _, since = pend
if not tr["path"] and st == "line":
tr["side"] = tr["entry_side"] # first seen on the line: the side it came into view from
tr["path"].append((st, since))
tr["pend"], tr["agree_box"] = None, car
log(self.name, "car", {"a": "on side A", "b": "on side B", "line": "on the line"}[st])
if st != "line":
self.note_side(tr, st, since)
if self.visit_done:
return # plate decided: nothing more is read for this visit
# Plate reads run in the BACKGROUND, tracking never waits for them. (A hi-res still can
# hang for seconds; in the tracking loop that froze the car's track, 2026-11-21.)
# STREAM: this very frame, as long as no read of it is still running. Fast (five a
# second, no camera load) but the WEAKER reader: on the night of 2026-11-21 it alone would
# have decided 3 of 20 visits, the stills 8. It reads only while the car APPROACHES; once
# the car stands at the line the plate is seen almost edge-on, so the tries are capped.
# The caps count tries while the car STANDS: whenever it has moved (its box overlaps
# the box of the last reset by under 70%) they start again, so a car creeping up slowly
# is read all the way and only a parked one runs out.
if "cap_box" not in tr or iou(car, tr["cap_box"]) < 0.7:
tr["cap_box"], tr["tries"] = car, {"stream": 0, "still": 0}
src, tries = self.visit_src, tr["tries"]
if not self.read_busy and tries["stream"] < cfg.get("max_stream_reads", 75):
self.read_busy = True
src["stream"][0] += 1
tries["stream"] += 1
threading.Thread(target=self.read_job, args=("stream", self.visit_id, f, ft, car, poly, W, H, None), daemon=True).start()
# STILL: the stronger reader (3x the pixels), at most one every still_interval_s and
# max_stills a visit, and not while backing off after a failure. Both sources vote in
# ONE consensus.
if (self.plate_snap_url and not self.still_busy and tries["still"] < cfg.get("max_stills", 20)
and now >= self.read_pause_until and now - self.still_t >= cfg.get("still_interval_s", 0.5)):
self.still_busy, self.still_t = True, now
src["still"][0] += 1
tries["still"] += 1
keep = tr.get("clip") if src["still"][0] <= cfg.get("still_keep", 15) else None # kept beside the visit's clip
threading.Thread(target=self.read_job, args=("still", self.visit_id, f, ft, car, poly, W, H, keep), daemon=True).start()
def leaving_box(self, tr, W, H):
"""(box, side state) the car's LEAVING is judged on. Normally the last box that agreed
with its side. A newer look that has not held yet replaces it in ONE case: its box is at
the picture's left or right edge and the agreed box was not at an edge. That is a car
driving out of view, which cannot be seen a second time (2026-11-21 17:01: on side A,
then one look stretched to the right edge, then gone = a crossing). A stray last box in
the middle of the picture is ignored (2026-11-22 16:27)."""
agreed = tr.get("agree_box", tr["box"])
state = tr["path"][-1][0] if tr["path"] else None
pend = tr.get("pend")
if pend and self.line and edge_side(self.line, tr["pend_box"], W, H) and not edge_side(self.line, agreed, W, H):
return tr["pend_box"], pend[0]
return agreed, state
def note_side(self, tr, side, ft):
"""The car is fully on `side` now. A change of side is a CROSSING: A → B = in, B → A = out.
The two are mutually exclusive: the last one replaces the one before."""
prev, tr["side"] = tr["side"], side
if prev == side:
return
if prev is None:
# First seen ON the line, origin unknown. Reaching B counts as in (it can only have
# come from A); reaching A is no crossing: nothing says it was ever on B.
if not (tr["path"][0][0] == "line" and side == "b"):
return
tr["cross"] = "a-to-b" if side == "b" else "b-to-a"
tr["crossings"].append((tr["cross"], ft))
log(self.name, "CROSSING", "A → B (in)" if side == "b" else "B → A (out)")
def read_job(self, src, vid, f, ft, car, poly, W, H, keep):
try:
if src == "still":
self.read_still(vid, f, ft, car, poly, W, H, keep)
else:
self.read_crop(src, vid, f, ft, car, poly, W, H, 0.05)
except Exception as e: # noqa: BLE001 - a failed read is only a missed vote
if src == "still":
# Back off: the camera answered 503 when hammered (2026-11-21).
self.read_fails += 1
self.read_pause_until = time.time() + min(30, 2 ** self.read_fails)
log(self.name, "plate still failed:", repr(e), f"(pause {min(30, 2 ** self.read_fails)} s)")
else:
log(self.name, "plate read failed:", repr(e))
else:
if src == "still":
self.read_fails = 0
finally:
if src == "still":
self.still_busy = False
else:
self.read_busy = False
def fetch_still(self):
"""The camera's hi-res still, decoded. A NEW opener for every fetch: urllib's digest
handler counts failed tries and, kept alive, refuses every request after six in a row
('digest auth failed') until the process restarts."""
clean, op = http_opener(self.plate_snap_url)
return cv2.imdecode(np.frombuffer(op.open(clean, timeout=1).read(), np.uint8), cv2.IMREAD_COLOR)
def read_still(self, vid, f, ft, car, poly, W, H, keep=None):
# Fetch the full-resolution still and map the box onto it (normalised coordinates).
# The car moves a little between the watch frame and the still: wider margin.
t = time.perf_counter()
hi = self.fetch_still()
self.stats["hires"] += 1
self.stats["hires_ms"] += (time.perf_counter() - t) * 1000
if hi is None:
return
sx, sy = hi.shape[1] / W, hi.shape[0] / H
x1, y1, x2, y2, s, c = car
car = (x1 * sx, y1 * sy, x2 * sx, y2 * sy, s, c)
poly = [(x * sx, y * sy) for x, y in poly]
self.read_crop("still", vid, hi, time.time(), car, poly, hi.shape[1], hi.shape[0], 0.15, keep)
def read_crop(self, src, vid, f, ft, car, poly, W, H, margin, keep=None):
x1, y1, x2, y2, s, c = car
pw, ph = (x2 - x1) * margin, (y2 - y1) * margin
cx1, cy1 = int(max(0, x1 - pw)), int(max(0, y1 - ph))
cx2, cy2 = int(min(W, x2 + pw)), int(min(H, y2 + ph))
t = time.perf_counter()
r = self.app.reader.read(f[cy1:cy2, cx1:cx2])
self.stats["read_runs"] += 1
self.stats["read_ms"] += (time.perf_counter() - t) * 1000
glare = plate_glare(f[cy1:cy2, cx1:cx2], r[2]) if r else 0.0
if keep is not None:
# Every still's car crop, WITH its read, kept beside the visit's clip (and pruned
# with it): a failed read can be looked at afterwards, by day and by night.
n = len(list(keep.glob("still_*.jpg"))) + 1
name = f"still_{n:02d}_{r[0] if r else 'noplate'}_{(r[1] if r else 0):.2f}.jpg"
cv2.imwrite(str(keep / name), f[cy1:cy2, cx1:cx2], [cv2.IMWRITE_JPEG_QUALITY, 85])
with open(keep / "stills.jsonl", "a") as fh:
fh.write(json.dumps(dict(n=n, t=round(ft, 3), file=name, plate=r[0] if r else None,
weakest_char=round(r[1], 3) if r else None,
plate_px=round(r[2][2] - r[2][0]) if r else None,
glare=round(glare, 3) if r else None)) + "\n")
if not r:
self.last_read = None
return
text, conf, (px1, py1, px2, py2) = r
# A plate that is SMALL in the stream frame does not vote. Measured on the night frames
# of 2026-11-21 (652 reads): under 5% of the frame's width (64 px of 1280) no read was
# right and sure, and the only two sure-but-WRONG reads were there; from 5% up, 133 of
# 172 were right and sure and none wrong. PROVISIONAL: the limit was chosen on the same
# reads it is scored on (one car, one night); plate_px is logged with every read so it
# can be set again from more drives. The still is 3x larger and has no such limit.
big = src != "stream" or (px2 - px1) / W >= self.app.cfg.get("stream_min_plate_w", 0.05)
# A plate with BURNT-OUT pixels right beside it does not vote either: the flare hides
# characters at that end. A check on the picture, not a rule about the plate's format.
clear = glare < self.app.cfg.get("plate_glare_max", 0.05)
with self.read_lock:
if vid != self.visit_id or self.visit_done:
return # that visit ended, or was decided, while this was being read
self.vote(src, f, ft, (x1, y1, x2, y2, s, c), poly, text, conf, (px1 + cx1, py1 + cy1, px2 + cx1, py2 + cy1),
big, clear, glare)
def vote(self, src, f, ft, box, poly, text, conf, pbox, big=True, clear=True, glare=0.0):
cfg = self.app.cfg
self.last_read = (text, conf, pbox)
# Consensus, one decision per visit, over BOTH sources. A read only VOTES when every
# character is sure (weakest >= min_plate_conf). No country/format rule: any plate. We
# keep reading until one text has `votes_needed` votes AND `agree_share` of all votes.
# A car that leaves first is still recorded, as UNDECIDED with its candidates.
self.visit_reads += 1
self.visit_src[src][1] += 1
self.log_read(src, ft, text, conf, round(pbox[2] - pbox[0]), big, glare, clear)
if conf < cfg["min_plate_conf"] or not big or not clear:
return
self.visit_src[src][2] += 1
n = self.visit_votes[text] = self.visit_votes.get(text, 0) + 1
if text not in self.visit_best or conf > self.visit_best[text][0]:
self.visit_best[text] = (conf, f, ft, box, pbox, poly, src)
total = sum(self.visit_votes.values())
if src == "still":
self.still_votes[text] = self.still_votes.get(text, 0) + 1
# The STILLS ALONE can decide too: the stream is the weaker reader, and a sure but
# wrong stream vote must not block a decision the stills would have made by themselves.
ns, ts = self.still_votes.get(text, 0), sum(self.still_votes.values())
if (n >= cfg["votes_needed"] and n / total >= cfg["agree_share"]) or (
ns >= cfg["votes_needed"] and ns / ts >= cfg["agree_share"]):
self.visit_done = True
self.decided_s = round(time.time() - self.visit_t0, 2) # wall clock, the read's own delay included
b = self.visit_best[text]
self.save(b[1], b[2], text, b[0], b[3], b[4], b[5], status="decided")
def log_read(self, src, ft, text, conf, plate_px, big, glare, clear):
"""Every single read, for tuning the consensus later."""
rec = dict(at=datetime.fromtimestamp(ft, timezone.utc).isoformat(), camera=self.name, src=src,
plate=text, weakest_char=round(conf, 3), plate_px=plate_px, too_small=not big,
glare=round(glare, 3), in_glare=not clear,
visit_s=round(ft - self.visit_t0, 2))
with self.app.io_lock, open(self.app.out / "reads-all.jsonl", "a") as fh:
fh.write(json.dumps(rec) + "\n")
def clip_frame(self, tr, f, ft, car):
"""Every processed frame of a visit, low-res JPEG + box, to tune the verdict/close rules
on real drives (out/clips/<camera>_<start UTC>/). The oldest clips are pruned."""
keep = self.app.cfg.get("clip_keep", 150)
if not keep:
return
if "clip" not in tr:
ts = datetime.fromtimestamp(ft, timezone.utc).strftime("%Y%m%dT%H%M%SZ")
tr["clip"] = self.app.out / "clips" / f"{ts}_{self.name}"
tr["clip"].mkdir(parents=True, exist_ok=True)
tr["clip_n"] = 0
dirs = sorted((self.app.out / "clips").iterdir())
for d in dirs[:max(0, len(dirs) - keep)]:
for x in d.iterdir():
x.unlink()
d.rmdir()
n = tr["clip_n"] = tr["clip_n"] + 1
cv2.imwrite(str(tr["clip"] / f"{n:04d}.jpg"), f, [cv2.IMWRITE_JPEG_QUALITY, 80])
with open(tr["clip"] / "frames.jsonl", "a") as fh:
fh.write(json.dumps(dict(n=n, t=round(ft, 3), box=[round(float(v), 1) for v in car[:4]])) + "\n")
def end_visit(self, end):
"""The zone is free: record the plate outcome, then decide (passed / abandoned → close)."""
tr = self.track
with self.read_lock:
self.visit_id += 1 # a read still running for this visit is now discarded
if not self.visit_done:
self.undecided()
close = bool(self.line and tr) and self.record_verdict(tr, end)
self.present, self.track, self.visit_done = False, None, False
self.visit_votes.clear()
self.still_votes.clear()
self.visit_best.clear()
self.visit_reads = 0
self.visit_src = {"stream": [0, 0, 0], "still": [0, 0, 0]}
self.visit_plate = (None, None)
log(self.name, "zone empty")
if close:
# R2, the user's flow: the barrier was opened in this busy period, the zone is now
# free, and the last crossing is not A → B → close, right away. Asked for only now,
# with the visit cleared: the relay loop looks at the zone again immediately before
# every datagram, and a vehicle back in the zone, a new visit or a stale picture
# drops the close.
self.app.relays.pulse(
"close", self.relay_close, f"{self.name}: crossing abandoned, zone free",
valid=lambda: self.track is None and not self.zone_busy and time.time() - self.checked_t < 1.0)
def record_verdict(self, tr, end):
"""Decide and record the visit. Returns True when the close relay is to be fired."""
path = [s for s, _ in tr["path"]]
f = tr["frame"]
# The leaving edge is judged on the last box that agreed with the car's side, not on a
# stray last one (see leaving_box).
ex = None
if f is not None:
lbox, lstate = self.leaving_box(tr, f.shape[1], f.shape[0])
if tr["path"] and lstate != tr["path"][-1][0]: # the unheld last look counts after all
tr["path"].append((lstate, tr["pend"][2]))
path.append(lstate)
if lstate != "line":
self.note_side(tr, lstate, tr["pend"][2])
ex = edge_side(self.line, lbox, f.shape[1], f.shape[0])
if path and path[-1] == "line" and ex:
# Last seen ON the line with its box at the frame's edge: it left the picture on that
# side (its rear is out of view, so the camera cannot see it clear the line).
self.note_side(tr, ex, tr["frame_t"])
v = decide(tr["cross"], end, self.app.cfg.get("close_on_lost", False))
plate, pstat = self.visit_plate
# The close itself is asked for by end_visit, once the visit is cleared.
tr["closed"] = bool(v == "abandoned" and self.relay_close and tr.get("opened"))
name = None
if f is not None:
img = f.copy()
H, W = img.shape[:2]
p1, p2 = self.line["p1"], self.line["p2"]
a, b = (int(p1["x"] * W), int(p1["y"] * H)), (int(p2["x"] * W), int(p2["y"] * H))
cv2.line(img, a, b, (255, 0, 255), 2)
# side labels: A is the screen-left of p1→p2
mx, my, dx, dy = (a[0] + b[0]) / 2, (a[1] + b[1]) / 2, b[0] - a[0], b[1] - a[1]
n = max(1.0, (dx * dx + dy * dy) ** 0.5)
for lab, k in (("A", 1), ("B", -1)):
cv2.putText(img, lab, (int(mx + k * dy / n * 30), int(my - k * dx / n * 30)),
cv2.FONT_HERSHEY_SIMPLEX, 0.9, (255, 0, 255), 2)
x1, y1, x2, y2 = map(int, tr["box"][:4])
cv2.rectangle(img, (x1, y1), (x2, y2), (0, 255, 0), 2)
cv2.putText(img, f"{v.upper()} {plate or ''}", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)
ts = datetime.fromtimestamp(tr["frame_t"], timezone.utc)
name = f"{ts.strftime('%Y%m%dT%H%M%S.%f')[:-3]}Z_{self.name}_{v}_{plate or 'noplate'}.jpg"
cv2.imwrite(str(self.app.out / "saves" / name), img, [cv2.IMWRITE_JPEG_QUALITY, 85])
t0 = tr["path"][0][1] if tr["path"] else tr["frame_t"]
rec = dict(at=datetime.now(timezone.utc).isoformat(), camera=self.name, verdict=v,
plate=plate, plate_status=pstat, last_crossing=tr["cross"], end=end,
crossings=[dict(crossing=c, at=datetime.fromtimestamp(t, timezone.utc).isoformat(timespec="milliseconds"))
for c, t in tr["crossings"]],
opened=bool(tr.get("opened")),
path=[dict(side=s, at=datetime.fromtimestamp(t, timezone.utc).isoformat(timespec="milliseconds"))
for s, t in tr["path"]],
left_view_on=ex if path and path[-1] == "line" else None,
came_into_view_on=tr["entry_side"] if path and path[0] == "line" else None,
seen_s=round(tr["frame_t"] - t0, 1), close_pulsed=tr.get("closed", False), last_frame=name)
with self.app.io_lock, open(self.app.out / "visits.jsonl", "a") as fh:
fh.write(json.dumps(rec) + "\n")
self.stats["verdicts"] += 1
log(self.name, "VERDICT", v.upper(), plate or "(no plate)", "path", "→".join(path) or "-",
"| last crossing:", tr["cross"] or "none", "| zone free:", end)
return tr["closed"]
def undecided(self):
"""The car left before a consensus: keep the evidence, flagged, never silently drop it."""
if not self.visit_votes:
log(self.name, f"car left, no usable plate read ({self.visit_reads} reads)")
if self.visit_reads == 0:
return
rec = dict(at=datetime.now(timezone.utc).isoformat(), camera=self.name, status="no_read",
plate=None, reads=self.visit_reads, sources=self.sources())
with self.app.io_lock, open(self.app.out / "reads.jsonl", "a") as fh:
fh.write(json.dumps(rec) + "\n")
return
text = max(self.visit_votes, key=lambda k: (self.visit_votes[k], self.visit_best[k][0]))
b = self.visit_best[text]
self.save(b[1], b[2], text, b[0], b[3], b[4], b[5], status="undecided")
def sources(self):
"""Per source: reads tried, reads that found a plate text, reads that voted."""
return {k: dict(tries=v[0], reads=v[1], votes=v[2]) for k, v in self.visit_src.items()}
def save(self, f, ft, text, conf, veh, pbox, poly, status="decided"):
img = f.copy()
cv2.polylines(img, [np.array(poly, np.int32)], True, (0, 210, 255), 2)
cv2.rectangle(img, (int(veh[0]), int(veh[1])), (int(veh[2]), int(veh[3])), (0, 255, 0), 2)
cv2.rectangle(img, (int(pbox[0]), int(pbox[1])), (int(pbox[2]), int(pbox[3])), (0, 0, 255), 2)
cv2.putText(img, f"{text} {conf:.2f}", (int(pbox[0]), max(20, int(pbox[1]) - 8)),
cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 0, 255), 2)
ts = datetime.fromtimestamp(ft, timezone.utc)
name = f"{ts.strftime('%Y%m%dT%H%M%S.%f')[:-3]}Z_{self.name}_{text}{'' if status == 'decided' else '_' + status}.jpg"
out = self.app.out / "saves"
cv2.imwrite(str(out / name), img, [cv2.IMWRITE_JPEG_QUALITY, 85])
rec = dict(at=ts.isoformat(), camera=self.name, status=status, plate=text, weakest_char=round(conf, 4),
votes=dict(self.visit_votes), reads=self.visit_reads, sources=self.sources(),
best_from=self.visit_best[text][6] if text in self.visit_best else None,
after_s=self.decided_s if status == "decided" else None,
vehicle=COCO_VEHICLES.get(veh[5]), vehicle_score=round(veh[4], 3),
latency_ms=round((time.time() - ft) * 1000), file=name)
with self.app.io_lock, open(self.app.out / "reads.jsonl", "a") as fh:
fh.write(json.dumps(rec) + "\n")
self.visit_plate = (text, status)
self.stats["saves"] += 1
log(self.name, "SAVED" if status == "decided" else status.upper(), text, f"votes {dict(self.visit_votes)}",
f"of {self.visit_reads} reads", "(stream %d/%d, still %d/%d voted)" % (
self.visit_src["stream"][2], self.visit_src["stream"][1], self.visit_src["still"][2], self.visit_src["still"][1]),
f"{rec['after_s']} s into the visit" if status == "decided" else "")
# --------------------------------------------------------------------------- app
class Relays:
"""Dingtian relay board, binary UDP protocol (the same frames as
packages/devices/src/drivers/access-dingtian.ts): jog = relay on, auto-off after pulse_ms.
Never a latch, never a timed close. DISARMED by default: every pulse is only logged as
WOULD PULSE until someone arms it on the page; arming lapses after arm_minutes. While it
is not live NOTHING is sent to the board: no pulse, no off command, no status read.
The relay password comes from the environment (DT_RELAY_PW), never from the file.
The rules (user, 2026-11-22), for the open and the close alike:
1. read the board's status before firing;
2. the OTHER relay of the pair reads off → fire;
3. it reads on → send it an off command, read again, fire once it reads off; if it
still reads on, keep trying;
4. the read fails → is the controller online? yes → keep looping; no → there is no
controller on the network to drive: the relay is flagged OFFLINE.
One worker sends everything, in order. Immediately before EVERY datagram it checks that
the command is still wanted: still armed, not replaced by a newer command, and still
valid (for a close: the zone still free on a fresh picture). So an open never waits
behind a close that is still trying."""
def __init__(self, cfg, app):
self.host = cfg.get("host")
self.port = int(cfg.get("port", 60000))
self.http_port = int(cfg.get("http_port", 80)) # the board's web/CGI port: the "online?" probe
self.channels = int(cfg.get("channels", 4))
self.pulse_ms = int(cfg.get("pulse_ms", 500))
self.arm_minutes = float(cfg.get("arm_minutes", 30))
self.timeout = float(cfg.get("timeout_s", 0.4)) # one LAN round trip; a missed read must not hold an open
self.retry_s = float(cfg.get("retry_s", 0.1))
self.pw = int(os.environ.get("DT_RELAY_PW", "0") or 0)
# The CLOSE is a dry run, even when armed, until close_live is set in the config.
self.close_live = bool(cfg.get("close_live", False))
self.armed_until = 0.0
self.offline = False
self.app = app
self.session = 0
self.seq = 0 # the newest command; an older one still trying gives way
self.pair: dict[int, int] = {} # relay -> the other relay of its pair (open <-> close of one barrier)
self.lock = threading.Lock()
self.q: queue.Queue = queue.Queue()
threading.Thread(target=self.worker, daemon=True, name="relays").start()
@property
def armed(self):
return time.time() < self.armed_until
def live(self, kind):
return self.armed and bool(self.host) and (kind == "open" or self.close_live)
def arm(self, on):
self.armed_until = time.time() + self.arm_minutes * 60 if on else 0.0
log("relays", (f"ARMED for {self.arm_minutes:g} min, close " + ("LIVE" if self.close_live else "dry run")) if on else "disarmed")
def frame(self, cmd, data=b""):
with self.lock:
self.session = (self.session + 1) & 0xFF
return bytes([0xFF, 0xAA, self.session, cmd, self.pw & 0xFF, (self.pw >> 8) & 0xFF]) + data
def udp(self, frame):
"""One request, one reply. The reply must echo the session and the command."""
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.settimeout(self.timeout)
try:
s.sendto(frame, (self.host, self.port))
r = s.recv(64)
finally:
s.close()
if len(r) < 4 or r[:2] != b"\xff\xaa" or r[2] != frame[2] or r[3] != frame[3]:
raise ValueError(f"unexpected reply {r.hex()}")
return r
def read(self):
"""Relay states as a bit mask (bit 0 = relay 1). Command 0x00: moves nothing.
Reply: FF AA <session> 00 <relay bytes> <input bytes>."""
w = max(1, -(-self.channels // 8))
r = self.udp(self.frame(0x00))
if len(r) < 4 + 2 * w:
raise ValueError(f"short status reply {r.hex()}")
return int.from_bytes(r[4:4 + w], "little")
def switch_off(self, channel):
"""Command 0x01: write relays, mask = this channel only, value = off."""
w = max(1, -(-self.channels // 8))
self.udp(self.frame(0x01, (1 << (channel - 1)).to_bytes(w, "little") + bytes(w)))
def jog(self, channel):
units = max(1, round(self.pulse_ms / 100))
relay_byte = (((channel - 1) & 0x7F) << 1) | 0x01
return self.udp(self.frame(0x03, bytes([relay_byte, units & 0xFF, units >> 8])))
def online(self):
"""Is there a controller on the network at all? A different question from the status
read, so a different probe: a TCP connect to the board's web port. A refused connection
still means the board is there."""
for _ in range(2):
try:
socket.create_connection((self.host, self.http_port), timeout=0.5).close()
return True
except ConnectionRefusedError:
return True
except OSError:
pass
return False
def status(self):
"""For the page: reachability + relay states. Moves nothing."""
if not self.host:
return dict(configured=False)
try:
m = self.read()
self.offline = False
return dict(online=True, relays=[bool(m >> i & 1) for i in range(self.channels)])
except Exception as e: # noqa: BLE001
on = self.online()
self.offline = not on
return dict(online=on, error=repr(e))
def pulse(self, kind, channel, why, valid=None):
"""Ask for a pulse on `channel`. `valid` says whether the pulse is still wanted; it is
asked again before every datagram. The other relay of the pair comes from self.pair."""
other = self.pair.get(channel, 0)
with self.lock:
self.seq += 1
n = self.seq
rec = dict(at=datetime.now(timezone.utc).isoformat(), relay=channel, action=kind, why=why, sent=False)
if not self.live(kind):
log("relays", "WOULD PULSE", f"R{channel}", kind, "-", why)
self.record(rec)
return
self.q.put((n, kind, channel, other, valid, rec))
def record(self, rec):
with self.app.io_lock, open(self.app.out / "relays.jsonl", "a") as fh:
fh.write(json.dumps(rec) + "\n")
def worker(self):
while True:
job = self.q.get()
try:
self.run(*job)
except Exception as e: # noqa: BLE001 - the worker must survive anything
job[-1]["error"] = repr(e)
log("relays", "FAILED", repr(e))
self.record(job[-1])
def run(self, n, kind, channel, other, valid, rec):
tag = f"R{channel} {kind}"
def unwanted(): # asked immediately before every datagram
if n != self.seq:
return "replaced by a newer command"
if not self.live(kind):
return "relays no longer armed"
if valid and not valid():
return "no longer valid: the zone is busy again, or the picture is stale" if kind == "close" else "no longer valid: that visit is over"
return None
def failed(what, e):
"""Rule 4. True = the controller is online, keep looping; False = flagged offline."""
rec["failures"] = rec.get("failures", 0) + 1
if self.online():
if rec["failures"] in (1, 10) or rec["failures"] % 50 == 0:
log("relays", f"{tag}: {what} failed ({e!r}), controller is online: trying again (failure {rec['failures']})")
time.sleep(self.retry_s)
return True
self.offline = True
rec["error"] = "relay controller offline"
log("relays", f"{tag} NOT SENT: {what} failed ({e!r}) and the controller does not answer on the network: flagged OFFLINE")
return False
while True:
why_not = unwanted()
if why_not:
break
if other:
try:
states = self.read()
except Exception as e: # noqa: BLE001
if failed("status read", e):
continue
return
self.offline = False
if states >> (other - 1) & 1:
rec["other_was_on"] = rec.get("other_was_on", 0) + 1
if rec["other_was_on"] in (1, 10) or rec["other_was_on"] % 50 == 0:
log("relays", f"{tag}: R{other} reads ON, switching it OFF first (try {rec['other_was_on']})"
+ (" — THIS CUTS AN OPEN TO MAKE WAY FOR A CLOSE" if kind == "close" else ""))
why_not = unwanted()
if why_not:
break
try:
self.switch_off(other)
except Exception as e: # noqa: BLE001
if not failed("off command", e):
return
time.sleep(self.retry_s)
continue # read again: fire only once it reads off
why_not = unwanted()
if why_not:
break
try:
rec["reply"] = self.jog(channel).hex()
except Exception as e: # noqa: BLE001
if failed("pulse", e):
continue
return
rec["sent"] = True
self.offline = False
log("relays", "PULSE", f"R{channel}", kind, "-", rec["why"])
return
rec["dropped"] = why_not
log("relays", f"{tag} DROPPED: {why_not}")
class App:
def __init__(self, cfg_path: str):
self.cfg_path = Path(cfg_path)
self.cfg = json.loads(self.cfg_path.read_text())
self.cfg.setdefault("detect_fps", 5)
self.cfg.setdefault("min_plate_conf", 0.9) # weakest character, to vote at all
self.cfg.setdefault("votes_needed", 3)
self.cfg.setdefault("agree_share", 0.75)
self.cfg.setdefault("visit_gap_s", 3)
self.cfg.setdefault("zone_overlap", 0.2) # share of a car's box in the zone to start a visit
self.cfg.setdefault("metrics_s", 10)
self.cfg.setdefault("http_port", 8090)
self.cfg.setdefault("threads", 2)
self.out = Path(self.cfg.get("out_dir", "out"))
(self.out / "saves").mkdir(parents=True, exist_ok=True)
self.io_lock = threading.Lock()
self.lane_lock = threading.Lock()
th = self.cfg["threads"]
self.yolox = Yolox(self.cfg["vehicle_model"], self.cfg.get("vehicle_input", 640), th, self.cfg.get("keep_conf", 0.15))
self.reader = Reader(self.cfg.get("plate_detector", "yolo-v9-t-384-license-plate-end2end"),
self.cfg.get("plate_ocr", "cct-xs-v2-global-model"), th)
self.relays = Relays(self.cfg.get("relays") or {}, self)
self.cams = [Camera(c, self) for c in self.cfg["cameras"]]
for c in self.cams: # a camera that names both relays defines the pair, for every camera using them
if c.relay_open and c.relay_close and c.relay_open != c.relay_close:
self.relays.pair[c.relay_open], self.relays.pair[c.relay_close] = c.relay_close, c.relay_open
def save_cam(self, name, key, value):
for c in self.cams:
if c.name == name:
setattr(c, key, value)
for c in self.cfg["cameras"]:
if c["name"] == name:
c[key] = value
self.cfg_path.write_text(json.dumps(self.cfg, indent=2) + "\n")
def metrics(self):
def proc():
p = open("/proc/self/stat").read().rsplit(")", 1)[1].split()
rss = int(open("/proc/self/statm").read().split()[1]) * os.sysconf("SC_PAGE_SIZE")
return (int(p[11]) + int(p[12])) / CLK, rss
def host():
a = list(map(int, open("/proc/stat").readline().split()[1:]))
return sum(a), a[3] + a[4]
def net_rx(): # bytes received on the machine's real network cards (host network)
n = 0
for ln in open("/proc/net/dev").read().splitlines()[2:]:
name, rest = ln.split(":", 1)
if name.strip().startswith(("en", "eth", "wl")):
n += int(rest.split()[0])
return n
cpu0, _ = proc()
h0 = host()
n0 = net_rx()
t0 = time.time()
prev = {c.name: dict(c.stats) for c in self.cams}
while True:
time.sleep(self.cfg["metrics_s"])
cpu1, rss = proc()
h1 = host()
n1 = net_rx()
t1 = time.time()
dt = t1 - t0
tot, idle = h1[0] - h0[0], h1[1] - h0[1]
m = dict(at=datetime.now(timezone.utc).isoformat(timespec="seconds"),
proc_cores=round((cpu1 - cpu0) / dt, 2),
proc_pct_of_host=round(100 * (cpu1 - cpu0) / dt / NCPU, 1),
host_busy_pct=round(100 * (tot - idle) / tot, 1) if tot else None,
rss_mb=round(rss / 2**20), load1=os.getloadavg()[0],
net_rx_mbps=round((n1 - n0) * 8 / dt / 1e6, 2), cams={})
for c in self.cams:
s, p = c.stats, prev[c.name]
d = {k: s[k] - p[k] for k in s}
m["cams"][c.name] = dict(
status=c.status, mode=c.mode, codec=c.codec, first_frame_s=c.first_frame_s,
live_viewers=c.live_viewers, live_per_s=round(d["live"] / dt, 1),
fps=round(d["received"] / dt, 1),
decoded_per_s=round(d["decoded"] / dt, 1),
snap_ms=round(d["snap_ms"] / d["received"], 1) if c.mode == "snapshot" and d["received"] else None,
det_per_s=round(d["det_runs"] / dt, 1),
det_ms=round(d["det_ms"] / d["det_runs"], 1) if d["det_runs"] else None,
reads=d["read_runs"], hires=d["hires"],
hires_ms=round(d["hires_ms"] / d["hires"], 1) if d["hires"] else None,
read_ms=round(d["read_ms"] / d["read_runs"], 1) if d["read_runs"] else None,
saves=d["saves"], verdicts=d["verdicts"], present=c.present)
prev[c.name] = dict(s)
cpu0, h0, n0, t0 = cpu1, h1, n1, t1
with self.io_lock, open(self.out / "metrics.jsonl", "a") as fh:
fh.write(json.dumps(m) + "\n")
log("metrics", f"proc {m['proc_cores']} cores ({m['proc_pct_of_host']}% of host)",
f"rss {m['rss_mb']} MB", f"host {m['host_busy_pct']}%", f"net in {m['net_rx_mbps']} Mbps",
" | ".join(f"{n}: {v['mode']} {v['codec']} {v['fps']} in/s, {v['decoded_per_s']} dec/s, live {v['live_per_s']}/s x{v['live_viewers']}"
+ (f", snap {v['snap_ms']} ms" if v['snap_ms'] else "") + f", det {v['det_ms']} ms, reads {v['reads']}"
+ (f" (hi-res {v['hires_ms']} ms)" if v['hires_ms'] else "") + ""
f" @ {v['read_ms']} ms" for n, v in m["cams"].items()))
def run(self):
for c in self.cams:
threading.Thread(target=c.grab, daemon=True, name=f"grab-{c.name}").start()
threading.Thread(target=c.work, daemon=True, name=f"work-{c.name}").start()
threading.Thread(target=c.live_loop, daemon=True, name=f"live-{c.name}").start()
threading.Thread(target=self.metrics, daemon=True, name="metrics").start()
Handler.app = self
srv = ThreadingHTTPServer(("0.0.0.0", self.cfg["http_port"]), Handler)
log(f"web page on http://0.0.0.0:{self.cfg['http_port']}/ out: {self.out}")
srv.serve_forever()
# --------------------------------------------------------------------------- web page
PAGE = """<!doctype html><meta charset=utf-8><meta name=viewport content="width=device-width">
<title>Zone ANPR PoC</title>
<style>body{font:14px system-ui;margin:16px;background:#111;color:#ddd}
.cam{margin-bottom:28px}.wrap{position:relative;display:inline-block;max-width:100%;user-select:none}
img{max-width:100%;display:block}svg{position:absolute;inset:0;width:100%;height:100%;cursor:crosshair;touch-action:none}
button{margin:6px 6px 0 0;padding:6px 12px;background:#222;color:#ddd;border:1px solid #555;border-radius:4px;cursor:pointer}
button.on{background:#facc15;color:#000;border-color:#facc15}button:disabled{opacity:.4;cursor:default}
.hint{color:#999;margin:4px 0}.warn{color:#facc15}#reads div,#visits div{font-family:monospace}</style>
<h2>Zone ANPR PoC</h2>
<div id=relaybar style="padding:8px;border:1px solid #555;border-radius:4px;margin-bottom:12px"></div>
<div id=cams></div><h3>Last verdicts</h3><div id=visits></div><h3>Last saved reads</h3><div id=reads></div>
<script>
// Per camera: mode 'zone' | 'line'. Zone: click points, Save zone. Line: same editor as the app's
// Setup (drag across the picture to draw, drag an end to move it, A→B / B→A / A↔B, Swap A/B).
// Side A is the screen-left of p1→p2, like the app (packages/shared crossingSide).
const S={mode:{},zone:{},line:{},drag:null};let last;
const HANDLE=14, MINLEN=0.03, AMBER='rgb(250 204 21)';
function cam(n){return last&&last.cams.find(c=>c.name==n)}
function curLine(n){return S.line[n]!==undefined?S.line[n]:(cam(n)||{}).line||null}
async function init(){
last=await (await fetch('status')).json();
for(const c of last.cams){S.mode[c.name]='zone';
const d=document.createElement('div');d.className='cam';d.id='c-'+c.name;cams.appendChild(d);
d.innerHTML=`<h3>${c.name} <small id=s-${c.name}></small></h3>
<button id=mz-${c.name} onclick="mode('${c.name}','zone')">Edit zone</button><button id=ml-${c.name} onclick="mode('${c.name}','line')">Edit crossing line</button>
<p class=hint id=h-${c.name}></p><div class=wrap><img id=i-${c.name} draggable=false><svg id=v-${c.name}></svg></div>
<div id=b-${c.name}></div>`;
const v=document.getElementById('v-'+c.name);
v.onpointerdown=e=>down(c.name,e);v.onpointermove=e=>move(c.name,e);v.onpointerup=e=>up(c.name);v.onpointercancel=e=>up(c.name);
mode(c.name,'zone');
}
tick();
}
function mode(n,m){S.mode[n]=m;
document.getElementById('mz-'+n).className=m=='zone'?'on':'';document.getElementById('ml-'+n).className=m=='line'?'on':'';
document.getElementById('h-'+n).textContent=m=='zone'
?'Click on the picture to place the zone points (3 or more), then Save zone.'
:'Drag across the picture to draw the line a vehicle must cross; drag an end to move it. A → B is in, B → A is out: Swap A/B if the arrow points the wrong way. Then Save line.';
buttons(n);draw();}
function buttons(n){const b=document.getElementById('b-'+n);
if(S.mode[n]=='zone'){b.innerHTML=`<button onclick="saveZone('${n}')">Save zone</button><button onclick="S.zone['${n}']=[];draw()">Clear draft</button>`;return}
const l=curLine(n),dirty=S.line[n]!==undefined;
b.innerHTML=`<span class=hint>A → B = in, B → A = out. </span><button ${!l?'disabled':''} onclick="swap('${n}')">Swap A/B</button>`+
`<button ${!dirty||!l?'disabled':''} onclick="saveLine('${n}')">Save line</button>`+
`<button ${!dirty?'disabled':''} onclick="delete S.line['${n}'];buttons('${n}');draw()">Undo changes</button>`+
(dirty?' <span class=warn>unsaved</span>':'')+(!l?' <span class=hint>No line drawn.</span>':'');}
function swap(n){const l=curLine(n);if(!l)return;S.line[n]={...l,p1:l.p2,p2:l.p1};buttons(n);draw()}
function pt(n,e){const r=document.getElementById('v-'+n).getBoundingClientRect(),cl=v=>Math.min(1,Math.max(0,v));
return {x:+cl((e.clientX-r.left)/r.width).toFixed(4),y:+cl((e.clientY-r.top)/r.height).toFixed(4),r}}
function down(n,e){const p=pt(n,e);
if(S.mode[n]=='zone'){(S.zone[n]=S.zone[n]||[]).push([p.x,p.y]);draw();return}
e.currentTarget.setPointerCapture(e.pointerId);const l=curLine(n);
if(l)for(const end of ['p1','p2']){if(Math.hypot((l[end].x-p.x)*p.r.width,(l[end].y-p.y)*p.r.height)<=HANDLE){S.drag={n,end,draft:false};return}}
S.drag={n,end:'p2',draft:true,line:{p1:{x:p.x,y:p.y},p2:{x:p.x,y:p.y},direction:l?l.direction:'a-to-b'}};draw()}
function move(n,e){const d=S.drag;if(!d||d.n!=n)return;const p=pt(n,e),q={x:p.x,y:p.y};
if(d.draft)d.line[d.end]=q;else S.line[n]={...curLine(n),[d.end]:q};draw()}
function up(n){const d=S.drag;if(!d||d.n!=n)return;S.drag=null;
if(d.draft&&Math.hypot(d.line.p2.x-d.line.p1.x,d.line.p2.y-d.line.p1.y)>=MINLEN)S.line[n]=d.line;
buttons(n);draw()}
async function saveLine(n){const l=curLine(n);if(!l)return;
const r=await fetch('line/'+n,{method:'POST',body:JSON.stringify({...l,direction:'a-to-b'})});if(!r.ok)return alert('Not saved: '+await r.text());
last=await (await fetch('status')).json();delete S.line[n];buttons(n);draw()}
async function saveZone(n){const z=S.zone[n]||[];if(z.length<3)return alert('Need at least 3 points');
await fetch('zone/'+n,{method:'POST',body:JSON.stringify(z)});S.zone[n]=[];last=await (await fetch('status')).json();draw()}
async function tick(){
try{last=await (await fetch('status')).json();
for(const c of last.cams){{const im=document.getElementById('i-'+c.name);if(!im.dataset.live){im.dataset.live=1;im.onerror=()=>{delete im.dataset.live};im.src='live/'+c.name+'.mjpg?'+Date.now()}}
document.getElementById('s-'+c.name).textContent=`${c.status} · ${c.present?'ZONE BUSY'+(c.crossing?' · last crossing '+({'a-to-b':'A → B (in)','b-to-a':'B → A (out)'})[c.crossing]:' · no crossing yet'):c.yielded?'lane busy (other camera)':c.busy?'vehicle in zone (no visit)':'empty'}${c.side?' · car '+({a:'on side A',b:'on side B',line:'on the line'})[c.side]:''}${c.read?' · '+c.read:''}`}
const R=last.relays;relaybar.innerHTML=!R.configured?'Relays: not configured':
(R.armed?`<b style="color:#f55">RELAYS ARMED</b> — R1 opens on a car in the zone. R2 (close) ${R.close_live?'<b style="color:#f55">is LIVE: it closes the real barrier on an abandoned open</b>':'stays a dry run (logged only)'}. Auto-disarm in ${Math.ceil(R.armed_left_s/60)} min. <button onclick="fetch('disarm',{method:'POST'})">Disarm</button>`
:`Relays: <b>disarmed</b> (dry run: actions are logged as WOULD PULSE, nothing is sent to the board). <button onclick="if(confirm('Arm the relays? R1 will open the real barrier.'+(${R.close_live}?' R2 is LIVE: it will CLOSE the real barrier on an abandoned open.':'')))fetch('arm',{method:'POST'})">Arm relays</button>`)+
(R.offline?' <b style="color:#f55">RELAY CONTROLLER OFFLINE</b>':'')+
` <button onclick="fetch('relaystatus').then(r=>r.json()).then(x=>alert(x.online?'Controller online. '+x.relays.map((v,i)=>'R'+(i+1)+' '+(v?'ON':'off')).join(', '):x.error?'Status read failed: '+x.error+(x.online?' (the controller answers on the network)':' (controller OFFLINE)'):'not configured'))">Read board</button>`+
R.log.map(x=>`<div style="font-family:monospace">${x.at.slice(11,19)} ${x.sent?'PULSE':x.dropped?'dropped':x.error?'FAILED':'would pulse'} R${x.relay} ${x.action} — ${x.why}${x.other_was_on?' — other relay read ON, switched off ×'+x.other_was_on:''}${x.dropped?' — '+x.dropped:''}${x.error?' — '+x.error:''}</div>`).join('');
visits.innerHTML=last.visits.map(v=>`<div>${v.at.slice(11,19)} ${v.camera} <b>${v.verdict.toUpperCase()}</b> ${v.plate||'(no plate)'} ${v.path.map(p=>p.side).join('→')} ${v.last_frame?`<a href="saves/${v.last_frame}" target=_blank>photo</a>`:''}</div>`).join('');
reads.innerHTML=last.reads.map(r=>`<div>${r.at.slice(11,19)} ${r.camera} ${r.status||''} <b>${r.plate||'-'}</b> ${r.votes?JSON.stringify(r.votes):''} ${r.file?`<a href="saves/${r.file}" target=_blank>photo</a>`:''}</div>`).join('');
draw()}catch(e){}
setTimeout(tick,700);
}
function lineSvg(l,W,H,faint){if(!l)return'';
const p1={x:l.p1.x*W,y:l.p1.y*H},p2={x:l.p2.x*W,y:l.p2.y*H},dx=p2.x-p1.x,dy=p2.y-p1.y,len=Math.hypot(dx,dy)||1;
const nA={x:dy/len,y:-dx/len},mid={x:(p1.x+p2.x)/2,y:(p1.y+p2.y)/2},at=k=>({x:mid.x+nA.x*k,y:mid.y+nA.y*k});
const aS=at(22),bS=at(-22),lA=at(40),lB=at(-40),[f,t]=[aS,bS],both=false;
const op=faint?' opacity=0.45':'';
return `<g${op}><line x1=${p1.x} y1=${p1.y} x2=${p2.x} y2=${p2.y} stroke=black stroke-opacity=.5 stroke-width=5 />
<line x1=${p1.x} y1=${p1.y} x2=${p2.x} y2=${p2.y} stroke="${AMBER}" stroke-width=3 />
<line x1=${f.x} y1=${f.y} x2=${t.x} y2=${t.y} stroke="${AMBER}" stroke-width=3 marker-end="url(#hd)" ${both?'marker-start="url(#hd)"':''} />
${[p1,p2].map(p=>`<circle cx=${p.x} cy=${p.y} r=6 fill="${AMBER}" stroke=black stroke-width=1.5 />`).join('')}
${[['A',lA],['B',lB]].map(([s,p])=>`<text x=${p.x} y=${p.y} text-anchor=middle dominant-baseline=central font-size=16 font-weight=700 fill="${AMBER}" stroke=black stroke-width=3 paint-order=stroke>${s}</text>`).join('')}</g>`}
function draw(){if(!last)return;for(const c of last.cams){const v=document.getElementById('v-'+c.name);if(!v)continue;
const r=v.getBoundingClientRect(),W=r.width,H=r.height;if(!W)continue;v.setAttribute('viewBox',`0 0 ${W} ${H}`);
const P=z=>z.map(q=>`${q[0]*W},${q[1]*H}`).join(' ');const zd=S.zone[c.name]||[];
const d=S.drag&&S.drag.n==c.name&&S.drag.draft?S.drag.line:curLine(c.name);
v.innerHTML=`<defs><marker id=hd viewBox="0 0 10 10" refX=8 refY=5 markerWidth=5 markerHeight=5 orient=auto-start-reverse><path d="M0,0 L10,5 L0,10 z" fill="${AMBER}"/></marker></defs>`+
(c.zone.length?`<polygon points="${P(c.zone)}" fill="#00e5ff18" stroke="#00e5ff" stroke-width=2 />`:'')+
(zd.length?`<polygon points="${P(zd)}" fill=none stroke="#fff" stroke-width=2 stroke-dasharray=6 />`+zd.map(q=>`<circle cx=${q[0]*W} cy=${q[1]*H} r=5 fill=#fff />`).join(''):'')+
lineSvg(d,W,H,S.mode[c.name]!='line')}}
addEventListener('resize',draw);
init();
</script>"""
class Handler(BaseHTTPRequestHandler):
app: App
def log_message(self, *a):
pass
def send(self, code, body, ctype):
self.send_response(code)
self.send_header("Content-Type", ctype)
self.send_header("Cache-Control", "no-store")
self.end_headers()
self.wfile.write(body)
def do_GET(self):
a = self.app
if self.path == "/":
return self.send(200, PAGE.encode(), "text/html; charset=utf-8")
if self.path == "/status":
reads = []
p = a.out / "reads.jsonl"
if p.exists():
reads = [json.loads(x) for x in p.read_text().splitlines()[-15:]][::-1]
visits = []
p = a.out / "visits.jsonl"
if p.exists():
visits = [json.loads(x) for x in p.read_text().splitlines()[-15:]][::-1]
cams = [dict(name=c.name, status=c.status, zone=c.zone, line=c.line, present=c.present, yielded=c.yielded,
busy=c.zone_busy, crossing=(c.track["cross"] if c.track else None),
side=(c.track["path"][-1][0] if c.track and c.track["path"] else None),
read=f"{c.last_read[0]} {c.last_read[1]:.2f}" if c.last_read else None)
for c in a.cams]
rl = a.relays
relays = dict(configured=bool(rl.host), armed=rl.armed, close_live=rl.close_live, offline=rl.offline,
armed_left_s=max(0, round(rl.armed_until - time.time())),
log=[json.loads(x) for x in (a.out / "relays.jsonl").read_text().splitlines()[-10:]][::-1]
if (a.out / "relays.jsonl").exists() else [])
return self.send(200, json.dumps(dict(cams=cams, reads=reads, visits=visits, relays=relays)).encode(), "application/json")
if self.path == "/relaystatus": # a status read on demand: moves nothing
return self.send(200, json.dumps(a.relays.status()).encode(), "application/json")
m = re.match(r"^/live/([\w-]+)\.mjpg", self.path)
if m: # the live picture: multipart JPEG, newest frame only (a slow viewer skips frames)
c = next((c for c in a.cams if c.name == m.group(1)), None)
if c is None:
return self.send(404, b"no camera", "text/plain")
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()
with c.live_cond:
c.live_viewers += 1
c.live_cond.notify_all()
seen = c.live_no
try:
while True:
with c.live_cond:
if not c.live_cond.wait_for(lambda: c.live_no != seen, timeout=10):
continue
jpeg, seen = c.live_jpeg, c.live_no
self.wfile.write(b"--frame\r\nContent-Type: image/jpeg\r\nContent-Length: "
+ str(len(jpeg)).encode() + b"\r\n\r\n" + jpeg + b"\r\n")
except OSError:
pass # the viewer went away
finally:
with c.live_cond:
c.live_viewers -= 1
return
m = re.match(r"^/frame/([\w-]+)\.jpg", self.path)
if m:
c = next((c for c in a.cams if c.name == m.group(1)), None)
f = c.latest()[0] if c else None
if f is None:
return self.send(404, b"no frame", "text/plain")
h, w = f.shape[:2]
small = cv2.resize(f, (960, int(960 * h / w)))
sx = 960 / w
for x1, y1, x2, y2, *_ in c.last_vehicles:
cv2.rectangle(small, (int(x1 * sx), int(y1 * sx)), (int(x2 * sx), int(y2 * sx)), (0, 255, 0), 2)
return self.send(200, cv2.imencode(".jpg", small, [cv2.IMWRITE_JPEG_QUALITY, 70])[1].tobytes(), "image/jpeg")
m = re.match(r"^/saves/([\w.\-]+\.jpg)$", self.path)
if m and (a.out / "saves" / m.group(1)).exists():
return self.send(200, (a.out / "saves" / m.group(1)).read_bytes(), "image/jpeg")
self.send(404, b"not found", "text/plain")
def do_POST(self):
if self.path in ("/arm", "/disarm"):
self.app.relays.arm(self.path == "/arm")
return self.send(200, b"ok", "text/plain")
m = re.match(r"^/line/([\w-]+)$", self.path)
if m:
ln = parse_line(json.loads(self.rfile.read(int(self.headers.get("Content-Length", 0)))))
if not ln:
return self.send(400, b"bad line", "text/plain")
self.app.save_cam(m.group(1), "line", ln)
log(m.group(1), "line saved", ln)
return self.send(200, b"ok", "text/plain")
m = re.match(r"^/zone/([\w-]+)$", self.path)
if not m:
return self.send(404, b"not found", "text/plain")
z = json.loads(self.rfile.read(int(self.headers.get("Content-Length", 0))))
if not (isinstance(z, list) and len(z) >= 3 and all(len(p) == 2 and 0 <= p[0] <= 1 and 0 <= p[1] <= 1 for p in z)):
return self.send(400, b"bad zone", "text/plain")
self.app.save_cam(m.group(1), "zone", z)
log(m.group(1), "zone saved", z)
self.send(200, b"ok", "text/plain")
if __name__ == "__main__":
if len(sys.argv) != 2:
sys.exit(__doc__)
App(sys.argv[1]).run()