osint-dashboard/news/summerizer/gazetteer.py

193 lines
6.2 KiB
Python
Raw Permalink Normal View History

"""Offline GeoNames gazetteer — proximate geolocation for graded articles.
When a map-phase block names a place but gives no coordinates, resolve the
name against vendored GeoNames data (``data/``): cities15000 first, then
country -> capital. Fully offline: no paid API, no rate-limited Nominatim,
no network at runtime. Every resolution is labelled confidence "approx"
by the caller — a gazetteer point is a proximate guess, never an exact fix.
Matching is best-effort and conservative: normalised (case/diacritic-folded)
exact-name lookups with country/admin1 context disambiguation ("Paris,
Texas" vs "Paris, France"), highest population wins ties. A miss returns
None — the article simply gets no blip. Never invents a place.
"""
from __future__ import annotations
import unicodedata
from functools import lru_cache
from pathlib import Path
_DATA_DIR = Path(__file__).resolve().parent / "data"
# Common short forms the model writes that GeoNames spells out.
_COUNTRY_ALIASES = {
"usa": "US",
"u.s.a.": "US",
"u.s.": "US",
"us": "US",
"uk": "GB",
"u.k.": "GB",
"united states of america": "US",
"england": "GB",
"south korea": "KR",
"north korea": "KP",
}
def _norm(text: str) -> str:
"""Casefold + strip diacritics + collapse whitespace for matching."""
text = unicodedata.normalize("NFKD", text)
text = "".join(ch for ch in text if not unicodedata.combining(ch))
return " ".join(text.casefold().split())
def _read_tsv(filename: str) -> list[list[str]]:
path = _DATA_DIR / filename
rows: list[list[str]] = []
try:
with open(path, encoding="utf-8") as fh:
for line in fh:
parts = line.rstrip("\n").split("\t")
if parts and parts[0]:
rows.append(parts)
except OSError:
return []
return rows
@lru_cache(maxsize=1)
def _city_index() -> dict[str, list[tuple[float, float, int, str, str]]]:
"""norm name -> [(lat, lon, population, country_code, admin1_code)]."""
index: dict[str, list[tuple[float, float, int, str, str]]] = {}
for parts in _read_tsv("cities15000.tsv"):
if len(parts) < 7:
continue
name, asciiname, lat, lon, pop, cc, admin1 = parts[:7]
try:
lat_f, lon_f, pop_i = float(lat), float(lon), int(pop)
except ValueError:
continue
if not (-90 <= lat_f <= 90 and -180 <= lon_f <= 180):
continue
entry = (lat_f, lon_f, pop_i, cc, admin1)
for key in {name, asciiname}:
key = _norm(key)
if key:
index.setdefault(key, []).append(entry)
return index
@lru_cache(maxsize=1)
def _country_index() -> dict[str, tuple[str, str]]:
"""norm country name/iso -> (iso_code, capital)."""
index: dict[str, tuple[str, str]] = {}
for parts in _read_tsv("countries.tsv"):
if len(parts) < 3:
continue
iso, name, capital = parts[:3]
value = (iso, capital)
index[_norm(name)] = value
index[iso.casefold()] = value
for alias, iso in _COUNTRY_ALIASES.items():
hit = index.get(iso.casefold())
if hit:
index[_norm(alias)] = hit
return index
@lru_cache(maxsize=1)
def _admin1_index() -> dict[str, list[tuple[str, str]]]:
"""norm division name -> [(country_code, admin1_code)]."""
index: dict[str, list[tuple[str, str]]] = {}
for parts in _read_tsv("admin1.tsv"):
if len(parts) < 3 or "." not in parts[0]:
continue
code, name, asciiname = parts[:3]
cc, _, a1 = code.partition(".")
for key in {name, asciiname}:
key = _norm(key)
if key:
index.setdefault(key, []).append((cc, a1))
return index
def _pick(entries: list[tuple[float, float, int, str, str]]) -> tuple[float, float]:
best = max(entries, key=lambda e: e[2])
return (best[0], best[1])
def resolve_place(location_name) -> tuple[float, float] | None:
"""Proximate (lat, lon) for a model-written place name, else None.
Tries the full string, then the comma-leading part, with trailing
parts as country/admin1 context. Falls back to country -> capital.
"""
if not isinstance(location_name, str):
return None
text = location_name.strip()
if not text:
return None
parts = [p.strip() for p in text.split(",") if p.strip()]
if not parts:
return None
countries = _country_index()
admin1s = _admin1_index()
context_country: str | None = None
context_admin1: list[tuple[str, str]] = []
for part in parts[1:]:
key = _norm(part)
hit = countries.get(key)
if hit:
context_country = hit[0]
continue
context_admin1.extend(admin1s.get(key, []))
cities = _city_index()
for candidate in (text, parts[0]):
entries = cities.get(_norm(candidate))
if not entries:
continue
if context_admin1:
scoped = [
e for e in entries
if any(e[3] == cc and e[4] == a1 for cc, a1 in context_admin1)
]
if scoped:
return _pick(scoped)
if context_country:
scoped = [e for e in entries if e[3] == context_country]
if scoped:
return _pick(scoped)
return _pick(entries)
# Country-only location ("Ukraine"): resolve to the capital.
hit = countries.get(_norm(parts[0]))
if hit:
entries = cities.get(_norm(hit[1]))
if entries:
return _pick(entries)
return None
def fill_block_geo(block: dict) -> dict:
"""Fill missing coords on a parsed map block from the gazetteer.
Blocks that already carry model coordinates are untouched. A resolved
place is labelled confidence "approx"; a miss leaves the block as-is
(name preserved, no coords) — never invents a place.
"""
if not isinstance(block, dict):
return block
if block.get("lat") is not None and block.get("lon") is not None:
return block
name = block.get("location_name")
if not name:
return block
coords = resolve_place(name)
if coords is None:
return block
block["lat"], block["lon"] = coords
block["location_confidence"] = "approx"
return block