{"id":47892511,"url":"https://github.com/cipher982/stopsign_ai","last_synced_at":"2026-04-04T03:10:48.612Z","repository":{"id":240420265,"uuid":"802584637","full_name":"cipher982/stopsign_ai","owner":"cipher982","description":"Tracking stopsign runners with an IP camera and AI","archived":false,"fork":false,"pushed_at":"2026-03-12T03:02:40.000Z","size":9755,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2026-03-12T08:06:07.571Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"https://crestwoodstopsign.com","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/cipher982.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":"AGENTS.md","dco":null,"cla":null}},"created_at":"2024-05-18T17:51:47.000Z","updated_at":"2026-03-12T03:02:43.000Z","dependencies_parsed_at":"2024-05-19T22:22:22.814Z","dependency_job_id":"67ce31f0-2928-449b-8fab-9d1616c8f547","html_url":"https://github.com/cipher982/stopsign_ai","commit_stats":null,"previous_names":["cipher982/stopsign_ai"],"tags_count":2,"template":false,"template_full_name":null,"purl":"pkg:github/cipher982/stopsign_ai","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cipher982%2Fstopsign_ai","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cipher982%2Fstopsign_ai/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cipher982%2Fstopsign_ai/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cipher982%2Fstopsign_ai/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/cipher982","download_url":"https://codeload.github.com/cipher982/stopsign_ai/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cipher982%2Fstopsign_ai/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":31386001,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-04-04T01:22:39.193Z","status":"online","status_checked_at":"2026-04-04T02:00:07.569Z","response_time":60,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2026-04-04T03:10:48.177Z","updated_at":"2026-04-04T03:10:48.606Z","avatar_url":"https://github.com/cipher982.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# 🚦 StopSign AI\n\nReal-time computer-vision pipeline that watches a stop sign, detects vehicles, and measures whether they actually stop.  \nRuns end-to-end from an RTSP camera to a web dashboard with nothing more than Docker and Python.\n\n🌐 **Live demo:** \u003chttps://crestwoodstopsign.com\u003e   [![Status](https://img.shields.io/uptimerobot/status/m797914657-f517a98377b6b7a2e883d57a)](https://stats.uptimerobot.com/m797914657-f517a98377b6b7a2e883d57a)\n\n![Afternoon screenshot](static/screenshot_afternoon.png)\n\n---\n\n## Tech-Stack Badges\n\n[![Python 3.12](https://img.shields.io/badge/python-3.12-blue.svg)](https://www.python.org/) \n[![Ruff](https://img.shields.io/badge/style-Ruff-000000.svg)](https://github.com/astral-sh/ruff) \n[![UV](https://img.shields.io/badge/deps-UV-4A4A4A.svg)](https://github.com/astral-sh/uv) \n[![YOLO11](https://img.shields.io/badge/AI-YOLO11-green.svg)](https://github.com/ultralytics/ultralytics) \n[![FastHTML](https://img.shields.io/badge/frontend-FastHTML-orange.svg)](https://github.com/answerdotai/fasthtml) \n[![Redis](https://img.shields.io/badge/cache-Redis-red.svg)](https://redis.io/) \n[![PostgreSQL](https://img.shields.io/badge/database-PostgreSQL-blue.svg)](https://www.postgresql.org/) \n[![MinIO](https://img.shields.io/badge/storage-MinIO-00C6FF.svg)](https://min.io/) \n\n---\n\n## Table of Contents\n\n1. What’s Interesting\n2. Architecture\n3. Configuration\n4. Frame Format \u0026 Timestamp Accuracy\n5. Health Model \u0026 Metrics\n6. Resilience Knobs\n7. Production Deployment\n8. Directory Layout\n\n---\n\n## 1. What’s Interesting\n\n- Capture‑time correctness end‑to‑end via SSFM headers (actual camera capture time used for all logic/overlays).\n- Deterministic FIFO across both legs of the pipeline (producer `LPUSH` + consumer `BRPOP`).\n- Clear health separation: liveness (`/healthz`) vs readiness (`/ready`) vs HLS freshness (`/health`, `/health/stream`).\n- Dynamic HLS freshness threshold derived from playlist window (no brittle hard‑coded timers).\n- Analyzer catch‑up mode that trims backlog after stalls to minimize time‑to‑fresh.\n- Observability triad: capture_age, process_age, hls_age to pinpoint where staleness originates.\n\nFor setup and development details, see the docs/ directory (e.g., `docs/architecture/first-principles-streaming.md`).\n\n---\n\n## 2. Project Architecture\n\n### Architecture at a Glance\n\n```mermaid\ngraph LR\n  C[RTSP Camera] --\u003e|RTSP| I[rtsp_to_redis]\n  I --\u003e|SSFM JPEG LPUSH RAW| R[(Redis)]\n  R --\u003e|BRPOP RAW| A[video_analyzer]\n  A --\u003e|LPUSH PROCESSED| R\n  R --\u003e|BRPOP PROCESSED| F[ffmpeg_service]\n  F --\u003e|HLS .m3u8/.ts| W[web_server]\n  W --\u003e|HTTP| B[(Browser)]\n\n  subgraph Health \u0026 Telemetry\n    F -.-\u003e|/healthz /ready /health| M[Monitoring]\n    W -.-\u003e|/health/stream| M\n  end\n```\n\nService | Purpose | Code | Docker image (local)\n---|---|---|---\nRTSP → Redis | Grabs frames from an RTSP feed (or sample .mp4) and publishes JPEGs to Redis with SSFM frame headers containing capture timestamps | `rtsp_to_redis/rtsp_to_redis.py` | `Dockerfile.rtsp.local`\nVideo Analyzer | YOLO11 inference + object tracking + stop-sign logic. Uses capture timestamps for accurate timing. Stores metadata in Postgres and images in MinIO. Publishes annotated frames. | `stopsign/video_analyzer.py` | `Dockerfile.processor.local`\nFFmpeg Service | Converts annotated frames → HLS stream (m3u8 + .ts) with Redis resilience and auto-recovery watchdog | `stopsign/ffmpeg_service.py` | `Dockerfile.ffmpeg.local`\nWeb Server | Simple FastAPI + FastHTML UI that shows the live stream \u0026 recent violations | `stopsign/web_server.py` | `Dockerfile.web.local`\nInfrastructure | Redis, Postgres, MinIO (+ console) | Official upstream images | –\n\nAll of the above are declared in `docker/local/docker-compose.yml` and wired together with environment variables in `docker/local/.env` (created by `make setup`).\n\n### Queue Semantics \u0026 Backlog Policy\n\n- Raw → Analyzer: `LPUSH` (producer) + `BRPOP` (consumer) on `RAW_FRAME_KEY` = FIFO; buffer bounded via `LTRIM`.\n- Analyzer → FFmpeg: `LPUSH` + `BRPOP` on `PROCESSED_FRAME_KEY` = FIFO.\n- Catch‑up policy: if a raw frame’s capture timestamp is older than `ANALYZER_CATCHUP_SEC`, trim RAW to last `ANALYZER_CATCHUP_KEEP_N` frames to jump back to near‑live.\n\n---\n\n## 3. Configuration\n\nKey settings are controlled via **environment variables** so that the exact same containers work in development and production.\n\nLocal (`docker/local/.env`):\n\n```env\nENV=local\nRTSP_URL=file:///app/sample_data/sample.mp4  # uses sample video\nYOLO_MODEL_NAME=yolo11n.pt                   # light-weight CPU model\nREDIS_URL=redis://redis:6379/0\nDB_URL=postgresql://postgres:password@postgres:5432/stopsign\nMINIO_ENDPOINT=minio:9000\n# … see template for all options\n```\n\nProduction: supply the same variables via your orchestrator (Docker Swarm, Kubernetes, Fly.io, etc.).  GPU models (`yolo11x.pt`) \u0026 NVIDIA runtimes are fully supported.\n\n### Configuration Management\n\n**Config File:** `config/config.yaml` (NOT in git - created from `config.example.yaml`)\n\n**Key Features:**\n- **Persistent across deployments:** Config stored in Docker volume, not in image\n- **Single source of truth:** One config file shared by all services\n- **Atomic updates:** Changes are written atomically with automatic versioning\n- **Instant reload:** Analyzer detects changes every frame (\u003c 100ms typical)\n- **Fail-fast:** Services exit immediately if config is missing or invalid\n\n**Initial Setup:**\n```bash\n# Local development\ncp config/config.example.yaml config/config.yaml\n\n# Production (after first deploy)\ndocker exec \u003ccontainer\u003e cp /app/config.example.yaml /app/config/config.yaml\n```\n\n**CLI Tools:**\n```bash\n# View current configuration\n./tools/print_config.py\n\n# Update stop zone coordinates (four corners)\n./tools/set_stop_zone.py \\\n  --x1 300 --y1 225 \\\n  --x2 380 --y2 225 \\\n  --x3 380 --y3 295 \\\n  --x4 300 --y4 295\n```\n\n**Web UI:** Navigate to `/debug` to visually adjust stop zones with instant feedback.\n\n**Production Persistence:** Use Coolify persistent volumes or Docker named volumes to maintain config across deployments. See `docs/config-deployment.md` for details.\n\n---\n\n## 4. Frame Format \u0026 Timestamp Accuracy\n\n### SSFM Wire Format\n\nThe pipeline uses a custom SSFM (StopSign Frame Message) format to ensure timestamp accuracy throughout the video processing chain:\n\n**Frame Structure:**\n- Bytes 0-3: `b'SSFM'` (magic header)\n- Byte 4: Version (currently `1`)\n- Bytes 5-8: Big-endian uint32 JSON metadata length\n- Bytes 9+: JSON metadata + JPEG frame data\n\n**JSON Metadata:**\n```json\n{\n  \"ts\": 1694621234.567,  // Capture timestamp (epoch float)\n  \"w\": 1920,             // Frame width\n  \"h\": 1080,             // Frame height\n  \"src\": \"rtsp\"          // Source identifier\n}\n```\n\n**Benefits:**\n- **Accurate timestamps**: Video overlay shows actual frame capture time, not processing time\n- **Pipeline visibility**: Metadata includes `latency_sec` showing capture-to-processing delay\n- **Backward compatibility**: Falls back gracefully for frames without SSFM headers\n\n### Timestamp Sources\n\n- **Capture timestamp**: Set at RTSP ingestion (`cap.read()` time) and preserved throughout pipeline\n- **Processing timestamp**: Available in metadata for latency calculation\n- **Video overlay**: Now displays capture timestamp in America/Chicago timezone for accuracy\n\n---\n\n## 5. Health Model \u0026 Metrics\n\nEvery custom service exposes a Prometheus `/metrics` endpoint. Mount a Prometheus/Grafana stack (or use the included Grafana data-source) to get:\n\n* FPS, processing latency, dropped frames\n* YOLO inference time, device utilisation (CPU/GPU)\n* Redis/DB query timings\n* FFmpeg encoder throughput\n\nGrafana dashboards are provided in `static/`.\n\n### Health endpoints and semantics\n\n- **rtsp_to_redis** — `/healthz` (liveness) and `/ready` (Redis push freshness + visual freeze detection).\n- **video_analyzer** — `/healthz` (liveness) and `/ready` (frame gap ≤ `ANALYZER_STALL_SEC`).\n- **ffmpeg_service** — `/healthz` (liveness) and `/ready` (fresh HLS + Redis + recent frame).\n- **web_server** — `/healthz` (process up) and `/health/stream` (HLS freshness for external monitors).\n- Legacy `/health` on ffmpeg_service remains for backwards compatibility.\n\nDocker healthchecks now target the liveness endpoints (`/healthz`) so short upstream hiccups don’t flip container health; alerting systems should watch `/ready` and treat `/health/stream` as an external freshness signal.\n\n### Netdata alert tuning\n\nNetdata ships with aggressive defaults that page on any short-lived HTTP failure. With the new readiness split:\n\n1. Monitor `video_analyzer` `/ready` and `ffmpeg_service` `/ready` with a **warning** threshold at ~2 minutes and a **critical** alert only after ≥10 minutes of failure. This filters transient Wi-Fi drops while still paging on real outages.\n2. Optionally keep `web_server` `/health/stream` as an informational alarm; set `delay: up`/`delay: down` to a few minutes so the recovered notification isn’t spammy.\n3. Use the new OTEL metrics `frame_queue_depth`, `frame_pipeline_lag_seconds`, and `redis_empty_polls_total` to build dashboards that show where the stall originated (camera ingest, analyzer, or encoder) before escalating.\n\nThese thresholds ensure operators see sustained issues without the “unhealthy/recovered” churn that previously flooded email.\n\n### Freshness and the “three ages”\n\n- `capture_age` = now − SSFM.capture_ts (ingest health)\n- `process_age` = now − last frame processed in ffmpeg_service (pipeline health)\n- `hls_age` = now − last `#EXT-X-PROGRAM-DATE-TIME` in playlist (edge/player health)\n\nFreshness threshold is derived from the playlist window (~3× window, floored at 60s) from `#EXTINF` and PDT.\n\n### Robust Stream Health Monitoring\n\nSilent failures in HLS segment generation can be hard to catch with simple HTTP liveness checks. This repo includes comprehensive health endpoints and auto-recovery:\n\n**Health Endpoints:**\n- `rtsp_to_redis` readiness: `http://localhost:8080/ready` – Redis push freshness + frozen-frame guardrail\n- `rtsp_to_redis` liveness: `http://localhost:8080/healthz`\n- `video_analyzer` readiness: `http://localhost:${ANALYZER_HEALTH_PORT:-8081}/ready` – frame pipeline (“can I serve fresh frames?”)\n- `video_analyzer` liveness: `http://localhost:${ANALYZER_HEALTH_PORT:-8081}/healthz`\n- `ffmpeg_service` readiness: `http://localhost:8080/ready` – HLS + Redis + recent frames\n- `ffmpeg_service` liveness: `http://localhost:8080/healthz`\n- `web_server` liveness: `http://localhost:8000/healthz`\n- `web_server` stream freshness: `http://localhost:8000/health/stream`\n\n**Auto-Recovery:** FFmpeg service includes a configurable watchdog that automatically restarts the container when HLS generation stalls, eliminating the need for manual intervention during network hiccups.\n\nHow it determines freshness (no extra config):\n\n- The services parse the HLS playlist (`stream.m3u8`) and compute a dynamic threshold from the manifest itself (target duration and the window of segments, via `#EXTINF`/`#EXT-X-PROGRAM-DATE-TIME`).\n- A stream is considered healthy if the last segment timestamp is newer than ~3× the playlist window, with a safe floor of ~60 seconds. This adapts automatically to your HLS settings and avoids tuning env vars.\n\nDefaults and resilience:\n\n- `restart: always` added to core services for automatic recovery\n- **Redis resilience**: Exponential backoff reconnection logic handles network interruptions gracefully\n- **Auto-restart watchdog**: Configurable via `PIPELINE_WATCHDOG_SEC` environment variable (e.g., 180 for 3-minute timeout)\n- **FIFO frame processing**: Proper queue semantics ensure frames are processed in correct order\n\nExamples\n\n- Encoder composite health: `curl -i http://localhost:8080/ready`\n- Encoder stream freshness: `curl -i http://localhost:8080/health`\n- Encoder liveness: `curl -i http://localhost:8080/healthz`\n- Web stream health: `curl -i http://localhost:8000/health/stream`\n\nNotes\n\n- Health endpoints set `Cache-Control: no-store` to avoid caching by proxies\n- **Watchdog configuration**: Set `PIPELINE_WATCHDOG_SEC=180` to enable 3-minute auto-restart on HLS staleness\n- **Redis configuration**: Optional `REDIS_MAX_BACKOFF_SEC=30` and `FRAME_STALL_SEC=120` for fine-tuning\n- Use `/ready` for comprehensive readiness checks, `/healthz` for simple liveness, `/health` for stream-specific monitoring\n- All services include exponential backoff Redis reconnection to handle network instability\n\n---\n\n## 6. Resilience Knobs\n\n- `RTSP_FREEZE_DETECT_SEC` (default 120): mark ingest as frozen if no visual motion over this window.\n- `RTSP_FREEZE_MAD_THRESHOLD` (default 0.015): frame-diff sensitivity for freeze detection.\n- `RTSP_FREEZE_RECONNECT_SEC` (default 180): force RTSP reconnect on sustained freeze.\n- `RTSP_FREEZE_REMEDIATION_CMD` (default empty): optional command hook for camera reboot automation.\n- `RTSP_FREEZE_REMEDIATION_SEC` (default 420): freeze age before running remediation command.\n- `ANALYZER_CATCHUP_SEC` (default 15): skip/trim stale raw frames older than this age to jump back to live.\n- `ANALYZER_CATCHUP_KEEP_N` (default 30): how many newest raw frames to retain when trimming.\n- `FRAME_STALL_SEC` (default 120): readiness requires frames newer than this.\n- `PIPELINE_WATCHDOG_SEC` (disabled by default): restart ffmpeg_service on sustained staleness.\n- `REDIS_MAX_BACKOFF_SEC` (default 30) and `REDIS_INITIAL_BACKOFF_SEC` (default 0.5): reconnect strategy.\n\n---\n\n## 7. Production Deployment\n\nThe legacy production setup is preserved in `docker/production/`.  Images are CUDA-enabled, use external managed databases, and **do not rely on .env files** – instead configure via environment variables / secrets.\n\nMinimal example:\n\n```bash\ncd docker/production\ndocker compose --profile all up -d  # or your preferred orchestrator\n```\n\nEnsure the following external services are reachable:\n\n* Redis 7+\n* PostgreSQL 14+\n* S3-compatible object storage (MinIO, AWS S3, etc.)\n\n---\n\n## 8. Directory Layout (top-level)\n\n```\n.\n├── docker/             # Dockerfiles \u0026 compose files (local \u0026 production)\n├── stopsign/           # Application source code (Python)\n├── models/             # Pre-downloaded YOLO models\n├── volumes/            # Bind-mounted data for local development\n├── static/             # UI assets, screenshots, Grafana dashboards\n├── sample_data/        # Sample video used in local mode\n├── docs/               # Design/architecture notes\n└── README.md           # You are here 💁\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcipher982%2Fstopsign_ai","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fcipher982%2Fstopsign_ai","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcipher982%2Fstopsign_ai/lists"}