Multi-Agent Geospatial Intelligence Platform for Real-Time Road Safety Monitoring in Kerala, India
SurakshaNet is an autonomous road safety monitoring system that uses 26 specialized AI agents organized into three operational clusters. The agents continuously analyze weather conditions, traffic flow, accident history, live camera feeds, flood risk, hospital capacity, and more — then fuse their assessments using Bayesian belief networks and Byzantine fault-tolerant voting to produce a single, calibrated risk score for each monitored road segment. When risk is elevated, the system generates causal attribution via the Anthropic Claude API and dispatches alerts through Slack, SMS, and webhook integrations.
Author: Sherin Joseph Roy
- Architecture Overview
- Agent Clusters
- Orchestration Pipeline
- Monitored Road Segments
- Tech Stack
- Project Structure
- Installation
- Configuration
- Running the Application
- Database Migrations and Seeding
- API Reference
- Frontend Pages
- Testing
- External API Integrations
- Key Algorithms
- Public Safety Features
- Alerting and Notifications
- Observability
- License
SurakshaNet follows a three-stage perception-fusion-action architecture:
+------------------+
| Road Segments |
| (6 in Kerala) |
+--------+---------+
|
+-------------------+-------------------+
| | |
+--------v--------+ +-------v--------+ +--------v--------+
| SurakshaNet | | DRISHTI | | SENTINEL |
| Cluster (9) | | Cluster (8) | | Cluster (6) |
| Road Safety | | Disaster Resp. | | Surveillance |
+---------+-------+ +-------+--------+ +--------+--------+
| | |
+-------------------+-------------------+
|
+-------------v--------------+
| Byzantine Fault-Tolerant |
| Weighted Voting |
+-------------+--------------+
|
+-------------v--------------+
| Bayesian Belief Fusion |
| (Correlation-Corrected) |
+-------------+--------------+
|
+-------------v--------------+
| Claude API Attribution |
| (Causal Explanation) |
+-------------+--------------+
|
+-------------------+-------------------+
| | |
+-----v-----+ +------v------+ +------v------+
| Persist | | Slack / | | WebSocket |
| PostgreSQL | | SMS Alert | | Dashboard |
+------------+ +-------------+ +-------------+
Every monitoring cycle (default: 5 minutes) processes all six road segments. Agents run concurrently within each cluster. Agent failures are handled gracefully — a failing agent returns risk_score=0.0, confidence=0.0, vote=HOLD and the pipeline continues without it.
These agents run in parallel and assess real-time road conditions:
| Agent | Data Source | What It Measures |
|---|---|---|
weather_friction |
Open-Meteo + OpenWeatherMap | Pavement friction using IRC SP:73-2015 model (rain, temperature, humidity, wind) |
historical_pattern |
NCRB accident database | Time-of-day and day-of-week accident probability from district-level statistics |
traffic_anomaly |
HERE Traffic Flow API v7 | Speed deviation from free-flow and jam factor analysis |
visual_risk |
YOLOv8 object detection | Hazard detection from camera feeds (vehicles, pedestrians, obstructions) |
infrastructure_decay |
Road condition database | Pavement quality index, pothole density, drainage status |
visibility |
Weather + time-of-day | Fog, rain, and darkness-adjusted visibility distance |
crowdsource |
Community reports API | Crowd-submitted incident reports within 500m of segment |
fleet_telemetry |
KSRTC bus GPS data | Bus speed anomalies, harsh braking events, route deviation |
near_miss_detector |
Computer vision pipeline | Time-to-collision (TTC), post-encroachment time (PET), deceleration rate (DRAC) |
These agents focus on disaster preparedness and emergency coordination:
| Agent | Data Source | What It Measures |
|---|---|---|
situation_awareness |
IMD weather warnings | India Meteorological Department cyclone/flood/rainfall warnings |
resource_inventory |
KSDMA resource database | Available rescue boats, pumps, shelters, and personnel |
population_vulnerability |
Census 2011 | Age demographics, disability prevalence, population density |
logistics_optimizer |
OR-Tools VRP solver | Optimal vehicle routing for emergency resource deployment |
counterfactual |
Claude API projection | "What if we do nothing?" scenario modeling |
flood_routing |
Elevation + rainfall data | Flood-safe evacuation route calculation |
hospital_capacity |
Hospital database | Bed availability, trauma center capability, ambulance count |
communication_resilience |
Network monitoring | Cell tower status and communication infrastructure assessment |
These agents form a sequential pipeline for evidence-grade surveillance:
| Agent | Data Source | What It Measures |
|---|---|---|
edge_perception |
RT-DETR detection | Real-time object detection optimized for edge deployment |
cross_camera |
OSNet Re-ID | Multi-camera person and vehicle re-identification |
threat_escalation |
Bayesian Beta-Binomial | Cumulative threat level tracking with statistical confidence |
evidence_packaging |
Chain of custody | Section 65B Indian Evidence Act compliant evidence packaging |
license_plate |
ALPR pipeline | Automatic license plate recognition and stolen vehicle checking |
audio_anomaly |
Audio classification | Crash sounds, gunshots, screams, tire screeches |
SENTINEL uses a sequential pipeline: edge_perception + cross_camera (parallel) then threat_escalation then evidence_packaging.
For each road segment in each monitoring cycle:
Step 1 — Agent Execution. All agents in the active clusters run concurrently using asyncio.gather(). Each agent returns a standardized AgentOutput containing risk_score (0.0-1.0), confidence (0.0-1.0), and vote (ESCALATE / HOLD / DISMISS).
Step 2 — Byzantine Fault-Tolerant Voting. Agent votes are weighted by confidence and tallied: ESCALATE contributes +1 x confidence, DISMISS contributes -1 x confidence, HOLD contributes 0. The weighted sum determines the consensus: above +0.50 is ESCALATE, below -0.50 is DISMISS, otherwise HOLD. Agents with confidence=0 are excluded. If more than 50% of agents fail, the system enters degraded mode.
Step 3 — Bayesian Belief Fusion. Individual risk scores are fused into a single posterior belief score. The fusion accounts for known correlations between agents (for example, visual_risk and traffic_anomaly share a correlation coefficient of 0.6). Independent agents are combined via precision-weighted averaging. Correlated pairs are down-weighted to avoid double-counting evidence.
Step 4 — Causal Attribution. If the vote is ESCALATE or the fused belief exceeds the threshold (default 0.72), the system sends all agent scores and metadata to the Anthropic Claude API (claude-sonnet-4-20250514) to generate a human-readable causal explanation. If the API is unavailable, the event is persisted with causal_attribution=None and a degraded alert is sent.
Step 5 — Persistence and Alerting. The complete event (all agent scores, vote result, fused belief, causal attribution) is persisted to PostgreSQL. If the database is unreachable, the event is buffered in a Redis queue and drained later with exponential backoff. High-risk events trigger Slack alerts, SMS notifications, and webhook dispatches.
The full pipeline is implemented as a LangGraph StateGraph with the following execution order:
START --> suraksha_net_node --> drishti_node --> coordinator_node
|
sentinel_perception_node
|
sentinel_escalation_node
|
sentinel_packaging_node
|
END
SurakshaNet monitors six road segments across Kerala, selected to represent diverse road conditions:
| Segment | Location | Surface | Speed Limit | Lanes | Notes |
|---|---|---|---|---|---|
| NH-66 Edapally Junction | Ernakulam (10.026N, 76.312E) | Asphalt | 60 km/h | 4 | High-traffic urban junction |
| NH-544 Thrissur-Palakkad | Thrissur (10.527N, 76.214E) | Asphalt | 80 km/h | 4 | National highway corridor |
| NH-66 Kasaragod Bypass | Kasaragod (12.501N, 74.989E) | Asphalt | 70 km/h | 2 | Northern Kerala bypass |
| MC Road Kottayam-Changanassery | Kottayam (9.591N, 76.522E) | Concrete | 50 km/h | 2 | State road with dense settlement |
| SH-1 Wayanad Ghat Road | Wayanad (11.685N, 76.132E) | WBM | 30 km/h | 2 | Mountain road with 9 hairpin bends |
| NH-66 Kozhikode Beach Road | Kozhikode (11.258N, 75.780E) | Asphalt | 40 km/h | 4 | Coastal urban road |
| Layer | Technology |
|---|---|
| Backend Framework | Python 3.12, FastAPI, async SQLAlchemy |
| Database | PostgreSQL 16 with PostGIS extension |
| Cache / Message Broker | Redis 7 |
| Agent Orchestration | LangGraph StateGraph |
| Computer Vision | YOLOv8, RT-DETR, OSNet (person/vehicle re-identification) |
| AI / LLM | Anthropic Claude API (claude-sonnet-4-20250514) |
| Frontend | Next.js 14, React 18, Tailwind CSS, Leaflet.js, Deck.gl, Recharts, D3.js |
| Real-Time Communication | WebSocket (Socket.IO), Server-Sent Events |
| Alerting | Slack Bolt SDK (Socket Mode), SMS via gateway, Webhooks with HMAC-SHA256 |
| Infrastructure | Docker Compose, Alembic migrations |
| Logging | structlog (JSON format) |
| Observability | OpenTelemetry (traces, metrics, spans) |
| Optimization | Google OR-Tools (vehicle routing) |
| Testing | pytest, pytest-asyncio (1,465+ tests) |
surakshanet/
|
|-- backend/
| |-- config.py Pydantic BaseSettings, startup validation
| |-- requirements.txt Pinned Python dependencies
| |-- Dockerfile
| |
| |-- agents/ 26 perception agents
| | |-- base.py BaseAgent ABC + AgentOutput schema
| | |-- weather_friction.py Open-Meteo + OpenWeatherMap
| | |-- historical_pattern.py NCRB accident statistics
| | |-- traffic_anomaly.py HERE Traffic Flow API v7
| | |-- visual_risk.py YOLOv8 object detection
| | |-- infrastructure_decay.py Road condition index
| | |-- visibility.py Visibility distance model
| | |-- crowdsource.py Community incident reports
| | |-- fleet_telemetry.py KSRTC bus GPS integration
| | |-- near_miss_detector.py TTC/PET/DRAC computation
| | |-- situation_awareness.py IMD warnings (DRISHTI)
| | |-- resource_inventory.py KSDMA resources (DRISHTI)
| | |-- population_vulnerability.py Census 2011 data (DRISHTI)
| | |-- logistics_optimizer.py OR-Tools VRP solver (DRISHTI)
| | |-- counterfactual.py Claude projection (DRISHTI)
| | |-- flood_routing.py Flood-safe routing (DRISHTI)
| | |-- hospital_capacity.py Hospital bed tracking (DRISHTI)
| | |-- communication_resilience.py Network status (DRISHTI)
| | |-- edge_perception.py RT-DETR detection (SENTINEL)
| | |-- cross_camera.py OSNet Re-ID (SENTINEL)
| | |-- threat_escalation.py Bayesian Beta-Binomial (SENTINEL)
| | |-- evidence_packaging.py Section 65B compliance (SENTINEL)
| | |-- license_plate.py ALPR pipeline (SENTINEL)
| | |-- audio_anomaly.py Audio classification (SENTINEL)
| | |-- spatiotemporal_forecast.py Risk trend prediction
| | +-- driver_behavior.py Driver scoring model
| |
| |-- api/
| | |-- main.py FastAPI app, lifespan, CORS, middleware
| | |-- middleware/
| | | +-- auth.py JWT authentication
| | +-- routes/ 41 route modules (see API Reference)
| |
| |-- models/
| | |-- base.py Async SQLAlchemy engine + session factory
| | |-- segment.py RoadSegment ORM (PostGIS geometry)
| | |-- event.py RiskEvent ORM (JSONB agent_scores)
| | |-- historical.py HistoricalAccident (NCRB data)
| | |-- disaster_resource.py DisasterResource (KSDMA)
| | |-- census.py CensusData (2011 demographics)
| | +-- segment_twin.py Digital twin state
| |
| |-- orchestrator/
| | |-- state.py GeospatialBeliefState TypedDict
| | |-- voting.py Byzantine fault-tolerant weighted voting
| | |-- belief_fusion.py Bayesian fusion with correlation correction
| | |-- coordinator.py 3-stage: vote, fuse, Claude attribution
| | |-- graph.py LangGraph StateGraph wiring
| | +-- monitoring_loop.py Continuous monitoring loop
| |
| +-- services/ 43 service modules
| |-- database.py Event persistence + Redis fallback
| |-- slack_service.py Slack alerts + slash commands
| |-- sms_service.py Multi-language SMS (EN/HI/ML)
| |-- webhook_service.py HMAC-signed webhook dispatch
| |-- telemetry.py OpenTelemetry instrumentation
| |-- flood_warning_service.py Flood state machine
| |-- school_zone_service.py School proximity safety
| |-- pedestrian_safety_service.py Pedestrian risk scoring
| |-- hospital_prealert_service.py Golden hour alerting
| |-- multi_agency_dispatch.py Multi-agency coordination
| +-- (38 more service modules)
|
|-- frontend/
| |-- package.json
| |-- Dockerfile
| +-- src/
| |-- app/
| | |-- page.tsx Main map dashboard (Leaflet + Deck.gl)
| | |-- events/page.tsx Risk event history table
| | |-- analytics/page.tsx Charts and trend analysis
| | |-- flood/page.tsx Flood early warning dashboard
| | |-- command-center/page.tsx Full-screen operations view
| | |-- forecast/page.tsx Risk trend forecasting
| | |-- simulation/page.tsx What-if scenario testing
| | |-- near-misses/page.tsx Near-miss conflict analysis
| | |-- school-zones/page.tsx School zone safety monitor
| | |-- cameras/page.tsx Live camera feeds
| | |-- districts/page.tsx District-level overview
| | |-- query/page.tsx Natural language data query
| | |-- compare/page.tsx Side-by-side segment comparison
| | |-- settings/page.tsx System configuration
| | |-- health/page.tsx System health dashboard
| | +-- admin/ API keys, webhooks, thresholds, compliance, audit
| |-- components/
| | |-- DeckGLMap.tsx Deck.gl 3D risk visualization
| | |-- RiskMap.tsx Leaflet 2D risk map
| | |-- AgentConstellation.tsx D3.js force-directed agent graph
| | |-- BeliefWaterfall.tsx Bayesian fusion waterfall chart
| | |-- MetricsPanel.tsx Real-time metrics display
| | +-- (20+ more components)
| +-- lib/
| +-- api.ts API client functions
|
|-- tests/ 1,465+ tests across 97 files
| |-- test_agents/ Per-agent unit tests
| |-- test_orchestrator/ Voting, fusion, coordinator tests
| |-- test_api/ Endpoint tests
| |-- test_services/ Service layer tests
| +-- test_integration/ Full pipeline E2E tests
|
|-- scripts/
| |-- seed_segments.py 6 Kerala road segments
| |-- parse_ncrb.py NCRB accident data loader
| |-- seed_disaster_resources.py KSDMA inventory
| |-- seed_census.py Census 2011 demographics
| |-- seed_all.py Run all seed scripts
| +-- setup_superset.py Apache Superset analytics
|
|-- alembic/ Async database migrations
|-- docker-compose.yml
|-- Makefile
+-- .env.example
- Python 3.12+
- Node.js 18+ and npm
- PostgreSQL 16 with PostGIS extension
- Redis 7
# Clone the repository
git clone https://github.com/Sherin-SEF-AI/SurakshaNet.git
cd SurakshaNet
# Create and activate virtual environment
python3.12 -m venv .venv
source .venv/bin/activate
# Install Python dependencies
pip install -r backend/requirements.txtcd frontend
npm install
cd ..# Create PostgreSQL database with PostGIS
sudo -u postgres psql -c "CREATE DATABASE surakshanet;"
sudo -u postgres psql -c "CREATE USER surakshanet WITH PASSWORD 'surakshanet';"
sudo -u postgres psql -c "GRANT ALL PRIVILEGES ON DATABASE surakshanet TO surakshanet;"
sudo -u postgres psql -d surakshanet -c "CREATE EXTENSION IF NOT EXISTS postgis;"
sudo -u postgres psql -d surakshanet -c "CREATE EXTENSION IF NOT EXISTS \"uuid-ossp\";"Copy the example environment file and fill in your API keys:
cp .env.example .env| Variable | Where to Get It | Free Tier Limit |
|---|---|---|
ANTHROPIC_API_KEY |
console.anthropic.com | Pay per token |
OPENWEATHERMAP_API_KEY |
openweathermap.org | 60 calls/min, 1M/month |
HERE_API_KEY |
developer.here.com | 1,000 requests/day |
SLACK_BOT_TOKEN |
api.slack.com/apps | Unlimited |
SLACK_APP_TOKEN |
Slack App > Socket Mode | Unlimited |
| Variable | Default |
|---|---|
DATABASE_URL |
postgresql+asyncpg://surakshanet:surakshanet@localhost:5432/surakshanet |
REDIS_URL |
redis://localhost:6379/0 |
| Variable | Default | Description |
|---|---|---|
MONITORING_INTERVAL_SECONDS |
300 |
Seconds between monitoring cycles |
HIGH_RISK_THRESHOLD |
0.72 |
Fused belief threshold for alerts |
LOG_LEVEL |
INFO |
Logging verbosity |
# Start PostgreSQL and Redis (if using Docker)
docker compose up -d postgres redisalembic upgrade headpython scripts/seed_all.pyThis loads: 6 road segments, NCRB accident statistics, KSDMA disaster resources, Census 2011 demographics, school zones, hospital data, KSRTC bus routes, and tourist routes.
uvicorn backend.api.main:app --host 0.0.0.0 --port 8001 --reloadThe API will be available at http://localhost:8001. Interactive documentation is at http://localhost:8001/docs.
cd frontend
NEXT_PUBLIC_API_URL=http://localhost:8001 npm run dev -- -p 3001The dashboard will be available at http://localhost:3001.
docker compose up --buildThis starts PostgreSQL (with PostGIS), Redis, the backend API, and the frontend dashboard.
The project uses Alembic for database schema management with four migration phases:
d8a2b1c43f59 (base)
--> f1a2b3c4d5e6 Phase 1: Core tables (segments, events, historical)
--> g2b3c4d5e6f7 Phase 2: Disaster tables (resources, census, flood)
--> h3c4d5e6f7g8 Phase 3: Surveillance tables (evidence, violations)
--> i4d5e6f7g8h9 Phase 4: Public safety tables (schools, hospitals, dispatch)
# Apply all migrations
alembic upgrade head
# Check current state
alembic current
# Generate a new migration
alembic revision --autogenerate -m "description"| Script | Records | Description |
|---|---|---|
seed_segments.py |
6 | Kerala road segments with PostGIS geometry |
parse_ncrb.py |
~200 | District-level accident statistics from NCRB |
seed_disaster_resources.py |
~50 | KSDMA rescue equipment and shelter inventory |
seed_census.py |
~14 | District demographics from Census 2011 |
seed_all.py |
All | Runs all seed scripts in dependency order |
The backend exposes 41 route modules. Key endpoint groups:
| Method | Path | Description |
|---|---|---|
GET |
/health |
System health check (DB, Redis, agents) |
GET |
/health/ratelimits |
Current API rate limit status |
GET |
/segments |
All road segments as GeoJSON FeatureCollection |
GET |
/segments/{id} |
Single segment with latest risk event |
GET |
/segments/{id}/events |
Paginated risk event history |
GET |
/segments/{id}/twin |
Digital twin state |
GET |
/segments/{id}/fusion-detail |
Decomposed Bayesian belief fusion |
GET |
/segments/{id}/speed-recommendation |
Weather-adaptive speed limit |
GET |
/events |
Filtered risk event listing |
GET |
/events/stats |
Aggregated event statistics |
WS |
/ws/riskmap |
Real-time risk updates via WebSocket |
| Method | Path | Description |
|---|---|---|
GET |
/school-zones |
Active school zone safety data |
GET |
/nighttime/status |
Nighttime safety assessment |
GET |
/nighttime/dark-spots |
Poorly lit road segments |
GET |
/pedestrian/{segment_id} |
Pedestrian risk scoring |
GET |
/pedestrian/scorecard |
System-wide pedestrian safety scorecard |
GET |
/flood/status |
Current flood state per segment |
GET |
/flood/{segment_id}/history |
Flood state transition history |
| Method | Path | Description |
|---|---|---|
POST |
/hospital-prealert |
Trigger hospital pre-alert for incoming trauma |
POST |
/dispatch/{id}/multi-send |
Multi-agency emergency dispatch |
GET |
/ksdma/feed |
KSDMA real-time event feed |
GET |
/ksdma/monsoon-overlay |
Monsoon risk overlay |
GET |
/ksdma/resource-gaps |
Resource gap analysis |
GET |
/evacuation/{segment_id}/routes |
Evacuation route planning |
| Method | Path | Description |
|---|---|---|
GET |
/forecast/{segment_id} |
Risk trend forecast (1-30 days) |
POST |
/simulation/run |
What-if scenario simulation |
GET |
/analytics/heatmap |
Risk heatmap data |
GET |
/analytics/weekly-digest |
Automated weekly safety digest |
POST |
/query |
Natural language data query |
GET |
/near-misses |
Near-miss conflict events |
GET |
/compare/{seg_a}/{seg_b} |
Segment comparison analysis |
| Method | Path | Description |
|---|---|---|
GET |
/admin/config |
Runtime configuration |
GET |
/admin/api-keys |
API key management |
GET |
/admin/metrics |
Prometheus-format metrics |
GET |
/admin/compliance/report |
ISO 39001 compliance report |
GET |
/admin/audit |
System audit log |
GET |
/cap/feed |
CAP (Common Alerting Protocol) XML feed |
| Method | Path | Description |
|---|---|---|
POST |
/external/incident |
External system incident ingestion |
GET |
/accessible/alerts |
WCAG-compliant alert format |
GET |
/subscriptions |
Alert subscription management |
POST |
/crowd-reports |
Community incident reporting |
Full interactive API documentation is available at /docs (Swagger UI) and /redoc (ReDoc) when the backend is running.
The frontend is a Next.js 14 application with 25 pages:
| Page | Path | Description |
|---|---|---|
| Risk Map | / |
Main dashboard with Leaflet 2D and Deck.gl 3D map views, real-time risk visualization, agent constellation display, and belief waterfall chart |
| Events | /events |
Searchable, filterable table of all risk events with export capability |
| Analytics | /analytics |
Time-series charts, risk heatmaps, trend analysis, and weekly digest |
| Districts | /districts |
District-level risk overview with monsoon scores |
| Cameras | /cameras |
Live camera feed grid with WebRTC player |
| Near-Misses | /near-misses |
Near-miss conflict analysis with TTC/PET/DRAC metrics |
| School Zones | /school-zones |
Active school zone monitoring with schedule awareness |
| Flood Warning | /flood |
Flood state machine visualization and history |
| Forecast | /forecast |
Multi-day risk trend prediction with confidence intervals |
| Simulation | /simulation |
Parameter adjustment and what-if scenario testing |
| Compare | /compare |
Side-by-side segment risk comparison |
| Query | /query |
Natural language interface for querying safety data |
| Command Center | /command-center |
Full-screen operations dashboard with ticker |
| Settings | /settings |
System configuration and threshold management |
| Health | /health |
Backend health, database status, rate limit monitoring |
| KSDMA Dashboard | /dashboard/ksdma |
KSDMA operations center with resource gaps and evacuation planning |
| KSRTC Dashboard | /dashboard/ksrtc |
KSRTC bus fleet safety monitoring |
| District Collector | /dashboard/collector |
District collector decision support |
| Violations | /enforcement/violations |
Traffic violation records |
| API Keys | /admin/api-keys |
API key lifecycle management |
| Webhooks | /admin/webhooks |
Webhook endpoint configuration and testing |
| Thresholds | /admin/thresholds |
Per-segment risk threshold configuration |
| Compliance | /admin/compliance |
ISO 39001 compliance status and reporting |
| Audit Log | /admin/audit |
Full system audit trail |
| Calibration | /admin/calibration |
Agent calibration and weight adjustment |
The project has 1,465+ tests across 97 test files:
# Run all tests
python -m pytest tests/ -v --override-ini=asyncio_mode=auto
# Run a specific test module
python -m pytest tests/test_agents/test_weather_friction.py -v
# Run integration tests
python -m pytest tests/test_integration/ -v
# Run with coverage
python -m pytest tests/ --cov=backend --cov-report=html| Category | Files | Description |
|---|---|---|
test_agents/ |
27 | Individual agent logic, API mocking, graceful failure |
test_orchestrator/ |
12 | Voting, belief fusion, coordinator, graph wiring |
test_api/ |
18 | HTTP endpoint testing, validation, error handling |
test_services/ |
25 | Service layer logic, database operations |
test_integration/ |
15 | Full pipeline E2E, cross-agent interaction, public safety features |
| API | Calls per Cycle | Daily Total | Free Limit | Status |
|---|---|---|---|---|
| Open-Meteo | 6 | 1,728 | 10,000/day | Within budget |
| HERE Traffic | 6 (hourly) | 144 | 1,000/day | Within budget |
| OpenWeatherMap | Fallback only | ~50 | 1,000/day | Within budget |
| Anthropic Claude | On escalation only | ~20-50 | 60 RPM | Within budget |
| IMD Warnings | 6 | 1,728 | ~100/day | Cached aggressively |
Rate limits are tracked per-API in Redis using token bucket and sliding window algorithms. When a limit is exhausted, the corresponding agent returns confidence=0.0, vote=HOLD and the pipeline continues without it.
friction = base_coefficient
* (1 - rain_reduction_factor)
* (1 - temperature_reduction_factor)
* humidity_adjustment
* wind_adjustment
Base coefficients vary by surface type: asphalt (0.70), concrete (0.75), WBM (0.55).
risk = min(1.0, district_accident_rate / (2 * national_average))
* time_of_day_multiplier
* day_of_week_multiplier
The national average baseline is 14.2 fatalities per 100,000 population (NCRB 2022).
risk = 0.6 * (1 - current_speed / free_flow_speed)
+ 0.4 * (jam_factor / 10)
posterior = (mean_independent * precision_independent
+ mean_correlated * precision_correlated)
/ (precision_independent + precision_correlated)
Known correlation pairs are down-weighted: visual_risk/traffic_anomaly (rho=0.6), edge_perception/cross_camera (rho=0.5), visibility/weather_friction (rho=0.7), flood_routing/situation_awareness (rho=0.5), hospital_capacity/resource_inventory (rho=0.4), license_plate/cross_camera (rho=0.5), audio_anomaly/edge_perception (rho=0.3).
SurakshaNet includes 19 public safety features implemented across four phases:
- School zone monitoring with time-of-day awareness
- Nighttime safety assessment with dark spot identification
- Pedestrian risk scoring based on crossing density, speed, and visibility
- Hit-and-run detection and vehicle tracking
- Hospital pre-alert with golden hour countdown
- Multi-agency dispatch coordination (police, fire, ambulance, NDRF)
- Signal preemption request for emergency vehicles
- Flood early warning with state machine (NORMAL, WATCH, WARNING, DANGER, IMPASSABLE)
- KSRTC bus route safety scoring and driver behavior monitoring
- Stolen vehicle detection via ALPR integration
- Infrastructure decay tracking and maintenance prioritization
- Traffic violation detection with evidence packaging
- Tourism route safety scoring for visitor awareness
- Crowd-sourced incident reporting with geofenced validation
- WCAG-compliant accessible alert formats (screen reader, audio TTS)
- District collector dashboard for administrative decision support
SurakshaNet sends Block Kit formatted alerts to a configured Slack channel. Alerts include the segment name, fused belief score, causal attribution, contributing agents, and recommended actions.
Slash commands are available:
/surakshanet status— Show all monitored segments and their current state/surakshanet pause <segment_id>— Pause monitoring for a segment/surakshanet resume <segment_id>— Resume monitoring/surakshanet threshold <value>— Update the risk threshold/surakshanet history <segment_id>— Show last 10 events
Multi-language SMS alerts in English, Hindi, and Malayalam are dispatched via SMS gateway for high-risk events. Messages include the segment name, severity level, and advisory text.
External systems can subscribe to risk events via webhooks. Payloads are signed with HMAC-SHA256 (using the X-SurakshaNet-Signature header) for verification. Webhook endpoints can be configured and tested through the admin dashboard.
A standards-compliant CAP XML feed is available at /cap/feed for integration with national warning systems and media broadcasters.
All backend logs are emitted in JSON format via structlog. Each log entry includes a request_id for distributed tracing. Log levels are configurable via the LOG_LEVEL environment variable.
The system exports traces and metrics via OpenTelemetry:
surakshanet.agent.execution_latency— Per-agent execution time histogramsurakshanet.monitoring_cycle.duration— Full cycle duration histogramsurakshanet.api.call_duration— External API call latency histogramsurakshanet.events.total— Total risk events countersurakshanet.api.errors_total— API error countersurakshanet.claude.tokens_used— Claude API token consumption counter
A Prometheus-compatible metrics endpoint is available at /admin/metrics exposing event counts, average fused belief per segment, and total event volume.
This project is developed for road safety research and public safety applications in Kerala, India.
Author: Sherin Joseph Roy