|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Namibia -> contributions/postcodes/NA.json importer for issue #1039. |
| 3 | +
|
| 4 | +Source data |
| 5 | +----------- |
| 6 | +The community ``KuberKode/namibia-postal-codes`` repository ships |
| 7 | +NamPost (Namibia Post Limited) postal codes scraped from the |
| 8 | +official PDF directory and reorganised into nested JSON: |
| 9 | +
|
| 10 | + { |
| 11 | + "Country": { "Alpha-2": "NA", "Regions": [ |
| 12 | + { "RegionName": "Erongo", "RegionCode": "NA-ER", |
| 13 | + "Locations": [ |
| 14 | + { "Location": "Swakopmund", "Postal Code": 13001 }, ... |
| 15 | + ] |
| 16 | + }, ... |
| 17 | + ]} |
| 18 | + } |
| 19 | +
|
| 20 | +14 regions × ~10-35 locations each = ~155 codes, 5-digit numeric. |
| 21 | +
|
| 22 | +Source URL: https://raw.githubusercontent.com/KuberKode/namibia-postal-codes/main/namibia-postal-codes.json |
| 23 | +
|
| 24 | +What this script does |
| 25 | +--------------------- |
| 26 | +1. Fetches the JSON via urllib. |
| 27 | +2. Walks ``Country.Regions[].Locations[]``. |
| 28 | +3. Maps source ``RegionCode`` ("NA-XX") to CSC iso2 by stripping |
| 29 | + the ``NA-`` prefix — all 14 region codes match CSC's states.json |
| 30 | + directly (ER, HA, KA, KE, KW, KH, KU, OW, OH, OS, ON, OT, OD, CA). |
| 31 | +4. Writes contributions/postcodes/NA.json idempotently. |
| 32 | +
|
| 33 | +Coverage |
| 34 | +-------- |
| 35 | +~155 records covering all 14 Namibian regions. Khomas (Windhoek |
| 36 | +metro) is the densest at ~35 codes; sparser rural regions like |
| 37 | +Kavango West average 2-6. |
| 38 | +
|
| 39 | +License & attribution |
| 40 | +--------------------- |
| 41 | +- Source: KuberKode/namibia-postal-codes (Unlicense / public domain) |
| 42 | +- Original data: NamPost public postal-code directory |
| 43 | +- Each row: ``source: "nampost-via-kuberkode"`` |
| 44 | +
|
| 45 | +Usage |
| 46 | +----- |
| 47 | + python3 bin/scripts/sync/import_namibia_postcodes.py |
| 48 | +""" |
| 49 | + |
| 50 | +from __future__ import annotations |
| 51 | + |
| 52 | +import argparse |
| 53 | +import json |
| 54 | +import re |
| 55 | +import sys |
| 56 | +import urllib.request |
| 57 | +from pathlib import Path |
| 58 | +from typing import Dict, List |
| 59 | + |
| 60 | + |
| 61 | +SOURCE_URL = ( |
| 62 | + "https://raw.githubusercontent.com/KuberKode/namibia-postal-codes/" |
| 63 | + "main/namibia-postal-codes.json" |
| 64 | +) |
| 65 | + |
| 66 | + |
| 67 | +def fetch_json(url: str) -> dict: |
| 68 | + """Fetch and parse JSON via urllib.""" |
| 69 | + req = urllib.request.Request( |
| 70 | + url, headers={"User-Agent": "csc-database-postcode-importer"} |
| 71 | + ) |
| 72 | + with urllib.request.urlopen(req, timeout=30) as r: |
| 73 | + return json.loads(r.read().decode("utf-8")) |
| 74 | + |
| 75 | + |
| 76 | +def main() -> int: |
| 77 | + parser = argparse.ArgumentParser(description=__doc__) |
| 78 | + parser.add_argument("--input", default=None, help="local JSON (skip fetch)") |
| 79 | + parser.add_argument("--dry-run", action="store_true") |
| 80 | + args = parser.parse_args() |
| 81 | + |
| 82 | + payload = ( |
| 83 | + json.loads(Path(args.input).read_text(encoding="utf-8")) |
| 84 | + if args.input |
| 85 | + else fetch_json(SOURCE_URL) |
| 86 | + ) |
| 87 | + regions = payload.get("Country", {}).get("Regions", []) |
| 88 | + print(f"Source regions: {len(regions)}") |
| 89 | + |
| 90 | + project_root = Path(__file__).resolve().parents[3] |
| 91 | + countries = json.load( |
| 92 | + (project_root / "contributions/countries/countries.json").open(encoding="utf-8") |
| 93 | + ) |
| 94 | + na_country = next((c for c in countries if c.get("iso2") == "NA"), None) |
| 95 | + if na_country is None: |
| 96 | + print("ERROR: NA not in countries.json", file=sys.stderr) |
| 97 | + return 2 |
| 98 | + regex = re.compile(na_country.get("postal_code_regex") or ".*") |
| 99 | + |
| 100 | + states_all = json.load( |
| 101 | + (project_root / "contributions/states/states.json").open(encoding="utf-8") |
| 102 | + ) |
| 103 | + na_states = [s for s in states_all if s.get("country_id") == na_country["id"]] |
| 104 | + state_by_iso2: Dict[str, dict] = { |
| 105 | + s["iso2"]: s for s in na_states if s.get("iso2") |
| 106 | + } |
| 107 | + print( |
| 108 | + f"Country: Namibia (id={na_country['id']}); " |
| 109 | + f"states indexed: {len(na_states)}" |
| 110 | + ) |
| 111 | + |
| 112 | + seen: set = set() |
| 113 | + records: List[dict] = [] |
| 114 | + skipped_bad_regex = 0 |
| 115 | + matched_state = 0 |
| 116 | + unknown_regions: Dict[str, int] = {} |
| 117 | + |
| 118 | + for region in regions: |
| 119 | + region_code = (region.get("RegionCode") or "").strip() |
| 120 | + # RegionCode is ISO 3166-2 ("NA-ER"); strip prefix. |
| 121 | + iso2 = region_code.split("-", 1)[-1] if region_code else "" |
| 122 | + state = state_by_iso2.get(iso2) |
| 123 | + if state is None: |
| 124 | + unknown_regions[region_code] = ( |
| 125 | + unknown_regions.get(region_code, 0) + len(region.get("Locations", [])) |
| 126 | + ) |
| 127 | + |
| 128 | + for loc in region.get("Locations", []): |
| 129 | + raw_code = loc.get("Postal Code") |
| 130 | + if raw_code is None: |
| 131 | + continue |
| 132 | + # Codes ship as integers — re-pad to 5 digits. |
| 133 | + code = str(raw_code).zfill(5) |
| 134 | + if not regex.match(code): |
| 135 | + skipped_bad_regex += 1 |
| 136 | + continue |
| 137 | + |
| 138 | + locality = (loc.get("Location") or "").strip() |
| 139 | + key = (code, locality.lower()) |
| 140 | + if key in seen: |
| 141 | + continue |
| 142 | + seen.add(key) |
| 143 | + |
| 144 | + record: Dict[str, object] = { |
| 145 | + "code": code, |
| 146 | + "country_id": int(na_country["id"]), |
| 147 | + "country_code": "NA", |
| 148 | + } |
| 149 | + if state is not None: |
| 150 | + record["state_id"] = int(state["id"]) |
| 151 | + record["state_code"] = state.get("iso2") |
| 152 | + matched_state += 1 |
| 153 | + if locality: |
| 154 | + record["locality_name"] = locality |
| 155 | + record["type"] = "full" |
| 156 | + record["source"] = "nampost-via-kuberkode" |
| 157 | + records.append(record) |
| 158 | + |
| 159 | + print(f"Skipped (regex fail): {skipped_bad_regex:,}") |
| 160 | + print(f"Records emitted: {len(records):,}") |
| 161 | + pct = matched_state * 100 // max(1, len(records)) |
| 162 | + print(f" with state: {matched_state:,} ({pct}%)") |
| 163 | + if unknown_regions: |
| 164 | + print("Unknown RegionCodes (not in CSC states.json):") |
| 165 | + for r, n in sorted(unknown_regions.items(), key=lambda x: -x[1]): |
| 166 | + print(f" {r!r}: {n}") |
| 167 | + |
| 168 | + if args.dry_run: |
| 169 | + return 0 |
| 170 | + |
| 171 | + target = project_root / "contributions/postcodes/NA.json" |
| 172 | + target.parent.mkdir(parents=True, exist_ok=True) |
| 173 | + if target.exists(): |
| 174 | + with target.open(encoding="utf-8") as f: |
| 175 | + existing = json.load(f) |
| 176 | + existing_seen = { |
| 177 | + (r["code"], (r.get("locality_name") or "").lower()) for r in existing |
| 178 | + } |
| 179 | + merged = list(existing) |
| 180 | + for r in records: |
| 181 | + key = (r["code"], (r.get("locality_name") or "").lower()) |
| 182 | + if key not in existing_seen: |
| 183 | + merged.append(r) |
| 184 | + existing_seen.add(key) |
| 185 | + merged.sort(key=lambda r: (r["code"], r.get("locality_name", ""))) |
| 186 | + else: |
| 187 | + merged = sorted(records, key=lambda r: (r["code"], r.get("locality_name", ""))) |
| 188 | + |
| 189 | + with target.open("w", encoding="utf-8") as f: |
| 190 | + json.dump(merged, f, ensure_ascii=False, indent=2) |
| 191 | + f.write("\n") |
| 192 | + size_kb = target.stat().st_size / 1024 |
| 193 | + print( |
| 194 | + f"\n[OK] Wrote {target.relative_to(project_root)} " |
| 195 | + f"({len(merged):,} rows, {size_kb:.0f} KB)" |
| 196 | + ) |
| 197 | + return 0 |
| 198 | + |
| 199 | + |
| 200 | +if __name__ == "__main__": |
| 201 | + raise SystemExit(main()) |
0 commit comments