""" Run the engine on images or a video from the command line. python tools/run_engine.py path/to/img_or_dir_or_video --out tmp/out [--scene configs/scenes/x.json] """ from __future__ import annotations import argparse import json import sys import time from pathlib import Path import cv2 ROOT = Path(__file__).resolve().parent.parent sys.path.insert(0, str(ROOT)) from core.detection_engine import EngineConfig, TrafficEnforcementEngine # noqa: E402 from core.scene import SceneConfig # noqa: E402 IMAGE_EXT = {".jpg", ".jpeg", ".png", ".bmp", ".webp"} def main() -> None: ap = argparse.ArgumentParser() ap.add_argument("source") ap.add_argument("--out", default=str(ROOT / "tmp" / "engine_out")) ap.add_argument("--scene", default=None) ap.add_argument("--limit", type=int, default=0) ap.add_argument("--all-plates", action="store_true") args = ap.parse_args() scene = SceneConfig.from_json(Path(args.scene).read_text()) if args.scene else SceneConfig() engine = TrafficEnforcementEngine(EngineConfig(read_all_plates=args.all_plates)) out = Path(args.out) out.mkdir(parents=True, exist_ok=True) src = Path(args.source) if src.is_dir() or src.suffix.lower() in IMAGE_EXT: files = sorted(p for p in (src.iterdir() if src.is_dir() else [src]) if p.suffix.lower() in IMAGE_EXT) if args.limit: files = files[: args.limit] for f in files: img = cv2.imread(str(f)) t0 = time.time() res, incidents = engine.process_image(img, scene) cv2.imwrite(str(out / (f.stem + ".jpg")), res.annotated) print(f.name, f"{(time.time() - t0) * 1000:.0f}ms", res.counts, json.dumps([i.summary() for i in incidents])) return cap = cv2.VideoCapture(str(src)) fps = cap.get(cv2.CAP_PROP_FPS) or 25 ok, frame = cap.read() engine.reset(scene, fps=fps, frame_shape=frame.shape) writer = cv2.VideoWriter(str(out / (src.stem + "_annotated.mp4")), cv2.VideoWriter_fourcc(*"mp4v"), fps, (frame.shape[1], frame.shape[0])) n = 0 while ok: res = engine.process_frame(frame, timestamp=n / fps) writer.write(res.annotated) for e in res.new_violations: print(f"t={e['time_s']}s", e["type"], "track", e["track_id"], e["reason"]) n += 1 if args.limit and n >= args.limit: break ok, frame = cap.read() writer.release() for inc in engine.finalize_all(): print(json.dumps(inc.summary())) if __name__ == "__main__": main()