Spaces:
Sleeping

File size: 28,349 Bytes
29088fd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6aee097
 
 
29088fd
6aee097
29088fd
6aee097
 
 
 
29088fd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6aee097
 
 
 
29088fd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6aee097
 
29088fd
 
 
6aee097
29088fd
 
 
 
 
6aee097
 
 
29088fd
6aee097
29088fd
 
 
 
 
 
 
 
 
 
 
 
 
6aee097
29088fd
 
 
 
 
 
 
 
 
 
 
6aee097
 
 
29088fd
 
 
 
 
 
 
 
 
 
 
 
 
6aee097
 
29088fd
 
 
7196a40
29088fd
 
 
 
7196a40
29088fd
 
 
 
 
 
 
 
 
 
 
 
7196a40
6aee097
29088fd
6aee097
29088fd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6aee097
29088fd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6aee097
29088fd
 
 
 
 
 
 
6aee097
29088fd
 
 
 
 
 
 
 
6aee097
29088fd
 
 
 
 
 
 
 
6aee097
29088fd
 
 
 
 
 
6aee097
29088fd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6aee097
 
29088fd
 
 
 
 
 
 
 
 
6aee097
29088fd
 
6aee097
29088fd
 
 
6aee097
29088fd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6aee097
29088fd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6aee097
29088fd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6aee097
 
29088fd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
"""
Traffic violation engine: turns frames into tracked vehicles, rider/occupant
evidence, rule hits and consolidated per-vehicle incidents.

    engine = TrafficEnforcementEngine(EngineConfig())
    engine.reset(scene, fps=25)
    for frame in video:
        out = engine.process_frame(frame)          # FrameOutput
        for incident in out.finalized: save(incident)
    for incident in engine.finalize_all(): save(incident)

    out = engine.process_image(image, scene)       # single photo

Appearance violations (helmet, triple riding, seatbelt) work on single images.
Motion violations need video: wrong-side (direction over ~1.5 s), red light /
stop line (crossing event; images get a static "past the line on red" check)
and illegal parking (dwell time, seconds).
"""
from __future__ import annotations

import logging
import time
from dataclasses import dataclass, field
from typing import Any, Callable

import cv2
import numpy as np

from core.geometry import BBox, bbox_bottom_center, expand_bbox
from core.models import CATEGORY_DISPLAY, Detection, YoloModels
from core.rules import (
    HELMET,
    PARKING,
    RED_LIGHT,
    SEATBELT,
    STOP_LINE,
    TRIPLE,
    WRONG_SIDE,
    ParkingRule,
    RuleHit,
    SignalFilter,
    StopLineRule,
    TemporalVote,
    TrackHistory,
    WrongSideRule,
    assign_heads,
    classify_traffic_light,
    nms_heads,
    rider_zone,
)
from core.scene import SceneConfig
from core.visualize import VIOLATION_COLORS, draw_frame, draw_scene, highlight
from utils.preprocessing import preprocess_frame

LOGGER = logging.getLogger(__name__)


@dataclass
class EngineConfig:
    vehicle_model: str = "models/uvh26_yolo11s.pt"
    helmet_model: str = "models/helmet_best.pt"
    seatbelt_model: str = "models/seatbelt_best.pt"
    plate_model: str = "models/lp_best.pt"
    coco_model: str = "yolov8s.pt"
    device: Any = None

    vehicle_conf: float = 0.30
    vehicle_imgsz: int = 960
    helmet_conf: float = 0.35          # detector threshold for heads
    no_helmet_conf: float = 0.50       # a NoHelmet head must reach this to count
    helmet_imgsz: int = 640
    min_two_wheeler_px: int = 48       # smaller bikes: rider heads are unreadable
    seatbelt_conf: float = 0.50
    min_car_width_px: int = 110        # smaller cars: windshield unreadable
    triple_min_riders: int = 3
    plate_conf: float = 0.30
    ocr_conf: float = 0.45
    read_all_plates: bool = False      # OCR every vehicle, not only violators
    plate_max_reads: int = 10          # per track
    preprocessing: str = "auto"
    enabled: tuple[str, ...] = (HELMET, TRIPLE, SEATBELT, WRONG_SIDE, STOP_LINE, RED_LIGHT, PARKING)
    traffic_light_every_s: float = 0.4
    incident_ttl_s: float = 2.0
    min_votes: int = 2                 # appearance violations in video need >= this many positive frames
    photo_fallback: bool = True        # photos: also run COCO detector for ground-level / close-up vehicles
    rider_model: str = "models/riders_best.pt"  # photos: two-wheeler+riders detector/classifier
    rider_det_conf: float = 0.25       # rider-model boxes below this are ignored
    # rider-model thresholds, chosen on the valid split (tools/evaluate.py --violations reports both splits)
    rider_no_helmet_conf: float = 0.40  # rider model "WithoutHelmet" at/above this flags No Helmet
    rider_triple_conf: float = 0.40    # rider model "TripleRiding" at/above this flags Triple Riding
    rider_evidence: str = "both"       # photos: "heads", "rider_model" or "both" (either source can flag)


@dataclass
class ViolationEvidence:
    violation: str
    confidence: float
    reason: str
    timestamp: float
    frame_index: int
    metadata: dict[str, Any] = field(default_factory=dict)
    snapshot: np.ndarray | None = field(default=None, repr=False)  # annotated full frame


@dataclass
class Incident:
    track_id: int
    category: str
    label: str
    first_t: float
    last_t: float
    violations: dict[str, ViolationEvidence] = field(default_factory=dict)
    vehicle_crop: np.ndarray | None = field(default=None, repr=False)
    plate_text: str = "MANUAL_REVIEW"
    plate_confidence: float = 0.0
    plate_crop: np.ndarray | None = field(default=None, repr=False)
    plate_reads: int = 0
    bbox: tuple[int, int, int, int] = (0, 0, 0, 0)

    def summary(self) -> dict[str, Any]:
        return {
            "track_id": self.track_id,
            "vehicle": CATEGORY_DISPLAY.get(self.category, self.category),
            "vehicle_class": self.label,
            "plate": self.plate_text,
            "plate_confidence": round(self.plate_confidence, 3),
            "bbox": [int(v) for v in self.bbox],
            "violations": [
                {"type": v.violation, "confidence": round(v.confidence, 3), "reason": v.reason,
                 "time_s": round(v.timestamp, 2)}
                for v in self.violations.values()
            ],
        }


@dataclass
class FrameOutput:
    frame_index: int
    timestamp: float
    annotated: np.ndarray
    detections: list[Detection]
    signal: str
    new_violations: list[dict[str, Any]]
    active_incidents: list[dict[str, Any]]
    finalized: list[Incident]
    timings_ms: dict[str, float]
    counts: dict[str, int]
    debug: dict[str, Any] = field(default_factory=dict)


class TrafficEnforcementEngine:
    def __init__(self, config: EngineConfig | None = None, models: Any = None,
                 plate_reader: Callable[[np.ndarray], Any] | None | str = "default") -> None:
        """
        models: object exposing vehicles/heads/seatbelt_check/traffic_lights (YoloModels by default;
                tests inject fakes).
        plate_reader: callable(vehicle_crop) -> core.ocr_engine.OCRResult; "default" uses the YOLO
                plate detector + OCR; None disables plate reading.
        """
        self.config = config or EngineConfig()
        c = self.config
        self.models = models or YoloModels(c.vehicle_model, c.helmet_model, c.seatbelt_model, c.coco_model,
                                           device=c.device, rider_model=c.rider_model)
        if plate_reader == "default":
            from core.ocr_engine import read_vehicle_license_plate

            def plate_reader(crop: np.ndarray):
                return read_vehicle_license_plate(crop, c.plate_model, c.plate_conf, c.ocr_conf, device=c.device)
        self.plate_reader = plate_reader
        self.scene = SceneConfig()
        self.reset(self.scene)

    # ------------------------------------------------------------------
    # State
    # ------------------------------------------------------------------
    def reset(self, scene: SceneConfig | None = None, fps: float = 25.0, frame_shape: tuple[int, ...] | None = None) -> None:
        if scene is not None:
            self.scene = scene
        self.fps = fps or 25.0
        self.frame_index = 0
        self.history = TrackHistory()
        self.signal_filter = SignalFilter()
        self.votes = TemporalVote(min_hits=self.config.min_votes)
        self.incidents: dict[int, Incident] = {}
        self.voters: dict[int, Any] = {}
        self.plate_reads: dict[int, int] = {}
        self.track_meta: dict[int, Detection] = {}
        self._rules_shape: tuple[int, int] | None = None
        self._last_light_t = -1e9
        self._light_box: BBox | None = None
        self._light_raw = "UNKNOWN"
        if hasattr(self.models, "reset_tracker"):
            self.models.reset_tracker()
        if frame_shape is not None:
            self._build_rules(frame_shape)

    def _build_rules(self, shape: tuple[int, ...]) -> None:
        self._rules_shape = tuple(shape[:2])
        self.lanes = self.scene.build_lanes(shape)
        self.stop_line = self.scene.build_stop_line(shape)
        self.parking_zones = self.scene.build_parking_zones(shape)
        self.wrong_side = WrongSideRule(self.lanes)
        self.stop_rule = StopLineRule(self.stop_line) if self.stop_line is not None else None
        self.parking = ParkingRule(self.parking_zones, dwell_s=self.scene.parking_dwell_s)

    # ------------------------------------------------------------------
    # Signal
    # ------------------------------------------------------------------
    def _signal_state(self, frame: np.ndarray, t: float, debug: dict[str, Any]) -> str:
        mode = (self.scene.signal_mode or "auto").upper()
        if mode in {"RED", "YELLOW", "GREEN"}:
            return mode
        roi = self.scene.traffic_light_box(frame.shape)
        if roi is not None:
            x1, y1, x2, y2 = roi
            state, ratios = classify_traffic_light(frame[y1:y2, x1:x2])
            self._light_box = roi
            debug["signal_ratios"] = ratios
            return self.signal_filter.update(state)
        needs_signal = self.stop_rule is not None and (STOP_LINE in self.config.enabled or RED_LIGHT in self.config.enabled)
        if not needs_signal:
            return "UNKNOWN"
        if t - self._last_light_t >= self.config.traffic_light_every_s:
            self._last_light_t = t
            lights = self.models.traffic_lights(frame)
            best_state, best_score = "UNKNOWN", 0.0
            for box, conf in lights:
                x1, y1, x2, y2 = box
                state, ratios = classify_traffic_light(frame[y1:y2, x1:x2])
                score = conf * (x2 - x1) * (y2 - y1)
                if state != "UNKNOWN" and score > best_score:
                    best_state, best_score, self._light_box = state, score, box
            self._light_raw = best_state
            debug["traffic_lights"] = [{"bbox": list(b), "conf": round(c, 3)} for b, c in lights]
        return self.signal_filter.update(self._light_raw)

    # ------------------------------------------------------------------
    # Plates
    # ------------------------------------------------------------------
    def _read_plate(self, raw: np.ndarray, det: Detection) -> None:
        if self.plate_reader is None:
            return
        from core.ocr_engine import PlateVoter

        tid = det.track_id
        if self.plate_reads.get(tid, 0) >= self.config.plate_max_reads:
            return
        box = expand_bbox(det.bbox, 0.04, 0.04, 0.04, 0.06, raw.shape)
        crop = raw[box[1]:box[3], box[0]:box[2]]
        if crop.size == 0 or min(crop.shape[:2]) < 24:
            return
        self.plate_reads[tid] = self.plate_reads.get(tid, 0) + 1
        try:
            result = self.plate_reader(crop)
        except Exception as exc:  # pragma: no cover
            LOGGER.warning("plate read failed: %s", exc)
            return
        if not result.plate_detected:
            return
        voter = self.voters.setdefault(tid, PlateVoter())
        voter.add(result)

    def _plate_for(self, tid: int) -> tuple[str, float, np.ndarray | None, int]:
        voter = self.voters.get(tid)
        if voter is None or len(voter) == 0:
            return "MANUAL_REVIEW", 0.0, None, 0
        reading = voter.result(self.config.ocr_conf)
        return reading.text, reading.confidence, voter.best_crop, len(voter)

    # ------------------------------------------------------------------
    # Incidents
    # ------------------------------------------------------------------
    def _record(self, hit: RuleHit, det: Detection, raw: np.ndarray, t: float,
                snapshot_base: np.ndarray, new_events: list[dict[str, Any]]) -> None:
        if hit.violation not in self.config.enabled:
            return
        inc = self.incidents.get(det.track_id)
        if inc is None:
            inc = Incident(det.track_id, det.category, det.label, t, t, bbox=det.bbox)
            self.incidents[det.track_id] = inc
        if hit.violation in inc.violations:
            return
        # Red-light jump supersedes the stop-line event for the same vehicle
        if hit.violation == RED_LIGHT:
            inc.violations.pop(STOP_LINE, None)
        if hit.violation == STOP_LINE and RED_LIGHT in inc.violations:
            return
        snap = highlight(snapshot_base, det.bbox, hit.violation.upper(), VIOLATION_COLORS.get(hit.violation, (0, 0, 255)))
        inc.violations[hit.violation] = ViolationEvidence(hit.violation, hit.confidence, hit.reason, t,
                                                          self.frame_index, hit.metadata, _shrink(snap, 1600))
        self._update_crop(inc, raw, det)
        new_events.append({"track_id": det.track_id, "type": hit.violation, "confidence": round(hit.confidence, 3),
                           "reason": hit.reason, "time_s": round(t, 2), "vehicle": CATEGORY_DISPLAY.get(det.category),
                           "bbox": list(det.bbox)})

    @staticmethod
    def _update_crop(inc: Incident, raw: np.ndarray, det: Detection) -> None:
        box = expand_bbox(det.bbox, 0.1, 0.1, 0.1, 0.1, raw.shape)
        crop = raw[box[1]:box[3], box[0]:box[2]]
        if crop.size and (inc.vehicle_crop is None or crop.size > inc.vehicle_crop.size):
            inc.vehicle_crop = crop.copy()

    def _finalize(self, tid: int) -> Incident | None:
        inc = self.incidents.pop(tid, None)
        if inc is None:
            return None
        inc.plate_text, inc.plate_confidence, inc.plate_crop, inc.plate_reads = self._plate_for(tid)
        return inc if inc.violations else None

    def finalize_all(self) -> list[Incident]:
        out = [self._finalize(tid) for tid in list(self.incidents)]
        return [i for i in out if i is not None]

    # ------------------------------------------------------------------
    # Main entry points
    # ------------------------------------------------------------------
    def process_image(self, image: np.ndarray, scene: SceneConfig | None = None, debug: bool = False) -> tuple[FrameOutput, list[Incident]]:
        self.reset(scene or self.scene, frame_shape=image.shape)
        out = self.process_frame(image, timestamp=0.0, debug=debug, video=False)
        return out, self.finalize_all()

    def process_frame(self, frame: np.ndarray, timestamp: float | None = None, debug: bool = False,
                      video: bool = True) -> FrameOutput:
        if frame is None or frame.ndim != 3 or frame.shape[2] != 3:
            raise ValueError("frame must be a BGR image (H, W, 3)")
        timings: dict[str, float] = {}
        tick = time.perf_counter()
        c = self.config
        self.frame_index += 1
        t = float(timestamp) if timestamp is not None else (self.frame_index - 1) / self.fps
        if self._rules_shape != tuple(frame.shape[:2]):
            self._build_rules(frame.shape)
        dbg: dict[str, Any] = {}
        raw = frame
        proc = preprocess_frame(frame, c.preprocessing)  # type: ignore[arg-type]
        timings["preprocess"] = _ms(tick)

        # 1) vehicles
        tick = time.perf_counter()
        dets = self.models.vehicles(proc, track=video, conf=c.vehicle_conf, imgsz=c.vehicle_imgsz)
        if not video and c.rider_evidence != "heads" and hasattr(self.models, "rider_units"):
            dets = merge_detections(dets, self.models.rider_units(proc, conf=c.rider_det_conf),
                                    prefer_fallback_two_wheeler=True)
        if not video and c.photo_fallback and hasattr(self.models, "coco_vehicles"):
            dets = merge_detections(dets, self.models.coco_vehicles(proc))
        if not video:
            for i, d in enumerate(dets):
                d.track_id = i + 1
        else:
            dets = [d for d in dets if d.track_id >= 0]  # untracked boxes cannot carry temporal evidence
        for d in dets:
            self.history.update(d.track_id, d.bbox, t)
            self.track_meta[d.track_id] = d
        timings["vehicles"] = _ms(tick)

        # 2) signal
        tick = time.perf_counter()
        signal = self._signal_state(proc, t, dbg)
        timings["signal"] = _ms(tick)

        hits: list[tuple[RuleHit, Detection]] = []
        heads_by_track: dict[int, list[Any]] = {}
        extra: dict[int, str] = {}

        # 3) two-wheeler riders
        tick = time.perf_counter()
        bikes = [d for d in dets if d.category == "two_wheeler" and (d.bbox[3] - d.bbox[1]) >= c.min_two_wheeler_px]
        if bikes and (HELMET in c.enabled or TRIPLE in c.enabled):
            regions = [_union(rider_zone(d.bbox), d.bbox) for d in bikes]
            heads = nms_heads(self.models.heads(proc, regions, conf=c.helmet_conf, imgsz=c.helmet_imgsz))
            assigned = assign_heads([(d.track_id, d.bbox) for d in bikes], heads)
            use_heads = video or c.rider_evidence != "rider_model"
            for d in bikes:
                hs = assigned.get(d.track_id, [])
                heads_by_track[d.track_id] = hs
                no_helmet = [h for h in hs if not h.helmet and h.confidence >= c.no_helmet_conf]
                riders = len(hs)
                extra[d.track_id] = f"riders:{riders}" + (f" no-helmet:{len(no_helmet)}" if no_helmet else "")
                # rider-model verdict for this bike (photos only)
                rclass, rconf = d.attributes.get("rider_class"), float(d.attributes.get("rider_conf", 0.0))
                if video or c.rider_evidence == "heads":
                    rclass = None
                r_no_helmet = rclass == "WithoutHelmet" and rconf >= c.rider_no_helmet_conf
                r_triple = rclass == "TripleRiding" and rconf >= c.rider_triple_conf
                if rclass:
                    extra[d.track_id] += f" model:{rclass}"

                h_conf = max(h.confidence for h in no_helmet) if (no_helmet and use_heads) else None
                conf = max(filter(None, [h_conf, rconf if r_no_helmet else None]), default=None)
                if hs or rclass:
                    reasons = []
                    if h_conf is not None:
                        reasons.append(f"{len(no_helmet)} of {riders} rider(s) without helmet")
                    if r_no_helmet:
                        reasons.append(f"rider classifier: no helmet ({rconf:.2f})")
                    hit = self._appearance(d.track_id, HELMET, conf, video, "; ".join(reasons) or "no helmet",
                                           {"riders": riders, "no_helmet": len(no_helmet),
                                            "rider_class": rclass, "rider_conf": round(rconf, 3)})
                    if hit:
                        hits.append((hit, d))
                    h_tconf = float(np.mean([h.confidence for h in hs])) \
                        if (use_heads and riders >= c.triple_min_riders) else None
                    tconf = max(filter(None, [h_tconf, rconf if r_triple else None]), default=None)
                    reasons = []
                    if h_tconf is not None:
                        reasons.append(f"{riders} riders on one two-wheeler")
                    if r_triple:
                        reasons.append(f"rider classifier: triple riding ({rconf:.2f})")
                    hit = self._appearance(d.track_id, TRIPLE, tconf, video, "; ".join(reasons) or "triple riding",
                                           {"riders": riders, "rider_class": rclass, "rider_conf": round(rconf, 3)})
                    if hit:
                        hits.append((hit, d))
            if debug:
                dbg["heads"] = [{"bbox": list(h.bbox), "helmet": h.helmet, "conf": round(h.confidence, 3)} for h in heads]
                dbg["rider_regions"] = [list(r) for r in regions]
        timings["helmet"] = _ms(tick)

        # 4) seatbelt
        tick = time.perf_counter()
        cars = [d for d in dets if d.category == "car" and (d.bbox[2] - d.bbox[0]) >= c.min_car_width_px]
        if cars and SEATBELT in c.enabled:
            observations = self.models.seatbelt_check(proc, [d.bbox for d in cars], conf=0.25)
            for d, obs in zip(cars, observations):
                if not obs.observable:
                    continue
                conf = obs.no_seatbelt_conf if (obs.no_seatbelt_conf or 0) >= c.seatbelt_conf else None
                hit = self._appearance(d.track_id, SEATBELT, conf, video, "Occupant without seatbelt",
                                       {"detections": [(n, round(s, 3)) for n, s, _ in obs.boxes]})
                if hit:
                    hits.append((hit, d))
                if debug:
                    dbg.setdefault("seatbelt", []).append({"track_id": d.track_id, "observable": obs.observable,
                                                           "no_seatbelt_conf": obs.no_seatbelt_conf,
                                                           "boxes": [(n, round(s, 3), list(b)) for n, s, b in obs.boxes]})
        timings["seatbelt"] = _ms(tick)

        # 5) motion / geometry rules
        tick = time.perf_counter()
        movers = [d for d in dets if d.category != "bicycle"]
        if video:
            if WRONG_SIDE in c.enabled:
                for d in movers:
                    hit = self.wrong_side.update(d.track_id, d.bbox, self.history)
                    if hit:
                        hits.append((hit, d))
            if self.stop_rule is not None:
                for d in movers:
                    for hit in self.stop_rule.update(d.track_id, d.bbox, signal):
                        hits.append((hit, d))
            if PARKING in c.enabled and self.parking_zones:
                by_id = {d.track_id: d for d in movers}
                for hit in self.parking.update([(d.track_id, d.bbox) for d in movers], t):
                    if hit.track_id in by_id:
                        hits.append((hit, by_id[hit.track_id]))
                for d in movers:
                    dwell = self.parking.dwell(d.track_id, t)
                    if dwell >= 1.0:
                        extra[d.track_id] = (extra.get(d.track_id, "") + f" parked:{dwell:.0f}s").strip()
        elif self.stop_rule is not None:
            for d in movers:
                hit = self.stop_rule.evaluate_static(d.track_id, d.bbox, signal, frame.shape[0])
                if hit:
                    hits.append((hit, d))
        timings["rules"] = _ms(tick)

        # 6) annotate + incidents
        tick = time.perf_counter()
        new_events: list[dict[str, Any]] = []
        base = proc.copy()
        draw_scene(base, self.lanes, self.stop_line, self.parking_zones, signal, self._light_box)
        for hit, det in hits:
            self._record(hit, det, raw, t, base, new_events)
        for d in dets:
            if d.track_id in self.incidents:
                inc = self.incidents[d.track_id]
                inc.last_t = t
                inc.bbox = d.bbox
                self._update_crop(inc, raw, d)
        violations_by_track = {tid: list(inc.violations) for tid, inc in self.incidents.items()}
        plates = {}
        for tid in violations_by_track:
            text, conf, _, n = self._plate_for(tid)
            if n:
                plates[tid] = text if text != "MANUAL_REVIEW" else "plate?"
        annotated = draw_frame(base, dets, violations_by_track, heads_by_track, signal, extra, plates)
        timings["annotate"] = _ms(tick)

        # 7) plates (violators, or everyone)
        tick = time.perf_counter()
        for d in dets:
            if d.track_id in self.incidents or c.read_all_plates:
                self._read_plate(raw, d)
        timings["plates"] = _ms(tick)

        # 8) finalize incidents whose vehicle left
        finalized: list[Incident] = []
        if video:
            seen_ids = {d.track_id for d in dets}
            for tid, inc in list(self.incidents.items()):
                if tid not in seen_ids and t - inc.last_t > c.incident_ttl_s:
                    done = self._finalize(tid)
                    if done:
                        finalized.append(done)
            for tid in self.history.prune(t, max_age_s=max(3.0, c.incident_ttl_s + 1)):
                self.wrong_side.forget(tid)
                if self.stop_rule is not None:
                    self.stop_rule.forget(tid)
                self.votes.forget(tid)
                self.voters.pop(tid, None) if tid not in self.incidents else None
                self.plate_reads.pop(tid, None) if tid not in self.incidents else None

        counts: dict[str, int] = {}
        for d in dets:
            counts[d.category] = counts.get(d.category, 0) + 1
        if debug:
            dbg["detections"] = [{"track_id": d.track_id, "category": d.category, "label": d.label,
                                  "conf": round(d.confidence, 3), "bbox": list(d.bbox),
                                  **({"wrong_side": self.wrong_side.last_debug.get(d.track_id)} if video else {})}
                                 for d in dets]
            dbg["signal"] = signal
            dbg["preprocessed"] = proc is not raw
        return FrameOutput(
            frame_index=self.frame_index,
            timestamp=t,
            annotated=annotated,
            detections=dets,
            signal=signal,
            new_violations=new_events,
            active_incidents=[inc.summary() for inc in self.incidents.values()],
            finalized=finalized,
            timings_ms=timings,
            counts=counts,
            debug=dbg,
        )

    # ------------------------------------------------------------------
    def _appearance(self, tid: int, violation: str, positive_conf: float | None, video: bool,
                    reason: str, metadata: dict[str, Any]) -> RuleHit | None:
        if violation not in self.config.enabled:
            return None
        if not video:
            if positive_conf is None:
                return None
            return RuleHit(tid, violation, float(positive_conf), reason, metadata)
        hit = self.votes.add(tid, violation, positive_conf)
        if hit is not None:
            hit.reason = f"{reason} ({hit.reason.lower()})"
            hit.metadata.update(metadata)
        return hit


def merge_detections(primary: list[Detection], fallback: list[Detection], iou_thr: float = 0.45,
                     prefer_fallback_two_wheeler: bool = False) -> list[Detection]:
    """
    Merge CCTV-model detections with photo-mode fallback detections (COCO or rider model).
    * fallback boxes that match nothing are added (close-up / ground-level vehicles);
    * a confident fallback two-wheeler overlapping a primary non-two-wheeler box re-labels it
      (the CCTV model sometimes calls a close-up motorbike a truck);
    * a fallback two-wheeler matching a primary two-wheeler passes on its attributes; with
      ``prefer_fallback_two_wheeler`` it also replaces the box (the rider model's box always
      includes the riders, which the head search depends on);
    * everything else keeps the primary detection.
    """
    from core.geometry import bbox_iou, containment

    merged = list(primary)
    for f in fallback:
        best, best_iou = None, 0.0
        for p in merged:
            iou = bbox_iou(f.bbox, p.bbox)
            if iou > best_iou:
                best, best_iou = p, iou
        two = f.category == "two_wheeler"
        if best is not None and best.category == "two_wheeler" and two and best_iou >= 0.3:
            if f.attributes and not best.attributes:
                best.attributes = dict(f.attributes)
                if prefer_fallback_two_wheeler:
                    best.bbox = f.bbox
            continue
        if best is not None and best_iou >= iou_thr:
            if two and best.category != "two_wheeler" and f.confidence >= 0.5:
                best.category, best.label, best.bbox = f.category, "Two-wheeler", f.bbox
                best.attributes = dict(f.attributes)
            continue
        if any(containment(f.bbox, p.bbox) > 0.7 or containment(p.bbox, f.bbox) > 0.7 for p in merged):
            continue
        merged.append(Detection(-1, f.category, f.label, f.confidence, f.bbox, dict(f.attributes)))
    return merged


def _ms(start: float) -> float:
    return round((time.perf_counter() - start) * 1000.0, 1)


def _union(a: BBox, b: BBox) -> BBox:
    return min(a[0], b[0]), min(a[1], b[1]), max(a[2], b[2]), max(a[3], b[3])


def _shrink(img: np.ndarray, max_w: int) -> np.ndarray:
    if img.shape[1] <= max_w:
        return img
    s = max_w / img.shape[1]
    return cv2.resize(img, (max_w, int(img.shape[0] * s)), interpolation=cv2.INTER_AREA)