|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Singleton-postcode UK overseas territories importer for issue #1039. |
| 3 | +
|
| 4 | +Source data |
| 5 | +----------- |
| 6 | +The following territories use a single fixed Royal Mail-style |
| 7 | +postcode each, assigned by the British postal system: |
| 8 | +
|
| 9 | + Country iso2 postcode ship to |
| 10 | + Falkland Islands FK FIQQ 1ZZ |
| 11 | + South Georgia (S. Sand.) GS SIQQ 1ZZ |
| 12 | + BIOT (Diego Garcia, ...) IO BBND 1ZZ |
| 13 | + Pitcairn Islands PN PCRN 1ZZ |
| 14 | + Saint Helena (Island) SH STHL 1ZZ |
| 15 | + Ascension Island SH ASCN 1ZZ (same SH country) |
| 16 | + Tristan da Cunha SH TDCU 1ZZ (same SH country) |
| 17 | + Turks and Caicos Islands TC TKCA 1ZZ |
| 18 | + Nauru NR NRU68 |
| 19 | +
|
| 20 | +Source: Royal Mail / Wikipedia public references for each Crown |
| 21 | +Dependency or Overseas Territory's postcode assignment. |
| 22 | +
|
| 23 | +What this script does |
| 24 | +--------------------- |
| 25 | +Emits 7 contributions/postcodes/<iso2>.json files (SH gets all |
| 26 | +three Atlantic Saint-Helena-overseas postcodes in one file). |
| 27 | +
|
| 28 | +State FK |
| 29 | +-------- |
| 30 | +Country-only ship for all (these countries have either a single |
| 31 | +state or no formal sub-state postcode mapping). |
| 32 | +
|
| 33 | +License & attribution |
| 34 | +--------------------- |
| 35 | +Postcode assignments are public Royal Mail / national-post conventions; |
| 36 | +no formal license required. Each row carries |
| 37 | +``source: "wikipedia-singleton-territory"`` for export-time provenance. |
| 38 | +
|
| 39 | +Usage |
| 40 | +----- |
| 41 | + python3 bin/scripts/sync/import_singleton_territory_postcodes.py |
| 42 | +""" |
| 43 | + |
| 44 | +from __future__ import annotations |
| 45 | + |
| 46 | +import argparse |
| 47 | +import json |
| 48 | +import re |
| 49 | +import sys |
| 50 | +from pathlib import Path |
| 51 | +from typing import Dict, List |
| 52 | + |
| 53 | + |
| 54 | +# iso2 -> list of (postcode, locality_name) tuples |
| 55 | +TERRITORIES: Dict[str, List[tuple]] = { |
| 56 | + "FK": [("FIQQ 1ZZ", "Falkland Islands")], |
| 57 | + "GS": [("SIQQ 1ZZ", "South Georgia and the South Sandwich Islands")], |
| 58 | + "IO": [("BBND 1ZZ", "British Indian Ocean Territory")], |
| 59 | + "PN": [("PCRN 1ZZ", "Pitcairn Islands")], |
| 60 | + "SH": [ |
| 61 | + ("STHL 1ZZ", "Saint Helena"), |
| 62 | + ("ASCN 1ZZ", "Ascension Island"), |
| 63 | + ("TDCU 1ZZ", "Tristan da Cunha"), |
| 64 | + ], |
| 65 | + "TC": [("TKCA 1ZZ", "Turks and Caicos Islands")], |
| 66 | + "NR": [("NRU68", "Nauru")], |
| 67 | +} |
| 68 | + |
| 69 | + |
| 70 | +def main() -> int: |
| 71 | + parser = argparse.ArgumentParser(description=__doc__) |
| 72 | + parser.add_argument("--dry-run", action="store_true") |
| 73 | + args = parser.parse_args() |
| 74 | + |
| 75 | + project_root = Path(__file__).resolve().parents[3] |
| 76 | + countries = json.load( |
| 77 | + (project_root / "contributions/countries/countries.json").open(encoding="utf-8") |
| 78 | + ) |
| 79 | + countries_by_iso2 = {c["iso2"]: c for c in countries} |
| 80 | + |
| 81 | + written: List[str] = [] |
| 82 | + for iso2, entries in TERRITORIES.items(): |
| 83 | + country = countries_by_iso2.get(iso2) |
| 84 | + if country is None: |
| 85 | + print(f"WARN: {iso2} not in countries.json", file=sys.stderr) |
| 86 | + continue |
| 87 | + regex = re.compile(country.get("postal_code_regex") or ".*") |
| 88 | + |
| 89 | + records: List[dict] = [] |
| 90 | + for code, locality in entries: |
| 91 | + if not regex.match(code): |
| 92 | + print( |
| 93 | + f" WARN: {iso2}/{code!r} fails regex {regex.pattern!r}", |
| 94 | + file=sys.stderr, |
| 95 | + ) |
| 96 | + continue |
| 97 | + record: Dict[str, object] = { |
| 98 | + "code": code, |
| 99 | + "country_id": int(country["id"]), |
| 100 | + "country_code": iso2, |
| 101 | + "locality_name": locality, |
| 102 | + "type": "full", |
| 103 | + "source": "wikipedia-singleton-territory", |
| 104 | + } |
| 105 | + records.append(record) |
| 106 | + |
| 107 | + if args.dry_run: |
| 108 | + print(f" {iso2}: would write {len(records)} record(s)") |
| 109 | + continue |
| 110 | + |
| 111 | + target = project_root / f"contributions/postcodes/{iso2}.json" |
| 112 | + target.parent.mkdir(parents=True, exist_ok=True) |
| 113 | + if target.exists(): |
| 114 | + with target.open(encoding="utf-8") as f: |
| 115 | + existing = json.load(f) |
| 116 | + existing_seen = { |
| 117 | + (r["code"], (r.get("locality_name") or "").lower()) |
| 118 | + for r in existing |
| 119 | + } |
| 120 | + merged = list(existing) |
| 121 | + for r in records: |
| 122 | + key = (r["code"], (r.get("locality_name") or "").lower()) |
| 123 | + if key not in existing_seen: |
| 124 | + merged.append(r) |
| 125 | + existing_seen.add(key) |
| 126 | + merged.sort(key=lambda r: (r["code"], r.get("locality_name", ""))) |
| 127 | + else: |
| 128 | + merged = sorted( |
| 129 | + records, key=lambda r: (r["code"], r.get("locality_name", "")) |
| 130 | + ) |
| 131 | + |
| 132 | + with target.open("w", encoding="utf-8") as f: |
| 133 | + json.dump(merged, f, ensure_ascii=False, indent=2) |
| 134 | + f.write("\n") |
| 135 | + size_kb = target.stat().st_size / 1024 |
| 136 | + print( |
| 137 | + f" [OK] {target.relative_to(project_root)} " |
| 138 | + f"({len(merged)} record(s), {size_kb:.1f} KB)" |
| 139 | + ) |
| 140 | + written.append(iso2) |
| 141 | + |
| 142 | + print(f"\nShipped: {len(written)} territories: {', '.join(written)}") |
| 143 | + return 0 |
| 144 | + |
| 145 | + |
| 146 | +if __name__ == "__main__": |
| 147 | + raise SystemExit(main()) |
0 commit comments