|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Fetch and normalize optional overlay files for geocompare. |
| 3 | +
|
| 4 | +Writes canonical overlay CSVs under: |
| 5 | + <out-dir>/overlays/{crime_data.csv,voter_data.csv} |
| 6 | +""" |
| 7 | + |
| 8 | +from __future__ import annotations |
| 9 | + |
| 10 | +import argparse |
| 11 | +import csv |
| 12 | +import json |
| 13 | +import sys |
| 14 | +import urllib.request |
| 15 | +from pathlib import Path |
| 16 | +from typing import Dict, Iterable, List, Optional |
| 17 | + |
| 18 | +CANONICAL_FILES = { |
| 19 | + "crime": "crime_data.csv", |
| 20 | + "voter": "voter_data.csv", |
| 21 | +} |
| 22 | + |
| 23 | + |
| 24 | +def _read_text_from_source(source: str) -> str: |
| 25 | + if source.startswith("http://") or source.startswith("https://"): |
| 26 | + with urllib.request.urlopen(source) as response: # nosec - user-provided source |
| 27 | + return response.read().decode("utf-8") |
| 28 | + return Path(source).read_text(encoding="utf-8") |
| 29 | + |
| 30 | + |
| 31 | +def _normalize_key(value: str) -> str: |
| 32 | + return value.strip().lower().replace(" ", "_") |
| 33 | + |
| 34 | + |
| 35 | +def _parse_records(source: str) -> List[Dict[str, str]]: |
| 36 | + text = _read_text_from_source(source) |
| 37 | + stripped = text.lstrip() |
| 38 | + if stripped.startswith("[") or stripped.startswith("{"): |
| 39 | + payload = json.loads(text) |
| 40 | + if isinstance(payload, dict): |
| 41 | + payload = payload.get("rows", []) |
| 42 | + if not isinstance(payload, list): |
| 43 | + raise ValueError("JSON payload must be a list or object with 'rows'.") |
| 44 | + out = [] |
| 45 | + for row in payload: |
| 46 | + if isinstance(row, dict): |
| 47 | + out.append({str(k): str(v) for k, v in row.items() if v is not None}) |
| 48 | + return out |
| 49 | + |
| 50 | + reader = csv.DictReader(text.splitlines()) |
| 51 | + rows = [] |
| 52 | + for row in reader: |
| 53 | + rows.append({str(k): ("" if v is None else str(v)) for k, v in row.items() if k}) |
| 54 | + return rows |
| 55 | + |
| 56 | + |
| 57 | +def _find_col(record: Dict[str, str], aliases: Iterable[str]) -> Optional[str]: |
| 58 | + key_map = {_normalize_key(k): k for k in record.keys()} |
| 59 | + for alias in aliases: |
| 60 | + if alias in key_map: |
| 61 | + return key_map[alias] |
| 62 | + return None |
| 63 | + |
| 64 | + |
| 65 | +def _as_float(value: str) -> Optional[float]: |
| 66 | + text = value.strip() |
| 67 | + if not text: |
| 68 | + return None |
| 69 | + text = text.replace(",", "") |
| 70 | + if text.endswith("%"): |
| 71 | + text = text[:-1] |
| 72 | + try: |
| 73 | + return float(text) |
| 74 | + except ValueError: |
| 75 | + return None |
| 76 | + |
| 77 | + |
| 78 | +def _canonicalize_crime(rows: List[Dict[str, str]]) -> List[Dict[str, object]]: |
| 79 | + out = [] |
| 80 | + for row in rows: |
| 81 | + geoid_col = _find_col(row, ("geoid", "geoid20", "geoid10")) |
| 82 | + if not geoid_col: |
| 83 | + continue |
| 84 | + geoid = row.get(geoid_col, "").strip() |
| 85 | + if not geoid: |
| 86 | + continue |
| 87 | + item: Dict[str, object] = {"GEOID": geoid} |
| 88 | + mappings = { |
| 89 | + "violent_crime_count": ("violent_crime_count", "violent_crime", "violent"), |
| 90 | + "property_crime_count": ("property_crime_count", "property_crime", "property"), |
| 91 | + "total_crime_count": ("total_crime_count", "total_crime", "crime_total"), |
| 92 | + } |
| 93 | + has_metric = False |
| 94 | + for canonical, aliases in mappings.items(): |
| 95 | + col = _find_col(row, aliases) |
| 96 | + if not col: |
| 97 | + continue |
| 98 | + value = _as_float(row.get(col, "")) |
| 99 | + if value is None: |
| 100 | + continue |
| 101 | + item[canonical] = value |
| 102 | + has_metric = True |
| 103 | + if has_metric: |
| 104 | + out.append(item) |
| 105 | + return out |
| 106 | + |
| 107 | + |
| 108 | +def _canonicalize_voter(rows: List[Dict[str, str]]) -> List[Dict[str, object]]: |
| 109 | + out = [] |
| 110 | + for row in rows: |
| 111 | + geoid_col = _find_col(row, ("geoid", "geoid20", "geoid10")) |
| 112 | + if not geoid_col: |
| 113 | + continue |
| 114 | + geoid = row.get(geoid_col, "").strip() |
| 115 | + if not geoid: |
| 116 | + continue |
| 117 | + item: Dict[str, object] = {"GEOID": geoid} |
| 118 | + mappings = { |
| 119 | + "registered_voters": ("registered_voters", "total_registered", "registered"), |
| 120 | + "democratic_voters": ("democratic_voters", "dem_voters", "democratic"), |
| 121 | + "republican_voters": ("republican_voters", "rep_voters", "republican"), |
| 122 | + "other_voters": ("other_voters", "oth_voters", "other"), |
| 123 | + } |
| 124 | + has_metric = False |
| 125 | + for canonical, aliases in mappings.items(): |
| 126 | + col = _find_col(row, aliases) |
| 127 | + if not col: |
| 128 | + continue |
| 129 | + value = _as_float(row.get(col, "")) |
| 130 | + if value is None: |
| 131 | + continue |
| 132 | + item[canonical] = value |
| 133 | + has_metric = True |
| 134 | + if has_metric: |
| 135 | + out.append(item) |
| 136 | + return out |
| 137 | + |
| 138 | + |
| 139 | +def _write_csv(path: Path, rows: List[Dict[str, object]], fieldnames: List[str]) -> None: |
| 140 | + path.parent.mkdir(parents=True, exist_ok=True) |
| 141 | + with path.open("w", newline="", encoding="utf-8") as f: |
| 142 | + writer = csv.DictWriter(f, fieldnames=fieldnames) |
| 143 | + writer.writeheader() |
| 144 | + for row in rows: |
| 145 | + writer.writerow(row) |
| 146 | + |
| 147 | + |
| 148 | +def _run_one(kind: str, source: str, out_dir: Path) -> None: |
| 149 | + rows = _parse_records(source) |
| 150 | + if kind == "crime": |
| 151 | + normalized = _canonicalize_crime(rows) |
| 152 | + fieldnames = ["GEOID", "violent_crime_count", "property_crime_count", "total_crime_count"] |
| 153 | + elif kind == "voter": |
| 154 | + normalized = _canonicalize_voter(rows) |
| 155 | + fieldnames = [ |
| 156 | + "GEOID", |
| 157 | + "registered_voters", |
| 158 | + "democratic_voters", |
| 159 | + "republican_voters", |
| 160 | + "other_voters", |
| 161 | + ] |
| 162 | + else: |
| 163 | + raise ValueError(f"unsupported overlay kind: {kind}") |
| 164 | + destination = out_dir / "overlays" / CANONICAL_FILES[kind] |
| 165 | + _write_csv(destination, normalized, fieldnames) |
| 166 | + print(f"{kind}: wrote {len(normalized)} rows -> {destination}") |
| 167 | + |
| 168 | + |
| 169 | +def main() -> int: |
| 170 | + parser = argparse.ArgumentParser( |
| 171 | + description="Fetch and normalize private overlay datasets for geocompare.", |
| 172 | + ) |
| 173 | + parser.add_argument( |
| 174 | + "--out-dir", |
| 175 | + default="../000-data", |
| 176 | + help="data root where overlays/ will be written (default: ../000-data)", |
| 177 | + ) |
| 178 | + parser.add_argument("--crime-source", help="crime source CSV/JSON path or URL") |
| 179 | + parser.add_argument("--voter-source", help="voter source CSV/JSON path or URL") |
| 180 | + args = parser.parse_args() |
| 181 | + |
| 182 | + if not any([args.crime_source, args.voter_source]): |
| 183 | + parser.error("Provide at least one source: --crime-source / --voter-source") |
| 184 | + |
| 185 | + out_dir = Path(args.out_dir).resolve() |
| 186 | + try: |
| 187 | + if args.crime_source: |
| 188 | + _run_one("crime", args.crime_source, out_dir) |
| 189 | + if args.voter_source: |
| 190 | + _run_one("voter", args.voter_source, out_dir) |
| 191 | + except Exception as exc: # noqa: BLE001 |
| 192 | + print(f"error: {exc}", file=sys.stderr) |
| 193 | + return 1 |
| 194 | + return 0 |
| 195 | + |
| 196 | + |
| 197 | +if __name__ == "__main__": |
| 198 | + raise SystemExit(main()) |
0 commit comments