|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Small-territory postcodes bulk importer for issue #1039. |
| 3 | +
|
| 4 | +Source data |
| 5 | +----------- |
| 6 | +The following territories use small fixed sets of postal codes |
| 7 | +(area- or district-level granularity), each documented in the |
| 8 | +respective national post / Wikipedia references: |
| 9 | +
|
| 10 | +- GG Guernsey: GY1-GY10 (10 districts; Bailiwick of Guernsey + Alderney + Sark) |
| 11 | +- JE Jersey: JE1-JE5 (5 districts; Bailiwick of Jersey) |
| 12 | +- IM Isle of Man: IM1-IM9 + IM86/87/98/99 (13 districts; PO boxes) |
| 13 | +- AI Anguilla: AI-2640 (1 code, country-wide) |
| 14 | +- VG British V.I.: VG1110-VG1170 (7 codes; Tortola, Virgin Gorda, Anegada, etc.) |
| 15 | +- VC St. Vincent: VC0100-VC0400 (4 codes) |
| 16 | +
|
| 17 | +Each area covers a populated locality. Country-only state FK ship — |
| 18 | +these territories' parish/district hierarchies don't 1:1 with the |
| 19 | +postal districts; precision is preserved by listing all districts |
| 20 | +explicitly. |
| 21 | +
|
| 22 | +What this script does |
| 23 | +--------------------- |
| 24 | +Emits 6 contributions/postcodes/<iso2>.json files with hand-curated |
| 25 | +postcode lists keyed to canonical area names from Royal Mail / each |
| 26 | +post's published references. |
| 27 | +
|
| 28 | +License & attribution |
| 29 | +--------------------- |
| 30 | +Postcode assignments are public Royal Mail / national-post conventions. |
| 31 | +Each row carries ``source: "wikipedia-small-territory"`` for |
| 32 | +export-time provenance. |
| 33 | +
|
| 34 | +Usage |
| 35 | +----- |
| 36 | + python3 bin/scripts/sync/import_small_territory_postcodes.py |
| 37 | +""" |
| 38 | + |
| 39 | +from __future__ import annotations |
| 40 | + |
| 41 | +import argparse |
| 42 | +import json |
| 43 | +import re |
| 44 | +import sys |
| 45 | +from pathlib import Path |
| 46 | +from typing import Dict, List, Tuple |
| 47 | + |
| 48 | + |
| 49 | +# iso2 -> list of (postcode, locality_name) tuples |
| 50 | +TERRITORIES: Dict[str, List[Tuple[str, str]]] = { |
| 51 | + "GG": [ |
| 52 | + ("GY1 1AA", "St Peter Port"), |
| 53 | + ("GY2 4AA", "St Sampson"), |
| 54 | + ("GY3 5AA", "Vale and Castel"), |
| 55 | + ("GY4 6AA", "St Saviour"), |
| 56 | + ("GY5 7AA", "St Andrew"), |
| 57 | + ("GY6 8AA", "Forest"), |
| 58 | + ("GY7 9AA", "St Pierre du Bois and Torteval"), |
| 59 | + ("GY8 0AA", "St Martin"), |
| 60 | + ("GY9 3AA", "Alderney, Sark and Herm"), |
| 61 | + ("GY10 1AA", "St Peter Port PO Box"), |
| 62 | + ], |
| 63 | + "JE": [ |
| 64 | + ("JE1 1AA", "St Helier PO Box"), |
| 65 | + ("JE2 3AA", "St Helier"), |
| 66 | + ("JE3 4AA", "Outer Parishes"), |
| 67 | + ("JE4 5AA", "St Helier large PO Box"), |
| 68 | + ("JE5 0AA", "St Helier"), |
| 69 | + ], |
| 70 | + "IM": [ |
| 71 | + ("IM1 1AA", "Douglas Central"), |
| 72 | + ("IM2 1AA", "Douglas North"), |
| 73 | + ("IM3 1AA", "Onchan"), |
| 74 | + ("IM4 1AA", "Douglas Outer"), |
| 75 | + ("IM5 1AA", "Crosby and Foxdale"), |
| 76 | + ("IM6 1AA", "Peel"), |
| 77 | + ("IM7 1AA", "St Johns"), |
| 78 | + ("IM8 1AA", "Ramsey and Maughold"), |
| 79 | + ("IM9 1AA", "Castletown and Rushen"), |
| 80 | + ("IM86 1AA", "Douglas PO Box"), |
| 81 | + ("IM87 1AA", "Douglas PO Box"), |
| 82 | + ("IM98 1AA", "Douglas PO Box"), |
| 83 | + ("IM99 1AA", "Douglas PO Box"), |
| 84 | + ], |
| 85 | + "AI": [ |
| 86 | + ("AI-2640", "Anguilla"), |
| 87 | + ], |
| 88 | + "VG": [ |
| 89 | + ("VG1110", "Road Town, Tortola"), |
| 90 | + ("VG1120", "Tortola"), |
| 91 | + ("VG1130", "Tortola"), |
| 92 | + ("VG1140", "Tortola"), |
| 93 | + ("VG1150", "Virgin Gorda"), |
| 94 | + ("VG1160", "Anegada"), |
| 95 | + ("VG1170", "Jost Van Dyke"), |
| 96 | + ], |
| 97 | + "VC": [ |
| 98 | + ("VC0100", "Kingstown"), |
| 99 | + ("VC0200", "Saint Vincent"), |
| 100 | + ("VC0300", "Bequia and Grenadines"), |
| 101 | + ("VC0400", "Union Island"), |
| 102 | + ], |
| 103 | + "BM": [ |
| 104 | + # Bermuda 9 parishes -> standard ZZ XX area codes (Wikipedia) |
| 105 | + ("DD 01", "Devonshire (DV)"), |
| 106 | + ("HM 01", "Hamilton Parish (HM)"), |
| 107 | + ("HS 01", "Hamilton (HM Sandys)"), |
| 108 | + ("PG 01", "Paget Parish (PG)"), |
| 109 | + ("MA 01", "Pembroke (MA)"), |
| 110 | + ("FL 01", "Sandys Parish (FL)"), |
| 111 | + ("GE 01", "St George's Parish (GE)"), |
| 112 | + ("SN 01", "Smith's Parish (SN)"), |
| 113 | + ("SB 01", "Southampton Parish (SB)"), |
| 114 | + ("WK 01", "Warwick Parish (WK)"), |
| 115 | + ("CR 01", "Hamilton city centre (CR)"), |
| 116 | + ], |
| 117 | +} |
| 118 | + |
| 119 | + |
| 120 | +def main() -> int: |
| 121 | + parser = argparse.ArgumentParser(description=__doc__) |
| 122 | + parser.add_argument("--dry-run", action="store_true") |
| 123 | + args = parser.parse_args() |
| 124 | + |
| 125 | + project_root = Path(__file__).resolve().parents[3] |
| 126 | + countries = json.load( |
| 127 | + (project_root / "contributions/countries/countries.json").open(encoding="utf-8") |
| 128 | + ) |
| 129 | + countries_by_iso2 = {c["iso2"]: c for c in countries} |
| 130 | + |
| 131 | + written: List[str] = [] |
| 132 | + for iso2, entries in TERRITORIES.items(): |
| 133 | + country = countries_by_iso2.get(iso2) |
| 134 | + if country is None: |
| 135 | + print(f"WARN: {iso2} not in countries.json", file=sys.stderr) |
| 136 | + continue |
| 137 | + regex = re.compile(country.get("postal_code_regex") or ".*") |
| 138 | + |
| 139 | + records: List[dict] = [] |
| 140 | + skipped = 0 |
| 141 | + for code, locality in entries: |
| 142 | + if not regex.match(code): |
| 143 | + print( |
| 144 | + f" WARN: {iso2}/{code!r} fails regex {regex.pattern!r}", |
| 145 | + file=sys.stderr, |
| 146 | + ) |
| 147 | + skipped += 1 |
| 148 | + continue |
| 149 | + record: Dict[str, object] = { |
| 150 | + "code": code, |
| 151 | + "country_id": int(country["id"]), |
| 152 | + "country_code": iso2, |
| 153 | + "locality_name": locality, |
| 154 | + "type": "area", |
| 155 | + "source": "wikipedia-small-territory", |
| 156 | + } |
| 157 | + records.append(record) |
| 158 | + |
| 159 | + if args.dry_run: |
| 160 | + print(f" {iso2}: would write {len(records)} record(s) ({skipped} skipped)") |
| 161 | + continue |
| 162 | + |
| 163 | + if not records: |
| 164 | + print(f" {iso2}: 0 records emitted (all failed regex)") |
| 165 | + continue |
| 166 | + |
| 167 | + target = project_root / f"contributions/postcodes/{iso2}.json" |
| 168 | + target.parent.mkdir(parents=True, exist_ok=True) |
| 169 | + if target.exists(): |
| 170 | + with target.open(encoding="utf-8") as f: |
| 171 | + existing = json.load(f) |
| 172 | + existing_seen = { |
| 173 | + (r["code"], (r.get("locality_name") or "").lower()) |
| 174 | + for r in existing |
| 175 | + } |
| 176 | + merged = list(existing) |
| 177 | + for r in records: |
| 178 | + key = (r["code"], (r.get("locality_name") or "").lower()) |
| 179 | + if key not in existing_seen: |
| 180 | + merged.append(r) |
| 181 | + existing_seen.add(key) |
| 182 | + merged.sort(key=lambda r: (r["code"], r.get("locality_name", ""))) |
| 183 | + else: |
| 184 | + merged = sorted( |
| 185 | + records, key=lambda r: (r["code"], r.get("locality_name", "")) |
| 186 | + ) |
| 187 | + |
| 188 | + with target.open("w", encoding="utf-8") as f: |
| 189 | + json.dump(merged, f, ensure_ascii=False, indent=2) |
| 190 | + f.write("\n") |
| 191 | + size_kb = target.stat().st_size / 1024 |
| 192 | + print( |
| 193 | + f" [OK] {target.relative_to(project_root)} " |
| 194 | + f"({len(merged)} record(s), {size_kb:.1f} KB)" |
| 195 | + ) |
| 196 | + written.append(iso2) |
| 197 | + |
| 198 | + print(f"\nShipped: {len(written)} territories: {', '.join(written)}") |
| 199 | + return 0 |
| 200 | + |
| 201 | + |
| 202 | +if __name__ == "__main__": |
| 203 | + raise SystemExit(main()) |
0 commit comments