Spaces:
Sleeping
Sleeping
Download app.py from Abhyuday-06/VisionGuard-AI: direct link, hf CLI and curl.
- Browser
- Download file 38.1 kB
-
https://huggingface.co/spaces/Abhyuday-06/VisionGuard-AI/resolve/main/app.py
- Command line
-
hf download hf://spaces/Abhyuday-06/VisionGuard-AI/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Abhyuday-06/VisionGuard-AI/resolve/main/app.py
38.1 kB
| """VisionGuard AI: traffic violation detection for Bengaluru traffic cameras (Streamlit UI).""" | |
| from __future__ import annotations | |
| import json | |
| import sqlite3 | |
| import tempfile | |
| import time | |
| from pathlib import Path | |
| from typing import Any | |
| import cv2 | |
| import numpy as np | |
| import pandas as pd | |
| import plotly.express as px | |
| import streamlit as st | |
| from core.rules import ALL_VIOLATIONS, HELMET, PARKING, RED_LIGHT, SEATBELT, STOP_LINE, TRIPLE, WRONG_SIDE | |
| from core.scene import SceneConfig | |
| from ui import style as S | |
| from utils.evidence_generator import ( | |
| DEFAULT_DB_PATH, | |
| PENALTY_TABLE, | |
| initialize_database, | |
| save_incident, | |
| set_status, | |
| update_plate, | |
| ) | |
| PROJECT_ROOT = Path(__file__).resolve().parent | |
| SAMPLES_DIR = PROJECT_ROOT / "samples" | |
| REPORT_PATH = PROJECT_ROOT / "reports" / "evaluation.json" | |
| IMAGE_TYPES = ["jpg", "jpeg", "png", "bmp", "webp"] | |
| VIDEO_TYPES = ["mp4", "avi", "mov", "mkv"] | |
| MOTION_VIOLATIONS = (WRONG_SIDE, STOP_LINE, RED_LIGHT, PARKING) | |
| PAGES = ["Analyze", "Records", "Analytics", "Model performance", "How it works"] | |
| VIEW_W = 1280 # result images are stored at this width so every rerun sends the same pixels | |
| CHART = dict(margin=dict(l=0, r=10, t=36, b=0), font=dict(size=12), title_font=dict(size=14)) | |
| # Settings widgets live in a popover that is not drawn on every page. Streamlit drops the state of | |
| # widgets that are not rendered, so their values are copied back at the start of every run. | |
| DEFAULTS: dict[str, Any] = { | |
| "set_enabled": list(ALL_VIOLATIONS), "set_read_all": False, "set_autosave": True, "set_vehicle_conf": 0.30, | |
| "set_no_helmet_conf": 0.50, "set_seatbelt_conf": 0.50, "set_ocr_conf": 0.45, "set_imgsz": 960, | |
| "set_pre": "auto", "set_stride": 2, "set_max_s": 0, "set_device": "auto", | |
| } | |
| def init_state() -> None: | |
| for k, v in DEFAULTS.items(): | |
| st.session_state[k] = st.session_state.get(k, v) | |
| def settings() -> dict[str, Any]: | |
| s = st.session_state | |
| dev = s.set_device | |
| return {"enabled": list(s.set_enabled), "read_all_plates": s.set_read_all, "autosave": s.set_autosave, | |
| "vehicle_conf": s.set_vehicle_conf, "no_helmet_conf": s.set_no_helmet_conf, | |
| "seatbelt_conf": s.set_seatbelt_conf, "ocr_conf": s.set_ocr_conf, "vehicle_imgsz": s.set_imgsz, | |
| "preprocessing": s.set_pre, "stride": s.set_stride, "max_seconds": float(s.set_max_s), | |
| "device": None if dev == "auto" else (0 if dev == "cuda" else "cpu")} | |
| # --------------------------------------------------------------------------- | |
| # Engine | |
| # --------------------------------------------------------------------------- | |
| def load_engine(device: str | None): | |
| from core.detection_engine import EngineConfig, TrafficEnforcementEngine | |
| return TrafficEnforcementEngine(EngineConfig(device=device)) | |
| def get_engine(cfg: dict[str, Any]): | |
| engine = load_engine(cfg["device"]) | |
| c = engine.config | |
| c.vehicle_conf, c.no_helmet_conf, c.seatbelt_conf = cfg["vehicle_conf"], cfg["no_helmet_conf"], cfg["seatbelt_conf"] | |
| c.ocr_conf, c.read_all_plates, c.enabled = cfg["ocr_conf"], cfg["read_all_plates"], tuple(cfg["enabled"]) | |
| c.preprocessing, c.vehicle_imgsz = cfg["preprocessing"], cfg["vehicle_imgsz"] | |
| return engine | |
| def rgb(img: np.ndarray) -> np.ndarray: | |
| return cv2.cvtColor(img, cv2.COLOR_BGR2RGB) if img is not None and img.ndim == 3 else img | |
| def fit(img: np.ndarray, width: int = VIEW_W) -> np.ndarray: | |
| h, w = img.shape[:2] | |
| return img if w <= width else cv2.resize(img, (width, int(h * width / w)), interpolation=cv2.INTER_AREA) | |
| def header(title: str, lead: str = "") -> None: | |
| st.markdown(f'<p class="vg-page">{S.esc(title)}</p>' + (f'<p class="vg-lead">{S.esc(lead)}</p>' if lead else ""), | |
| unsafe_allow_html=True) | |
| # --------------------------------------------------------------------------- | |
| # Sidebar | |
| # --------------------------------------------------------------------------- | |
| def sidebar() -> str: | |
| with st.sidebar: | |
| st.markdown('<p class="vg-brand">VisionGuard AI</p>' | |
| '<p class="vg-sub">Traffic violation detection for Bengaluru traffic cameras</p>', | |
| unsafe_allow_html=True) | |
| page = st.radio("Page", PAGES, label_visibility="collapsed", key="nav") | |
| st.divider() | |
| try: | |
| df = load_records() | |
| pending = int((df["status"].fillna("pending") == "pending").sum()) if not df.empty else 0 | |
| st.caption(f"{len(df)} records · {pending} awaiting review") | |
| except Exception: | |
| pass | |
| return page | |
| def settings_popover() -> None: | |
| with st.popover("Settings", width="stretch"): | |
| st.markdown("**Violations to check**") | |
| st.pills("Violations", list(ALL_VIOLATIONS), selection_mode="multi", key="set_enabled", | |
| label_visibility="collapsed") | |
| st.toggle("Read every number plate", key="set_read_all", | |
| help="Off: plates are read only for violating vehicles, which is faster.") | |
| st.toggle("Save violations to Records", key="set_autosave") | |
| st.markdown("**Thresholds**") | |
| st.slider("Vehicle detection confidence", 0.1, 0.9, step=0.05, key="set_vehicle_conf") | |
| st.slider("No-helmet confidence", 0.2, 0.95, step=0.05, key="set_no_helmet_conf", | |
| help="Higher means fewer false alarms and more missed violations.") | |
| st.slider("No-seatbelt confidence", 0.2, 0.95, step=0.05, key="set_seatbelt_conf") | |
| st.slider("Plate reading acceptance", 0.2, 0.95, step=0.05, key="set_ocr_conf", | |
| help="Plates read with lower confidence go to manual review.") | |
| st.markdown("**Processing**") | |
| st.select_slider("Detector resolution", [640, 800, 960, 1280], key="set_imgsz", | |
| help="Higher finds smaller, farther vehicles but is slower.") | |
| st.selectbox("Image enhancement", ["auto", "none", "clahe", "denoise"], key="set_pre", | |
| help="auto boosts contrast only for night or hazy frames.") | |
| st.slider("Video: analyse every Nth frame", 1, 6, key="set_stride", | |
| help="Motion rules use timestamps, so skipping frames keeps them correct.") | |
| st.number_input("Video: max seconds (0 = whole video)", 0, 3600, step=10, key="set_max_s") | |
| st.selectbox("Device", ["auto", "cpu", "cuda"], key="set_device") | |
| # --------------------------------------------------------------------------- | |
| # Violation cards | |
| # --------------------------------------------------------------------------- | |
| def card_html(inc: Any, saved_id: int | None = None) -> str: | |
| from core.models import CATEGORY_DISPLAY | |
| names = list(inc.violations) | |
| color = S.COLORS.get(names[0], "#4b5563") if names else "#4b5563" | |
| img = S.thumb(inc.vehicle_crop) | |
| rows = "".join( | |
| f"<li><b>{S.esc(v.violation)}</b> {v.confidence * 100:.0f}%" | |
| f"{f' · {v.timestamp:.1f}s' if v.timestamp else ''}: {S.esc(v.reason)}</li>" | |
| for v in inc.violations.values()) | |
| fine = sum(PENALTY_TABLE.get(v, 500) for v in names) | |
| foot = f"Vehicle #{inc.track_id} · fine ₹{fine:,}" + (f" · record #{saved_id:06d}" if saved_id else "") | |
| return (f'<div class="vg-card" style="--c:{color}">' + (f'<img src="{img}" alt="vehicle">' if img else "") | |
| + '<div class="body"><div class="top">' | |
| f'<span class="veh">{S.esc(CATEGORY_DISPLAY.get(inc.category, inc.category))}</span>' | |
| f'{S.plate(inc.plate_text)}</div>{S.tags(names)}<ul>{rows}</ul>' | |
| f'<div class="foot">{foot}</div></div></div>') | |
| def card_list(incidents: list[Any], saved: dict[int, int], height: int) -> None: | |
| """Fixed-height, scrolling list: the page height does not depend on the number of violations.""" | |
| with st.container(height=height, border=False): | |
| if not incidents: | |
| st.markdown(S.empty("No violations found."), unsafe_allow_html=True) | |
| else: | |
| st.markdown("".join(card_html(i, saved.get(i.track_id)) for i in incidents), unsafe_allow_html=True) | |
| def save_all(incidents: list[Any], source: str, camera: str) -> dict[int, int]: | |
| ids = {} | |
| for inc in incidents: | |
| try: | |
| ids[inc.track_id] = save_incident(inc, source=source, camera=camera)["id"] | |
| except Exception as exc: | |
| st.warning(f"Could not save vehicle #{inc.track_id}: {exc}") | |
| return ids | |
| def count_types(incidents: list[Any]) -> dict[str, int]: | |
| out: dict[str, int] = {} | |
| for inc in incidents: | |
| for v in inc.violations: | |
| out[v] = out.get(v, 0) + 1 | |
| return out | |
| # --------------------------------------------------------------------------- | |
| # Analyze | |
| # --------------------------------------------------------------------------- | |
| def list_samples() -> list[Path]: | |
| if not SAMPLES_DIR.exists(): | |
| return [] | |
| return sorted(p for p in SAMPLES_DIR.iterdir() if p.suffix.lower().lstrip(".") in IMAGE_TYPES + VIDEO_TYPES) | |
| def scene_status(scene: SceneConfig, enabled: list[str]) -> str: | |
| missing = [] | |
| if WRONG_SIDE in enabled and not scene.lanes: | |
| missing.append("lanes") | |
| if (STOP_LINE in enabled or RED_LIGHT in enabled) and not scene.stop_line: | |
| missing.append("stop line") | |
| if PARKING in enabled and not scene.no_parking_zones: | |
| missing.append("no-parking zone") | |
| if not missing: | |
| return "Camera setup complete." | |
| return "Not drawn yet: " + ", ".join(missing) + ". Those checks are skipped until you draw them." | |
| def page_analyze() -> None: | |
| cfg = settings() | |
| header("Analyze", "Upload traffic camera photos or a video clip, then run the analysis.") | |
| with st.container(border=True, key="input_panel"): | |
| left, right = st.columns([3, 1], vertical_alignment="bottom") | |
| with left: | |
| src = st.segmented_control("Source", ["Upload", "Samples"], default="Upload", key="src", | |
| label_visibility="collapsed") or "Upload" | |
| if src == "Upload": | |
| ups = st.file_uploader("Photos or one video", type=IMAGE_TYPES + VIDEO_TYPES, | |
| accept_multiple_files=True, label_visibility="collapsed") | |
| files = [(u.name, u.getvalue()) for u in ups or []] | |
| else: | |
| samples = list_samples() | |
| pick = st.multiselect("Sample files", [p.name for p in samples], | |
| default=[p.name for p in samples[:1]], label_visibility="collapsed", | |
| placeholder="Choose sample files") | |
| files = [(p.name, p.read_bytes()) for p in samples if p.name in pick] | |
| with right: | |
| settings_popover() | |
| run = st.button("Run analysis", type="primary", width="stretch", disabled=not files) | |
| status_slot = st.empty() # progress while analysing; always present so the layout below never shifts | |
| if not files: | |
| st.markdown(S.empty("Photos: No Helmet, Triple Riding and No Seatbelt. Video: also Wrong-side, Stop line, " | |
| "Red-light Jump and Illegal Parking, after you draw the camera setup."), | |
| unsafe_allow_html=True) | |
| return | |
| videos = [f for f in files if Path(f[0]).suffix.lower().lstrip(".") in VIDEO_TYPES] | |
| images = [f for f in files if f not in videos] | |
| is_video = bool(videos) | |
| key = f"{files[0][0]}:{len(files[0][1])}:{len(files)}" | |
| if is_video: | |
| tmp = Path(tempfile.gettempdir()) / f"vg_{abs(hash(key))}{Path(videos[0][0]).suffix}" | |
| if not tmp.exists(): | |
| tmp.write_bytes(videos[0][1]) | |
| from utils.video_io import read_first_frame | |
| ref, fps, n_frames = read_first_frame(tmp) | |
| if ref is None: | |
| st.error("Could not read this video.") | |
| return | |
| if len(files) > 1: | |
| st.caption("Several files selected: only the first video is analysed.") | |
| else: | |
| ref = cv2.imdecode(np.frombuffer(images[0][1], np.uint8), cv2.IMREAD_COLOR) | |
| if ref is None: | |
| st.error(f"Could not read {images[0][0]}.") | |
| return | |
| scene = st.session_state.get("scene", SceneConfig()) | |
| motion = [v for v in cfg["enabled"] if v in MOTION_VIOLATIONS] | |
| if motion: | |
| with st.container(border=True, key="scene_panel"): | |
| c1, c2 = st.columns([3, 1], vertical_alignment="center") | |
| c1.markdown(f"**Camera setup** <span class='vg-muted'>· {S.esc(scene_status(scene, motion))}</span>", | |
| unsafe_allow_html=True) | |
| editing = c2.toggle("Edit camera setup", key="edit_scene") | |
| if editing: | |
| from ui.scene_editor import scene_editor | |
| scene = scene_editor(ref) | |
| if run: | |
| engine = get_engine(cfg) | |
| with status_slot.container(): | |
| if is_video: | |
| res = run_video(engine, tmp, scene, cfg, videos[0][0], fps) | |
| else: | |
| res = run_images(engine, images, scene, cfg) | |
| st.session_state.result, st.session_state.result_key = res, key | |
| st.rerun() # draw results on a clean run, identical to every later rerun (no layout jumps) | |
| res = st.session_state.get("result") | |
| if res and st.session_state.get("result_key") == key: | |
| (show_video_result if res["kind"] == "video" else show_image_results)(res) | |
| else: | |
| info = f"{n_frames} frames at {fps:.0f} fps" if is_video else f"{len(images)} photo(s)" | |
| st.caption(f"Preview · {files[0][0]} · {info}") | |
| st.image(rgb(fit(ref, 1000)), width=1000) | |
| def run_images(engine: Any, images: list[tuple[str, bytes]], scene: SceneConfig, cfg: dict[str, Any]) -> dict: | |
| items = [] | |
| bar = st.progress(0.0, text="Analysing…") | |
| for i, (name, data) in enumerate(images): | |
| frame = cv2.imdecode(np.frombuffer(data, np.uint8), cv2.IMREAD_COLOR) | |
| if frame is None: | |
| continue | |
| out, incidents = engine.process_image(frame, scene, debug=True) | |
| saved = save_all(incidents, name, scene.name) if cfg["autosave"] and incidents else {} | |
| items.append({"name": name, "view": fit(out.annotated), "original": fit(frame), "debug": out.debug, | |
| "timings": out.timings_ms, "signal": out.signal, "counts": out.counts, | |
| "incidents": incidents, "saved": saved}) | |
| bar.progress((i + 1) / len(images), text=f"Analysed {i + 1} of {len(images)}") | |
| return {"kind": "images", "items": items} | |
| def show_image_results(res: dict) -> None: | |
| items = res["items"] | |
| if not items: | |
| st.warning("None of the files could be read.") | |
| return | |
| all_inc = [i for it in items for i in it["incidents"]] | |
| types = count_types(all_inc) | |
| st.markdown(S.kpis([("Photos", len(items)), ("Vehicles", sum(sum(it["counts"].values()) for it in items)), | |
| ("Violating vehicles", len(all_inc)), ("Violations", sum(types.values())), | |
| ("Plates read", sum(1 for i in all_inc if i.plate_text not in S.UNREAD))]), | |
| unsafe_allow_html=True) | |
| idx = 0 | |
| if len(items) > 1: | |
| idx = st.selectbox("Photo", range(len(items)), key="photo_idx", | |
| format_func=lambda i: f"{items[i]['name']} · {len(items[i]['incidents'])} violating") | |
| it = items[min(idx, len(items) - 1)] | |
| c1, c2 = st.columns([1.9, 1], gap="medium") | |
| with c1: | |
| st.image(rgb(it["view"]), width="stretch") | |
| st.caption("Coloured boxes: violating vehicles. Head boxes: green with helmet, red without.") | |
| with c2: | |
| st.markdown(f"**Violations in this photo** {S.tags(count_types(it['incidents']))}", unsafe_allow_html=True) | |
| card_list(it["incidents"], it["saved"], height=520) | |
| with st.expander("Debug: detections, rider heads, timings"): | |
| debug_panel(it) | |
| def debug_panel(it: dict) -> None: | |
| d = it["debug"] | |
| c1, c2 = st.columns([1.4, 1], gap="medium") | |
| with c1: | |
| st.markdown("**Detected vehicles**") | |
| if d.get("detections"): | |
| st.dataframe(pd.DataFrame(d["detections"]), width="stretch", hide_index=True, height=240) | |
| else: | |
| st.caption("No vehicles detected. Lower the vehicle confidence or raise the detector resolution in Settings.") | |
| if d.get("heads"): | |
| st.markdown("**Rider heads (helmet model)**") | |
| st.dataframe(pd.DataFrame(d["heads"]), width="stretch", hide_index=True, height=180) | |
| if d.get("seatbelt"): | |
| st.markdown("**Seatbelt model on cars**") | |
| st.dataframe(pd.DataFrame(d["seatbelt"]), width="stretch", hide_index=True, height=180) | |
| with c2: | |
| t = it["timings"] | |
| fig = px.bar(x=list(t.values()), y=list(t.keys()), orientation="h", labels={"x": "ms", "y": ""}, | |
| title="Time per stage (ms)", color_discrete_sequence=["#ff4b4b"]) | |
| fig.update_layout(height=260, **CHART) | |
| st.plotly_chart(fig, width="stretch", key="dbg_timing") | |
| st.caption(f"Signal: {it['signal']} · enhancement applied: {d.get('preprocessed')}") | |
| st.image(rgb(it["original"]), caption="Original input", width="stretch") | |
| def run_video(engine: Any, path: Path, scene: SceneConfig, cfg: dict[str, Any], name: str, fps: float) -> dict: | |
| from utils.video_io import VideoWriter | |
| cap = cv2.VideoCapture(str(path)) | |
| n_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT) or 0) | |
| ok, frame = cap.read() | |
| if not ok: | |
| st.error("Could not read video frames.") | |
| return {"kind": "video", "video": "", "h264": False, "incidents": [], "events": [], "saved": {}, | |
| "signal": [], "duration": 0.0} | |
| stride = cfg["stride"] | |
| limit = int(cfg["max_seconds"] * fps) if cfg["max_seconds"] else n_frames | |
| engine.reset(scene, fps=fps, frame_shape=frame.shape) | |
| out_path = Path(tempfile.gettempdir()) / f"vg_annotated_{int(time.time())}.mp4" | |
| writer = VideoWriter(out_path, fps / stride, (frame.shape[1], frame.shape[0])) | |
| incidents, events, signal_trace, saved = [], [], [], {} | |
| bar = st.progress(0.0, text="Analysing video…") | |
| c1, c2 = st.columns([1.9, 1], gap="medium") | |
| live = c1.empty() | |
| with c2: | |
| st.markdown("**Live violations**") | |
| feed = st.container(height=420, border=True).empty() | |
| preview_w = 960 | |
| last_ui, i, t0 = 0.0, 0, time.time() | |
| while ok and i < limit: | |
| if i % stride == 0: | |
| out = engine.process_frame(frame, timestamp=i / fps) | |
| writer.write(out.annotated) | |
| signal_trace.append((i / fps, out.signal)) | |
| events += out.new_violations | |
| for inc in out.finalized: | |
| incidents.append(inc) | |
| if cfg["autosave"]: | |
| saved.update(save_all([inc], name, scene.name)) | |
| now = time.time() | |
| if now - last_ui > 1.0: # throttled; the preview always has the same size, so nothing reflows | |
| last_ui = now | |
| live.image(rgb(fit(out.annotated, preview_w)), width=preview_w) | |
| feed.markdown("".join( | |
| f"<div class='vg-event'><span class='t'>{e['time_s']:.1f}s</span>{S.tag(e['type'])}" | |
| f"<span>#{e['track_id']} {S.esc(e.get('vehicle') or '')}</span></div>" | |
| for e in reversed(events[-30:])) or "<span class='vg-muted'>None yet</span>", | |
| unsafe_allow_html=True) | |
| bar.progress(min(1.0, i / max(limit, 1)), | |
| text=f"{i / fps:.0f}s of {min(limit, n_frames) / fps:.0f}s · " | |
| f"{(i + 1) / max(now - t0, 1e-6):.1f} frames/s") | |
| i += 1 | |
| ok, frame = cap.read() | |
| cap.release() | |
| for inc in engine.finalize_all(): | |
| incidents.append(inc) | |
| if cfg["autosave"]: | |
| saved.update(save_all([inc], name, scene.name)) | |
| writer.close() | |
| return {"kind": "video", "video": str(out_path), "h264": writer.h264, "incidents": incidents, "events": events, | |
| "saved": saved, "signal": signal_trace, "duration": i / fps, "processing_s": time.time() - t0} | |
| def show_video_result(res: dict) -> None: | |
| incidents = res["incidents"] | |
| types = count_types(incidents) | |
| st.markdown(S.kpis([("Video analysed", f"{res['duration']:.0f} s"), ("Violating vehicles", len(incidents)), | |
| ("Violations", sum(types.values())), | |
| ("Plates read", sum(1 for i in incidents if i.plate_text not in S.UNREAD)), | |
| ("Processing time", f"{res.get('processing_s', 0):.0f} s")]), unsafe_allow_html=True) | |
| c1, c2 = st.columns([1.9, 1], gap="medium") | |
| with c1: | |
| data = Path(res["video"]).read_bytes() if res["video"] and Path(res["video"]).exists() else None | |
| if data and res["h264"]: | |
| st.video(data) | |
| elif data: | |
| st.info("The browser cannot play this encoding. Download the annotated video instead.") | |
| if data: | |
| st.download_button("Download annotated video", data, "annotated.mp4", "video/mp4") | |
| if res["events"]: | |
| df = pd.DataFrame(res["events"]) | |
| fig = px.scatter(df, x="time_s", y="type", color="type", hover_data=["track_id", "vehicle", "reason"], | |
| color_discrete_map=S.COLORS, labels={"time_s": "video time (s)", "type": ""}, | |
| title="When each violation happened") | |
| fig.update_traces(marker=dict(size=11)) | |
| fig.update_layout(height=260, showlegend=False, **CHART) | |
| st.plotly_chart(fig, width="stretch", key="vid_timeline") | |
| with c2: | |
| shown = incidents | |
| if types: | |
| pick = st.pills("Filter", list(types), selection_mode="multi", key="vid_filter", | |
| label_visibility="collapsed") | |
| if pick: | |
| shown = [i for i in incidents if set(i.violations) & set(pick)] | |
| card_list(shown, res["saved"], height=520) | |
| with_snap = [i for i in incidents if any(v.snapshot is not None for v in i.violations.values())] | |
| if with_snap: | |
| with st.expander("Scene at the moment of each violation"): | |
| sel = st.selectbox("Vehicle", range(len(with_snap)), key="snap_idx", | |
| format_func=lambda k: f"#{with_snap[k].track_id} · " + ", ".join(with_snap[k].violations)) | |
| inc = with_snap[min(sel, len(with_snap) - 1)] | |
| snap = next(v.snapshot for v in inc.violations.values() if v.snapshot is not None) | |
| st.image(rgb(fit(snap)), width="stretch") | |
| # --------------------------------------------------------------------------- | |
| # Records | |
| # --------------------------------------------------------------------------- | |
| def load_records() -> pd.DataFrame: | |
| db = initialize_database(DEFAULT_DB_PATH) | |
| with sqlite3.connect(db) as con: | |
| df = pd.read_sql_query("SELECT * FROM challans ORDER BY id DESC", con) | |
| if not df.empty: | |
| df["timestamp"] = pd.to_datetime(df["timestamp"], errors="coerce") | |
| df["status"] = df["status"].fillna("pending") | |
| return df | |
| def page_records() -> None: | |
| header("Records", "Every saved violation. Select a row to review the evidence, correct the plate, and confirm or reject it.") | |
| df = load_records() | |
| if df.empty: | |
| st.markdown(S.empty("No records yet. Run an analysis with “Save violations to Records” on."), unsafe_allow_html=True) | |
| return | |
| f = st.columns([2, 2, 1.2, 1.2], vertical_alignment="bottom") | |
| q = f[0].text_input("Search", placeholder="Plate, violation or file name") | |
| types = f[1].multiselect("Violation", list(ALL_VIOLATIONS), placeholder="All violations") | |
| status = f[2].selectbox("Status", ["all", "pending", "confirmed", "rejected"]) | |
| days = f[3].selectbox("Period", ["all", "today", "7 days", "30 days"]) | |
| view = df | |
| if q: | |
| ql = q.lower().replace(" ", "") | |
| view = view[view.apply(lambda r: ql in f"{r['license_plate']}{r['violation_type']}{r['source']}".lower().replace(" ", ""), axis=1)] | |
| if types: | |
| view = view[view["violation_type"].apply(lambda s: any(t in str(s) for t in types))] | |
| if status != "all": | |
| view = view[view["status"] == status] | |
| if days != "all": | |
| view = view[view["timestamp"] >= pd.Timestamp.now() - pd.Timedelta(days={"today": 1, "7 days": 7, "30 days": 30}[days])] | |
| view = view.reset_index(drop=True) | |
| shown = view.assign(license_plate=view["license_plate"].where(~view["license_plate"].isin(S.UNREAD), "not read")) | |
| c1, c2 = st.columns([1.5, 1], gap="medium") | |
| with c1: | |
| cols = ["id", "timestamp", "license_plate", "violation_type", "vehicle_type", "fine_inr", "status", "source"] | |
| event = st.dataframe( | |
| shown[[c for c in cols if c in shown.columns]], width="stretch", hide_index=True, height=480, | |
| on_select="rerun", selection_mode="single-row", key="records_table", | |
| column_config={"id": st.column_config.NumberColumn("Record", format="%06d"), | |
| "timestamp": st.column_config.DatetimeColumn("Time", format="D MMM, HH:mm"), | |
| "license_plate": "Plate", "violation_type": "Violation", "vehicle_type": "Vehicle", | |
| "fine_inr": st.column_config.NumberColumn("Fine (₹)", format="%d"), | |
| "status": "Status", "source": "Source"}) | |
| b = st.columns([1, 3]) | |
| b[0].download_button("Export CSV", view.to_csv(index=False).encode(), "violations.csv", "text/csv") | |
| b[1].caption(f"{len(view)} of {len(df)} records") | |
| with c2: | |
| rows = event.selection.rows if event and event.selection else [] | |
| if not rows or view.empty: | |
| st.markdown(S.empty("Select a record to see its evidence."), unsafe_allow_html=True) | |
| return | |
| record_detail(view.iloc[rows[0]]) | |
| def record_detail(r: pd.Series) -> None: | |
| rid = int(r["id"]) | |
| with st.container(border=True): | |
| st.markdown(f"**Record #{rid:06d}** · {S.plate(r['license_plate'])}", unsafe_allow_html=True) | |
| try: | |
| details = json.loads(r.get("details") or "[]") | |
| except Exception: | |
| details = [] | |
| st.markdown(S.tags([d["type"] for d in details] or str(r["violation_type"]).split(" | ")), unsafe_allow_html=True) | |
| for d in details: | |
| st.markdown(f"<span class='vg-muted'><b>{S.esc(d['type'])}</b> {float(d.get('confidence', 0)) * 100:.0f}%: " | |
| f"{S.esc(d.get('reason', ''))}</span>", unsafe_allow_html=True) | |
| for col, cap in (("snapshot_path", "Scene"), ("crop_path", "Vehicle")): | |
| p = r.get(col) | |
| if isinstance(p, str) and p and Path(p).exists(): | |
| st.image(p, caption=cap, width="stretch") | |
| break | |
| p = r.get("plate_crop_path") | |
| if isinstance(p, str) and p and Path(p).exists(): | |
| st.image(p, caption="Plate", width=240) | |
| st.caption(f"Fine ₹{int(r.get('fine_inr') or 0):,} · status: {r['status']}") | |
| plate = st.text_input("Plate", value="" if r["license_plate"] in S.UNREAD else r["license_plate"], | |
| key=f"plate_{rid}", placeholder="Type the plate if it was not read") | |
| b = st.columns(3) | |
| if b[0].button("Confirm", key=f"ok_{rid}", type="primary", width="stretch"): | |
| if plate and plate != r["license_plate"]: | |
| update_plate(rid, plate) | |
| set_status(rid, "confirmed") | |
| st.rerun() | |
| if b[1].button("Reject", key=f"no_{rid}", width="stretch"): | |
| set_status(rid, "rejected") | |
| st.rerun() | |
| pdf = r.get("pdf_path") | |
| if isinstance(pdf, str) and pdf and Path(pdf).exists(): | |
| b[2].download_button("Challan PDF", Path(pdf).read_bytes(), Path(pdf).name, "application/pdf", | |
| key=f"pdf_{rid}", width="stretch") | |
| # --------------------------------------------------------------------------- | |
| # Analytics | |
| # --------------------------------------------------------------------------- | |
| def page_analytics() -> None: | |
| header("Analytics", "Summary of saved violations.") | |
| df = load_records() | |
| if df.empty: | |
| st.markdown(S.empty("No records yet."), unsafe_allow_html=True) | |
| return | |
| rows = [{"type": t, "timestamp": r["timestamp"], "plate": r["license_plate"], | |
| "vehicle": str(r.get("vehicle_type") or "").split(":")[0] or "unknown", "status": r["status"], | |
| "fine": PENALTY_TABLE.get(t, 500)} | |
| for _, r in df.iterrows() for t in str(r["violation_type"]).split(" | ")] | |
| v = pd.DataFrame(rows) | |
| cmap = {k: S.color_for(k) for k in v["type"].unique()} | |
| st.markdown(S.kpis([("Records", len(df)), ("Violations", len(v)), | |
| ("Plates identified", int((~df["license_plate"].isin(S.UNREAD)).sum())), | |
| ("Awaiting review", int((df["status"] == "pending").sum())), | |
| ("Fines (default)", f"₹{int(v['fine'].sum()):,}")]), unsafe_allow_html=True) | |
| c1, c2 = st.columns(2, gap="medium") | |
| with c1, st.container(border=True): | |
| counts = v["type"].value_counts().reset_index() | |
| fig = px.bar(counts, x="count", y="type", orientation="h", color="type", color_discrete_map=cmap, | |
| labels={"type": "", "count": "violations"}, title="Violations by type") | |
| fig.update_layout(showlegend=False, height=300, yaxis=dict(categoryorder="total ascending"), **CHART) | |
| st.plotly_chart(fig, width="stretch", key="an_type") | |
| with c2, st.container(border=True): | |
| veh = v["vehicle"].value_counts().reset_index() | |
| fig = px.bar(veh, x="count", y="vehicle", orientation="h", labels={"vehicle": "", "count": "violations"}, | |
| title="Violations by vehicle type", color_discrete_sequence=["#8b93a1"]) | |
| fig.update_layout(height=300, yaxis=dict(categoryorder="total ascending"), **CHART) | |
| st.plotly_chart(fig, width="stretch", key="an_vehicle") | |
| with st.container(border=True): | |
| v["day"] = v["timestamp"].dt.floor("D") if v["timestamp"].dt.normalize().nunique() > 1 else v["timestamp"].dt.floor("h") | |
| trend = v.groupby(["day", "type"]).size().reset_index(name="count") | |
| fig = px.bar(trend, x="day", y="count", color="type", color_discrete_map=cmap, title="Over time", | |
| labels={"day": "", "count": "violations", "type": ""}) | |
| fig.update_layout(height=280, legend=dict(orientation="h", y=-0.25), **CHART) | |
| st.plotly_chart(fig, width="stretch", key="an_trend") | |
| rep = v[~v["plate"].isin(S.UNREAD)].groupby("plate").size().sort_values(ascending=False) | |
| rep = rep[rep > 1] | |
| if not rep.empty: | |
| st.markdown("**Repeat offenders**") | |
| st.dataframe(rep.reset_index(name="violations"), hide_index=True, width="stretch") | |
| # --------------------------------------------------------------------------- | |
| # Model performance | |
| # --------------------------------------------------------------------------- | |
| def page_performance() -> None: | |
| header("Model performance", "Measured on held-out data with tools/evaluate.py.") | |
| if not REPORT_PATH.exists(): | |
| st.info("Run `python tools/evaluate.py --all` to generate the evaluation report.") | |
| return | |
| rep = json.loads(REPORT_PATH.read_text()) | |
| vio, plates = rep.get("violations", {}), rep.get("plates", {}) | |
| kp = [] | |
| for v in (HELMET, TRIPLE): | |
| if v in vio: | |
| kp.append((f"{v} recall", f"{vio[v]['vehicle_level']['recall'] * 100:.0f}%")) | |
| if plates.get("end_to_end"): | |
| kp.append(("Plates read exactly", f"{plates['end_to_end']['exact_match'] * 100:.0f}%")) | |
| if rep.get("vehicles"): | |
| kp.append(("Vehicle mAP50 (Bengaluru)", f"{next(iter(rep['vehicles'].values()))['mAP50']:.2f}")) | |
| st.markdown(S.kpis(kp), unsafe_allow_html=True) | |
| st.caption(f"Report generated {rep.get('generated')}.") | |
| tab_v, tab_p, tab_m, tab_s = st.tabs(["Violations", "Number plates", "Detectors", "Speed"]) | |
| with tab_v: | |
| rows = [] | |
| for v in (HELMET, TRIPLE): | |
| for split, src in (("test", vio), ("valid", vio.get("valid", {}))): | |
| r = src.get(v) | |
| if r: | |
| vl = r["vehicle_level"] | |
| rows.append({"Violation": v, "Split": split, "Precision": vl["precision"], "Recall": vl["recall"], | |
| "F1": vl["f1"], "TP": vl["tp"], "FP": vl["fp"], "FN": vl["fn"]}) | |
| if "seatbelt" in rep: | |
| s = rep["seatbelt"] | |
| rows.append({"Violation": SEATBELT + " (per image)", "Split": "test", "Precision": s["precision"], | |
| "Recall": s["recall"], "F1": s["f1"], "TP": s["tp"], "FP": s["fp"], "FN": s["fn"]}) | |
| st.dataframe(pd.DataFrame(rows), hide_index=True, width="stretch") | |
| st.caption("Per vehicle on Indian two-wheeler photos. Thresholds were chosen on the valid split; " | |
| "the test split was not used for tuning.") | |
| with tab_p: | |
| o, e = plates.get("ocr_on_crops", {}), plates.get("end_to_end", {}) | |
| st.markdown(S.kpis([("Read exactly (crops)", f"{o.get('all', {}).get('exact_match', 0) * 100:.1f}%"), | |
| ("Two-line plates", f"{o.get('two_line', {}).get('exact_match', 0) * 100:.1f}%"), | |
| ("Characters correct", f"{o.get('all', {}).get('char_accuracy', 0) * 100:.1f}%"), | |
| ("Plate found (full photo)", f"{e.get('plate_detected', 0) * 100:.0f}%"), | |
| ("Read exactly (full photo)", f"{e.get('exact_match', 0) * 100:.0f}%")]), | |
| unsafe_allow_html=True) | |
| st.caption(f"{o.get('all', {}).get('n', 0)} held-out plate crops and {e.get('images', 0)} held-out vehicle " | |
| "photos. The previous EasyOCR pipeline read 13.4% of the same crops exactly.") | |
| with tab_m: | |
| if "vehicles" in rep: | |
| st.markdown("**Vehicle detection on Bengaluru CCTV (UVH-26 sample), AP50 per class**") | |
| st.dataframe(pd.DataFrame([{"Model": n, "mAP50": r["mAP50"], **{k: x["AP50"] for k, x in r["per_class"].items()}} | |
| for n, r in rep["vehicles"].items()]), hide_index=True, width="stretch") | |
| if "models" in rep: | |
| st.markdown("**Component detectors (test splits)**") | |
| st.dataframe(pd.DataFrame([{"Model": k, **{m: x.get(m) for m in ("precision", "recall", "f1", "mAP50", "mAP50-95")}} | |
| for k, x in rep["models"].items() if "error" not in x]), | |
| hide_index=True, width="stretch") | |
| with tab_s: | |
| s = rep.get("speed") | |
| if s: | |
| stages = {k: x for k, x in s.items() if k not in ("device", "frames", "total")} | |
| fig = px.bar(x=list(stages.values()), y=list(stages.keys()), orientation="h", labels={"x": "ms", "y": ""}, | |
| title=f"Per 1080p photo on {s.get('device')}: {s.get('total')} ms total", | |
| color_discrete_sequence=["#ff4b4b"]) | |
| fig.update_layout(height=300, yaxis=dict(categoryorder="total ascending"), **CHART) | |
| st.plotly_chart(fig, width="stretch", key="perf_speed") | |
| def page_how() -> None: | |
| header("How it works") | |
| st.markdown( | |
| """ | |
| 1. **Enhance**: night or hazy frames get a contrast boost (CLAHE); clear frames are left untouched. | |
| 2. **Detect and track vehicles** with a YOLO11 model trained by IISc on 26,000 Bengaluru Safe-City CCTV frames | |
| (UVH-26). It knows Indian classes such as auto-rickshaws, two-wheelers, tempo travellers and LCVs. | |
| ByteTrack gives each vehicle an ID across video frames. | |
| 3. **Two-wheelers**: every bike is cropped with its riders and a head detector marks each head as *helmet* or | |
| *no helmet*. Heads are assigned to the nearest bike, so dense traffic does not mix riders up. | |
| No-helmet heads give **No Helmet**; three or more heads give **Triple Riding**. | |
| For **photos**, a second model trained on ground-level Indian road photos finds each bike with its riders | |
| (the CCTV model misses many close-up bikes) and classifies it as helmet / no helmet / triple riding. | |
| Either source can flag the violation, and the card says which one did. | |
| 4. **Cars**: the windshield area is checked for occupants with or without a seatbelt (**No Seatbelt**). | |
| 5. **Motion rules (video)** use timestamps, so they don't depend on frame rate: | |
| * **Wrong-side**: the vehicle moves against the drawn lane direction for about 1.5 s. | |
| * **Stop line / red light**: the vehicle crosses the drawn stop line while the signal is red. If it carries | |
| on through the junction, that is a **Red-light Jump**. | |
| * **Illegal parking**: the vehicle stays still in a no-parking zone longer than the limit. This also holds | |
| when the tracker loses and re-finds the vehicle. | |
| 6. **Confirmation**: in video, photo-based violations must show up in at least 2 frames before they are reported. | |
| 7. **Number plates**: a plate detector finds the plate, and an OCR model fine-tuned on Indian one- and two-line | |
| plates reads it. A decoder only accepts legal Indian formats (state code, RTO, series, number, BH series), | |
| which fixes O/0, I/1 and B/8 mistakes. In video, readings from many frames are averaged. Unclear plates go to | |
| **manual review** instead of being guessed. | |
| 8. **Evidence**: each violating vehicle gets one record with a scene snapshot, vehicle crop, plate crop and the | |
| reason for each violation. An officer confirms or rejects it on the Records page. | |
| """ | |
| ) | |
| def main() -> None: | |
| st.set_page_config(page_title="VisionGuard AI · Traffic violations", page_icon="🚦", layout="wide") | |
| st.markdown(S.CSS, unsafe_allow_html=True) | |
| init_state() | |
| page = sidebar() | |
| {"Analyze": page_analyze, "Records": page_records, "Analytics": page_analytics, | |
| "Model performance": page_performance}.get(page, page_how)() | |
| if __name__ == "__main__": | |
| main() | |