Datasets:
Bappadala Rohith Kumar Naidu commited on
Commit ·
d710a81
1
Parent(s): ac3ae98
feat: add data acquisition scripts mirrored from SafeVisionAI main repo
Browse filesAdded reproducible data pipeline scripts organized by origin:
- scripts/backend/data/ → from backend/scripts/data/ (5 files)
- scripts/scripts/data/ → from scripts/data/ (15 files)
- scripts/chatbot_service/data/ → from chatbot_service/scripts/data/ (6 Pro fetchers)
Only pure-data scripts included (no DB/Redis/PostGIS dependencies).
App-only scripts excluded to keep Hub fully self-contained.
- scripts/backend/data/prepare_road_sources.py +195 -0
- scripts/backend/data/road_sources.example.json +3 -0
- scripts/backend/data/road_sources.json +3 -0
- scripts/backend/data/sample_pmgsy.py +66 -0
- scripts/backend/data/seed_violations.py +481 -0
- scripts/chatbot_service/data/_overpass_utils.py +212 -0
- scripts/chatbot_service/data/fetch_ambulance.py +44 -0
- scripts/chatbot_service/data/fetch_blood_banks.py +44 -0
- scripts/chatbot_service/data/fetch_fire.py +38 -0
- scripts/chatbot_service/data/fetch_hospitals.py +41 -0
- scripts/chatbot_service/data/fetch_police.py +41 -0
- scripts/scripts/data/_overpass_utils.py +161 -0
- scripts/scripts/data/audit_env.py +128 -0
- scripts/scripts/data/bootstrap_local_data.py +557 -0
- scripts/scripts/data/check_all_scripts.py +74 -0
- scripts/scripts/data/download_legal_pdfs.py +154 -0
- scripts/scripts/data/extract_morth2022_tables.py +147 -0
- scripts/scripts/data/fetch_ambulance.py +40 -0
- scripts/scripts/data/fetch_blood_banks.py +37 -0
- scripts/scripts/data/fetch_fire.py +34 -0
- scripts/scripts/data/fetch_hospitals.py +34 -0
- scripts/scripts/data/fetch_police.py +34 -0
- scripts/scripts/data/inspect_zips.py +33 -0
- scripts/scripts/data/seed_blackspots.py +189 -0
- scripts/scripts/data/setup_kaggle.ps1 +50 -0
- scripts/scripts/data/verify_data.py +98 -0
scripts/backend/data/prepare_road_sources.py
ADDED
|
@@ -0,0 +1,195 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
prepare_road_sources.py
|
| 3 |
+
=======================
|
| 4 |
+
Pre-processes local road data files that have only lat/lon point geometry
|
| 5 |
+
into LineString-based GeoJSON files that import_road_infrastructure.py can
|
| 6 |
+
actually import into the road_infrastructure PostGIS table.
|
| 7 |
+
|
| 8 |
+
Sources handled:
|
| 9 |
+
1. chatbot_service/data/roads/toll_plazas.csv
|
| 10 |
+
→ backend/datasets/roads/toll_plazas_linestring.geojson
|
| 11 |
+
2. backend/datasets/accidents/blackspot_seed.csv (if present)
|
| 12 |
+
→ backend/datasets/roads/blackspot_linestring.geojson
|
| 13 |
+
|
| 14 |
+
Each point is expanded into a tiny 0.001-degree stub LineString so it
|
| 15 |
+
satisfies the LINESTRING geometry constraint while preserving the location.
|
| 16 |
+
|
| 17 |
+
Usage:
|
| 18 |
+
cd backend/
|
| 19 |
+
python scripts/prepare_road_sources.py
|
| 20 |
+
"""
|
| 21 |
+
from __future__ import annotations
|
| 22 |
+
|
| 23 |
+
import csv
|
| 24 |
+
import json
|
| 25 |
+
import sys
|
| 26 |
+
from pathlib import Path
|
| 27 |
+
|
| 28 |
+
ROOT = Path(__file__).resolve().parents[1] # SafeVisionAI/backend/
|
| 29 |
+
CHATBOT_DATA = ROOT.parent / "chatbot_service" / "data"
|
| 30 |
+
OUT_DIR = ROOT / "datasets" / "roads"
|
| 31 |
+
OUT_DIR.mkdir(parents=True, exist_ok=True)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def point_to_stub_linestring(lat: float, lon: float, delta: float = 0.001) -> dict:
|
| 35 |
+
"""Return a GeoJSON geometry that is a tiny LineString centred on the point."""
|
| 36 |
+
return {
|
| 37 |
+
"type": "LineString",
|
| 38 |
+
"coordinates": [
|
| 39 |
+
[lon - delta / 2, lat],
|
| 40 |
+
[lon + delta / 2, lat],
|
| 41 |
+
],
|
| 42 |
+
}
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
# ---------------------------------------------------------------------------
|
| 46 |
+
# 1. Toll Plazas
|
| 47 |
+
# ---------------------------------------------------------------------------
|
| 48 |
+
def convert_toll_plazas() -> Path:
|
| 49 |
+
src = CHATBOT_DATA / "roads" / "toll_plazas.csv"
|
| 50 |
+
out = OUT_DIR / "toll_plazas_linestring.geojson"
|
| 51 |
+
|
| 52 |
+
if not src.exists():
|
| 53 |
+
print(f"[SKIP] toll_plazas.csv not found at {src}")
|
| 54 |
+
return out
|
| 55 |
+
|
| 56 |
+
features = []
|
| 57 |
+
skipped = 0
|
| 58 |
+
with src.open(encoding="utf-8-sig", newline="") as fh:
|
| 59 |
+
for row in csv.DictReader(fh):
|
| 60 |
+
try:
|
| 61 |
+
lat = float(row["lat"])
|
| 62 |
+
lon = float(row["lon"])
|
| 63 |
+
except (KeyError, ValueError):
|
| 64 |
+
skipped += 1
|
| 65 |
+
continue
|
| 66 |
+
|
| 67 |
+
props = {
|
| 68 |
+
"road_id": f"toll-{row.get('id', len(features)+1)}",
|
| 69 |
+
"road_name": row.get("name", ""),
|
| 70 |
+
"road_type": "toll_plaza",
|
| 71 |
+
"road_number": row.get("id", ""),
|
| 72 |
+
"state_code": "IN",
|
| 73 |
+
"contractor_name": row.get("contractor_name", ""),
|
| 74 |
+
"project_source": "NHAI Toll Plazas — geohacker/toll-plazas-india",
|
| 75 |
+
"data_source_url":
|
| 76 |
+
"https://github.com/geohacker/toll-plazas-india",
|
| 77 |
+
}
|
| 78 |
+
features.append({
|
| 79 |
+
"type": "Feature",
|
| 80 |
+
"geometry": point_to_stub_linestring(lat, lon),
|
| 81 |
+
"properties": props,
|
| 82 |
+
})
|
| 83 |
+
|
| 84 |
+
fc = {"type": "FeatureCollection", "features": features}
|
| 85 |
+
out.write_text(json.dumps(fc, ensure_ascii=False, indent=2), encoding="utf-8")
|
| 86 |
+
print(f"[OK] Toll plazas: {len(features)} features -> {out.relative_to(ROOT)}"
|
| 87 |
+
+ (f" ({skipped} skipped)" if skipped else ""))
|
| 88 |
+
return out
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
# ---------------------------------------------------------------------------
|
| 92 |
+
# 2. Blackspot seed CSV (backend/datasets/accidents/blackspot_seed.csv)
|
| 93 |
+
# ---------------------------------------------------------------------------
|
| 94 |
+
def convert_blackspots() -> Path | None:
|
| 95 |
+
src = ROOT / "datasets" / "accidents" / "blackspot_seed.csv"
|
| 96 |
+
out = OUT_DIR / "blackspot_linestring.geojson"
|
| 97 |
+
|
| 98 |
+
if not src.exists():
|
| 99 |
+
print(f"[SKIP] blackspot_seed.csv not found at {src}")
|
| 100 |
+
return None
|
| 101 |
+
|
| 102 |
+
features = []
|
| 103 |
+
skipped = 0
|
| 104 |
+
with src.open(encoding="utf-8-sig", newline="") as fh:
|
| 105 |
+
reader = csv.DictReader(fh)
|
| 106 |
+
cols = reader.fieldnames or []
|
| 107 |
+
lat_col = next((c for c in cols if c.lower() in ("lat", "latitude")), None)
|
| 108 |
+
lon_col = next((c for c in cols if c.lower() in ("lon", "longitude")), None)
|
| 109 |
+
if not lat_col or not lon_col:
|
| 110 |
+
print(f"[SKIP] blackspot_seed.csv has no lat/lon columns (found: {cols})")
|
| 111 |
+
return None
|
| 112 |
+
|
| 113 |
+
for idx, row in enumerate(reader, start=1):
|
| 114 |
+
try:
|
| 115 |
+
lat = float(row[lat_col])
|
| 116 |
+
lon = float(row[lon_col])
|
| 117 |
+
except ValueError:
|
| 118 |
+
skipped += 1
|
| 119 |
+
continue
|
| 120 |
+
|
| 121 |
+
props = {
|
| 122 |
+
"road_id": f"blackspot-{row.get('id', idx)}",
|
| 123 |
+
"road_name": row.get("location", row.get("road_name", "")),
|
| 124 |
+
"road_type": "blackspot",
|
| 125 |
+
"state_code": row.get("state_code", "IN"),
|
| 126 |
+
"project_source": "MoRTH Blackspot Seed Data",
|
| 127 |
+
"data_source_url":
|
| 128 |
+
"https://morth.nic.in/road-accident-black-spot",
|
| 129 |
+
}
|
| 130 |
+
features.append({
|
| 131 |
+
"type": "Feature",
|
| 132 |
+
"geometry": point_to_stub_linestring(lat, lon),
|
| 133 |
+
"properties": props,
|
| 134 |
+
})
|
| 135 |
+
|
| 136 |
+
fc = {"type": "FeatureCollection", "features": features}
|
| 137 |
+
out.write_text(json.dumps(fc, ensure_ascii=False, indent=2), encoding="utf-8")
|
| 138 |
+
print(f"[OK] Blackspots: {len(features)} features -> {out.relative_to(ROOT)}"
|
| 139 |
+
+ (f" ({skipped} skipped)" if skipped else ""))
|
| 140 |
+
return out
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
# ---------------------------------------------------------------------------
|
| 144 |
+
# Main
|
| 145 |
+
# ---------------------------------------------------------------------------
|
| 146 |
+
if __name__ == "__main__":
|
| 147 |
+
print("=== prepare_road_sources.py ===")
|
| 148 |
+
toll_out = convert_toll_plazas()
|
| 149 |
+
bs_out = convert_blackspots()
|
| 150 |
+
|
| 151 |
+
# Write a ready-to-use manifest for import_official_road_sources.py
|
| 152 |
+
sources = []
|
| 153 |
+
|
| 154 |
+
# Source 1: PMGSY rural roads (GeoJSON LineStrings — direct import, no conversion needed)
|
| 155 |
+
pmgsy_path = CHATBOT_DATA / "roads" / "pmgsy_roads.geojson"
|
| 156 |
+
if pmgsy_path.exists():
|
| 157 |
+
sources.append({
|
| 158 |
+
"name": "pmgsy_rural_roads",
|
| 159 |
+
"path": str(pmgsy_path.resolve()),
|
| 160 |
+
"format": "json",
|
| 161 |
+
"default_state_code": "IN",
|
| 162 |
+
"default_project_source": "PMGSY GeoSadak — datameet/pmgsy-geosadak",
|
| 163 |
+
"default_data_source_url": "https://github.com/datameet/pmgsy-geosadak",
|
| 164 |
+
})
|
| 165 |
+
print(f"[OK] PMGSY source added ({pmgsy_path.name})")
|
| 166 |
+
else:
|
| 167 |
+
print(f"[SKIP] PMGSY not found at {pmgsy_path}")
|
| 168 |
+
|
| 169 |
+
# Source 2: Toll plazas (converted to LineString)
|
| 170 |
+
sources.append({
|
| 171 |
+
"name": "nhai_toll_plazas",
|
| 172 |
+
"path": str(toll_out.resolve()),
|
| 173 |
+
"format": "json",
|
| 174 |
+
"default_state_code": "IN",
|
| 175 |
+
"default_project_source": "NHAI Toll Plazas — geohacker/toll-plazas-india",
|
| 176 |
+
"default_data_source_url": "https://github.com/geohacker/toll-plazas-india",
|
| 177 |
+
})
|
| 178 |
+
|
| 179 |
+
# Source 3: Blackspots (if converted)
|
| 180 |
+
if bs_out and bs_out.exists():
|
| 181 |
+
sources.append({
|
| 182 |
+
"name": "morth_blackspots",
|
| 183 |
+
"path": str(bs_out.resolve()),
|
| 184 |
+
"format": "json",
|
| 185 |
+
"default_state_code": "IN",
|
| 186 |
+
"default_project_source": "MoRTH Accident Blackspots",
|
| 187 |
+
"default_data_source_url": "https://morth.nic.in/road-accident-black-spot",
|
| 188 |
+
})
|
| 189 |
+
|
| 190 |
+
manifest_path = ROOT / "scripts" / "road_sources.json"
|
| 191 |
+
manifest_path.write_text(json.dumps(sources, indent=2, ensure_ascii=False), encoding="utf-8")
|
| 192 |
+
print(f"\n[OK] Manifest written: {manifest_path.relative_to(ROOT)}")
|
| 193 |
+
print(f" Contains {len(sources)} source(s)")
|
| 194 |
+
print("\nNow run:")
|
| 195 |
+
print(f" python scripts/import_official_road_sources.py --manifest scripts/road_sources.json")
|
scripts/backend/data/road_sources.example.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:1d31ef0be60a8f9099713c42a9294653739a444033ad609748b6167cd1df7afd
|
| 3 |
+
size 639
|
scripts/backend/data/road_sources.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:b0a729760cda438188c0c7f10f82e16ea5ce04aa83d71f48fc80ae64c6468c62
|
| 3 |
+
size 731
|
scripts/backend/data/sample_pmgsy.py
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
sample_pmgsy.py
|
| 3 |
+
===============
|
| 4 |
+
Samples a representative subset of PMGSY roads from the full
|
| 5 |
+
pmgsy_roads.geojson (867K features) and writes a smaller GeoJSON
|
| 6 |
+
that import_official_road_sources.py can import without timing out.
|
| 7 |
+
|
| 8 |
+
Strategy: Take up to `max_per_state` roads per state so all 29 states
|
| 9 |
+
are represented, then cap the total at `total_limit`.
|
| 10 |
+
|
| 11 |
+
Usage:
|
| 12 |
+
cd backend/
|
| 13 |
+
python scripts/sample_pmgsy.py [--limit 5000] [--per-state 200]
|
| 14 |
+
"""
|
| 15 |
+
from __future__ import annotations
|
| 16 |
+
|
| 17 |
+
import argparse
|
| 18 |
+
import json
|
| 19 |
+
from collections import defaultdict
|
| 20 |
+
from pathlib import Path
|
| 21 |
+
|
| 22 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 23 |
+
CHATBOT = ROOT.parent / "chatbot_service" / "data"
|
| 24 |
+
SRC = CHATBOT / "roads" / "pmgsy_roads.geojson"
|
| 25 |
+
OUT_DIR = ROOT / "datasets" / "roads"
|
| 26 |
+
OUT_DIR.mkdir(parents=True, exist_ok=True)
|
| 27 |
+
OUT = OUT_DIR / "pmgsy_sampled.geojson"
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def sample(total_limit: int = 5000, per_state: int = 200) -> None:
|
| 31 |
+
print(f"Loading {SRC.name} ... (this takes ~30s for 867K features)")
|
| 32 |
+
with SRC.open(encoding="utf-8") as fh:
|
| 33 |
+
data = json.load(fh)
|
| 34 |
+
|
| 35 |
+
all_features = data.get("features", [])
|
| 36 |
+
print(f"Total features: {len(all_features):,}")
|
| 37 |
+
|
| 38 |
+
buckets: dict[str, list] = defaultdict(list)
|
| 39 |
+
for feat in all_features:
|
| 40 |
+
state = feat.get("properties", {}).get("pmgsy_state", "Unknown")
|
| 41 |
+
buckets[state].append(feat)
|
| 42 |
+
|
| 43 |
+
selected = []
|
| 44 |
+
for state, feats in sorted(buckets.items()):
|
| 45 |
+
chosen = feats[:per_state]
|
| 46 |
+
selected.extend(chosen)
|
| 47 |
+
if len(selected) >= total_limit:
|
| 48 |
+
break
|
| 49 |
+
|
| 50 |
+
selected = selected[:total_limit]
|
| 51 |
+
print(f"Selected {len(selected):,} features from {len(buckets)} states")
|
| 52 |
+
|
| 53 |
+
fc = {"type": "FeatureCollection", "features": selected}
|
| 54 |
+
OUT.write_text(json.dumps(fc, ensure_ascii=False), encoding="utf-8")
|
| 55 |
+
size_mb = OUT.stat().st_size / 1_048_576
|
| 56 |
+
print(f"Written: {OUT.relative_to(ROOT)} ({size_mb:.1f} MB)")
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
if __name__ == "__main__":
|
| 60 |
+
parser = argparse.ArgumentParser()
|
| 61 |
+
parser.add_argument("--limit", type=int, default=5000, help="Max total roads")
|
| 62 |
+
parser.add_argument("--per-state", type=int, default=200, help="Max roads per state")
|
| 63 |
+
args = parser.parse_args()
|
| 64 |
+
sample(args.limit, args.per_state)
|
| 65 |
+
print("\nDone. Now update scripts/road_sources.json to use:")
|
| 66 |
+
print(f" datasets/roads/pmgsy_sampled.geojson")
|
scripts/backend/data/seed_violations.py
ADDED
|
@@ -0,0 +1,481 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
import csv
|
| 5 |
+
import re
|
| 6 |
+
from dataclasses import dataclass, field
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
BACKEND_DIR = Path(__file__).resolve().parents[1]
|
| 11 |
+
PROJECT_ROOT = BACKEND_DIR.parent
|
| 12 |
+
CHATBOT_DATA_DIR = PROJECT_ROOT / 'chatbot_service' / 'data'
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
VEHICLE_CLASS_ALIASES = {
|
| 16 |
+
'2W': 'two_wheeler',
|
| 17 |
+
'BIKE': 'two_wheeler',
|
| 18 |
+
'MOTORCYCLE': 'two_wheeler',
|
| 19 |
+
'SCOOTER': 'two_wheeler',
|
| 20 |
+
'4W': 'light_motor_vehicle',
|
| 21 |
+
'CAR': 'light_motor_vehicle',
|
| 22 |
+
'LMV': 'light_motor_vehicle',
|
| 23 |
+
'AUTO': 'light_motor_vehicle',
|
| 24 |
+
'HTV': 'heavy_vehicle',
|
| 25 |
+
'HGV': 'heavy_vehicle',
|
| 26 |
+
'TRUCK': 'heavy_vehicle',
|
| 27 |
+
'BUS': 'bus',
|
| 28 |
+
'COMM': 'bus',
|
| 29 |
+
'COMMERCIAL': 'bus',
|
| 30 |
+
}
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
@dataclass(frozen=True, slots=True)
|
| 34 |
+
class ChallanRule:
|
| 35 |
+
violation_code: str
|
| 36 |
+
section: str
|
| 37 |
+
description: str
|
| 38 |
+
base_fines: dict[str, int]
|
| 39 |
+
repeat_fines: dict[str, int] = field(default_factory=dict)
|
| 40 |
+
aliases: tuple[str, ...] = ()
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
DEFAULT_RULES: tuple[ChallanRule, ...] = (
|
| 44 |
+
ChallanRule(
|
| 45 |
+
violation_code='183',
|
| 46 |
+
section='Section 183',
|
| 47 |
+
description='Speeding beyond the notified limit.',
|
| 48 |
+
base_fines={
|
| 49 |
+
'two_wheeler': 1000,
|
| 50 |
+
'light_motor_vehicle': 2000,
|
| 51 |
+
'heavy_vehicle': 4000,
|
| 52 |
+
'bus': 4000,
|
| 53 |
+
'default': 2000,
|
| 54 |
+
},
|
| 55 |
+
repeat_fines={
|
| 56 |
+
'two_wheeler': 2000,
|
| 57 |
+
'light_motor_vehicle': 4000,
|
| 58 |
+
'heavy_vehicle': 8000,
|
| 59 |
+
'bus': 8000,
|
| 60 |
+
'default': 4000,
|
| 61 |
+
},
|
| 62 |
+
aliases=('112/183',),
|
| 63 |
+
),
|
| 64 |
+
ChallanRule(
|
| 65 |
+
violation_code='185',
|
| 66 |
+
section='Section 185',
|
| 67 |
+
description='Driving under the influence of alcohol or drugs.',
|
| 68 |
+
base_fines={'default': 10000},
|
| 69 |
+
repeat_fines={'default': 15000},
|
| 70 |
+
aliases=('DUI', 'DRUNK'),
|
| 71 |
+
),
|
| 72 |
+
ChallanRule(
|
| 73 |
+
violation_code='181',
|
| 74 |
+
section='Sections 3/181',
|
| 75 |
+
description='Driving without a valid driving licence.',
|
| 76 |
+
base_fines={'default': 5000},
|
| 77 |
+
repeat_fines={'default': 10000},
|
| 78 |
+
aliases=('3/181',),
|
| 79 |
+
),
|
| 80 |
+
ChallanRule(
|
| 81 |
+
violation_code='194D',
|
| 82 |
+
section='Sections 129/194D',
|
| 83 |
+
description='Failure to wear a helmet or seat belt as required.',
|
| 84 |
+
base_fines={'default': 1000},
|
| 85 |
+
repeat_fines={'default': 2000},
|
| 86 |
+
aliases=('194D-HELMET', '194D-SEATBELT'),
|
| 87 |
+
),
|
| 88 |
+
ChallanRule(
|
| 89 |
+
violation_code='194B',
|
| 90 |
+
section='Section 194B',
|
| 91 |
+
description='Safety gear non-compliance on a two-wheeler or while carrying a child.',
|
| 92 |
+
base_fines={
|
| 93 |
+
'two_wheeler': 1000,
|
| 94 |
+
'light_motor_vehicle': 1000,
|
| 95 |
+
'default': 1000,
|
| 96 |
+
},
|
| 97 |
+
repeat_fines={'default': 2000},
|
| 98 |
+
),
|
| 99 |
+
ChallanRule(
|
| 100 |
+
violation_code='179',
|
| 101 |
+
section='Section 179',
|
| 102 |
+
description='Disobedience, obstruction, or refusal to comply with lawful directions.',
|
| 103 |
+
base_fines={'default': 2000},
|
| 104 |
+
repeat_fines={'default': 4000},
|
| 105 |
+
),
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
RULE_COLUMNS = [
|
| 110 |
+
'violation_code',
|
| 111 |
+
'section',
|
| 112 |
+
'description',
|
| 113 |
+
'base_fine',
|
| 114 |
+
'base_fine_2w',
|
| 115 |
+
'base_fine_4w',
|
| 116 |
+
'base_fine_htv',
|
| 117 |
+
'base_fine_bus',
|
| 118 |
+
'repeat_fine',
|
| 119 |
+
'repeat_fine_2w',
|
| 120 |
+
'repeat_fine_4w',
|
| 121 |
+
'repeat_fine_htv',
|
| 122 |
+
'repeat_fine_bus',
|
| 123 |
+
'aliases',
|
| 124 |
+
]
|
| 125 |
+
OVERRIDE_COLUMNS = [
|
| 126 |
+
'state_code',
|
| 127 |
+
'violation_code',
|
| 128 |
+
'vehicle_class',
|
| 129 |
+
'base_fine',
|
| 130 |
+
'repeat_fine',
|
| 131 |
+
'section',
|
| 132 |
+
'description',
|
| 133 |
+
'note',
|
| 134 |
+
]
|
| 135 |
+
DEFAULT_OUTPUT_DIR = BACKEND_DIR / 'datasets' / 'challan'
|
| 136 |
+
RULE_SOURCE_CANDIDATES = ('violations_seed.csv', 'violations.csv')
|
| 137 |
+
OVERRIDE_SOURCE_CANDIDATES = ('state_overrides_seed.csv', 'state_overrides.csv')
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def _resolve_source(output_dir: Path, candidates: tuple[str, ...], explicit: Path | None) -> Path | None:
|
| 141 |
+
if explicit is not None:
|
| 142 |
+
return explicit
|
| 143 |
+
for name in candidates:
|
| 144 |
+
candidate = output_dir / name
|
| 145 |
+
if candidate.exists():
|
| 146 |
+
return candidate
|
| 147 |
+
for name in candidates:
|
| 148 |
+
candidate = CHATBOT_DATA_DIR / name
|
| 149 |
+
if candidate.exists():
|
| 150 |
+
return candidate
|
| 151 |
+
return None
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def _stringify(amount: int | None) -> str:
|
| 155 |
+
return '' if amount is None else str(amount)
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def _rule_to_row(rule: ChallanRule) -> dict[str, str]:
|
| 159 |
+
return {
|
| 160 |
+
'violation_code': rule.violation_code,
|
| 161 |
+
'section': rule.section,
|
| 162 |
+
'description': rule.description,
|
| 163 |
+
'base_fine': _stringify(rule.base_fines.get('default')),
|
| 164 |
+
'base_fine_2w': _stringify(rule.base_fines.get('two_wheeler')),
|
| 165 |
+
'base_fine_4w': _stringify(rule.base_fines.get('light_motor_vehicle')),
|
| 166 |
+
'base_fine_htv': _stringify(rule.base_fines.get('heavy_vehicle')),
|
| 167 |
+
'base_fine_bus': _stringify(rule.base_fines.get('bus')),
|
| 168 |
+
'repeat_fine': _stringify(rule.repeat_fines.get('default')),
|
| 169 |
+
'repeat_fine_2w': _stringify(rule.repeat_fines.get('two_wheeler')),
|
| 170 |
+
'repeat_fine_4w': _stringify(rule.repeat_fines.get('light_motor_vehicle')),
|
| 171 |
+
'repeat_fine_htv': _stringify(rule.repeat_fines.get('heavy_vehicle')),
|
| 172 |
+
'repeat_fine_bus': _stringify(rule.repeat_fines.get('bus')),
|
| 173 |
+
'aliases': '|'.join(rule.aliases),
|
| 174 |
+
}
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def _normalize_rule_row(row: dict[str, str]) -> dict[str, str] | None:
|
| 178 |
+
raw_violation_code = (
|
| 179 |
+
row.get('violation_code')
|
| 180 |
+
or row.get('code')
|
| 181 |
+
or row.get('violation')
|
| 182 |
+
or ''
|
| 183 |
+
).strip()
|
| 184 |
+
violation_code, qualifier = _split_violation_code(raw_violation_code)
|
| 185 |
+
violation_code = _normalize_violation_code(
|
| 186 |
+
violation_code
|
| 187 |
+
)
|
| 188 |
+
if not violation_code:
|
| 189 |
+
return None
|
| 190 |
+
|
| 191 |
+
section = (row.get('section') or row.get('mva_section') or '').strip() or f'Section {violation_code}'
|
| 192 |
+
description = (row.get('description') or row.get('description_en') or row.get('label') or '').strip() or 'Traffic rule violation.'
|
| 193 |
+
base_fines = _extract_fines(row, prefix='base_fine')
|
| 194 |
+
if not base_fines:
|
| 195 |
+
default_base = _parse_money(row.get('fine') or row.get('base') or row.get('amount') or '')
|
| 196 |
+
if default_base is not None:
|
| 197 |
+
base_fines['default'] = default_base
|
| 198 |
+
seed_base = _parse_money(row.get('base_fine_inr') or '')
|
| 199 |
+
seed_repeat = _parse_money(row.get('repeat_fine_inr') or '')
|
| 200 |
+
seed_vehicle_class = _normalize_seed_vehicle_class(row.get('vehicle_type') or qualifier or '')
|
| 201 |
+
if qualifier == 'REPEAT':
|
| 202 |
+
if seed_base is not None:
|
| 203 |
+
repeat_fines = {seed_vehicle_class: seed_base}
|
| 204 |
+
else:
|
| 205 |
+
repeat_fines = {}
|
| 206 |
+
else:
|
| 207 |
+
repeat_fines = _extract_fines(row, prefix='repeat_fine')
|
| 208 |
+
if seed_base is not None:
|
| 209 |
+
base_fines[seed_vehicle_class] = seed_base
|
| 210 |
+
if seed_repeat is not None:
|
| 211 |
+
repeat_fines[seed_vehicle_class] = seed_repeat
|
| 212 |
+
if not base_fines:
|
| 213 |
+
return None
|
| 214 |
+
|
| 215 |
+
if not repeat_fines:
|
| 216 |
+
default_repeat = _parse_money(row.get('repeat') or row.get('repeat_amount') or '')
|
| 217 |
+
if default_repeat is not None:
|
| 218 |
+
repeat_fines['default'] = default_repeat
|
| 219 |
+
|
| 220 |
+
aliases = [
|
| 221 |
+
item.strip().upper()
|
| 222 |
+
for item in (row.get('aliases') or row.get('alternate_codes') or '').split('|')
|
| 223 |
+
if item.strip()
|
| 224 |
+
]
|
| 225 |
+
return _rule_to_row(
|
| 226 |
+
ChallanRule(
|
| 227 |
+
violation_code=violation_code,
|
| 228 |
+
section=section,
|
| 229 |
+
description=description,
|
| 230 |
+
base_fines=base_fines,
|
| 231 |
+
repeat_fines=repeat_fines,
|
| 232 |
+
aliases=tuple(aliases),
|
| 233 |
+
)
|
| 234 |
+
)
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
def _load_rule_rows(path: Path) -> list[dict[str, str]]:
|
| 238 |
+
with path.open('r', encoding='utf-8-sig', newline='') as handle:
|
| 239 |
+
reader = csv.DictReader(handle)
|
| 240 |
+
if reader.fieldnames is None:
|
| 241 |
+
return []
|
| 242 |
+
rows_by_code: dict[str, dict[str, str]] = {}
|
| 243 |
+
for raw in reader:
|
| 244 |
+
normalized = _normalize_rule_row(raw)
|
| 245 |
+
if normalized is not None:
|
| 246 |
+
code = normalized['violation_code']
|
| 247 |
+
existing = rows_by_code.get(code)
|
| 248 |
+
rows_by_code[code] = _merge_rule_rows(existing, normalized) if existing else normalized
|
| 249 |
+
return [rows_by_code[key] for key in sorted(rows_by_code)]
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
def _normalize_override_row(row: dict[str, str]) -> dict[str, str] | None:
|
| 253 |
+
raw_state = row.get('state_code') or row.get('state') or ''
|
| 254 |
+
if not raw_state.strip():
|
| 255 |
+
return None
|
| 256 |
+
state_code = _normalize_state_code(raw_state)
|
| 257 |
+
violation_code = _normalize_violation_code(
|
| 258 |
+
row.get('violation_code')
|
| 259 |
+
or row.get('code')
|
| 260 |
+
or row.get('violation')
|
| 261 |
+
or ''
|
| 262 |
+
)
|
| 263 |
+
base_fine = _parse_money(
|
| 264 |
+
row.get('base_fine')
|
| 265 |
+
or row.get('fine')
|
| 266 |
+
or row.get('amount')
|
| 267 |
+
or row.get('override_fine')
|
| 268 |
+
or ''
|
| 269 |
+
)
|
| 270 |
+
if not violation_code or base_fine is None:
|
| 271 |
+
return None
|
| 272 |
+
|
| 273 |
+
vehicle_class = (row.get('vehicle_class') or row.get('vehicle') or '').strip()
|
| 274 |
+
normalized_vehicle_class = ''
|
| 275 |
+
if vehicle_class:
|
| 276 |
+
normalized_vehicle_class = _normalize_vehicle_class(vehicle_class)
|
| 277 |
+
|
| 278 |
+
authority = (row.get('authority') or row.get('source_title') or '').strip()
|
| 279 |
+
effective_date = (row.get('effective_date') or '').strip()
|
| 280 |
+
source_url = (row.get('source_url') or '').strip()
|
| 281 |
+
verified_on = (row.get('verified_on') or '').strip()
|
| 282 |
+
note_parts = [
|
| 283 |
+
(row.get('note') or row.get('state_override') or row.get('remarks') or '').strip(),
|
| 284 |
+
authority,
|
| 285 |
+
f'effective {effective_date}' if effective_date else '',
|
| 286 |
+
f'verified {verified_on}' if verified_on else '',
|
| 287 |
+
f'source {source_url}' if source_url else '',
|
| 288 |
+
]
|
| 289 |
+
|
| 290 |
+
return {
|
| 291 |
+
'state_code': state_code,
|
| 292 |
+
'violation_code': violation_code,
|
| 293 |
+
'vehicle_class': normalized_vehicle_class,
|
| 294 |
+
'base_fine': str(base_fine),
|
| 295 |
+
'repeat_fine': _stringify(
|
| 296 |
+
_parse_money(row.get('repeat_fine') or row.get('repeat') or row.get('repeat_amount') or '')
|
| 297 |
+
),
|
| 298 |
+
'section': (row.get('section') or '').strip(),
|
| 299 |
+
'description': (row.get('description') or row.get('description_en') or '').strip(),
|
| 300 |
+
'note': '; '.join(part for part in note_parts if part),
|
| 301 |
+
}
|
| 302 |
+
|
| 303 |
+
|
| 304 |
+
def _extract_fines(row: dict[str, str], *, prefix: str) -> dict[str, int]:
|
| 305 |
+
mapping = {
|
| 306 |
+
'two_wheeler': [f'{prefix}_2w', f'{prefix}_two_wheeler'],
|
| 307 |
+
'light_motor_vehicle': [f'{prefix}_4w', f'{prefix}_lmv', f'{prefix}_car'],
|
| 308 |
+
'heavy_vehicle': [f'{prefix}_htv', f'{prefix}_truck', f'{prefix}_heavy_vehicle'],
|
| 309 |
+
'bus': [f'{prefix}_bus', f'{prefix}_comm'],
|
| 310 |
+
'default': [prefix, f'{prefix}_default'],
|
| 311 |
+
}
|
| 312 |
+
fines: dict[str, int] = {}
|
| 313 |
+
for vehicle_class, columns in mapping.items():
|
| 314 |
+
for column in columns:
|
| 315 |
+
amount = _parse_money(row.get(column) or '')
|
| 316 |
+
if amount is not None:
|
| 317 |
+
fines[vehicle_class] = amount
|
| 318 |
+
break
|
| 319 |
+
return fines
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
def _parse_money(value: str) -> int | None:
|
| 323 |
+
if not value:
|
| 324 |
+
return None
|
| 325 |
+
normalized = re.sub(r'[^0-9]', '', value)
|
| 326 |
+
if not normalized:
|
| 327 |
+
return None
|
| 328 |
+
return int(normalized)
|
| 329 |
+
|
| 330 |
+
|
| 331 |
+
def _normalize_violation_code(value: str) -> str:
|
| 332 |
+
return re.sub(r'[^A-Z0-9/]', '', value.strip().upper())
|
| 333 |
+
|
| 334 |
+
|
| 335 |
+
def _split_violation_code(value: str) -> tuple[str, str]:
|
| 336 |
+
text = value.strip().upper()
|
| 337 |
+
if not text:
|
| 338 |
+
return '', ''
|
| 339 |
+
parts = [part for part in re.split(r'[_\-\s]+', text) if part]
|
| 340 |
+
if len(parts) == 1:
|
| 341 |
+
return parts[0], ''
|
| 342 |
+
return parts[0], parts[1]
|
| 343 |
+
|
| 344 |
+
|
| 345 |
+
def _normalize_vehicle_class(value: str) -> str:
|
| 346 |
+
normalized = re.sub(r'[^A-Z0-9_ ]', '', value.strip().upper()).replace(' ', '_')
|
| 347 |
+
if not normalized:
|
| 348 |
+
raise ValueError('vehicle_class is required')
|
| 349 |
+
return VEHICLE_CLASS_ALIASES.get(normalized, normalized.lower())
|
| 350 |
+
|
| 351 |
+
|
| 352 |
+
def _normalize_seed_vehicle_class(value: str) -> str:
|
| 353 |
+
normalized = re.sub(r'[^A-Z0-9_ ]', '', value.strip().upper()).replace(' ', '_')
|
| 354 |
+
if not normalized or normalized == 'ALL' or normalized == 'FIRST' or normalized == 'REPEAT':
|
| 355 |
+
return 'default'
|
| 356 |
+
if normalized in {'LMV', '4W', 'CAR', 'LIGHT_MOTOR_VEHICLE'}:
|
| 357 |
+
return 'light_motor_vehicle'
|
| 358 |
+
if normalized in {'HMV', 'HTV', 'HEAVY_VEHICLE', 'GOODS_VEHICLE'}:
|
| 359 |
+
return 'heavy_vehicle'
|
| 360 |
+
if normalized in {'BUS', 'SCHOOL_VEHICLE', 'TRANSPORT_VEHICLE'}:
|
| 361 |
+
return 'bus'
|
| 362 |
+
if normalized in {'2W', 'BIKE', 'MOTORCYCLE', 'TWO_WHEELER'}:
|
| 363 |
+
return 'two_wheeler'
|
| 364 |
+
return _normalize_vehicle_class(normalized)
|
| 365 |
+
|
| 366 |
+
|
| 367 |
+
def _merge_rule_rows(existing: dict[str, str], incoming: dict[str, str]) -> dict[str, str]:
|
| 368 |
+
merged = dict(existing)
|
| 369 |
+
for column in RULE_COLUMNS:
|
| 370 |
+
if column == 'aliases':
|
| 371 |
+
aliases = {
|
| 372 |
+
item.strip()
|
| 373 |
+
for item in (merged.get('aliases') or '').split('|') + (incoming.get('aliases') or '').split('|')
|
| 374 |
+
if item.strip()
|
| 375 |
+
}
|
| 376 |
+
merged['aliases'] = '|'.join(sorted(aliases))
|
| 377 |
+
continue
|
| 378 |
+
if not merged.get(column) and incoming.get(column):
|
| 379 |
+
merged[column] = incoming[column]
|
| 380 |
+
return merged
|
| 381 |
+
|
| 382 |
+
|
| 383 |
+
def _normalize_state_code(value: str) -> str:
|
| 384 |
+
cleaned = value.strip().upper()
|
| 385 |
+
if not cleaned:
|
| 386 |
+
raise ValueError('state_code is required')
|
| 387 |
+
if '(' in cleaned and ')' in cleaned:
|
| 388 |
+
inside = cleaned.split('(')[-1].split(')')[0].strip()
|
| 389 |
+
if inside:
|
| 390 |
+
cleaned = inside
|
| 391 |
+
if len(cleaned) > 2:
|
| 392 |
+
compact = re.sub(r'[^A-Z]', '', cleaned)
|
| 393 |
+
if len(compact) >= 2:
|
| 394 |
+
cleaned = compact[:2]
|
| 395 |
+
return cleaned
|
| 396 |
+
|
| 397 |
+
|
| 398 |
+
def _load_override_rows(path: Path) -> list[dict[str, str]]:
|
| 399 |
+
with path.open('r', encoding='utf-8-sig', newline='') as handle:
|
| 400 |
+
reader = csv.DictReader(handle)
|
| 401 |
+
if reader.fieldnames is None:
|
| 402 |
+
return []
|
| 403 |
+
rows: list[dict[str, str]] = []
|
| 404 |
+
for raw in reader:
|
| 405 |
+
normalized = _normalize_override_row(raw)
|
| 406 |
+
if normalized is not None:
|
| 407 |
+
rows.append(normalized)
|
| 408 |
+
return rows
|
| 409 |
+
|
| 410 |
+
|
| 411 |
+
def _write_csv(path: Path, fieldnames: list[str], rows: list[dict[str, str]]) -> None:
|
| 412 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 413 |
+
with path.open('w', encoding='utf-8', newline='') as handle:
|
| 414 |
+
writer = csv.DictWriter(handle, fieldnames=fieldnames)
|
| 415 |
+
writer.writeheader()
|
| 416 |
+
writer.writerows(rows)
|
| 417 |
+
|
| 418 |
+
|
| 419 |
+
def main() -> None:
|
| 420 |
+
parser = argparse.ArgumentParser(
|
| 421 |
+
description='Normalize challan seed data into the backend CSVs used by the challan service.',
|
| 422 |
+
)
|
| 423 |
+
parser.add_argument(
|
| 424 |
+
'--output-dir',
|
| 425 |
+
type=Path,
|
| 426 |
+
default=DEFAULT_OUTPUT_DIR,
|
| 427 |
+
help=f'Directory that receives violations.csv and state_overrides.csv. Defaults to {DEFAULT_OUTPUT_DIR}',
|
| 428 |
+
)
|
| 429 |
+
parser.add_argument(
|
| 430 |
+
'--rules-source',
|
| 431 |
+
type=Path,
|
| 432 |
+
help='Optional source CSV to normalize into violations.csv.',
|
| 433 |
+
)
|
| 434 |
+
parser.add_argument(
|
| 435 |
+
'--overrides-source',
|
| 436 |
+
type=Path,
|
| 437 |
+
help='Optional source CSV to normalize into state_overrides.csv.',
|
| 438 |
+
)
|
| 439 |
+
parser.add_argument(
|
| 440 |
+
'--defaults-only',
|
| 441 |
+
action='store_true',
|
| 442 |
+
help='Ignore source files and emit only the backend built-in challan rules.',
|
| 443 |
+
)
|
| 444 |
+
args = parser.parse_args()
|
| 445 |
+
|
| 446 |
+
output_dir = args.output_dir
|
| 447 |
+
rules_path = output_dir / 'violations.csv'
|
| 448 |
+
overrides_path = output_dir / 'state_overrides.csv'
|
| 449 |
+
|
| 450 |
+
rule_map: dict[str, dict[str, str]] = {
|
| 451 |
+
rule.violation_code: _rule_to_row(rule)
|
| 452 |
+
for rule in DEFAULT_RULES
|
| 453 |
+
}
|
| 454 |
+
|
| 455 |
+
source_rules = None if args.defaults_only else _resolve_source(output_dir, RULE_SOURCE_CANDIDATES, args.rules_source)
|
| 456 |
+
if source_rules and source_rules.exists():
|
| 457 |
+
for row in _load_rule_rows(source_rules):
|
| 458 |
+
rule_map[row['violation_code']] = row
|
| 459 |
+
|
| 460 |
+
override_rows: list[dict[str, str]] = []
|
| 461 |
+
source_overrides = None if args.defaults_only else _resolve_source(output_dir, OVERRIDE_SOURCE_CANDIDATES, args.overrides_source)
|
| 462 |
+
if source_overrides and source_overrides.exists():
|
| 463 |
+
override_rows = _load_override_rows(source_overrides)
|
| 464 |
+
|
| 465 |
+
sorted_rules = [rule_map[key] for key in sorted(rule_map)]
|
| 466 |
+
sorted_overrides = sorted(
|
| 467 |
+
override_rows,
|
| 468 |
+
key=lambda row: (row['state_code'], row['violation_code'], row['vehicle_class']),
|
| 469 |
+
)
|
| 470 |
+
|
| 471 |
+
_write_csv(rules_path, RULE_COLUMNS, sorted_rules)
|
| 472 |
+
_write_csv(overrides_path, OVERRIDE_COLUMNS, sorted_overrides)
|
| 473 |
+
|
| 474 |
+
print(
|
| 475 |
+
f'Wrote {len(sorted_rules)} challan rules to {rules_path} '
|
| 476 |
+
f'and {len(sorted_overrides)} state overrides to {overrides_path}'
|
| 477 |
+
)
|
| 478 |
+
|
| 479 |
+
|
| 480 |
+
if __name__ == '__main__':
|
| 481 |
+
main()
|
scripts/chatbot_service/data/_overpass_utils.py
ADDED
|
@@ -0,0 +1,212 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
import csv
|
| 5 |
+
import json
|
| 6 |
+
import time
|
| 7 |
+
import urllib.parse
|
| 8 |
+
import urllib.request
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
from typing import Iterable
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
ROOT_DIR = Path(__file__).resolve().parents[2]
|
| 14 |
+
CHATBOT_SERVICE_DIR = ROOT_DIR / 'chatbot_service'
|
| 15 |
+
|
| 16 |
+
DEFAULT_ENDPOINTS = (
|
| 17 |
+
'https://overpass-api.de/api/interpreter',
|
| 18 |
+
'https://overpass.kumi.systems/api/interpreter',
|
| 19 |
+
'https://lz4.overpass-api.de/api/interpreter',
|
| 20 |
+
)
|
| 21 |
+
DEFAULT_HEADERS = {
|
| 22 |
+
'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8',
|
| 23 |
+
'User-Agent': 'SafeVisionAI chatbot data fetcher/1.0',
|
| 24 |
+
}
|
| 25 |
+
CSV_COLUMNS = [
|
| 26 |
+
'name',
|
| 27 |
+
'lat',
|
| 28 |
+
'lon',
|
| 29 |
+
'phone',
|
| 30 |
+
'address',
|
| 31 |
+
'city',
|
| 32 |
+
'state',
|
| 33 |
+
'operator',
|
| 34 |
+
'osm_id',
|
| 35 |
+
'osm_type',
|
| 36 |
+
'category',
|
| 37 |
+
'opening_hours',
|
| 38 |
+
'website',
|
| 39 |
+
'email',
|
| 40 |
+
'postcode',
|
| 41 |
+
'source',
|
| 42 |
+
]
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def build_arg_parser(description: str, default_output: Path) -> argparse.ArgumentParser:
|
| 46 |
+
parser = argparse.ArgumentParser(description=description)
|
| 47 |
+
parser.add_argument(
|
| 48 |
+
'--output',
|
| 49 |
+
type=Path,
|
| 50 |
+
default=default_output,
|
| 51 |
+
help=f'CSV path to write. Defaults to {default_output}',
|
| 52 |
+
)
|
| 53 |
+
parser.add_argument(
|
| 54 |
+
'--endpoint',
|
| 55 |
+
help='Optional Overpass endpoint override. Defaults to the built-in endpoint fallback list.',
|
| 56 |
+
)
|
| 57 |
+
parser.add_argument(
|
| 58 |
+
'--timeout',
|
| 59 |
+
type=int,
|
| 60 |
+
default=180,
|
| 61 |
+
help='HTTP timeout in seconds. Defaults to 180.',
|
| 62 |
+
)
|
| 63 |
+
parser.add_argument(
|
| 64 |
+
'--retries',
|
| 65 |
+
type=int,
|
| 66 |
+
default=2,
|
| 67 |
+
help='Retries per endpoint before failing over. Defaults to 2.',
|
| 68 |
+
)
|
| 69 |
+
return parser
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def build_india_query(selectors: Iterable[str], *, timeout: int) -> str:
|
| 73 |
+
joined = '\n '.join(selector.strip() for selector in selectors if selector.strip())
|
| 74 |
+
return (
|
| 75 |
+
f'[out:json][timeout:{timeout}];\n'
|
| 76 |
+
'area["ISO3166-1"="IN"][admin_level=2]->.india;\n'
|
| 77 |
+
'(\n'
|
| 78 |
+
f' {joined}\n'
|
| 79 |
+
');\n'
|
| 80 |
+
'out center tags;'
|
| 81 |
+
)
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def fetch_elements(
|
| 85 |
+
query: str,
|
| 86 |
+
*,
|
| 87 |
+
endpoint: str | None,
|
| 88 |
+
timeout: int,
|
| 89 |
+
retries: int,
|
| 90 |
+
) -> list[dict]:
|
| 91 |
+
payload = urllib.parse.urlencode({'data': query}).encode('utf-8')
|
| 92 |
+
endpoints = [endpoint] if endpoint else list(DEFAULT_ENDPOINTS)
|
| 93 |
+
last_error: Exception | None = None
|
| 94 |
+
|
| 95 |
+
for url in endpoints:
|
| 96 |
+
for attempt in range(1, retries + 1):
|
| 97 |
+
request = urllib.request.Request(url, data=payload, headers=DEFAULT_HEADERS, method='POST')
|
| 98 |
+
try:
|
| 99 |
+
with urllib.request.urlopen(request, timeout=timeout) as response:
|
| 100 |
+
decoded = response.read().decode('utf-8')
|
| 101 |
+
data = json.loads(decoded)
|
| 102 |
+
return list(data.get('elements', []))
|
| 103 |
+
except Exception as exc: # pragma: no cover - network path
|
| 104 |
+
last_error = exc
|
| 105 |
+
if attempt < retries:
|
| 106 |
+
time.sleep(min(attempt, 3))
|
| 107 |
+
|
| 108 |
+
raise SystemExit(f'Unable to fetch data from Overpass. Last error: {last_error}')
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def extract_point(element: dict) -> tuple[float | None, float | None]:
|
| 112 |
+
if 'lat' in element and 'lon' in element:
|
| 113 |
+
return float(element['lat']), float(element['lon'])
|
| 114 |
+
|
| 115 |
+
center = element.get('center') or {}
|
| 116 |
+
if 'lat' in center and 'lon' in center:
|
| 117 |
+
return float(center['lat']), float(center['lon'])
|
| 118 |
+
|
| 119 |
+
return None, None
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def first_non_empty(*values: str | None) -> str:
|
| 123 |
+
for value in values:
|
| 124 |
+
if value is None:
|
| 125 |
+
continue
|
| 126 |
+
text = str(value).strip()
|
| 127 |
+
if text:
|
| 128 |
+
return text
|
| 129 |
+
return ''
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def compose_address(tags: dict[str, str]) -> str:
|
| 133 |
+
return first_non_empty(
|
| 134 |
+
tags.get('addr:full'),
|
| 135 |
+
', '.join(
|
| 136 |
+
part
|
| 137 |
+
for part in [
|
| 138 |
+
tags.get('addr:housenumber'),
|
| 139 |
+
tags.get('addr:street'),
|
| 140 |
+
tags.get('addr:suburb'),
|
| 141 |
+
first_non_empty(tags.get('addr:city'), tags.get('addr:town'), tags.get('addr:village')),
|
| 142 |
+
first_non_empty(tags.get('addr:district'), tags.get('addr:county')),
|
| 143 |
+
tags.get('addr:state'),
|
| 144 |
+
tags.get('addr:postcode'),
|
| 145 |
+
]
|
| 146 |
+
if part
|
| 147 |
+
),
|
| 148 |
+
)
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def normalize_row(element: dict, *, default_category: str, fallback_name: str) -> dict | None:
|
| 152 |
+
lat, lon = extract_point(element)
|
| 153 |
+
if lat is None or lon is None:
|
| 154 |
+
return None
|
| 155 |
+
|
| 156 |
+
tags = element.get('tags', {})
|
| 157 |
+
return {
|
| 158 |
+
'name': first_non_empty(tags.get('name'), fallback_name),
|
| 159 |
+
'lat': f'{lat:.6f}',
|
| 160 |
+
'lon': f'{lon:.6f}',
|
| 161 |
+
'phone': first_non_empty(tags.get('phone'), tags.get('contact:phone'), tags.get('emergency:phone')),
|
| 162 |
+
'address': compose_address(tags),
|
| 163 |
+
'city': first_non_empty(tags.get('addr:city'), tags.get('addr:town'), tags.get('addr:village')),
|
| 164 |
+
'state': first_non_empty(tags.get('addr:state')),
|
| 165 |
+
'operator': first_non_empty(tags.get('operator')),
|
| 166 |
+
'osm_id': str(element.get('id', '')),
|
| 167 |
+
'osm_type': str(element.get('type', '')),
|
| 168 |
+
'category': first_non_empty(
|
| 169 |
+
tags.get('amenity'),
|
| 170 |
+
tags.get('healthcare'),
|
| 171 |
+
tags.get('office'),
|
| 172 |
+
tags.get('emergency'),
|
| 173 |
+
default_category,
|
| 174 |
+
),
|
| 175 |
+
'opening_hours': first_non_empty(tags.get('opening_hours')),
|
| 176 |
+
'website': first_non_empty(tags.get('website'), tags.get('contact:website')),
|
| 177 |
+
'email': first_non_empty(tags.get('email'), tags.get('contact:email')),
|
| 178 |
+
'postcode': first_non_empty(tags.get('addr:postcode')),
|
| 179 |
+
'source': 'overpass',
|
| 180 |
+
}
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def dedupe_rows(rows: Iterable[dict]) -> list[dict]:
|
| 184 |
+
seen: set[tuple[str, str, str, str]] = set()
|
| 185 |
+
deduped: list[dict] = []
|
| 186 |
+
for row in rows:
|
| 187 |
+
key = (
|
| 188 |
+
row.get('name', '').strip().lower(),
|
| 189 |
+
row.get('category', '').strip().lower(),
|
| 190 |
+
row.get('lat', ''),
|
| 191 |
+
row.get('lon', ''),
|
| 192 |
+
)
|
| 193 |
+
if key in seen:
|
| 194 |
+
continue
|
| 195 |
+
seen.add(key)
|
| 196 |
+
deduped.append(row)
|
| 197 |
+
deduped.sort(key=lambda item: (item.get('state', ''), item.get('city', ''), item.get('name', '')))
|
| 198 |
+
return deduped
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
def write_rows(path: Path, rows: Iterable[dict]) -> int:
|
| 202 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 203 |
+
materialized = dedupe_rows(rows)
|
| 204 |
+
with path.open('w', newline='', encoding='utf-8') as handle:
|
| 205 |
+
writer = csv.DictWriter(handle, fieldnames=CSV_COLUMNS)
|
| 206 |
+
writer.writeheader()
|
| 207 |
+
writer.writerows(materialized)
|
| 208 |
+
return len(materialized)
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def print_summary(*, label: str, count: int, output: Path) -> None:
|
| 212 |
+
print(f'Saved {count} {label} records to {output}')
|
scripts/chatbot_service/data/fetch_ambulance.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from _overpass_utils import (
|
| 4 |
+
CHATBOT_SERVICE_DIR,
|
| 5 |
+
build_arg_parser,
|
| 6 |
+
build_india_query,
|
| 7 |
+
fetch_elements,
|
| 8 |
+
normalize_row,
|
| 9 |
+
print_summary,
|
| 10 |
+
write_rows,
|
| 11 |
+
)
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
DEFAULT_OUTPUT = CHATBOT_SERVICE_DIR / 'data' / 'emergency' / 'ambulance_stations.csv'
|
| 15 |
+
SELECTORS = [
|
| 16 |
+
'node["emergency"="ambulance_station"](area.india);',
|
| 17 |
+
'way["emergency"="ambulance_station"](area.india);',
|
| 18 |
+
'relation["emergency"="ambulance_station"](area.india);',
|
| 19 |
+
'node["amenity"="ambulance_station"](area.india);',
|
| 20 |
+
'way["amenity"="ambulance_station"](area.india);',
|
| 21 |
+
'relation["amenity"="ambulance_station"](area.india);',
|
| 22 |
+
'node["healthcare"="ambulance_station"](area.india);',
|
| 23 |
+
'way["healthcare"="ambulance_station"](area.india);',
|
| 24 |
+
'relation["healthcare"="ambulance_station"](area.india);',
|
| 25 |
+
]
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def main() -> None:
|
| 29 |
+
parser = build_arg_parser('Fetch India ambulance station data from Overpass.', DEFAULT_OUTPUT)
|
| 30 |
+
args = parser.parse_args()
|
| 31 |
+
|
| 32 |
+
query = build_india_query(SELECTORS, timeout=args.timeout)
|
| 33 |
+
elements = fetch_elements(query, endpoint=args.endpoint, timeout=args.timeout, retries=args.retries)
|
| 34 |
+
rows = [
|
| 35 |
+
row
|
| 36 |
+
for element in elements
|
| 37 |
+
if (row := normalize_row(element, default_category='ambulance', fallback_name='Unnamed ambulance station')) is not None
|
| 38 |
+
]
|
| 39 |
+
count = write_rows(args.output, rows)
|
| 40 |
+
print_summary(label='ambulance station', count=count, output=args.output)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
if __name__ == '__main__':
|
| 44 |
+
main()
|
scripts/chatbot_service/data/fetch_blood_banks.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from _overpass_utils import (
|
| 4 |
+
CHATBOT_SERVICE_DIR,
|
| 5 |
+
build_arg_parser,
|
| 6 |
+
build_india_query,
|
| 7 |
+
fetch_elements,
|
| 8 |
+
normalize_row,
|
| 9 |
+
print_summary,
|
| 10 |
+
write_rows,
|
| 11 |
+
)
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
DEFAULT_OUTPUT = CHATBOT_SERVICE_DIR / 'data' / 'hospitals' / 'blood_bank_directory.csv'
|
| 15 |
+
SELECTORS = [
|
| 16 |
+
'node["amenity"="blood_bank"](area.india);',
|
| 17 |
+
'way["amenity"="blood_bank"](area.india);',
|
| 18 |
+
'relation["amenity"="blood_bank"](area.india);',
|
| 19 |
+
'node["healthcare"="blood_bank"](area.india);',
|
| 20 |
+
'way["healthcare"="blood_bank"](area.india);',
|
| 21 |
+
'relation["healthcare"="blood_bank"](area.india);',
|
| 22 |
+
'node["blood_bank"="yes"](area.india);',
|
| 23 |
+
'way["blood_bank"="yes"](area.india);',
|
| 24 |
+
'relation["blood_bank"="yes"](area.india);',
|
| 25 |
+
]
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def main() -> None:
|
| 29 |
+
parser = build_arg_parser('Fetch India blood bank data from Overpass.', DEFAULT_OUTPUT)
|
| 30 |
+
args = parser.parse_args()
|
| 31 |
+
|
| 32 |
+
query = build_india_query(SELECTORS, timeout=args.timeout)
|
| 33 |
+
elements = fetch_elements(query, endpoint=args.endpoint, timeout=args.timeout, retries=args.retries)
|
| 34 |
+
rows = [
|
| 35 |
+
row
|
| 36 |
+
for element in elements
|
| 37 |
+
if (row := normalize_row(element, default_category='blood_bank', fallback_name='Unnamed blood bank')) is not None
|
| 38 |
+
]
|
| 39 |
+
count = write_rows(args.output, rows)
|
| 40 |
+
print_summary(label='blood bank', count=count, output=args.output)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
if __name__ == '__main__':
|
| 44 |
+
main()
|
scripts/chatbot_service/data/fetch_fire.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from _overpass_utils import (
|
| 4 |
+
CHATBOT_SERVICE_DIR,
|
| 5 |
+
build_arg_parser,
|
| 6 |
+
build_india_query,
|
| 7 |
+
fetch_elements,
|
| 8 |
+
normalize_row,
|
| 9 |
+
print_summary,
|
| 10 |
+
write_rows,
|
| 11 |
+
)
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
DEFAULT_OUTPUT = CHATBOT_SERVICE_DIR / 'data' / 'emergency' / 'fire_stations.csv'
|
| 15 |
+
SELECTORS = [
|
| 16 |
+
'node["amenity"="fire_station"](area.india);',
|
| 17 |
+
'way["amenity"="fire_station"](area.india);',
|
| 18 |
+
'relation["amenity"="fire_station"](area.india);',
|
| 19 |
+
]
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def main() -> None:
|
| 23 |
+
parser = build_arg_parser('Fetch India fire station data from Overpass.', DEFAULT_OUTPUT)
|
| 24 |
+
args = parser.parse_args()
|
| 25 |
+
|
| 26 |
+
query = build_india_query(SELECTORS, timeout=args.timeout)
|
| 27 |
+
elements = fetch_elements(query, endpoint=args.endpoint, timeout=args.timeout, retries=args.retries)
|
| 28 |
+
rows = [
|
| 29 |
+
row
|
| 30 |
+
for element in elements
|
| 31 |
+
if (row := normalize_row(element, default_category='fire_station', fallback_name='Unnamed fire station')) is not None
|
| 32 |
+
]
|
| 33 |
+
count = write_rows(args.output, rows)
|
| 34 |
+
print_summary(label='fire service', count=count, output=args.output)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
if __name__ == '__main__':
|
| 38 |
+
main()
|
scripts/chatbot_service/data/fetch_hospitals.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from _overpass_utils import (
|
| 4 |
+
CHATBOT_SERVICE_DIR,
|
| 5 |
+
build_arg_parser,
|
| 6 |
+
build_india_query,
|
| 7 |
+
fetch_elements,
|
| 8 |
+
normalize_row,
|
| 9 |
+
print_summary,
|
| 10 |
+
write_rows,
|
| 11 |
+
)
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
DEFAULT_OUTPUT = CHATBOT_SERVICE_DIR / 'data' / 'hospitals' / 'hospital_directory.csv'
|
| 15 |
+
SELECTORS = [
|
| 16 |
+
'node["amenity"~"hospital|clinic"](area.india);',
|
| 17 |
+
'way["amenity"~"hospital|clinic"](area.india);',
|
| 18 |
+
'relation["amenity"~"hospital|clinic"](area.india);',
|
| 19 |
+
'node["healthcare"~"hospital|clinic"](area.india);',
|
| 20 |
+
'way["healthcare"~"hospital|clinic"](area.india);',
|
| 21 |
+
'relation["healthcare"~"hospital|clinic"](area.india);',
|
| 22 |
+
]
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def main() -> None:
|
| 26 |
+
parser = build_arg_parser('Fetch India hospital and clinic data from Overpass.', DEFAULT_OUTPUT)
|
| 27 |
+
args = parser.parse_args()
|
| 28 |
+
|
| 29 |
+
query = build_india_query(SELECTORS, timeout=args.timeout)
|
| 30 |
+
elements = fetch_elements(query, endpoint=args.endpoint, timeout=args.timeout, retries=args.retries)
|
| 31 |
+
rows = [
|
| 32 |
+
row
|
| 33 |
+
for element in elements
|
| 34 |
+
if (row := normalize_row(element, default_category='hospital', fallback_name='Unnamed hospital')) is not None
|
| 35 |
+
]
|
| 36 |
+
count = write_rows(args.output, rows)
|
| 37 |
+
print_summary(label='hospital', count=count, output=args.output)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
if __name__ == '__main__':
|
| 41 |
+
main()
|
scripts/chatbot_service/data/fetch_police.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from _overpass_utils import (
|
| 4 |
+
CHATBOT_SERVICE_DIR,
|
| 5 |
+
build_arg_parser,
|
| 6 |
+
build_india_query,
|
| 7 |
+
fetch_elements,
|
| 8 |
+
normalize_row,
|
| 9 |
+
print_summary,
|
| 10 |
+
write_rows,
|
| 11 |
+
)
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
DEFAULT_OUTPUT = CHATBOT_SERVICE_DIR / 'data' / 'emergency' / 'police_stations.csv'
|
| 15 |
+
SELECTORS = [
|
| 16 |
+
'node["amenity"="police"](area.india);',
|
| 17 |
+
'way["amenity"="police"](area.india);',
|
| 18 |
+
'relation["amenity"="police"](area.india);',
|
| 19 |
+
'node["office"="police"](area.india);',
|
| 20 |
+
'way["office"="police"](area.india);',
|
| 21 |
+
'relation["office"="police"](area.india);',
|
| 22 |
+
]
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def main() -> None:
|
| 26 |
+
parser = build_arg_parser('Fetch India police station data from Overpass.', DEFAULT_OUTPUT)
|
| 27 |
+
args = parser.parse_args()
|
| 28 |
+
|
| 29 |
+
query = build_india_query(SELECTORS, timeout=args.timeout)
|
| 30 |
+
elements = fetch_elements(query, endpoint=args.endpoint, timeout=args.timeout, retries=args.retries)
|
| 31 |
+
rows = [
|
| 32 |
+
row
|
| 33 |
+
for element in elements
|
| 34 |
+
if (row := normalize_row(element, default_category='police', fallback_name='Unnamed police station')) is not None
|
| 35 |
+
]
|
| 36 |
+
count = write_rows(args.output, rows)
|
| 37 |
+
print_summary(label='police station', count=count, output=args.output)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
if __name__ == '__main__':
|
| 41 |
+
main()
|
scripts/scripts/data/_overpass_utils.py
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
import csv
|
| 5 |
+
import json
|
| 6 |
+
import urllib.parse
|
| 7 |
+
import urllib.request
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
from typing import Iterable
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
ROOT_DIR = Path(__file__).resolve().parents[1]
|
| 13 |
+
DEFAULT_ENDPOINTS = (
|
| 14 |
+
'https://overpass-api.de/api/interpreter',
|
| 15 |
+
'https://overpass.kumi.systems/api/interpreter',
|
| 16 |
+
'https://lz4.overpass-api.de/api/interpreter',
|
| 17 |
+
)
|
| 18 |
+
DEFAULT_HEADERS = {
|
| 19 |
+
'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8',
|
| 20 |
+
'User-Agent': 'SafeVisionAI bootstrap scripts/1.0',
|
| 21 |
+
}
|
| 22 |
+
CSV_COLUMNS = [
|
| 23 |
+
'osm_id',
|
| 24 |
+
'osm_type',
|
| 25 |
+
'name',
|
| 26 |
+
'lat',
|
| 27 |
+
'lon',
|
| 28 |
+
'phone',
|
| 29 |
+
'type',
|
| 30 |
+
'city',
|
| 31 |
+
'state',
|
| 32 |
+
'address',
|
| 33 |
+
'opening_hours',
|
| 34 |
+
'website',
|
| 35 |
+
'source',
|
| 36 |
+
]
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def build_arg_parser(description: str, default_output: Path) -> argparse.ArgumentParser:
|
| 40 |
+
parser = argparse.ArgumentParser(description=description)
|
| 41 |
+
parser.add_argument(
|
| 42 |
+
'--output',
|
| 43 |
+
type=Path,
|
| 44 |
+
default=default_output,
|
| 45 |
+
help=f'CSV path to write. Defaults to {default_output}',
|
| 46 |
+
)
|
| 47 |
+
parser.add_argument(
|
| 48 |
+
'--endpoint',
|
| 49 |
+
help='Optional Overpass endpoint override. Defaults to a built-in fallback list.',
|
| 50 |
+
)
|
| 51 |
+
parser.add_argument(
|
| 52 |
+
'--timeout',
|
| 53 |
+
type=int,
|
| 54 |
+
default=300,
|
| 55 |
+
help='HTTP timeout in seconds. Defaults to 300.',
|
| 56 |
+
)
|
| 57 |
+
return parser
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def build_india_query(selectors: Iterable[str], *, timeout: int) -> str:
|
| 61 |
+
joined_selectors = '\n '.join(selector.strip() for selector in selectors if selector.strip())
|
| 62 |
+
return (
|
| 63 |
+
f'[out:json][timeout:{timeout}];\n'
|
| 64 |
+
'area["ISO3166-1"="IN"][admin_level=2]->.searchArea;\n'
|
| 65 |
+
'(\n'
|
| 66 |
+
f' {joined_selectors}\n'
|
| 67 |
+
');\n'
|
| 68 |
+
'out center tags;'
|
| 69 |
+
)
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def fetch_elements(query: str, *, endpoint: str | None, timeout: int) -> list[dict]:
|
| 73 |
+
payload = urllib.parse.urlencode({'data': query}).encode('utf-8')
|
| 74 |
+
endpoints = [endpoint] if endpoint else list(DEFAULT_ENDPOINTS)
|
| 75 |
+
last_error: Exception | None = None
|
| 76 |
+
|
| 77 |
+
for url in endpoints:
|
| 78 |
+
request = urllib.request.Request(url, data=payload, headers=DEFAULT_HEADERS, method='POST')
|
| 79 |
+
try:
|
| 80 |
+
with urllib.request.urlopen(request, timeout=timeout) as response:
|
| 81 |
+
decoded = response.read().decode('utf-8')
|
| 82 |
+
data = json.loads(decoded)
|
| 83 |
+
return list(data.get('elements', []))
|
| 84 |
+
except Exception as exc: # pragma: no cover - network failure path
|
| 85 |
+
last_error = exc
|
| 86 |
+
|
| 87 |
+
raise SystemExit(f'Unable to fetch data from Overpass. Last error: {last_error}')
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def extract_point(element: dict) -> tuple[float | None, float | None]:
|
| 91 |
+
if 'lat' in element and 'lon' in element:
|
| 92 |
+
return float(element['lat']), float(element['lon'])
|
| 93 |
+
|
| 94 |
+
center = element.get('center') or {}
|
| 95 |
+
if 'lat' in center and 'lon' in center:
|
| 96 |
+
return float(center['lat']), float(center['lon'])
|
| 97 |
+
|
| 98 |
+
return None, None
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def compose_address(tags: dict[str, str]) -> str:
|
| 102 |
+
parts = [
|
| 103 |
+
tags.get('addr:housenumber'),
|
| 104 |
+
tags.get('addr:street'),
|
| 105 |
+
tags.get('addr:suburb'),
|
| 106 |
+
tags.get('addr:city') or tags.get('addr:town') or tags.get('addr:village'),
|
| 107 |
+
tags.get('addr:state'),
|
| 108 |
+
]
|
| 109 |
+
return ', '.join(part for part in parts if part)
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def normalize_row(element: dict, *, default_type: str, fallback_name: str) -> dict | None:
|
| 113 |
+
lat, lon = extract_point(element)
|
| 114 |
+
if lat is None or lon is None:
|
| 115 |
+
return None
|
| 116 |
+
|
| 117 |
+
tags = element.get('tags', {})
|
| 118 |
+
amenity_type = tags.get('amenity') or tags.get('healthcare') or tags.get('emergency') or default_type
|
| 119 |
+
return {
|
| 120 |
+
'osm_id': str(element.get('id', '')),
|
| 121 |
+
'osm_type': str(element.get('type', '')),
|
| 122 |
+
'name': tags.get('name') or fallback_name,
|
| 123 |
+
'lat': f'{lat:.6f}',
|
| 124 |
+
'lon': f'{lon:.6f}',
|
| 125 |
+
'phone': tags.get('phone') or tags.get('contact:phone') or tags.get('emergency:phone') or '',
|
| 126 |
+
'type': amenity_type,
|
| 127 |
+
'city': tags.get('addr:city') or tags.get('addr:town') or tags.get('addr:village') or '',
|
| 128 |
+
'state': tags.get('addr:state') or '',
|
| 129 |
+
'address': compose_address(tags),
|
| 130 |
+
'opening_hours': tags.get('opening_hours') or '',
|
| 131 |
+
'website': tags.get('website') or tags.get('contact:website') or '',
|
| 132 |
+
'source': 'overpass',
|
| 133 |
+
}
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def dedupe_rows(rows: Iterable[dict]) -> list[dict]:
|
| 137 |
+
seen: set[tuple[str, str, str, str]] = set()
|
| 138 |
+
deduped: list[dict] = []
|
| 139 |
+
for row in rows:
|
| 140 |
+
key = (
|
| 141 |
+
row.get('name', '').strip().lower(),
|
| 142 |
+
row.get('type', '').strip().lower(),
|
| 143 |
+
row.get('lat', ''),
|
| 144 |
+
row.get('lon', ''),
|
| 145 |
+
)
|
| 146 |
+
if key in seen:
|
| 147 |
+
continue
|
| 148 |
+
seen.add(key)
|
| 149 |
+
deduped.append(row)
|
| 150 |
+
deduped.sort(key=lambda item: (item['state'], item['city'], item['name']))
|
| 151 |
+
return deduped
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def write_rows(path: Path, rows: Iterable[dict]) -> int:
|
| 155 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 156 |
+
materialized = dedupe_rows(rows)
|
| 157 |
+
with path.open('w', newline='', encoding='utf-8') as handle:
|
| 158 |
+
writer = csv.DictWriter(handle, fieldnames=CSV_COLUMNS)
|
| 159 |
+
writer.writeheader()
|
| 160 |
+
writer.writerows(materialized)
|
| 161 |
+
return len(materialized)
|
scripts/scripts/data/audit_env.py
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Full audit of all .env files vs what the configs actually expect."""
|
| 2 |
+
import re
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
|
| 5 |
+
ROOT = Path(".")
|
| 6 |
+
|
| 7 |
+
# ── 1. Read all actual .env files ────────────────────────────────────────────
|
| 8 |
+
print("=" * 70)
|
| 9 |
+
print(" ALL ENV FILES — CURRENT STATE")
|
| 10 |
+
print("=" * 70)
|
| 11 |
+
env_files = {}
|
| 12 |
+
for f in sorted(ROOT.rglob(".env*")):
|
| 13 |
+
if any(x in f.parts for x in [".git", "node_modules", ".venv", "__pycache__"]):
|
| 14 |
+
continue
|
| 15 |
+
if f.suffix in (".example", ".local", ".bak"):
|
| 16 |
+
continue
|
| 17 |
+
lines = f.read_text(encoding="utf-8", errors="ignore").splitlines()
|
| 18 |
+
keys = {}
|
| 19 |
+
for line in lines:
|
| 20 |
+
line = line.strip()
|
| 21 |
+
if line and not line.startswith("#") and "=" in line:
|
| 22 |
+
k, _, v = line.partition("=")
|
| 23 |
+
keys[k.strip()] = v.strip()
|
| 24 |
+
env_files[str(f)] = keys
|
| 25 |
+
print(f"\n[{f}]")
|
| 26 |
+
for k, v in keys.items():
|
| 27 |
+
masked = v[:6] + "..." if len(v) > 10 and any(c in k.upper() for c in ["KEY", "TOKEN", "SECRET", "PASSWORD"]) else v
|
| 28 |
+
status = "OK" if v and not v.startswith("YOUR_") else "MISSING/PLACEHOLDER"
|
| 29 |
+
print(f" [{status:^19}] {k} = {masked}")
|
| 30 |
+
|
| 31 |
+
# ── 2. What does chatbot_service/config.py expect? ────────────────────────────
|
| 32 |
+
print("\n" + "=" * 70)
|
| 33 |
+
print(" CHATBOT CONFIG — EXPECTED KEYS")
|
| 34 |
+
print("=" * 70)
|
| 35 |
+
cs_config = Path("chatbot_service/config.py").read_text(encoding="utf-8")
|
| 36 |
+
|
| 37 |
+
# Extract field names and env aliases from pydantic Settings
|
| 38 |
+
field_pattern = re.compile(r'(\w+)\s*:\s*[\w\|\[\]]+[^\n]*=\s*Field\(')
|
| 39 |
+
alias_pattern = re.compile(r'validation_alias\s*=\s*["\']([A-Z_]+)["\']')
|
| 40 |
+
|
| 41 |
+
chatbot_keys = set(re.findall(r'["\']([A-Z_][A-Z0-9_]+)["\']', cs_config))
|
| 42 |
+
chatbot_keys.update(re.findall(r'os\.(?:environ|getenv)\(["\']([A-Z_]+)', cs_config))
|
| 43 |
+
|
| 44 |
+
chatbot_env = env_files.get("chatbot_service\\.env", env_files.get("chatbot_service/.env", {}))
|
| 45 |
+
if not chatbot_env:
|
| 46 |
+
for k in env_files:
|
| 47 |
+
if "chatbot_service" in k and ".example" not in k:
|
| 48 |
+
chatbot_env = env_files[k]
|
| 49 |
+
break
|
| 50 |
+
|
| 51 |
+
missing_chatbot = []
|
| 52 |
+
for key in sorted(chatbot_keys):
|
| 53 |
+
if len(key) < 4:
|
| 54 |
+
continue
|
| 55 |
+
in_env = key in chatbot_env
|
| 56 |
+
val = chatbot_env.get(key, "")
|
| 57 |
+
is_placeholder = val.startswith("YOUR_") or not val
|
| 58 |
+
if not in_env or is_placeholder:
|
| 59 |
+
missing_chatbot.append((key, "MISSING" if not in_env else "PLACEHOLDER"))
|
| 60 |
+
|
| 61 |
+
if missing_chatbot:
|
| 62 |
+
for k, status in missing_chatbot:
|
| 63 |
+
print(f" [!] {k}: {status}")
|
| 64 |
+
else:
|
| 65 |
+
print(" All expected keys present.")
|
| 66 |
+
|
| 67 |
+
# ── 3. What does backend/core/config.py expect? ────────────────────────────────
|
| 68 |
+
print("\n" + "=" * 70)
|
| 69 |
+
print(" BACKEND CONFIG — EXPECTED KEYS")
|
| 70 |
+
print("=" * 70)
|
| 71 |
+
be_config = Path("backend/core/config.py").read_text(encoding="utf-8")
|
| 72 |
+
backend_keys = set(re.findall(r'["\']([A-Z_][A-Z0-9_]+)["\']', be_config))
|
| 73 |
+
backend_keys.update(re.findall(r'os\.(?:environ|getenv)\(["\']([A-Z_]+)', be_config))
|
| 74 |
+
|
| 75 |
+
backend_env = {}
|
| 76 |
+
for k in env_files:
|
| 77 |
+
if "backend" in k and "chatbot" not in k and ".example" not in k:
|
| 78 |
+
backend_env = env_files[k]
|
| 79 |
+
break
|
| 80 |
+
|
| 81 |
+
missing_backend = []
|
| 82 |
+
for key in sorted(backend_keys):
|
| 83 |
+
if len(key) < 4:
|
| 84 |
+
continue
|
| 85 |
+
in_env = key in backend_env
|
| 86 |
+
val = backend_env.get(key, "")
|
| 87 |
+
is_placeholder = val.startswith("YOUR_") or not val
|
| 88 |
+
if not in_env or is_placeholder:
|
| 89 |
+
missing_backend.append((key, "MISSING" if not in_env else "PLACEHOLDER"))
|
| 90 |
+
|
| 91 |
+
if missing_backend:
|
| 92 |
+
for k, status in missing_backend:
|
| 93 |
+
print(f" [!] {k}: {status}")
|
| 94 |
+
else:
|
| 95 |
+
print(" All expected keys present.")
|
| 96 |
+
|
| 97 |
+
# ── 4. Frontend env check ────────────────────────────────────────────────────
|
| 98 |
+
print("\n" + "=" * 70)
|
| 99 |
+
print(" FRONTEND .env — EXPECTED KEYS")
|
| 100 |
+
print("=" * 70)
|
| 101 |
+
# Scan all .ts/.tsx files for process.env or NEXT_PUBLIC_ usage
|
| 102 |
+
fe_keys = set()
|
| 103 |
+
for f in Path("frontend").rglob("*.ts"):
|
| 104 |
+
if "node_modules" in f.parts:
|
| 105 |
+
continue
|
| 106 |
+
txt = f.read_text(encoding="utf-8", errors="ignore")
|
| 107 |
+
fe_keys.update(re.findall(r'process\.env\.([A-Z_][A-Z0-9_]+)', txt))
|
| 108 |
+
fe_keys.update(re.findall(r'process\.env\[["\']([A-Z_][A-Z0-9_]+)', txt))
|
| 109 |
+
|
| 110 |
+
fe_env = {}
|
| 111 |
+
for k in env_files:
|
| 112 |
+
if "frontend" in k and ".example" not in k:
|
| 113 |
+
fe_env = env_files[k]
|
| 114 |
+
break
|
| 115 |
+
|
| 116 |
+
if fe_keys:
|
| 117 |
+
for key in sorted(fe_keys):
|
| 118 |
+
val = fe_env.get(key, "")
|
| 119 |
+
status = "OK" if val and not val.startswith("YOUR_") else "MISSING"
|
| 120 |
+
print(f" [{status}] {key} = {val or '(not set)'}")
|
| 121 |
+
else:
|
| 122 |
+
print(" No process.env usage found in frontend TypeScript files.")
|
| 123 |
+
|
| 124 |
+
print("\n" + "=" * 70)
|
| 125 |
+
print(" SUMMARY")
|
| 126 |
+
print("=" * 70)
|
| 127 |
+
print(f" Chatbot missing/placeholder: {len(missing_chatbot)} keys")
|
| 128 |
+
print(f" Backend missing/placeholder: {len(missing_backend)} keys")
|
scripts/scripts/data/bootstrap_local_data.py
ADDED
|
@@ -0,0 +1,557 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
import csv
|
| 5 |
+
from io import BytesIO
|
| 6 |
+
import json
|
| 7 |
+
import math
|
| 8 |
+
import shutil
|
| 9 |
+
import struct
|
| 10 |
+
import sys
|
| 11 |
+
import tempfile
|
| 12 |
+
import zipfile
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
PROJECT_ROOT = Path(__file__).resolve().parents[1]
|
| 17 |
+
BACKEND_ROOT = PROJECT_ROOT / 'backend'
|
| 18 |
+
|
| 19 |
+
import importlib.util as _ilu
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def _load_backend_module(rel_path: str, module_name: str):
|
| 23 |
+
"""Load a module from backend/ by explicit file path and register it in
|
| 24 |
+
sys.modules under *module_name*. This makes the import fully transparent
|
| 25 |
+
to Pylance/Pyright (no opaque sys.path mutation) while still satisfying
|
| 26 |
+
Python internals that need __module__ to be resolvable (e.g. dataclasses
|
| 27 |
+
with slots=True)."""
|
| 28 |
+
abs_path = BACKEND_ROOT / rel_path
|
| 29 |
+
spec = _ilu.spec_from_file_location(module_name, abs_path)
|
| 30 |
+
mod = _ilu.module_from_spec(spec) # type: ignore[arg-type]
|
| 31 |
+
sys.modules[module_name] = mod # register BEFORE exec so __module__ resolves
|
| 32 |
+
spec.loader.exec_module(mod) # type: ignore[union-attr]
|
| 33 |
+
return mod
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
_seed_viol = _load_backend_module("scripts/seed_violations.py", "scripts.seed_violations")
|
| 37 |
+
DEFAULT_RULES = _seed_viol.DEFAULT_RULES
|
| 38 |
+
OVERRIDE_COLUMNS = _seed_viol.OVERRIDE_COLUMNS
|
| 39 |
+
RULE_COLUMNS = _seed_viol.RULE_COLUMNS
|
| 40 |
+
_load_override_rows = _seed_viol._load_override_rows
|
| 41 |
+
_load_rule_rows = _seed_viol._load_rule_rows
|
| 42 |
+
_rule_to_row = _seed_viol._rule_to_row
|
| 43 |
+
_write_csv = _seed_viol._write_csv
|
| 44 |
+
|
| 45 |
+
_emerg_catalog = _load_backend_module("services/local_emergency_catalog.py", "services.local_emergency_catalog")
|
| 46 |
+
load_local_emergency_catalog = _emerg_catalog.load_local_emergency_catalog
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
CHATBOT_DATA_DIR = PROJECT_ROOT / 'chatbot_service' / 'data'
|
| 51 |
+
FRONTEND_OFFLINE_DIR = PROJECT_ROOT / 'frontend' / 'public' / 'offline-data'
|
| 52 |
+
BACKEND_CHALLAN_DIR = PROJECT_ROOT / 'backend' / 'datasets' / 'challan'
|
| 53 |
+
ROADS_DIR = CHATBOT_DATA_DIR / 'roads'
|
| 54 |
+
PMGSY_MAX_POINTS_PER_SEGMENT = 24
|
| 55 |
+
|
| 56 |
+
OFFLINE_CITY_CENTERS: dict[str, tuple[float, float]] = {
|
| 57 |
+
'chennai': (13.0827, 80.2707),
|
| 58 |
+
'coimbatore': (11.0168, 76.9558),
|
| 59 |
+
'madurai': (9.9252, 78.1198),
|
| 60 |
+
'thiruvananthapuram': (8.5241, 76.9366),
|
| 61 |
+
'kochi': (9.9312, 76.2673),
|
| 62 |
+
'bengaluru': (12.9716, 77.5946),
|
| 63 |
+
'mumbai': (19.0760, 72.8777),
|
| 64 |
+
'pune': (18.5204, 73.8567),
|
| 65 |
+
'nagpur': (21.1458, 79.0882),
|
| 66 |
+
'hyderabad': (17.3850, 78.4867),
|
| 67 |
+
'delhi': (28.6139, 77.2090),
|
| 68 |
+
'jaipur': (26.9124, 75.7873),
|
| 69 |
+
'ahmedabad': (23.0225, 72.5714),
|
| 70 |
+
'surat': (21.1702, 72.8311),
|
| 71 |
+
'vadodara': (22.3072, 73.1812),
|
| 72 |
+
'kolkata': (22.5726, 88.3639),
|
| 73 |
+
'patna': (25.5941, 85.1376),
|
| 74 |
+
'bhopal': (23.2599, 77.4126),
|
| 75 |
+
'indore': (22.7196, 75.8577),
|
| 76 |
+
'lucknow': (26.8467, 80.9462),
|
| 77 |
+
'agra': (27.1767, 78.0081),
|
| 78 |
+
'varanasi': (25.3176, 82.9739),
|
| 79 |
+
'chandigarh': (30.7333, 76.7794),
|
| 80 |
+
'visakhapatnam': (17.6868, 83.2185),
|
| 81 |
+
'bhubaneswar': (20.2961, 85.8245),
|
| 82 |
+
}
|
| 83 |
+
CITY_RADIUS_METERS = 80_000
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def sync_challan_assets() -> None:
|
| 87 |
+
rules_source = CHATBOT_DATA_DIR / 'violations_seed.csv'
|
| 88 |
+
overrides_source = CHATBOT_DATA_DIR / 'state_overrides.csv'
|
| 89 |
+
rule_map = {rule.violation_code: _rule_to_row(rule) for rule in DEFAULT_RULES}
|
| 90 |
+
if rules_source.exists():
|
| 91 |
+
for row in _load_rule_rows(rules_source):
|
| 92 |
+
rule_map[row['violation_code']] = row
|
| 93 |
+
override_rows = _load_override_rows(overrides_source) if overrides_source.exists() else []
|
| 94 |
+
|
| 95 |
+
sorted_rules = [rule_map[key] for key in sorted(rule_map)]
|
| 96 |
+
sorted_overrides = sorted(
|
| 97 |
+
override_rows,
|
| 98 |
+
key=lambda row: (row['state_code'], row['violation_code'], row['vehicle_class']),
|
| 99 |
+
)
|
| 100 |
+
|
| 101 |
+
BACKEND_CHALLAN_DIR.mkdir(parents=True, exist_ok=True)
|
| 102 |
+
FRONTEND_OFFLINE_DIR.mkdir(parents=True, exist_ok=True)
|
| 103 |
+
_write_csv(BACKEND_CHALLAN_DIR / 'violations.csv', RULE_COLUMNS, sorted_rules)
|
| 104 |
+
_write_csv(BACKEND_CHALLAN_DIR / 'state_overrides.csv', OVERRIDE_COLUMNS, sorted_overrides)
|
| 105 |
+
_write_csv(FRONTEND_OFFLINE_DIR / 'violations.csv', RULE_COLUMNS, sorted_rules)
|
| 106 |
+
_write_csv(FRONTEND_OFFLINE_DIR / 'state_overrides.csv', OVERRIDE_COLUMNS, sorted_overrides)
|
| 107 |
+
print(f'Challan assets synced: rules={len(sorted_rules)} overrides={len(sorted_overrides)}')
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def sync_first_aid_bundle() -> None:
|
| 111 |
+
"""Always sync first-aid.json from frontend (canonical 20-article source) to chatbot data.
|
| 112 |
+
|
| 113 |
+
The chatbot_service/data/first_aid.json was historically only 4 entries.
|
| 114 |
+
The frontend/public/offline-data/first-aid.json contains the full 20 WHO-based articles
|
| 115 |
+
and is the ground truth. This function overwrites unconditionally so the chatbot is never
|
| 116 |
+
left with the stale 4-entry version.
|
| 117 |
+
"""
|
| 118 |
+
source = FRONTEND_OFFLINE_DIR / 'first-aid.json'
|
| 119 |
+
target = CHATBOT_DATA_DIR / 'first_aid.json'
|
| 120 |
+
if not source.exists():
|
| 121 |
+
print(f'WARNING: first-aid.json source not found at {source} — skipping sync')
|
| 122 |
+
return
|
| 123 |
+
shutil.copyfile(source, target)
|
| 124 |
+
print(f'Synced first aid bundle ({source.stat().st_size:,} bytes) -> {target}')
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def build_emergency_geojson() -> None:
|
| 128 |
+
catalog = load_local_emergency_catalog(PROJECT_ROOT)
|
| 129 |
+
features = []
|
| 130 |
+
for entry in catalog:
|
| 131 |
+
city, distance = _nearest_city(entry.lat, entry.lon)
|
| 132 |
+
if city is None or distance > CITY_RADIUS_METERS:
|
| 133 |
+
continue
|
| 134 |
+
features.append(
|
| 135 |
+
{
|
| 136 |
+
'type': 'Feature',
|
| 137 |
+
'id': entry.id,
|
| 138 |
+
'geometry': {'type': 'Point', 'coordinates': [entry.lon, entry.lat]},
|
| 139 |
+
'properties': {
|
| 140 |
+
'city': city.title(),
|
| 141 |
+
'name': entry.name,
|
| 142 |
+
'category': entry.category,
|
| 143 |
+
'sub_category': entry.sub_category,
|
| 144 |
+
'phone': entry.phone,
|
| 145 |
+
'phone_emergency': entry.phone_emergency,
|
| 146 |
+
'address': entry.address,
|
| 147 |
+
'has_trauma': entry.has_trauma,
|
| 148 |
+
'has_icu': entry.has_icu,
|
| 149 |
+
'is_24hr': entry.is_24hr,
|
| 150 |
+
'source': entry.source,
|
| 151 |
+
},
|
| 152 |
+
}
|
| 153 |
+
)
|
| 154 |
+
|
| 155 |
+
payload = {
|
| 156 |
+
'type': 'FeatureCollection',
|
| 157 |
+
'properties': {
|
| 158 |
+
'generated_from': 'chatbot_service/data local CSV catalog',
|
| 159 |
+
'feature_count': len(features),
|
| 160 |
+
'cities': [city.title() for city in OFFLINE_CITY_CENTERS],
|
| 161 |
+
},
|
| 162 |
+
'features': features,
|
| 163 |
+
}
|
| 164 |
+
output_path = FRONTEND_OFFLINE_DIR / 'india-emergency.geojson'
|
| 165 |
+
output_path.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding='utf-8')
|
| 166 |
+
print(f'Emergency GeoJSON written: features={len(features)} path={output_path}')
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
def export_pmgsy_geojson() -> None:
|
| 170 |
+
source = ROADS_DIR / 'pmgsy-geosadak-master.zip'
|
| 171 |
+
target = ROADS_DIR / 'pmgsy_roads.geojson'
|
| 172 |
+
if not source.exists():
|
| 173 |
+
print('PMGSY archive not found; skipping pmgsy_roads.geojson export')
|
| 174 |
+
return
|
| 175 |
+
|
| 176 |
+
planned_states: list[str] = []
|
| 177 |
+
skipped_archives: list[str] = []
|
| 178 |
+
feature_count = 0
|
| 179 |
+
|
| 180 |
+
with zipfile.ZipFile(source) as outer, target.open('w', encoding='utf-8') as handle:
|
| 181 |
+
planned_states = _list_pmgsy_state_members(outer)
|
| 182 |
+
skipped_archives = _list_pmgsy_split_archives(outer)
|
| 183 |
+
properties = {
|
| 184 |
+
'generated_from': source.name,
|
| 185 |
+
'geometry_generalization': f'max {PMGSY_MAX_POINTS_PER_SEGMENT} points per segment',
|
| 186 |
+
'planned_states': planned_states,
|
| 187 |
+
'skipped_archives': skipped_archives,
|
| 188 |
+
}
|
| 189 |
+
handle.write('{"type":"FeatureCollection","properties":')
|
| 190 |
+
json.dump(properties, handle, ensure_ascii=False, separators=(',', ':'))
|
| 191 |
+
handle.write(',"features":[')
|
| 192 |
+
|
| 193 |
+
is_first_feature = True
|
| 194 |
+
exported_states: list[str] = []
|
| 195 |
+
for state_name, archive_bytes in _iter_pmgsy_state_archives(outer):
|
| 196 |
+
try:
|
| 197 |
+
shp_bytes, dbf_bytes = _read_shapefile_bundle(archive_bytes)
|
| 198 |
+
except ValueError:
|
| 199 |
+
continue
|
| 200 |
+
|
| 201 |
+
exported_states.append(state_name)
|
| 202 |
+
for row, geometry in zip(_iter_dbf_rows(dbf_bytes), _iter_polyline_geometries(shp_bytes)):
|
| 203 |
+
if geometry is None:
|
| 204 |
+
continue
|
| 205 |
+
feature = {
|
| 206 |
+
'type': 'Feature',
|
| 207 |
+
'id': f'pmgsy-{state_name}-{row.get("ER_ID") or feature_count + 1}',
|
| 208 |
+
'geometry': geometry,
|
| 209 |
+
'properties': _build_pmgsy_properties(row, state_name),
|
| 210 |
+
}
|
| 211 |
+
if not is_first_feature:
|
| 212 |
+
handle.write(',')
|
| 213 |
+
json.dump(feature, handle, ensure_ascii=False, separators=(',', ':'))
|
| 214 |
+
is_first_feature = False
|
| 215 |
+
feature_count += 1
|
| 216 |
+
|
| 217 |
+
handle.write(']}')
|
| 218 |
+
|
| 219 |
+
print(
|
| 220 |
+
'PMGSY GeoJSON exported: '
|
| 221 |
+
f'rows={feature_count} states={len(exported_states)} skipped={len(skipped_archives)} path={target}'
|
| 222 |
+
)
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
def export_national_highways_csv() -> None:
|
| 226 |
+
target = ROADS_DIR / 'national_highways.csv'
|
| 227 |
+
if target.exists() and target.stat().st_size > 0:
|
| 228 |
+
print(f'National highways CSV already present: {target}')
|
| 229 |
+
return
|
| 230 |
+
|
| 231 |
+
candidates = sorted(
|
| 232 |
+
path for path in ROADS_DIR.glob('*.csv')
|
| 233 |
+
if path.name != target.name and any(token in path.stem.lower() for token in ('nh', 'highway', 'nhai'))
|
| 234 |
+
)
|
| 235 |
+
if not candidates:
|
| 236 |
+
summary_rows = _build_road_summary_rows()
|
| 237 |
+
if not summary_rows:
|
| 238 |
+
print('No usable local road CSVs found; skipping national_highways.csv export')
|
| 239 |
+
return
|
| 240 |
+
|
| 241 |
+
target.parent.mkdir(parents=True, exist_ok=True)
|
| 242 |
+
with target.open('w', encoding='utf-8', newline='') as handle:
|
| 243 |
+
writer = csv.DictWriter(
|
| 244 |
+
handle,
|
| 245 |
+
fieldnames=[
|
| 246 |
+
'source_file',
|
| 247 |
+
'geography_level',
|
| 248 |
+
'geography_name',
|
| 249 |
+
'period',
|
| 250 |
+
'metric_name',
|
| 251 |
+
'value',
|
| 252 |
+
'unit',
|
| 253 |
+
'notes',
|
| 254 |
+
],
|
| 255 |
+
)
|
| 256 |
+
writer.writeheader()
|
| 257 |
+
writer.writerows(summary_rows)
|
| 258 |
+
print(
|
| 259 |
+
'National highways CSV synthesized from local road tables: '
|
| 260 |
+
f'rows={len(summary_rows)} path={target}'
|
| 261 |
+
)
|
| 262 |
+
return
|
| 263 |
+
|
| 264 |
+
shutil.copyfile(candidates[0], target)
|
| 265 |
+
print(f'National highways CSV copied from {candidates[0].name} to {target}')
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
def _nearest_city(lat: float, lon: float) -> tuple[str | None, float]:
|
| 269 |
+
best_city = None
|
| 270 |
+
best_distance = float('inf')
|
| 271 |
+
for city, (city_lat, city_lon) in OFFLINE_CITY_CENTERS.items():
|
| 272 |
+
distance = _distance_meters(lat, lon, city_lat, city_lon)
|
| 273 |
+
if distance < best_distance:
|
| 274 |
+
best_city = city
|
| 275 |
+
best_distance = distance
|
| 276 |
+
return best_city, best_distance
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
def _distance_meters(lat1: float, lon1: float, lat2: float, lon2: float) -> float:
|
| 280 |
+
radius = 6_371_000
|
| 281 |
+
phi1 = math.radians(lat1)
|
| 282 |
+
phi2 = math.radians(lat2)
|
| 283 |
+
delta_phi = math.radians(lat2 - lat1)
|
| 284 |
+
delta_lambda = math.radians(lon2 - lon1)
|
| 285 |
+
a = (
|
| 286 |
+
math.sin(delta_phi / 2) ** 2
|
| 287 |
+
+ math.cos(phi1) * math.cos(phi2) * math.sin(delta_lambda / 2) ** 2
|
| 288 |
+
)
|
| 289 |
+
return 2 * radius * math.atan2(math.sqrt(a), math.sqrt(1 - a))
|
| 290 |
+
|
| 291 |
+
|
| 292 |
+
def _list_pmgsy_state_members(outer: zipfile.ZipFile) -> list[str]:
|
| 293 |
+
return [
|
| 294 |
+
Path(member).stem
|
| 295 |
+
for member in sorted(name for name in outer.namelist() if '/Road_DRRP/' in name and name.endswith('.zip'))
|
| 296 |
+
if not member.endswith('-split.zip')
|
| 297 |
+
]
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
def _list_pmgsy_split_archives(outer: zipfile.ZipFile) -> list[str]:
|
| 301 |
+
return [
|
| 302 |
+
Path(member).stem
|
| 303 |
+
for member in sorted(name for name in outer.namelist() if '/Road_DRRP/' in name and name.endswith('-split.zip'))
|
| 304 |
+
]
|
| 305 |
+
|
| 306 |
+
|
| 307 |
+
def _iter_pmgsy_state_archives(outer: zipfile.ZipFile):
|
| 308 |
+
for member in sorted(name for name in outer.namelist() if '/Road_DRRP/' in name and name.endswith('.zip')):
|
| 309 |
+
if member.endswith('-split.zip'):
|
| 310 |
+
continue
|
| 311 |
+
yield Path(member).stem, outer.read(member)
|
| 312 |
+
|
| 313 |
+
|
| 314 |
+
def _read_shapefile_bundle(archive_bytes: bytes) -> tuple[bytes, bytes]:
|
| 315 |
+
with zipfile.ZipFile(BytesIO(archive_bytes)) as archive:
|
| 316 |
+
shp_names = [name for name in archive.namelist() if name.lower().endswith('.shp')]
|
| 317 |
+
dbf_names = [name for name in archive.namelist() if name.lower().endswith('.dbf')]
|
| 318 |
+
if not shp_names or not dbf_names:
|
| 319 |
+
raise ValueError('Missing shapefile members')
|
| 320 |
+
return archive.read(shp_names[0]), archive.read(dbf_names[0])
|
| 321 |
+
|
| 322 |
+
|
| 323 |
+
def _iter_dbf_rows(dbf_bytes: bytes) -> list[dict[str, object]]:
|
| 324 |
+
header_length = struct.unpack('<H', dbf_bytes[8:10])[0]
|
| 325 |
+
record_length = struct.unpack('<H', dbf_bytes[10:12])[0]
|
| 326 |
+
field_specs = []
|
| 327 |
+
pos = 32
|
| 328 |
+
offset = 1
|
| 329 |
+
while pos < header_length - 1:
|
| 330 |
+
field = dbf_bytes[pos:pos + 32]
|
| 331 |
+
if field[0] == 0x0D:
|
| 332 |
+
break
|
| 333 |
+
field_specs.append(
|
| 334 |
+
(
|
| 335 |
+
field[:11].split(b'\x00', 1)[0].decode('ascii', 'ignore'),
|
| 336 |
+
chr(field[11]),
|
| 337 |
+
field[16],
|
| 338 |
+
field[17],
|
| 339 |
+
offset,
|
| 340 |
+
)
|
| 341 |
+
)
|
| 342 |
+
offset += field[16]
|
| 343 |
+
pos += 32
|
| 344 |
+
|
| 345 |
+
records = struct.unpack('<I', dbf_bytes[4:8])[0]
|
| 346 |
+
row_start = header_length
|
| 347 |
+
for _ in range(records):
|
| 348 |
+
record = dbf_bytes[row_start:row_start + record_length]
|
| 349 |
+
row_start += record_length
|
| 350 |
+
if not record or record[0:1] == b'*':
|
| 351 |
+
continue
|
| 352 |
+
row: dict[str, object] = {}
|
| 353 |
+
for name, field_type, field_len, decimals, value_offset in field_specs:
|
| 354 |
+
raw = record[value_offset:value_offset + field_len]
|
| 355 |
+
text = raw.decode('latin1', 'ignore').strip()
|
| 356 |
+
if not text:
|
| 357 |
+
continue
|
| 358 |
+
if field_type == 'N':
|
| 359 |
+
if decimals:
|
| 360 |
+
try:
|
| 361 |
+
row[name] = float(text)
|
| 362 |
+
except ValueError:
|
| 363 |
+
row[name] = text
|
| 364 |
+
else:
|
| 365 |
+
try:
|
| 366 |
+
row[name] = int(text)
|
| 367 |
+
except ValueError:
|
| 368 |
+
row[name] = text
|
| 369 |
+
else:
|
| 370 |
+
row[name] = text
|
| 371 |
+
yield row
|
| 372 |
+
|
| 373 |
+
|
| 374 |
+
def _iter_polyline_geometries(shp_bytes: bytes) -> list[dict[str, object] | None]:
|
| 375 |
+
pos = 100
|
| 376 |
+
total_size = len(shp_bytes)
|
| 377 |
+
while pos + 8 <= total_size:
|
| 378 |
+
content_length_words = struct.unpack('>i', shp_bytes[pos + 4:pos + 8])[0]
|
| 379 |
+
record_end = pos + 8 + content_length_words * 2
|
| 380 |
+
record = shp_bytes[pos + 8:record_end]
|
| 381 |
+
pos = record_end
|
| 382 |
+
if len(record) < 44:
|
| 383 |
+
yield None
|
| 384 |
+
continue
|
| 385 |
+
|
| 386 |
+
shape_type = struct.unpack('<i', record[:4])[0]
|
| 387 |
+
if shape_type == 0:
|
| 388 |
+
yield None
|
| 389 |
+
continue
|
| 390 |
+
if shape_type not in {3, 13, 23}:
|
| 391 |
+
yield None
|
| 392 |
+
continue
|
| 393 |
+
|
| 394 |
+
num_parts = struct.unpack('<i', record[36:40])[0]
|
| 395 |
+
num_points = struct.unpack('<i', record[40:44])[0]
|
| 396 |
+
parts_offset = 44
|
| 397 |
+
points_offset = parts_offset + 4 * num_parts
|
| 398 |
+
parts = [
|
| 399 |
+
struct.unpack('<i', record[parts_offset + index * 4:parts_offset + (index + 1) * 4])[0]
|
| 400 |
+
for index in range(num_parts)
|
| 401 |
+
]
|
| 402 |
+
points = [
|
| 403 |
+
struct.unpack('<2d', record[points_offset + index * 16:points_offset + (index + 1) * 16])
|
| 404 |
+
for index in range(num_points)
|
| 405 |
+
]
|
| 406 |
+
|
| 407 |
+
coordinates = []
|
| 408 |
+
for index, start in enumerate(parts):
|
| 409 |
+
end = parts[index + 1] if index + 1 < len(parts) else len(points)
|
| 410 |
+
line = _downsample_line(points[start:end], max_points=PMGSY_MAX_POINTS_PER_SEGMENT)
|
| 411 |
+
if len(line) < 2:
|
| 412 |
+
continue
|
| 413 |
+
coordinates.append([[round(lon, 6), round(lat, 6)] for lon, lat in line])
|
| 414 |
+
|
| 415 |
+
if not coordinates:
|
| 416 |
+
yield None
|
| 417 |
+
elif len(coordinates) == 1:
|
| 418 |
+
yield {'type': 'LineString', 'coordinates': coordinates[0]}
|
| 419 |
+
else:
|
| 420 |
+
yield {'type': 'MultiLineString', 'coordinates': coordinates}
|
| 421 |
+
|
| 422 |
+
|
| 423 |
+
def _downsample_line(points: list[tuple[float, float]], *, max_points: int) -> list[tuple[float, float]]:
|
| 424 |
+
if len(points) <= max_points:
|
| 425 |
+
return points
|
| 426 |
+
last_index = len(points) - 1
|
| 427 |
+
indexes = {
|
| 428 |
+
0,
|
| 429 |
+
last_index,
|
| 430 |
+
*(
|
| 431 |
+
min(last_index, round(step * last_index / (max_points - 1)))
|
| 432 |
+
for step in range(1, max_points - 1)
|
| 433 |
+
),
|
| 434 |
+
}
|
| 435 |
+
return [points[index] for index in sorted(indexes)]
|
| 436 |
+
|
| 437 |
+
|
| 438 |
+
def _build_pmgsy_properties(row: dict[str, object], state_name: str) -> dict[str, object]:
|
| 439 |
+
props: dict[str, object] = {'pmgsy_state': state_name}
|
| 440 |
+
field_map = {
|
| 441 |
+
'ER_ID': 'er_id',
|
| 442 |
+
'STATE_ID': 'state_id',
|
| 443 |
+
'BLOCK_ID': 'block_id',
|
| 444 |
+
'DISTRICT_I': 'district_id',
|
| 445 |
+
'DRRP_ROAD_': 'road_code',
|
| 446 |
+
'RoadCatego': 'road_category',
|
| 447 |
+
'RoadName': 'road_name',
|
| 448 |
+
'RoadOwner': 'road_owner',
|
| 449 |
+
}
|
| 450 |
+
for source_key, target_key in field_map.items():
|
| 451 |
+
value = row.get(source_key)
|
| 452 |
+
if value not in (None, ''):
|
| 453 |
+
props[target_key] = value
|
| 454 |
+
return props
|
| 455 |
+
|
| 456 |
+
|
| 457 |
+
def _build_road_summary_rows() -> list[dict[str, str]]:
|
| 458 |
+
rows: list[dict[str, str]] = []
|
| 459 |
+
for path in sorted(ROADS_DIR.glob('*.csv')):
|
| 460 |
+
if path.name in {'national_highways.csv', 'tolls-with-metadata.csv'}:
|
| 461 |
+
continue
|
| 462 |
+
if path.name.endswith('-metadata-hotosm_ind_roads_lines_geojson-zip.csv'):
|
| 463 |
+
continue
|
| 464 |
+
rows.extend(_normalize_road_summary_table(path))
|
| 465 |
+
return rows
|
| 466 |
+
|
| 467 |
+
|
| 468 |
+
def _normalize_road_summary_table(path: Path) -> list[dict[str, str]]:
|
| 469 |
+
with path.open('r', encoding='utf-8-sig', newline='') as handle:
|
| 470 |
+
reader = csv.DictReader(handle)
|
| 471 |
+
if reader.fieldnames is None:
|
| 472 |
+
return []
|
| 473 |
+
|
| 474 |
+
geography_column = _detect_geography_column(reader.fieldnames)
|
| 475 |
+
serial_columns = {'Sr. No.', 'Sl. No.', 'Sl.No.', 'S.No.', 'S. No.'}
|
| 476 |
+
notes = (
|
| 477 |
+
'Generated from local road programme CSVs because no direct NHAI/NH master CSV '
|
| 478 |
+
'was present in chatbot_service/data/roads.'
|
| 479 |
+
)
|
| 480 |
+
rows: list[dict[str, str]] = []
|
| 481 |
+
for raw in reader:
|
| 482 |
+
geography_name = (raw.get(geography_column) or '').strip() if geography_column else ''
|
| 483 |
+
if not geography_name:
|
| 484 |
+
continue
|
| 485 |
+
for column, value in raw.items():
|
| 486 |
+
if column in serial_columns or column == geography_column:
|
| 487 |
+
continue
|
| 488 |
+
metric_value = _normalize_metric_value(value or '')
|
| 489 |
+
if metric_value is None:
|
| 490 |
+
continue
|
| 491 |
+
metric_name, period = _split_metric_column(column)
|
| 492 |
+
rows.append(
|
| 493 |
+
{
|
| 494 |
+
'source_file': path.name,
|
| 495 |
+
'geography_level': 'district' if geography_column == 'District Name' else 'state',
|
| 496 |
+
'geography_name': geography_name,
|
| 497 |
+
'period': period,
|
| 498 |
+
'metric_name': metric_name,
|
| 499 |
+
'value': metric_value,
|
| 500 |
+
'unit': 'km_or_count',
|
| 501 |
+
'notes': notes,
|
| 502 |
+
}
|
| 503 |
+
)
|
| 504 |
+
return rows
|
| 505 |
+
|
| 506 |
+
|
| 507 |
+
def _detect_geography_column(fieldnames: list[str]) -> str | None:
|
| 508 |
+
candidates = ['District Name', 'State/UT', 'State', 'District', 'State/UT ']
|
| 509 |
+
for candidate in candidates:
|
| 510 |
+
if candidate in fieldnames:
|
| 511 |
+
return candidate
|
| 512 |
+
return None
|
| 513 |
+
|
| 514 |
+
|
| 515 |
+
def _normalize_metric_value(value: str) -> str | None:
|
| 516 |
+
cleaned = value.strip()
|
| 517 |
+
if not cleaned or cleaned.upper() in {'NA', 'N/A', '-'}:
|
| 518 |
+
return None
|
| 519 |
+
try:
|
| 520 |
+
return str(int(cleaned))
|
| 521 |
+
except ValueError:
|
| 522 |
+
try:
|
| 523 |
+
return str(float(cleaned))
|
| 524 |
+
except ValueError:
|
| 525 |
+
return None
|
| 526 |
+
|
| 527 |
+
|
| 528 |
+
def _split_metric_column(column: str) -> tuple[str, str]:
|
| 529 |
+
cleaned = column.strip()
|
| 530 |
+
period_match = None
|
| 531 |
+
for token in ('2024-25', '2023-24', '2022-23', '2021-22', '2020-21', '2019-20'):
|
| 532 |
+
if token in cleaned:
|
| 533 |
+
period_match = token
|
| 534 |
+
break
|
| 535 |
+
if period_match is None:
|
| 536 |
+
return cleaned, ''
|
| 537 |
+
|
| 538 |
+
metric_name = cleaned.replace(period_match, '').replace(' - ', ' ').replace('(as on 14.07.2022)', '').strip()
|
| 539 |
+
metric_name = ' '.join(metric_name.split()) or cleaned
|
| 540 |
+
return metric_name, period_match
|
| 541 |
+
|
| 542 |
+
|
| 543 |
+
def main() -> None:
|
| 544 |
+
parser = argparse.ArgumentParser(description='Build app-facing assets from chatbot_service/data local datasets.')
|
| 545 |
+
parser.add_argument('--skip-pmgsy', action='store_true', help='Skip extracting PMGSY shapefiles into GeoJSON.')
|
| 546 |
+
args = parser.parse_args()
|
| 547 |
+
|
| 548 |
+
sync_challan_assets()
|
| 549 |
+
sync_first_aid_bundle()
|
| 550 |
+
build_emergency_geojson()
|
| 551 |
+
export_national_highways_csv()
|
| 552 |
+
if not args.skip_pmgsy:
|
| 553 |
+
export_pmgsy_geojson()
|
| 554 |
+
|
| 555 |
+
|
| 556 |
+
if __name__ == '__main__':
|
| 557 |
+
main()
|
scripts/scripts/data/check_all_scripts.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import subprocess, sys
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
|
| 4 |
+
ROOT = Path(".")
|
| 5 |
+
|
| 6 |
+
scripts = [
|
| 7 |
+
# Root scripts/data/
|
| 8 |
+
"scripts/data/bootstrap_local_data.py",
|
| 9 |
+
"scripts/data/download_legal_pdfs.py",
|
| 10 |
+
"scripts/data/extract_morth2022_tables.py",
|
| 11 |
+
"scripts/data/verify_data.py",
|
| 12 |
+
"scripts/data/seed_blackspots.py",
|
| 13 |
+
"scripts/data/fetch_hospitals.py",
|
| 14 |
+
"scripts/data/fetch_police.py",
|
| 15 |
+
"scripts/data/fetch_fire.py",
|
| 16 |
+
"scripts/data/fetch_ambulance.py",
|
| 17 |
+
"scripts/data/fetch_blood_banks.py",
|
| 18 |
+
"scripts/data/_overpass_utils.py",
|
| 19 |
+
"scripts/data/inspect_zips.py",
|
| 20 |
+
# Root scripts/app/
|
| 21 |
+
"scripts/app/seed_nhp_hospitals.py",
|
| 22 |
+
"scripts/app/seed_emergency.py",
|
| 23 |
+
# Backend scripts/data/
|
| 24 |
+
"backend/scripts/data/seed_violations.py",
|
| 25 |
+
"backend/scripts/data/prepare_road_sources.py",
|
| 26 |
+
"backend/scripts/data/sample_pmgsy.py",
|
| 27 |
+
# Backend scripts/app/
|
| 28 |
+
"backend/scripts/app/build_vectorstore.py",
|
| 29 |
+
"backend/scripts/app/seed_emergency.py",
|
| 30 |
+
"backend/scripts/app/build_offline_bundle.py",
|
| 31 |
+
"backend/scripts/app/seed_roadwatch_sample.py",
|
| 32 |
+
"backend/scripts/app/import_road_infrastructure.py",
|
| 33 |
+
"backend/scripts/app/import_official_road_sources.py",
|
| 34 |
+
# Chatbot scripts/data/
|
| 35 |
+
"chatbot_service/scripts/data/fetch_hospitals.py",
|
| 36 |
+
"chatbot_service/scripts/data/fetch_police.py",
|
| 37 |
+
"chatbot_service/scripts/data/fetch_ambulance.py",
|
| 38 |
+
"chatbot_service/scripts/data/fetch_blood_banks.py",
|
| 39 |
+
"chatbot_service/scripts/data/fetch_fire.py",
|
| 40 |
+
"chatbot_service/scripts/data/_overpass_utils.py",
|
| 41 |
+
# Chatbot scripts/app/
|
| 42 |
+
"chatbot_service/scripts/app/seed_emergency.py",
|
| 43 |
+
]
|
| 44 |
+
|
| 45 |
+
passed = []
|
| 46 |
+
failed = []
|
| 47 |
+
|
| 48 |
+
for s in scripts:
|
| 49 |
+
p = ROOT / s
|
| 50 |
+
if not p.exists():
|
| 51 |
+
failed.append((s, "FILE NOT FOUND"))
|
| 52 |
+
continue
|
| 53 |
+
result = subprocess.run(
|
| 54 |
+
[sys.executable, "-m", "py_compile", str(p)],
|
| 55 |
+
capture_output=True, text=True
|
| 56 |
+
)
|
| 57 |
+
if result.returncode == 0:
|
| 58 |
+
passed.append(s)
|
| 59 |
+
else:
|
| 60 |
+
err = (result.stderr or result.stdout).strip().splitlines()[-1]
|
| 61 |
+
failed.append((s, err))
|
| 62 |
+
|
| 63 |
+
print()
|
| 64 |
+
print("=" * 70)
|
| 65 |
+
print(f" SCRIPT SYNTAX CHECK — {len(scripts)} scripts")
|
| 66 |
+
print("=" * 70)
|
| 67 |
+
for s in passed:
|
| 68 |
+
print(f" [PASS] {s}")
|
| 69 |
+
for s, err in failed:
|
| 70 |
+
print(f" [FAIL] {s}")
|
| 71 |
+
print(f" {err}")
|
| 72 |
+
print("=" * 70)
|
| 73 |
+
print(f" {len(passed)} PASS | {len(failed)} FAIL")
|
| 74 |
+
print("=" * 70)
|
scripts/scripts/data/download_legal_pdfs.py
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
download_legal_pdfs.py
|
| 3 |
+
======================
|
| 4 |
+
Downloads the three critical RAG knowledge-base PDFs from official government
|
| 5 |
+
and WHO sources. All URLs are verified working as of April 2026.
|
| 6 |
+
|
| 7 |
+
Run:
|
| 8 |
+
python scripts/download_legal_pdfs.py
|
| 9 |
+
|
| 10 |
+
The three placeholder files will be replaced with real PDFs.
|
| 11 |
+
"""
|
| 12 |
+
from __future__ import annotations
|
| 13 |
+
|
| 14 |
+
import sys
|
| 15 |
+
import urllib.request
|
| 16 |
+
import urllib.error
|
| 17 |
+
from pathlib import Path
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
PROJECT_ROOT = Path(__file__).resolve().parents[1]
|
| 21 |
+
CHATBOT_DATA = PROJECT_ROOT / "chatbot_service" / "data"
|
| 22 |
+
|
| 23 |
+
TARGETS: list[dict] = [
|
| 24 |
+
{
|
| 25 |
+
"name": "Motor Vehicles Act 1988",
|
| 26 |
+
"destinations": [CHATBOT_DATA / "legal" / "motor_vehicles_act_1988.pdf"],
|
| 27 |
+
"sources": [
|
| 28 |
+
# indiacode.nic.in — official government portal
|
| 29 |
+
"https://indiacode.nic.in/bitstream/123456789/15577/1/the_motor_vehicles_act_1988.pdf",
|
| 30 |
+
# legislative.gov.in — Ministry of Law fallback
|
| 31 |
+
"https://legislative.gov.in/sites/default/files/A1988-59.pdf",
|
| 32 |
+
],
|
| 33 |
+
},
|
| 34 |
+
{
|
| 35 |
+
"name": "Motor Vehicles Amendment Act 2019",
|
| 36 |
+
"destinations": [CHATBOT_DATA / "legal" / "mv_amendment_act_2019.pdf"],
|
| 37 |
+
"sources": [
|
| 38 |
+
# gazette of India official notification
|
| 39 |
+
"https://egazette.nic.in/WriteReadData/2019/210355.pdf",
|
| 40 |
+
# MoRTH official page
|
| 41 |
+
"https://morth.nic.in/sites/default/files/MV_Amendment_Act_2019.pdf",
|
| 42 |
+
],
|
| 43 |
+
},
|
| 44 |
+
{
|
| 45 |
+
"name": "WHO Emergency Care Systems Guidelines (Trauma)",
|
| 46 |
+
"destinations": [CHATBOT_DATA / "medical" / "who_trauma_care_guidelines.pdf"],
|
| 47 |
+
"sources": [
|
| 48 |
+
# WHO publications — direct PDF download
|
| 49 |
+
"https://iris.who.int/bitstream/handle/10665/350523/9789240052215-eng.pdf",
|
| 50 |
+
# Alternative WHO trauma care document
|
| 51 |
+
"https://www.who.int/publications/i/item/9789241548526",
|
| 52 |
+
],
|
| 53 |
+
},
|
| 54 |
+
]
|
| 55 |
+
|
| 56 |
+
PLACEHOLDER_MARKERS = {
|
| 57 |
+
b"# Placeholder",
|
| 58 |
+
b"Placeholder",
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def is_placeholder(path: Path) -> bool:
|
| 63 |
+
"""Return True if the file is one of the tiny text placeholder stubs."""
|
| 64 |
+
if not path.exists():
|
| 65 |
+
return True
|
| 66 |
+
if path.stat().st_size < 256:
|
| 67 |
+
try:
|
| 68 |
+
preview = path.read_bytes()[:64]
|
| 69 |
+
return any(marker in preview for marker in PLACEHOLDER_MARKERS)
|
| 70 |
+
except OSError:
|
| 71 |
+
return True
|
| 72 |
+
return False
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def download_first_working(sources: list[str], destination: Path) -> bool:
|
| 76 |
+
"""Try each source URL in order; return True on the first successful download."""
|
| 77 |
+
for url in sources:
|
| 78 |
+
print(f" Trying: {url}")
|
| 79 |
+
try:
|
| 80 |
+
req = urllib.request.Request(
|
| 81 |
+
url,
|
| 82 |
+
headers={
|
| 83 |
+
"User-Agent": "Mozilla/5.0 (RoadSoS-DataPipeline/1.0; +https://github.com)"
|
| 84 |
+
},
|
| 85 |
+
)
|
| 86 |
+
with urllib.request.urlopen(req, timeout=60) as response:
|
| 87 |
+
data = response.read()
|
| 88 |
+
if len(data) < 1024:
|
| 89 |
+
print(f" Response too small ({len(data)} bytes) — likely not a PDF, skipping")
|
| 90 |
+
continue
|
| 91 |
+
destination.parent.mkdir(parents=True, exist_ok=True)
|
| 92 |
+
destination.write_bytes(data)
|
| 93 |
+
print(f" Downloaded: {len(data):,} bytes -> {destination.name}")
|
| 94 |
+
return True
|
| 95 |
+
except urllib.error.HTTPError as exc:
|
| 96 |
+
print(f" HTTP {exc.code}: {exc.reason}")
|
| 97 |
+
except urllib.error.URLError as exc:
|
| 98 |
+
print(f" Network error: {exc.reason}")
|
| 99 |
+
except Exception as exc: # noqa: BLE001
|
| 100 |
+
print(f" Unexpected error: {exc}")
|
| 101 |
+
return False
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def main() -> None:
|
| 105 |
+
failed: list[str] = []
|
| 106 |
+
|
| 107 |
+
for target in TARGETS:
|
| 108 |
+
name: str = target["name"]
|
| 109 |
+
destinations: list[Path] = target["destinations"]
|
| 110 |
+
sources: list[str] = target["sources"]
|
| 111 |
+
|
| 112 |
+
print(f"\n{'='*60}")
|
| 113 |
+
print(f" {name}")
|
| 114 |
+
|
| 115 |
+
placeholder_paths = [p for p in destinations if is_placeholder(p)]
|
| 116 |
+
if not placeholder_paths:
|
| 117 |
+
real_paths = [p for p in destinations if p.exists()]
|
| 118 |
+
sizes = ", ".join(f"{p.name} ({p.stat().st_size:,}B)" for p in real_paths)
|
| 119 |
+
print(f" Already present: {sizes} — skipping")
|
| 120 |
+
continue
|
| 121 |
+
|
| 122 |
+
print(f" Placeholder detected — downloading real PDF...")
|
| 123 |
+
success = download_first_working(sources, destinations[0])
|
| 124 |
+
|
| 125 |
+
if success and len(destinations) > 1:
|
| 126 |
+
# Mirror to additional destination paths
|
| 127 |
+
base = destinations[0]
|
| 128 |
+
for extra_dest in destinations[1:]:
|
| 129 |
+
extra_dest.parent.mkdir(parents=True, exist_ok=True)
|
| 130 |
+
extra_dest.write_bytes(base.read_bytes())
|
| 131 |
+
print(f" Mirrored to: {extra_dest}")
|
| 132 |
+
|
| 133 |
+
if not success:
|
| 134 |
+
failed.append(name)
|
| 135 |
+
print(
|
| 136 |
+
f"\n !!! DOWNLOAD FAILED for: {name}\n"
|
| 137 |
+
f" Manual steps:\n"
|
| 138 |
+
f" 1. Open a browser and go to one of these URLs:\n"
|
| 139 |
+
+ "\n".join(f" {url}" for url in sources)
|
| 140 |
+
+ f"\n 2. Save the PDF to: {destinations[0]}"
|
| 141 |
+
)
|
| 142 |
+
|
| 143 |
+
print(f"\n{'='*60}")
|
| 144 |
+
if failed:
|
| 145 |
+
print(f"RESULT: {len(TARGETS) - len(failed)}/{len(TARGETS)} downloaded successfully")
|
| 146 |
+
print(f"Manual download required for: {', '.join(failed)}")
|
| 147 |
+
sys.exit(1)
|
| 148 |
+
else:
|
| 149 |
+
print(f"RESULT: All {len(TARGETS)} PDFs downloaded successfully")
|
| 150 |
+
print("RAG pipeline now has real legal and medical knowledge.")
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
if __name__ == "__main__":
|
| 154 |
+
main()
|
scripts/scripts/data/extract_morth2022_tables.py
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
extract_morth2022_tables.py
|
| 3 |
+
===========================
|
| 4 |
+
Extracts tabular accident data from the raw MoRTH 2022 PDF reports that were
|
| 5 |
+
downloaded into chatbot_service/data/accidents/morth_2022/.
|
| 6 |
+
|
| 7 |
+
The morth_2022 folder currently has two large PDFs but only one tabular CSV.
|
| 8 |
+
This script uses pdfplumber to extract all tables from those PDFs and saves
|
| 9 |
+
them as clean, labelled CSVs — matching the format of morth_2021/ and morth_2020/.
|
| 10 |
+
|
| 11 |
+
Run:
|
| 12 |
+
pip install pdfplumber
|
| 13 |
+
python scripts/extract_morth2022_tables.py
|
| 14 |
+
|
| 15 |
+
Output:
|
| 16 |
+
chatbot_service/data/accidents/morth_2022/extracted_table_*.csv
|
| 17 |
+
"""
|
| 18 |
+
from __future__ import annotations
|
| 19 |
+
|
| 20 |
+
import csv
|
| 21 |
+
import re
|
| 22 |
+
import sys
|
| 23 |
+
from pathlib import Path
|
| 24 |
+
|
| 25 |
+
try:
|
| 26 |
+
import pdfplumber
|
| 27 |
+
except ImportError:
|
| 28 |
+
print("ERROR: pdfplumber not installed. Run: pip install pdfplumber")
|
| 29 |
+
sys.exit(1)
|
| 30 |
+
|
| 31 |
+
PROJECT_ROOT = Path(__file__).resolve().parents[1]
|
| 32 |
+
MORTH_2022_DIR = PROJECT_ROOT / "chatbot_service" / "data" / "accidents" / "morth_2022"
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def _clean_cell(text: str | None) -> str:
|
| 36 |
+
"""Normalise whitespace in a table cell value."""
|
| 37 |
+
if text is None:
|
| 38 |
+
return ""
|
| 39 |
+
return re.sub(r"\s+", " ", text.strip())
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def _is_empty_row(row: list[str]) -> bool:
|
| 43 |
+
return all(c == "" for c in row)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def _is_header_row(row: list[str]) -> bool:
|
| 47 |
+
"""Heuristic: a row is a header if most cells look like labels not numbers."""
|
| 48 |
+
non_empty = [c for c in row if c]
|
| 49 |
+
if not non_empty:
|
| 50 |
+
return False
|
| 51 |
+
numeric_count = sum(1 for c in non_empty if re.match(r"^[\d,.\s]+$", c))
|
| 52 |
+
return numeric_count < len(non_empty) / 2
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def extract_tables_from_pdf(pdf_path: Path, output_dir: Path) -> int:
|
| 56 |
+
"""Extract all tables from a PDF and write them to numbered CSVs."""
|
| 57 |
+
output_dir.mkdir(parents=True, exist_ok=True)
|
| 58 |
+
stem = pdf_path.stem[:24] # keep filename manageable
|
| 59 |
+
tables_written = 0
|
| 60 |
+
|
| 61 |
+
print(f"\nProcessing: {pdf_path.name} ({pdf_path.stat().st_size / 1_048_576:.1f} MB)")
|
| 62 |
+
|
| 63 |
+
with pdfplumber.open(pdf_path) as pdf:
|
| 64 |
+
global_table_idx = 0
|
| 65 |
+
buffer_rows: list[list[str]] = []
|
| 66 |
+
buffer_header: list[str] = []
|
| 67 |
+
|
| 68 |
+
for page_num, page in enumerate(pdf.pages, start=1):
|
| 69 |
+
tables = page.extract_tables()
|
| 70 |
+
if not tables:
|
| 71 |
+
continue
|
| 72 |
+
|
| 73 |
+
for table in tables:
|
| 74 |
+
if not table:
|
| 75 |
+
continue
|
| 76 |
+
|
| 77 |
+
cleaned = [
|
| 78 |
+
[_clean_cell(cell) for cell in row]
|
| 79 |
+
for row in table
|
| 80 |
+
]
|
| 81 |
+
cleaned = [r for r in cleaned if not _is_empty_row(r)]
|
| 82 |
+
|
| 83 |
+
if not cleaned:
|
| 84 |
+
continue
|
| 85 |
+
|
| 86 |
+
# Detect if this page continues a previous table (no header in first row)
|
| 87 |
+
first_row_looks_like_header = _is_header_row(cleaned[0])
|
| 88 |
+
|
| 89 |
+
if first_row_looks_like_header and buffer_rows:
|
| 90 |
+
# Flush previous buffer
|
| 91 |
+
_write_table(output_dir, stem, global_table_idx, buffer_header, buffer_rows)
|
| 92 |
+
tables_written += 1
|
| 93 |
+
global_table_idx += 1
|
| 94 |
+
buffer_rows = []
|
| 95 |
+
buffer_header = []
|
| 96 |
+
|
| 97 |
+
if first_row_looks_like_header:
|
| 98 |
+
buffer_header = cleaned[0]
|
| 99 |
+
buffer_rows = cleaned[1:]
|
| 100 |
+
else:
|
| 101 |
+
# Continuation of previous table
|
| 102 |
+
buffer_rows.extend(cleaned)
|
| 103 |
+
|
| 104 |
+
# Flush any remaining buffer
|
| 105 |
+
if buffer_rows:
|
| 106 |
+
_write_table(output_dir, stem, global_table_idx, buffer_header, buffer_rows)
|
| 107 |
+
tables_written += 1
|
| 108 |
+
|
| 109 |
+
return tables_written
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def _write_table(
|
| 113 |
+
output_dir: Path,
|
| 114 |
+
stem: str,
|
| 115 |
+
index: int,
|
| 116 |
+
header: list[str],
|
| 117 |
+
rows: list[list[str]],
|
| 118 |
+
) -> None:
|
| 119 |
+
filename = output_dir / f"extracted_{stem}_table_{index:03d}.csv"
|
| 120 |
+
with filename.open("w", newline="", encoding="utf-8") as fp:
|
| 121 |
+
writer = csv.writer(fp)
|
| 122 |
+
if header:
|
| 123 |
+
writer.writerow(header)
|
| 124 |
+
writer.writerows(rows)
|
| 125 |
+
print(f" Wrote: {filename.name} ({len(rows)} data rows)")
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def main() -> None:
|
| 129 |
+
pdfs = sorted(MORTH_2022_DIR.glob("*.pdf"))
|
| 130 |
+
if not pdfs:
|
| 131 |
+
print(f"No PDFs found in {MORTH_2022_DIR}")
|
| 132 |
+
print("Download the MoRTH 2022 report from:")
|
| 133 |
+
print(" https://morth.nic.in/road-accident-in-india")
|
| 134 |
+
sys.exit(1)
|
| 135 |
+
|
| 136 |
+
total_tables = 0
|
| 137 |
+
for pdf_path in pdfs:
|
| 138 |
+
n = extract_tables_from_pdf(pdf_path, MORTH_2022_DIR)
|
| 139 |
+
total_tables += n
|
| 140 |
+
print(f" => {n} tables extracted from {pdf_path.name}")
|
| 141 |
+
|
| 142 |
+
print(f"\nDone: {total_tables} total table CSVs written to {MORTH_2022_DIR}")
|
| 143 |
+
print("These CSVs can now be used by seed_blackspots.py for accident data seeding.")
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
if __name__ == "__main__":
|
| 147 |
+
main()
|
scripts/scripts/data/fetch_ambulance.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import logging
|
| 4 |
+
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
| 5 |
+
LOGGER = logging.getLogger(__name__)
|
| 6 |
+
|
| 7 |
+
from _overpass_utils import ROOT_DIR, build_arg_parser, build_india_query, fetch_elements, normalize_row, write_rows
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
DEFAULT_OUTPUT = ROOT_DIR / 'chatbot_service' / 'data' / 'emergency' / 'ambulance_stations.csv'
|
| 11 |
+
SELECTORS = [
|
| 12 |
+
'node["emergency"="ambulance_station"](area.searchArea);',
|
| 13 |
+
'way["emergency"="ambulance_station"](area.searchArea);',
|
| 14 |
+
'relation["emergency"="ambulance_station"](area.searchArea);',
|
| 15 |
+
'node["amenity"="ambulance_station"](area.searchArea);',
|
| 16 |
+
'way["amenity"="ambulance_station"](area.searchArea);',
|
| 17 |
+
'relation["amenity"="ambulance_station"](area.searchArea);',
|
| 18 |
+
'node["healthcare"="ambulance_station"](area.searchArea);',
|
| 19 |
+
'way["healthcare"="ambulance_station"](area.searchArea);',
|
| 20 |
+
'relation["healthcare"="ambulance_station"](area.searchArea);',
|
| 21 |
+
]
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def main() -> None:
|
| 25 |
+
parser = build_arg_parser('Fetch India ambulance station data from Overpass.', DEFAULT_OUTPUT)
|
| 26 |
+
args = parser.parse_args()
|
| 27 |
+
|
| 28 |
+
query = build_india_query(SELECTORS, timeout=args.timeout)
|
| 29 |
+
elements = fetch_elements(query, endpoint=args.endpoint, timeout=args.timeout)
|
| 30 |
+
rows = [
|
| 31 |
+
row
|
| 32 |
+
for element in elements
|
| 33 |
+
if (row := normalize_row(element, default_type='ambulance', fallback_name='Unnamed ambulance station')) is not None
|
| 34 |
+
]
|
| 35 |
+
count = write_rows(args.output, rows)
|
| 36 |
+
LOGGER.info(f'Saved {count} ambulance station records to {args.output}')
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
if __name__ == '__main__':
|
| 40 |
+
main()
|
scripts/scripts/data/fetch_blood_banks.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import logging
|
| 4 |
+
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
| 5 |
+
LOGGER = logging.getLogger(__name__)
|
| 6 |
+
|
| 7 |
+
from _overpass_utils import ROOT_DIR, build_arg_parser, build_india_query, fetch_elements, normalize_row, write_rows
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
DEFAULT_OUTPUT = ROOT_DIR / 'chatbot_service' / 'data' / 'hospitals' / 'blood_bank_directory.csv'
|
| 11 |
+
SELECTORS = [
|
| 12 |
+
'node["amenity"="blood_bank"](area.searchArea);',
|
| 13 |
+
'way["amenity"="blood_bank"](area.searchArea);',
|
| 14 |
+
'relation["amenity"="blood_bank"](area.searchArea);',
|
| 15 |
+
'node["healthcare"="blood_bank"](area.searchArea);',
|
| 16 |
+
'way["healthcare"="blood_bank"](area.searchArea);',
|
| 17 |
+
'relation["healthcare"="blood_bank"](area.searchArea);',
|
| 18 |
+
]
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def main() -> None:
|
| 22 |
+
parser = build_arg_parser('Fetch India blood bank data from Overpass.', DEFAULT_OUTPUT)
|
| 23 |
+
args = parser.parse_args()
|
| 24 |
+
|
| 25 |
+
query = build_india_query(SELECTORS, timeout=args.timeout)
|
| 26 |
+
elements = fetch_elements(query, endpoint=args.endpoint, timeout=args.timeout)
|
| 27 |
+
rows = [
|
| 28 |
+
row
|
| 29 |
+
for element in elements
|
| 30 |
+
if (row := normalize_row(element, default_type='blood_bank', fallback_name='Unnamed blood bank')) is not None
|
| 31 |
+
]
|
| 32 |
+
count = write_rows(args.output, rows)
|
| 33 |
+
LOGGER.info(f'Saved {count} blood bank records to {args.output}')
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
if __name__ == '__main__':
|
| 37 |
+
main()
|
scripts/scripts/data/fetch_fire.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import logging
|
| 4 |
+
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
| 5 |
+
LOGGER = logging.getLogger(__name__)
|
| 6 |
+
|
| 7 |
+
from _overpass_utils import ROOT_DIR, build_arg_parser, build_india_query, fetch_elements, normalize_row, write_rows
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
DEFAULT_OUTPUT = ROOT_DIR / 'chatbot_service' / 'data' / 'emergency' / 'fire_stations.csv'
|
| 11 |
+
SELECTORS = [
|
| 12 |
+
'node["amenity"="fire_station"](area.searchArea);',
|
| 13 |
+
'way["amenity"="fire_station"](area.searchArea);',
|
| 14 |
+
'relation["amenity"="fire_station"](area.searchArea);',
|
| 15 |
+
]
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def main() -> None:
|
| 19 |
+
parser = build_arg_parser('Fetch India fire station data from Overpass.', DEFAULT_OUTPUT)
|
| 20 |
+
args = parser.parse_args()
|
| 21 |
+
|
| 22 |
+
query = build_india_query(SELECTORS, timeout=args.timeout)
|
| 23 |
+
elements = fetch_elements(query, endpoint=args.endpoint, timeout=args.timeout)
|
| 24 |
+
rows = [
|
| 25 |
+
row
|
| 26 |
+
for element in elements
|
| 27 |
+
if (row := normalize_row(element, default_type='fire_station', fallback_name='Unnamed fire station')) is not None
|
| 28 |
+
]
|
| 29 |
+
count = write_rows(args.output, rows)
|
| 30 |
+
LOGGER.info(f'Saved {count} fire station records to {args.output}')
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
if __name__ == '__main__':
|
| 34 |
+
main()
|
scripts/scripts/data/fetch_hospitals.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import logging
|
| 4 |
+
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
| 5 |
+
LOGGER = logging.getLogger(__name__)
|
| 6 |
+
|
| 7 |
+
from _overpass_utils import ROOT_DIR, build_arg_parser, build_india_query, fetch_elements, normalize_row, write_rows
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
DEFAULT_OUTPUT = ROOT_DIR / 'chatbot_service' / 'data' / 'hospitals' / 'hospital_directory.csv'
|
| 11 |
+
SELECTORS = [
|
| 12 |
+
'node["amenity"~"hospital|clinic"](area.searchArea);',
|
| 13 |
+
'way["amenity"~"hospital|clinic"](area.searchArea);',
|
| 14 |
+
'relation["amenity"~"hospital|clinic"](area.searchArea);',
|
| 15 |
+
]
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def main() -> None:
|
| 19 |
+
parser = build_arg_parser('Fetch India hospital and clinic data from Overpass.', DEFAULT_OUTPUT)
|
| 20 |
+
args = parser.parse_args()
|
| 21 |
+
|
| 22 |
+
query = build_india_query(SELECTORS, timeout=args.timeout)
|
| 23 |
+
elements = fetch_elements(query, endpoint=args.endpoint, timeout=args.timeout)
|
| 24 |
+
rows = [
|
| 25 |
+
row
|
| 26 |
+
for element in elements
|
| 27 |
+
if (row := normalize_row(element, default_type='hospital', fallback_name='Unnamed hospital')) is not None
|
| 28 |
+
]
|
| 29 |
+
count = write_rows(args.output, rows)
|
| 30 |
+
LOGGER.info(f'Saved {count} hospital records to {args.output}')
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
if __name__ == '__main__':
|
| 34 |
+
main()
|
scripts/scripts/data/fetch_police.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import logging
|
| 4 |
+
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
| 5 |
+
LOGGER = logging.getLogger(__name__)
|
| 6 |
+
|
| 7 |
+
from _overpass_utils import ROOT_DIR, build_arg_parser, build_india_query, fetch_elements, normalize_row, write_rows
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
DEFAULT_OUTPUT = ROOT_DIR / 'chatbot_service' / 'data' / 'emergency' / 'police_stations.csv'
|
| 11 |
+
SELECTORS = [
|
| 12 |
+
'node["amenity"="police"](area.searchArea);',
|
| 13 |
+
'way["amenity"="police"](area.searchArea);',
|
| 14 |
+
'relation["amenity"="police"](area.searchArea);',
|
| 15 |
+
]
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def main() -> None:
|
| 19 |
+
parser = build_arg_parser('Fetch India police station data from Overpass.', DEFAULT_OUTPUT)
|
| 20 |
+
args = parser.parse_args()
|
| 21 |
+
|
| 22 |
+
query = build_india_query(SELECTORS, timeout=args.timeout)
|
| 23 |
+
elements = fetch_elements(query, endpoint=args.endpoint, timeout=args.timeout)
|
| 24 |
+
rows = [
|
| 25 |
+
row
|
| 26 |
+
for element in elements
|
| 27 |
+
if (row := normalize_row(element, default_type='police', fallback_name='Unnamed police station')) is not None
|
| 28 |
+
]
|
| 29 |
+
count = write_rows(args.output, rows)
|
| 30 |
+
LOGGER.info(f'Saved {count} police station records to {args.output}')
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
if __name__ == '__main__':
|
| 34 |
+
main()
|
scripts/scripts/data/inspect_zips.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import zipfile
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
|
| 4 |
+
ROOT = Path(".")
|
| 5 |
+
|
| 6 |
+
zips = [
|
| 7 |
+
"backend/datasets/accidents/kaggle/AccidentsBig.csv.zip",
|
| 8 |
+
"chatbot_service/data/legal/indian_kanoon/indian_kanoon_statistics_v1.zip",
|
| 9 |
+
"chatbot_service/data/pothole_training/road_damage_2025/archive.zip",
|
| 10 |
+
"chatbot_service/data/qa_pairs/file-1745432916167-910662924.zip",
|
| 11 |
+
"chatbot_service/data/roads/pmgsy-geosadak-master.zip",
|
| 12 |
+
]
|
| 13 |
+
|
| 14 |
+
for zpath in zips:
|
| 15 |
+
p = ROOT / zpath
|
| 16 |
+
if not p.exists():
|
| 17 |
+
print(f"MISSING: {zpath}")
|
| 18 |
+
continue
|
| 19 |
+
size_mb = p.stat().st_size / 1024 / 1024
|
| 20 |
+
print(f"\n[{size_mb:.1f}MB] {p.name}")
|
| 21 |
+
try:
|
| 22 |
+
with zipfile.ZipFile(p) as z:
|
| 23 |
+
members = z.namelist()
|
| 24 |
+
print(f" Total entries: {len(members)}")
|
| 25 |
+
top = sorted(set(m.split("/")[0] for m in members))
|
| 26 |
+
for t in top[:6]:
|
| 27 |
+
print(f" root-dir: {t}/")
|
| 28 |
+
sample = [m for m in members if not m.endswith("/")][:6]
|
| 29 |
+
for s in sample:
|
| 30 |
+
info = z.getinfo(s)
|
| 31 |
+
print(f" file: {s} ({info.file_size:,}B uncompressed)")
|
| 32 |
+
except Exception as e:
|
| 33 |
+
print(f" Cannot open: {e}")
|
scripts/scripts/data/seed_blackspots.py
ADDED
|
@@ -0,0 +1,189 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
import csv
|
| 5 |
+
import json
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
ROOT_DIR = Path(__file__).resolve().parents[1]
|
| 10 |
+
DEFAULT_INPUT = ROOT_DIR / 'chatbot_service' / 'data' / 'accidents' / 'morth_2022'
|
| 11 |
+
DEFAULT_OUTPUT_CSV = ROOT_DIR / 'chatbot_service' / 'data' / 'accidents' / 'accident_blackspots_preview.csv'
|
| 12 |
+
DEFAULT_OUTPUT_GEOJSON = ROOT_DIR / 'frontend' / 'public' / 'offline-data' / 'accident-blackspots.geojson'
|
| 13 |
+
STATE_CENTROIDS = {
|
| 14 |
+
'andhra pradesh': (15.9129, 79.74),
|
| 15 |
+
'arunachal pradesh': (28.2180, 94.7278),
|
| 16 |
+
'assam': (26.2006, 92.9376),
|
| 17 |
+
'bihar': (25.0961, 85.3131),
|
| 18 |
+
'chhattisgarh': (21.2787, 81.8661),
|
| 19 |
+
'delhi': (28.7041, 77.1025),
|
| 20 |
+
'goa': (15.2993, 74.1240),
|
| 21 |
+
'gujarat': (22.2587, 71.1924),
|
| 22 |
+
'haryana': (29.0588, 76.0856),
|
| 23 |
+
'himachal pradesh': (31.1048, 77.1734),
|
| 24 |
+
'jharkhand': (23.6102, 85.2799),
|
| 25 |
+
'karnataka': (15.3173, 75.7139),
|
| 26 |
+
'kerala': (10.8505, 76.2711),
|
| 27 |
+
'madhya pradesh': (22.9734, 78.6569),
|
| 28 |
+
'maharashtra': (19.7515, 75.7139),
|
| 29 |
+
'manipur': (24.6637, 93.9063),
|
| 30 |
+
'meghalaya': (25.4670, 91.3662),
|
| 31 |
+
'mizoram': (23.1645, 92.9376),
|
| 32 |
+
'nagaland': (26.1584, 94.5624),
|
| 33 |
+
'odisha': (20.9517, 85.0985),
|
| 34 |
+
'punjab': (31.1471, 75.3412),
|
| 35 |
+
'rajasthan': (27.0238, 74.2179),
|
| 36 |
+
'sikkim': (27.5330, 88.5122),
|
| 37 |
+
'tamil nadu': (11.1271, 78.6569),
|
| 38 |
+
'telangana': (18.1124, 79.0193),
|
| 39 |
+
'tripura': (23.9408, 91.9882),
|
| 40 |
+
'uttar pradesh': (26.8467, 80.9462),
|
| 41 |
+
'uttarakhand': (30.0668, 79.0193),
|
| 42 |
+
'west bengal': (22.9868, 87.8550),
|
| 43 |
+
}
|
| 44 |
+
STATE_FIELDS = ('state', 'state_name', 'state_ut', 'state/ut', 'state_ut_name')
|
| 45 |
+
CITY_FIELDS = ('city', 'city_name', 'district', 'district_name', 'location')
|
| 46 |
+
LAT_FIELDS = ('lat', 'latitude')
|
| 47 |
+
LON_FIELDS = ('lon', 'lng', 'longitude')
|
| 48 |
+
ACCIDENT_FIELDS = ('total_accidents', 'accidents', 'road_accidents', 'fatal_accidents')
|
| 49 |
+
DEATH_FIELDS = ('persons_killed', 'killed', 'deaths')
|
| 50 |
+
INJURY_FIELDS = ('persons_injured', 'injured')
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def _first_value(row: dict[str, str], names: tuple[str, ...]) -> str:
|
| 54 |
+
for name in names:
|
| 55 |
+
value = (row.get(name) or '').strip()
|
| 56 |
+
if value:
|
| 57 |
+
return value
|
| 58 |
+
return ''
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def _parse_float(value: str) -> float | None:
|
| 62 |
+
try:
|
| 63 |
+
return float(value)
|
| 64 |
+
except (TypeError, ValueError):
|
| 65 |
+
return None
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def _parse_int(value: str) -> int:
|
| 69 |
+
try:
|
| 70 |
+
return int(float(value))
|
| 71 |
+
except (TypeError, ValueError):
|
| 72 |
+
return 0
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def _discover_csvs(path: Path) -> list[Path]:
|
| 76 |
+
if path.is_file():
|
| 77 |
+
return [path]
|
| 78 |
+
return sorted(candidate for candidate in path.rglob('*.csv') if candidate.is_file())
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def _normalize_row(row: dict[str, str], *, source_file: str, index: int) -> dict | None:
|
| 82 |
+
state = _first_value(row, STATE_FIELDS)
|
| 83 |
+
city = _first_value(row, CITY_FIELDS)
|
| 84 |
+
lat = _parse_float(_first_value(row, LAT_FIELDS))
|
| 85 |
+
lon = _parse_float(_first_value(row, LON_FIELDS))
|
| 86 |
+
|
| 87 |
+
if (lat is None or lon is None) and state.lower() in STATE_CENTROIDS:
|
| 88 |
+
lat, lon = STATE_CENTROIDS[state.lower()]
|
| 89 |
+
|
| 90 |
+
if lat is None or lon is None:
|
| 91 |
+
return None
|
| 92 |
+
|
| 93 |
+
accidents = _parse_int(_first_value(row, ACCIDENT_FIELDS))
|
| 94 |
+
killed = _parse_int(_first_value(row, DEATH_FIELDS))
|
| 95 |
+
injured = _parse_int(_first_value(row, INJURY_FIELDS))
|
| 96 |
+
severity_score = accidents + (2 * killed) + injured
|
| 97 |
+
|
| 98 |
+
return {
|
| 99 |
+
'blackspot_id': f'{source_file}:{index}',
|
| 100 |
+
'state': state,
|
| 101 |
+
'city': city,
|
| 102 |
+
'lat': f'{lat:.6f}',
|
| 103 |
+
'lon': f'{lon:.6f}',
|
| 104 |
+
'accidents': accidents,
|
| 105 |
+
'killed': killed,
|
| 106 |
+
'injured': injured,
|
| 107 |
+
'severity_score': severity_score,
|
| 108 |
+
'source_file': source_file,
|
| 109 |
+
}
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def _load_records(input_path: Path) -> list[dict]:
|
| 113 |
+
records: list[dict] = []
|
| 114 |
+
for csv_path in _discover_csvs(input_path):
|
| 115 |
+
with csv_path.open('r', encoding='utf-8', newline='') as handle:
|
| 116 |
+
reader = csv.DictReader(handle)
|
| 117 |
+
for index, row in enumerate(reader, start=1):
|
| 118 |
+
normalized = _normalize_row(row, source_file=csv_path.name, index=index)
|
| 119 |
+
if normalized is not None:
|
| 120 |
+
records.append(normalized)
|
| 121 |
+
return records
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def _write_csv(path: Path, rows: list[dict]) -> None:
|
| 125 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 126 |
+
with path.open('w', encoding='utf-8', newline='') as handle:
|
| 127 |
+
writer = csv.DictWriter(
|
| 128 |
+
handle,
|
| 129 |
+
fieldnames=['blackspot_id', 'state', 'city', 'lat', 'lon', 'accidents', 'killed', 'injured', 'severity_score', 'source_file'],
|
| 130 |
+
)
|
| 131 |
+
writer.writeheader()
|
| 132 |
+
writer.writerows(rows)
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def _write_geojson(path: Path, rows: list[dict]) -> None:
|
| 136 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 137 |
+
geojson = {
|
| 138 |
+
'type': 'FeatureCollection',
|
| 139 |
+
'features': [
|
| 140 |
+
{
|
| 141 |
+
'type': 'Feature',
|
| 142 |
+
'geometry': {'type': 'Point', 'coordinates': [float(row['lon']), float(row['lat'])]},
|
| 143 |
+
'properties': {
|
| 144 |
+
'blackspot_id': row['blackspot_id'],
|
| 145 |
+
'state': row['state'],
|
| 146 |
+
'city': row['city'],
|
| 147 |
+
'accidents': row['accidents'],
|
| 148 |
+
'killed': row['killed'],
|
| 149 |
+
'injured': row['injured'],
|
| 150 |
+
'severity_score': row['severity_score'],
|
| 151 |
+
'source_file': row['source_file'],
|
| 152 |
+
},
|
| 153 |
+
}
|
| 154 |
+
for row in rows
|
| 155 |
+
],
|
| 156 |
+
}
|
| 157 |
+
path.write_text(json.dumps(geojson, indent=2), encoding='utf-8')
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def main() -> None:
|
| 161 |
+
parser = argparse.ArgumentParser(
|
| 162 |
+
description='Normalize accident CSVs into a blackspot preview CSV and GeoJSON bundle.',
|
| 163 |
+
)
|
| 164 |
+
parser.add_argument('--input', type=Path, default=DEFAULT_INPUT, help=f'CSV file or directory. Defaults to {DEFAULT_INPUT}')
|
| 165 |
+
parser.add_argument('--output-csv', type=Path, default=DEFAULT_OUTPUT_CSV, help=f'Normalized CSV output. Defaults to {DEFAULT_OUTPUT_CSV}')
|
| 166 |
+
parser.add_argument(
|
| 167 |
+
'--output-geojson',
|
| 168 |
+
type=Path,
|
| 169 |
+
default=DEFAULT_OUTPUT_GEOJSON,
|
| 170 |
+
help=f'GeoJSON output for offline mapping. Defaults to {DEFAULT_OUTPUT_GEOJSON}',
|
| 171 |
+
)
|
| 172 |
+
args = parser.parse_args()
|
| 173 |
+
|
| 174 |
+
if not args.input.exists():
|
| 175 |
+
raise SystemExit(f'Input path not found: {args.input}')
|
| 176 |
+
|
| 177 |
+
rows = _load_records(args.input)
|
| 178 |
+
if not rows:
|
| 179 |
+
raise SystemExit('No accident CSV rows could be normalized from the provided input.')
|
| 180 |
+
|
| 181 |
+
rows.sort(key=lambda item: item['severity_score'], reverse=True)
|
| 182 |
+
_write_csv(args.output_csv, rows)
|
| 183 |
+
_write_geojson(args.output_geojson, rows)
|
| 184 |
+
print(f'Wrote {len(rows)} normalized blackspot rows to {args.output_csv}')
|
| 185 |
+
print(f'Wrote GeoJSON preview to {args.output_geojson}')
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
if __name__ == '__main__':
|
| 189 |
+
main()
|
scripts/scripts/data/setup_kaggle.ps1
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
param(
|
| 2 |
+
[string]$RepoRoot = (Split-Path -Parent $PSScriptRoot)
|
| 3 |
+
)
|
| 4 |
+
|
| 5 |
+
function Get-KaggleToken {
|
| 6 |
+
param(
|
| 7 |
+
[string[]]$EnvFiles
|
| 8 |
+
)
|
| 9 |
+
|
| 10 |
+
foreach ($envFile in $EnvFiles) {
|
| 11 |
+
if (-not (Test-Path -LiteralPath $envFile)) {
|
| 12 |
+
continue
|
| 13 |
+
}
|
| 14 |
+
|
| 15 |
+
foreach ($line in Get-Content -LiteralPath $envFile) {
|
| 16 |
+
if ($line -match '^\s*(?:export\s+)?KAGGLE_API_TOKEN\s*=\s*(.+?)\s*$') {
|
| 17 |
+
$token = $matches[1].Trim()
|
| 18 |
+
if (
|
| 19 |
+
($token.StartsWith('"') -and $token.EndsWith('"')) -or
|
| 20 |
+
($token.StartsWith("'") -and $token.EndsWith("'"))
|
| 21 |
+
) {
|
| 22 |
+
$token = $token.Substring(1, $token.Length - 2)
|
| 23 |
+
}
|
| 24 |
+
if ($token) {
|
| 25 |
+
return $token
|
| 26 |
+
}
|
| 27 |
+
}
|
| 28 |
+
}
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
throw "KAGGLE_API_TOKEN was not found in backend/.env or chatbot_service/.env."
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
$envFiles = @(
|
| 35 |
+
(Join-Path $RepoRoot 'backend\.env'),
|
| 36 |
+
(Join-Path $RepoRoot 'chatbot_service\.env')
|
| 37 |
+
)
|
| 38 |
+
|
| 39 |
+
$token = Get-KaggleToken -EnvFiles $envFiles
|
| 40 |
+
$kaggleDir = Join-Path $HOME '.kaggle'
|
| 41 |
+
$accessTokenPath = Join-Path $kaggleDir 'access_token'
|
| 42 |
+
$repoDatasetDir = Join-Path $RepoRoot 'backend\datasets\accidents\kaggle'
|
| 43 |
+
|
| 44 |
+
New-Item -ItemType Directory -Force -Path $kaggleDir | Out-Null
|
| 45 |
+
Set-Content -LiteralPath $accessTokenPath -Value $token -NoNewline
|
| 46 |
+
New-Item -ItemType Directory -Force -Path $repoDatasetDir | Out-Null
|
| 47 |
+
|
| 48 |
+
Write-Output "Configured Kaggle token file: $accessTokenPath"
|
| 49 |
+
Write-Output "Confirmed dataset folder: $repoDatasetDir"
|
| 50 |
+
Write-Output "Authentication is configured, but datasets still need an explicit download command."
|
scripts/scripts/data/verify_data.py
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from pathlib import Path
|
| 2 |
+
import json, csv
|
| 3 |
+
|
| 4 |
+
ROOT = Path(".")
|
| 5 |
+
DATA = ROOT / "chatbot_service/data"
|
| 6 |
+
FRONTEND = ROOT / "frontend/public/offline-data"
|
| 7 |
+
|
| 8 |
+
checks = []
|
| 9 |
+
|
| 10 |
+
def check(label, path, min_bytes=100, check_fn=None):
|
| 11 |
+
p = Path(path)
|
| 12 |
+
if not p.exists():
|
| 13 |
+
checks.append(("FAIL", label, "FILE MISSING"))
|
| 14 |
+
return
|
| 15 |
+
size = p.stat().st_size
|
| 16 |
+
if size < min_bytes:
|
| 17 |
+
checks.append(("FAIL", label, f"Too small: {size} bytes"))
|
| 18 |
+
return
|
| 19 |
+
if check_fn:
|
| 20 |
+
try:
|
| 21 |
+
result = check_fn(p)
|
| 22 |
+
checks.append(("PASS", label, result))
|
| 23 |
+
except Exception as e:
|
| 24 |
+
checks.append(("WARN", label, str(e)))
|
| 25 |
+
else:
|
| 26 |
+
checks.append(("PASS", label, f"{size:,} bytes"))
|
| 27 |
+
|
| 28 |
+
def count_csv(p):
|
| 29 |
+
with p.open(encoding="utf-8-sig") as f:
|
| 30 |
+
return f"{sum(1 for _ in csv.DictReader(f))} rows"
|
| 31 |
+
|
| 32 |
+
def check_pdf(p):
|
| 33 |
+
data = p.read_bytes()
|
| 34 |
+
if data[:4] != b"%PDF":
|
| 35 |
+
preview = data[:30].decode("latin-1", errors="replace")
|
| 36 |
+
return f"NOT REAL PDF -- {preview}"
|
| 37 |
+
return f"{p.stat().st_size:,} bytes (valid PDF)"
|
| 38 |
+
|
| 39 |
+
def count_json(p):
|
| 40 |
+
data = json.loads(p.read_text(encoding="utf-8"))
|
| 41 |
+
if isinstance(data, list):
|
| 42 |
+
return f"{len(data)} items"
|
| 43 |
+
if isinstance(data, dict):
|
| 44 |
+
return f"{len(data)} keys"
|
| 45 |
+
return "JSON ok"
|
| 46 |
+
|
| 47 |
+
def geojson_features(p):
|
| 48 |
+
data = json.loads(p.read_text(encoding="utf-8"))
|
| 49 |
+
return f"{len(data['features']):,} features"
|
| 50 |
+
|
| 51 |
+
# PDFs
|
| 52 |
+
check("MVA 1988 PDF", DATA/"legal/motor_vehicles_act_1988.pdf", 100000, check_pdf)
|
| 53 |
+
check("MVA Amendment 2019 PDF", DATA/"legal/mv_amendment_act_2019.pdf", 500, check_pdf)
|
| 54 |
+
check("WHO Trauma Guidelines", DATA/"medical/who_trauma_care_guidelines.pdf", 500, check_pdf)
|
| 55 |
+
check("MVA 1988 TXT summary", DATA/"legal/motor_vehicles_act_1988_summary.txt", 10000)
|
| 56 |
+
|
| 57 |
+
# CSVs
|
| 58 |
+
check("violations_seed.csv", DATA/"violations_seed.csv", 500, count_csv)
|
| 59 |
+
check("state_overrides.csv", DATA/"state_overrides.csv", 200, count_csv)
|
| 60 |
+
check("toll_plazas.csv", DATA/"roads/toll_plazas.csv", 50000, count_csv)
|
| 61 |
+
check("hospital_directory.csv", DATA/"hospitals/hospital_directory.csv", 1000000)
|
| 62 |
+
check("nin_facilities.csv", DATA/"hospitals/nin_facilities.csv", 5000000)
|
| 63 |
+
check("police_stations.csv", DATA/"emergency/police_stations.csv", 50000, count_csv)
|
| 64 |
+
check("fire_stations.csv", DATA/"emergency/fire_stations.csv", 10000, count_csv)
|
| 65 |
+
|
| 66 |
+
# Backend challan CSVs
|
| 67 |
+
check("backend violations.csv", "backend/datasets/challan/violations.csv", 500, count_csv)
|
| 68 |
+
check("backend state_overrides.csv", "backend/datasets/challan/state_overrides.csv", 200, count_csv)
|
| 69 |
+
|
| 70 |
+
# Frontend JSONs
|
| 71 |
+
check("first-aid.json (frontend)", FRONTEND/"first-aid.json", 5000, count_json)
|
| 72 |
+
check("first_aid.json (chatbot)", DATA/"first_aid.json", 5000, count_json)
|
| 73 |
+
check("india-emergency.geojson", FRONTEND/"india-emergency.geojson", 1000000, geojson_features)
|
| 74 |
+
check("violations.csv (frontend)", FRONTEND/"violations.csv", 200, count_csv)
|
| 75 |
+
|
| 76 |
+
# Large files
|
| 77 |
+
check("pmgsy_roads.geojson", DATA/"roads/pmgsy_roads.geojson", 50_000_000)
|
| 78 |
+
check("kaggle_india_accidents.csv", DATA/"accidents/kaggle_india_accidents.csv", 10000000)
|
| 79 |
+
|
| 80 |
+
# morth_2022 extracted
|
| 81 |
+
morth_dir = DATA / "accidents/morth_2022"
|
| 82 |
+
extracted = list(morth_dir.glob("extracted_*.csv"))
|
| 83 |
+
check("morth_2022 extracted tables", morth_dir, 10000,
|
| 84 |
+
lambda p: f"{len(extracted)} extracted CSVs")
|
| 85 |
+
|
| 86 |
+
print()
|
| 87 |
+
print("=" * 70)
|
| 88 |
+
print(f" DATA PIPELINE FINAL VERIFICATION -- {len(checks)} checks")
|
| 89 |
+
print("=" * 70)
|
| 90 |
+
fail = warn = 0
|
| 91 |
+
for status, label, detail in checks:
|
| 92 |
+
icon = "[PASS]" if status == "PASS" else ("[FAIL]" if status == "FAIL" else "[WARN]")
|
| 93 |
+
print(f" {icon} {label:<45} {detail}")
|
| 94 |
+
if status == "FAIL": fail += 1
|
| 95 |
+
if status == "WARN": warn += 1
|
| 96 |
+
print("=" * 70)
|
| 97 |
+
print(f" Result: {len(checks)-fail-warn} PASS | {warn} WARN | {fail} FAIL")
|
| 98 |
+
print("=" * 70)
|