AI-powered geospatial logistics and decision-support platform for Northeast India — integrating ML-based road risk prediction, real-time hazard intelligence, weather analytics, vehicle compatibility, and risk-aware route optimization.
Built for the Smart India Hackathon (SIH), framed around the Ministry of Development of North Eastern Region (MDoNER), covering the eight Northeast Indian states — Assam, Meghalaya, Arunachal Pradesh, Nagaland, Manipur, Mizoram, Tripura, and Sikkim ("Ashta Lakshmi").
Freight and emergency transport in Northeast India runs on mountain roads that flood, get buried by landslides, and carry hard posted weight limits. A route that is shortest is often not passable for a 40-tonne truck in monsoon.
NER SafeRoute scores every road segment for hazard risk, checks whether a specific vehicle with a specific load can legally and physically use that segment, and routes around what it can't — combining a trained ML risk model, live hazard feeds, and a risk-aware routing engine into one decision pipeline.
👉 Try it live: ner-safe-route-psi.vercel.app
Record a ~20–30 s screen capture of route planning + the live hazard overlay and save it as
docs/screenshots/demo.gif. A moving demo is the single highest-impact thing you can add to a hackathon README — judges watch it before they read anything below.
~14,200 lines of Python (backend) + ~19,800 lines of JS/JSX (frontend).
React + React-Leaflet
│
▼
FastAPI
│
▼
Routing engine (OSRM) + PostGIS ──► candidate routes
│
▼
Road segments
│
▼
Random Forest ──► per-segment risk class
│
▼
Live rain / alerts / quake / flood escalation
│
▼
Risk-aware A* ──► risk as edge cost
│
▼
Safest suitable route → GeoJSON → map
Backend — Python / FastAPI
- FastAPI 0.110+, Uvicorn, Pydantic v2 + pydantic-settings
- SQLAlchemy 2.0 + GeoAlchemy2 + psycopg2 (PostGIS)
- Shapely for geometry, httpx / requests for external feeds
- scikit-learn, pandas, numpy, joblib (the ML model)
- psutil (real host telemetry), python-multipart (SMS webhooks)
- pytest for tests
Frontend — React / Vite
- React 18.2, Vite 5, React-Leaflet 4.2 + Leaflet 1.9
- axios, lucide-react icons
- No router library — navigation is role-gated state in
App.jsxwithReact.lazycode splitting - IndexedDB for driver offline mode
Data / infra
- PostgreSQL 16 + PostGIS 3.4 (spatial tables, GIST indexes)
- OSRM v5.27.1 (road routing engine, custom truck profile at
routing/osrm/truck_ner.lua) - SQLite for auth / fleet / ops stores (deliberate — see Authentication & roles)
- Docker Compose for the full local stack
sihproject/
├── backend/ FastAPI application
│ ├── app/
│ │ ├── api/ 17 mounted routers (see API surface)
│ │ ├── auth/ accounts, sessions, face 2FA
│ │ ├── core/ pydantic-settings config
│ │ ├── db/ SQLAlchemy session + PostGIS health
│ │ ├── decision_engine/ 11-level transport decision hierarchy
│ │ ├── fleet/ vehicle + driver store
│ │ ├── incidents/ field reports / SOS store
│ │ ├── live_feeds/ SACHET, USGS, GloFAS, Overpass pollers
│ │ ├── logistics/ 6-tier road ladder + transshipment planner
│ │ ├── ml/ adapter over the trained model + live-rain re-scoring
│ │ ├── models/ SQLAlchemy ORM models
│ │ ├── ops/ operations tooling + analysis
│ │ ├── risk/ weighted RiskEngine
│ │ ├── routing/ OSRM adapter + risk-aware A*
│ │ ├── schemas/ Pydantic request/response schemas
│ │ ├── services/ health, hazards, routes, Bhuvan, vehicle fit/swap
│ │ ├── telemetry/ measured node telemetry (psutil)
│ │ └── weather/ Open-Meteo client
│ └── tests/ 7 pytest files
├── frontend/ React + Vite dashboard
│ └── src/
│ ├── components/ ~36 components
│ ├── pages/
│ │ ├── dashboards/ 3 role dashboards
│ │ └── views/ 10 sidebar sections
│ ├── services/ 19 axios API clients
│ ├── context/ OpsDataContext (shared ops state + toasts)
│ ├── hooks/, map/, utils/, offline/
├── ml/ Standalone ML package (trains + predicts, no web deps)
│ ├── advanced/ model search, ordinal model, conformal, explain, rain triggers
│ ├── model/ trained .pkl artifacts + evaluation results
│ └── train_model.py, predict.py, evaluate_model.py, preprocessing.py
├── data/ North_East_Combined_Road_Risk_Dataset.csv (the only dataset)
├── database/ init.sql (PostGIS schema + GIST indexes) + seed/
├── gis/ extract_roads.py, process_dem.py, hazard_intersection.py
├── routing/osrm/ custom truck profile
├── auth-module/ separate Java/Spring Boot auth service (see below)
├── docs/ ARCHITECTURE, API_SPECIFICATION, GIS_PIPELINE_GUIDE, TEAM_COLLABORATION_GUIDE
├── docker-compose.yml PostGIS + FastAPI + Vite + OSRM
├── render.yaml Render deployment blueprint (backend)
└── .env.example
Dataset: data/North_East_Combined_Road_Risk_Dataset.csv — 3,447 rows × 43 columns, covering 25 road corridors across the 8 NE states. One row per ~1 km road segment. Zero duplicate segment IDs, zero coordinates outside NE India.
Target: risk_level — 4 classes (LOW 43.4% / MODERATE 33.5% / HIGH 22.6% / CRITICAL 0.5%, i.e. only 17 rows). The continuous overall_risk column is dropped as leakage because risk_level is exactly overall_risk cut at 25/50/75 (verified, not assumed). CRITICAL is not merged into HIGH to flatter the metrics — the 88:1 imbalance is handled with class_weight="balanced_subsample" and reported honestly.
Features: 25 columns across terrain (elevation, mean/max slope, aspect), landslide (susceptibility, counts, nearest distance), flood (risk, history, distance to river), rainfall, road (type, condition, damage count, width, closure history, length), load capacity (weight limit, bridge capacity, heavy-vehicle restriction/suitability), and region (state, district).
Latitude/longitude are deliberately excluded. With only 25 contiguous corridors, a raw coordinate acts as a corridor fingerprint — a tree can split on longitude, recover "this is NH-13," and get the label without learning anything about hazard. Measured: dropping the coordinate columns raised unseen-corridor accuracy from 0.9228 to 0.9539.
Baseline model: RandomForestClassifier(n_estimators=200, min_samples_leaf=2, max_features="sqrt", class_weight="balanced_subsample"), no scaler (trees split on thresholds), outliers kept (an 11,430 mm Mawsynram rainfall reading is signal).
Honest headline number — quote 0.9539, not 0.9986:
| Evaluation | Accuracy | Balanced acc. | Macro F1 | Kappa |
|---|---|---|---|---|
| Held-out random split | 0.9986 | 0.9984 | 0.9987 | 0.9978 |
| Stratified 5-fold CV | 0.9919 | 0.9499 | 0.9383 | 0.9875 |
GroupKFold by road_id |
0.9539 | 0.8776 | 0.8818 | 0.9292 |
A random split puts near-copies of test rows into training (consecutive 1 km segments of one corridor look almost identical), so it scores ~99.9% by recognising the corridor. GroupKFold holds out whole corridors and measures what matters operationally.
Production model (ml/advanced/): a severity-score forest — a RandomForestRegressor on overall_risk (0–100), cut at the dataset's own 25/50/75 boundaries. This lets the 17 CRITICAL rows borrow strength from HIGH rows just below 75. Chosen by a two-stage search (12 candidates on 6 corridor partitions, then the winner re-confirmed on 6 fresh partitions). Confirmed result: balanced accuracy 87.1% vs 84.2% (won 6/6), CRITICAL recall 66.7% vs 55.9%.
A retracted finding, documented on purpose: an earlier write-up adopted 2-hop road-graph feature propagation claiming +3.0 points. Those seeds all shared one corridor partition; on fresh partitions the graph model scored 82.8% vs the plain forest's 83.3%. Graph features were retired.
Also in the advanced layer: split-conformal confidence intervals (90% level: 86.9% score coverage, 99.3% class coverage, 79% single-class answers), exact Saabas tree-path explanations, and live rain triggers (Open-Meteo 24h/72h rainfall escalating a segment's class past susceptibility-dependent landslide thresholds).
Stated limitations:
- 25 corridors, not 3,447 independent samples — 14 columns are constant within a corridor.
- CRITICAL has 17 examples; its metrics are indicative at best.
- Labels are rubric-derived, not incident-derived — the model reproduces an expert scoring rubric and has not been validated against real closures or accidents.
- Rain-trigger thresholds are literature/IMD-informed defaults, not fitted to local records.
backend/app/routing/astar.py builds a graph from the 3,447 dataset rows — each row is one edge, endpoints snapped to a ~11 m grid so segments meeting at a junction share a node.
edge_cost = length_km * (1 + risk_weight * risk_penalty(level))
risk_weight=0 gives a pure shortest path; higher values buy safety with detour. The heuristic is great-circle distance, which never overestimates, so A* stays admissible and the route is optimal for this cost.
Known limitation: the surveyed network is not fully connected — the 25 corridors form 12 separate components, the largest holding ~27% of nodes. A* can only route within a component. When it can't, it returns reachable=False and the API falls back to OSRM geometry scored by the model — and the response is labelled with which engine produced it, so a caller always knows.
backend/app/decision_engine/engine.py enforces an explicit 11-level hierarchy:
- Physical feasibility
- Legal vehicle restrictions
- Road closures
- Critical safety hazards
- Vehicle compatibility
- ML natural-hazard risk
- Road condition
- Data uncertainty
- Travel time
- Distance
- Cost
Possible verdicts: SAFE_ROUTE, SAFE_ROUTE_WITH_WARNING, ALTERNATIVE_ROUTE, VEHICLE_INCOMPATIBLE, VEHICLE_SWAP_REQUIRED, REROUTING_REQUIRED, NO_FEASIBLE_ROUTE, NO_REPLACEMENT_AVAILABLE.
backend/app/risk/engine.py — a configurable weighted score used for the non-ML risk path, separate from the trained model. Weights are env-tunable and sum to 1.0:
| Factor | Weight |
|---|---|
| Flood | 0.25 |
| Landslide | 0.25 |
| Weather | 0.15 |
| Slope | 0.15 |
| Road condition | 0.10 |
| Vehicle penalty | 0.10 |
Bands: SAFE ≤20, LOW ≤40, MODERATE ≤60, HIGH ≤80, CRITICAL >80. Vehicle penalty multipliers — car 5, bus 25, truck 40, heavy truck 60 — reflect that heavy multi-axle vehicles on steep or unpaved mountain roads carry rollover/breakdown risk.
backend/app/logistics/ models how freight actually moves into the Northeast: a 40-tonne truck runs the national highway, cargo is broken at a hub onto a smaller truck for the regional road, again for the mountain road, and the last stretch into a remote village may be a pickup, a bike, or a porter. Six tiers.
Total cost = distance + travel time + vehicle + transfer
+ road risk + landslide risk + weather risk
+ vehicle restriction + delay risk
Seven of the nine terms come from surveyed per-segment data. Two — money — have no source anywhere in the project (no rate card, payroll, or billing table exists), so per-km rates and handling charges are caller-supplied assumptions with documented defaults. Every response echoes the rates used in assumptions, and cost_basis states which terms are measured vs. assumed. tier_coverage reports which tiers are data-backed — the dataset has no village roads or footpaths at all (weight limits only range 16.2–49.0 T, widths 5.5–14.0 m), so VILLAGE and PORTER tiers exist in code but can never be selected from current data, and the API says so.
17 mounted routers under FastAPI. Root / returns a self-describing index; /docs serves interactive Swagger UI.
| Prefix | Tag | What it does |
|---|---|---|
| (root) | Health & Diagnostics | /health, /api/health |
/api/route |
Vehicle-Aware Routing | POST /, GET /{route_id}, POST /compare |
/api/hazards |
GIS Hazard Layers | hazard polygons as GeoJSON |
/api/road-risk |
Road Risk Analysis | GET /{road_id} |
/api/weather |
Weather Intelligence | Open-Meteo live, mock fallback |
/api/layers |
GIS Layer Management | layer catalog |
/api/auth |
Authentication | login, me (GET/PATCH), logout, face/status, face/enroll, face/start, face/verify, DELETE /face |
/api/incidents |
Field Reports & SOS | POST /, GET /, PATCH /{id} |
/api/ml |
ML Road Risk (Random Forest) | status, predict, segment/{id}, nearest?lat=&lon=, corridor |
/api/ml |
AI Risk Intelligence | live-risk, live-risk/segments, live-risk/refresh, live-risk/scenario (POST/DELETE), explain/{segment_id}, insights |
/api/admin |
Developer Admin | telemetry, hardware |
/api/fleet |
Logistics Admin | fleet list, summary, paths, stops/all, deliveries, road-path, dispatch, driver CRUD, drivers/near-route, per-vehicle position/status/stops, SOS raise + resolve, route/astar, route/graph |
/api/network |
Road Network | corridors, states, summary |
/api/logistics |
Logistics | ladder, transship-plan |
/api/ops |
Operations Tools | clearance, settlements (+PATCH), stockpile (+PATCH, dispatch), compliance/check, compliance/rules (PUT/DELETE), driver permits, sms/inbound (webhook) + sms/log, backhaul marketplace (list / create / assign / cancel) |
/api/feeds |
Live Hazard Feeds | status, alerts, earthquakes, rivers, pois/along-route, pois/near, refresh |
/api/bhuvan |
Bhuvan (ISRO/NRSC) | status, services, routing, lulc/aoi, service/{service} |
In progress, not live:
backend/app/api/tracking.py(shipment tracking + checkpoints) andbackend/app/api/transport.py(transport planning / decision-engine endpoints) are fully written but not currently mounted inmain.pyor exported fromapp/api/__init__.py.
Started on app boot, each on its own schedule. After any refresh, the live-risk layer re-applies so routing sees the change immediately.
| Feed | Source | Refresh | Escalates segment risk? |
|---|---|---|---|
| SACHET | Indian official disaster warnings | 15 min | Yes — orange/red road-relevant warnings |
| USGS | Earthquakes | 15 min | Yes — M4+ near susceptible slopes |
| GloFAS | River flood forecasts | 6 h | Yes — forecast flow above 2-/5-year flood level |
| Overpass | OSM points of interest | cache checked daily, re-downloaded every 14 days | No |
| Open-Meteo | Live rainfall | 30 min | Yes — via the rain-trigger model |
| Bhuvan (ISRO/NRSC) | WMS geospatial layers | on demand | Optional, key-gated |
Bhuvan caveat: Bhuvan issues one token per service, and each expires one day after issue — a deployed instance needs tokens refreshed daily. Config supports a JSON map BHUVAN_TOKENS={"routing":"...","lulc_aoi":"..."} with BHUVAN_API_KEY as a single-key fallback. Without a key, the Bhuvan layers report themselves unavailable rather than failing at import.
Startup warm-up: on boot the app eagerly loads the risk model (~1.5 s) and the A* graph (~2 s), starts the live-risk and feed loops in the background, and pre-fetches the hub-to-hub corridors the dashboards open — so the first "find route" click is a cache hit and the first telemetry reading isn't polluted by one-off load cost.
Storage: SQLite (backend/data/users.db, fleet.db) rather than Postgres — deliberate: the rest of the app degrades gracefully when Postgres is offline, and sign-in should not be the one thing that breaks.
Passwords: PBKDF2-HMAC-SHA256, 600,000 iterations (OWASP's recommended floor), stdlib only (no native dependency to build on Windows/Python 3.14). Per-password random salt. Stored value is self-describing (pbkdf2_sha256$<iters>$<salt>$<hash>) so the cost can be raised later without invalidating existing accounts. Constant-time verification.
Sessions: opaque bearer tokens (secrets.token_urlsafe(32)), 7-day lifetime, stored by fingerprint.
Face second factor: the browser computes a 128-dim descriptor and only the numbers are transmitted — no camera frame ever reaches the server or database. The comparison sits behind a verify_descriptor interface so a real government identity provider can be swapped in without touching the login flow.
⚠️ The current browser-side descriptor is a development placeholder — a coarse image statistic, not face recognition. It cannot distinguish one person from another with any assurance, has no liveness check, and a photograph will satisfy it. The 0.995 cosine threshold was calibrated against synthesised descriptors, not real captures. It is a demonstrable second step on top of the password, not identity proof.
Three roles, chosen at login (no in-app role switching):
| Role | Label | Sections |
|---|---|---|
official |
Official Command | dashboard, live-map, route-planner, vehicle-tracking, road-infra, supply-chain, field-reports, emergency-ops, ai-intel, analytics, reports (11) |
admin |
Admin | same minus a reordering — fleet/driver/cargo focused (10) |
field_user |
Field Driver | dashboard, live-map, route-planner, field-reports (4) |
Developer Admin and Logistics Admin were merged into one Admin role — both needed the same operational picture, and two dashboards over the same data only split attention. Legacy dev_admin / logistics_admin account IDs still resolve to Admin.
Three role dashboards + 10 dedicated sidebar views: Live Map, Route Planner, Vehicle Tracking, Road & Infrastructure, Supply Chain, Field Reports, Emergency Ops, AI Risk Intelligence, Analytics, Reports.
Notable components: MapView (React-Leaflet), FleetLayer with animated vehicles, TurnByTurnPanel, RouteComparison, RouteRiskProfile, MLRiskPanel, LiveFeedsPanel, BhuvanPanel, WeatherPanel, StockpilePlanner, TransshipmentPlanner, BackhaulBoard, PermitDesk, ComplianceResult, ClearancePriority, DriverWorkforce, SmsFieldLink, HelplineStrip, FaceScanStep, BootSequence, ModelNetworkIntegrity, SystemHealthStatus.
Performance:
- All three role dashboards and all 10 views are
React.lazycode-split — only one dashboard per session, and charting/PDF/heavy map layers are only paid for when a section is opened. - Session restore skips the round trip entirely when there's no token, so the login page paints on the first frame.
- Hazards are only fetched once there's a dashboard to draw them on.
Theming: light/dark/system, applied as a class on <html> — deliberately not on a wrapper, because a filter on any other element would become the containing block for every position: fixed dialog inside it.
Offline driver mode: frontend/src/offline/indexedDb.js — IndexedDB queues for GPS fixes and checkpoints plus cached offline route packages, enabling zero-connectivity tracking and navigation with later sync.
Emergency access: a HelplineStrip renders on every dashboard and view, so emergency numbers are always one tap away.
API client: axios, same-origin by default so requests go through the Vite dev proxy. This exists for a reason — uvicorn binds 0.0.0.0:8000 (IPv4 only) while Chrome resolves localhost to IPv6 ::1, so hitting http://localhost:8000 directly failed as a bare "Network Error." The proxy also avoids CORS preflight entirely and survives Vite landing on a different port. 45 s timeout, because live OSRM and weather probes can legitimately take 15–20 s.
A standalone service that shares no code with the main project — a different language and stack entirely, intended to be integrated over HTTP later.
- Backend: Java 21 · Spring Boot 3.3 · Spring Security · PostgreSQL · Flyway
- Frontend: React 18 · TypeScript · Vite (officer sign-in console, port 5174)
- Named "ResiliRoute-NER" in its own docs (an earlier project name)
- Argon2id password hashing, per-account lockout, optional face 2FA behind a swappable provider, roles
ADMIN/GOVERNMENT_OFFICER/DISASTER_RESPONSE/LOGISTICS_OFFICER, short-lived JWTs + rotating opaque refresh tokens, OAuth2/JWKS readiness for a government IdP, fixed-window rate limiting, server-side session revocation with reuse detection, and an append-only audit table.
cp .env.example .env # then set DB_PASSWORD — compose fails fast without it
docker-compose up -d --buildBrings up PostGIS 16-3.4, FastAPI, Vite, and OSRM.
- Frontend:
http://localhost:5173 - API docs:
http://localhost:8000/docs - Health:
http://localhost:8000/health
# backend
cd backend
python -m pip install -r requirements.txt
uvicorn app.main:app --host 0.0.0.0 --port 8000 --reload
# frontend
cd frontend
npm install
npm run dev
# tests
python -m pytest backend/tests -vpip install -r ml/requirements.txt
python ml/train_model.py # retrains, rewrites ml/model/
python ml/train_model.py --trees 400 --no-plot
python ml/predict.py --sample
python ml/predict.py --segment-id NH-13-AR-SEG-0001
python ml/evaluate_model.py --grouped # the honest GroupKFold number
python ml/advanced/model_search.py # 12 candidates, 2-stage selection
python ml/advanced/train_ordinal_model.py # production model + conformal- Backend → Render (
render.yaml): Docker web service frombackend/Dockerfile.prod, Singapore region, free plan, health check at/health. No PostGIS on the free plan — the health endpoint reports the DB as unavailable and routing/hazards fall back to the bundled datasets. - Frontend → Vercel (
frontend/vercel.json): Vite build todist, SPA rewrites.
ENVIRONMENT, DEBUG, CORS_ORIGINS, DB_* / DATABASE_URL, ROUTING_ENGINE, OSRM_URL, MOCK_ROUTING_FALLBACK, WEATHER_API_PROVIDER, MOCK_WEATHER, BHUVAN_TOKENS, BHUVAN_API_KEY, DATASET_PATH, the six WEIGHT_* risk weights, the four RISK_*_MAX thresholds, and FLEET_SIM_SPEEDUP.
FLEET_SIM_SPEEDUP is a demo-only time multiplier (default 25 in the example env, 1.0 in code). At 1.0 a vehicle moves ~130 m between polls — under one pixel on a map framed around all eight states, so a moving fleet looks frozen. It scales only how far a tick advances; the speed each vehicle reports stays a realistic 28–52 km/h, and so do the derived ETAs.
No credential lives in code. DB_PASSWORD defaults to empty and compose fails fast with Set DB_PASSWORD in .env. Config resolves .env from the project root rather than the working directory, so the same file is read whether uvicorn starts in backend/ or the repo root.
backend/tests/ — 7 pytest files:
test_health.pytest_risk_engine.pytest_ml_risk.pytest_ml_intelligence.pytest_hazard_routing_system.pytest_admin_fleet.pytest_live_feeds.py
This codebase is unusually rigorous about separating what is measured from what is assumed, and it does so in the API responses themselves, not just in comments:
- The ML evaluation quotes 0.9539, not 0.9986 — and explains why the flattering number is an artifact of corridor leakage.
- A previously published +3.0-point result (graph features) was retracted in the repo after fresh corridor partitions failed to reproduce it.
- Telemetry reports
measured=Falsewith an explanatory note where a figure genuinely can't be measured, and the dashboard renders those differently — nothing here invents a healthy reading for a service that isn't running. - The logistics planner returns
cost_basisandassumptionsstating which of its nine cost terms are surveyed data and which are caller-supplied rates, because no rate card exists anywhere in the project. tier_coveragetells the reader which road tiers are data-backed, so nobody believes a village-road leg was computed from evidence that doesn't exist.- A* reports
reachable=Falseand labels which engine produced a path when it falls back to OSRM. - The face-auth module documents in its own docstring that it is a placeholder that "a photograph will satisfy."
- The road-risk dataset covers 25 corridors, not 3,447 independent samples.
- CRITICAL risk has only 17 labeled examples.
- Risk labels are rubric-derived, not validated against real closures or accidents.
- Rain-trigger thresholds are literature/IMD-informed defaults, not locally fitted.
- The routing graph is split across 12 disconnected components; A* falls back to OSRM where it can't reach.
- Face 2FA is a development placeholder, not production-grade biometric verification.
tracking.pyandtransport.pyendpoints exist in code but are not yet mounted.
See LICENSE at the repository root.