news: per-article proximate geolocation + GET /api/news/blips
Every graded article now carries best-effort geo on article_scores: - parse_map_scores extracts Location/Lat/Lon/Confidence per block (clamp_coords-validated; Unknown -> no geo; never invent a place) - place-name-only blocks resolve via a vendored offline GeoNames gazetteer (cities15000 + admin1 + country->capital), confidence approx - nullable location_name/lat/lon/location_confidence columns (alembic 014, single head; idempotent ensure_tables mirror) + partial bbox index - GET /api/news/blips: frozen contract, dedup by article id (latest geo wins), finite coords only, created_at DESC, bbox/since/limit, default 1000 max 5000, public read like /api/news/map - critical/high map pins, ticker, grading thresholds, dedupe unchanged Tests: 50 new summarizer geo tests (161 total), 18 new blips API contract tests; alembic upgrade heads proven on fresh DBs both start orders; forced batch on test DB yielded 10 non-critical blips with geo. Card: t_bc15eb53
This commit is contained in:
parent
5ea43a3d0b
commit
ca1c73e1a6
16 changed files with 39639 additions and 10 deletions
|
|
@ -13,7 +13,8 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
|
|||
COPY requirements.txt .
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
|
||||
COPY summarizer.py run_news_summarizer.py intel.py nous_client.py ./
|
||||
COPY summarizer.py run_news_summarizer.py intel.py nous_client.py gazetteer.py ./
|
||||
COPY data/ ./data/
|
||||
|
||||
# Security: run as a non-privileged user.
|
||||
RUN useradd -m summarizer_user
|
||||
|
|
|
|||
28
news/summerizer/data/README.md
Normal file
28
news/summerizer/data/README.md
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
# GeoNames reference data (offline gazetteer)
|
||||
|
||||
Vendored from GeoNames (https://www.geonames.org/), licensed CC-BY 4.0
|
||||
(https://creativecommons.org/licenses/by/4.0/). Attribution: "GeoNames"
|
||||
(https://www.geonames.org/) — the summarizer resolves place names to
|
||||
proximate coordinates fully offline from these files; no geocoding API
|
||||
is called at runtime.
|
||||
|
||||
## Files
|
||||
|
||||
- `cities15000.tsv` — trimmed `cities15000.txt` dump (all cities with
|
||||
population > 15000, ~34k rows). Columns (tab-separated, no header):
|
||||
`name asciiname latitude longitude population country_code admin1_code`
|
||||
Source: https://download.geonames.org/export/dump/cities15000.zip
|
||||
- `admin1.tsv` — trimmed `admin1CodesASCII.txt` (~3.9k first-level
|
||||
divisions: states/regions). Columns: `code name asciiname`
|
||||
(code is `CC.A1`, e.g. `US.TX`). Used to disambiguate "Paris, Texas"
|
||||
from "Paris, France".
|
||||
Source: https://download.geonames.org/export/dump/admin1CodesASCII.txt
|
||||
- `countries.tsv` — trimmed `countryInfo.txt` (252 rows). Columns:
|
||||
`iso_code country_name capital`
|
||||
Source: https://download.geonames.org/export/dump/countryInfo.txt
|
||||
Country-level lookups resolve to the capital's coordinates (the
|
||||
countryInfo dump carries no centroid), confidence "approx".
|
||||
|
||||
Refresh: re-download the dumps, keep the same column layout. The loader
|
||||
(`../gazetteer.py`) tolerates extra/missing trailing columns and skips
|
||||
malformed rows.
|
||||
3865
news/summerizer/data/admin1.tsv
Normal file
3865
news/summerizer/data/admin1.tsv
Normal file
File diff suppressed because it is too large
Load diff
34248
news/summerizer/data/cities15000.tsv
Normal file
34248
news/summerizer/data/cities15000.tsv
Normal file
File diff suppressed because it is too large
Load diff
252
news/summerizer/data/countries.tsv
Normal file
252
news/summerizer/data/countries.tsv
Normal file
|
|
@ -0,0 +1,252 @@
|
|||
AD Andorra Andorra la Vella
|
||||
AE United Arab Emirates Abu Dhabi
|
||||
AF Afghanistan Kabul
|
||||
AG Antigua and Barbuda St. John's
|
||||
AI Anguilla The Valley
|
||||
AL Albania Tirana
|
||||
AM Armenia Yerevan
|
||||
AO Angola Luanda
|
||||
AQ Antarctica
|
||||
AR Argentina Buenos Aires
|
||||
AS American Samoa Pago Pago
|
||||
AT Austria Vienna
|
||||
AU Australia Canberra
|
||||
AW Aruba Oranjestad
|
||||
AX Aland Islands Mariehamn
|
||||
AZ Azerbaijan Baku
|
||||
BA Bosnia and Herzegovina Sarajevo
|
||||
BB Barbados Bridgetown
|
||||
BD Bangladesh Dhaka
|
||||
BE Belgium Brussels
|
||||
BF Burkina Faso Ouagadougou
|
||||
BG Bulgaria Sofia
|
||||
BH Bahrain Manama
|
||||
BI Burundi Gitega
|
||||
BJ Benin Porto-Novo
|
||||
BL Saint Barthelemy Gustavia
|
||||
BM Bermuda Hamilton
|
||||
BN Brunei Bandar Seri Begawan
|
||||
BO Bolivia Sucre
|
||||
BQ Bonaire, Saint Eustatius and Saba
|
||||
BR Brazil Brasilia
|
||||
BS Bahamas Nassau
|
||||
BT Bhutan Thimphu
|
||||
BV Bouvet Island
|
||||
BW Botswana Gaborone
|
||||
BY Belarus Minsk
|
||||
BZ Belize Belmopan
|
||||
CA Canada Ottawa
|
||||
CC Cocos Islands West Island
|
||||
CD Democratic Republic of the Congo Kinshasa
|
||||
CF Central African Republic Bangui
|
||||
CG Republic of the Congo Brazzaville
|
||||
CH Switzerland Bern
|
||||
CI Ivory Coast Yamoussoukro
|
||||
CK Cook Islands Avarua
|
||||
CL Chile Santiago
|
||||
CM Cameroon Yaounde
|
||||
CN China Beijing
|
||||
CO Colombia Bogota
|
||||
CR Costa Rica San Jose
|
||||
CU Cuba Havana
|
||||
CV Cabo Verde Praia
|
||||
CW Curacao Willemstad
|
||||
CX Christmas Island Flying Fish Cove
|
||||
CY Cyprus Nicosia
|
||||
CZ Czechia Prague
|
||||
DE Germany Berlin
|
||||
DJ Djibouti Djibouti
|
||||
DK Denmark Copenhagen
|
||||
DM Dominica Roseau
|
||||
DO Dominican Republic Santo Domingo
|
||||
DZ Algeria Algiers
|
||||
EC Ecuador Quito
|
||||
EE Estonia Tallinn
|
||||
EG Egypt Cairo
|
||||
EH Western Sahara El-Aaiun
|
||||
ER Eritrea Asmara
|
||||
ES Spain Madrid
|
||||
ET Ethiopia Addis Ababa
|
||||
FI Finland Helsinki
|
||||
FJ Fiji Suva
|
||||
FK Falkland Islands Stanley
|
||||
FM Micronesia Palikir
|
||||
FO Faroe Islands Torshavn
|
||||
FR France Paris
|
||||
GA Gabon Libreville
|
||||
GB United Kingdom London
|
||||
GD Grenada St. George's
|
||||
GE Georgia Tbilisi
|
||||
GF French Guiana Cayenne
|
||||
GG Guernsey St Peter Port
|
||||
GH Ghana Accra
|
||||
GI Gibraltar Gibraltar
|
||||
GL Greenland Nuuk
|
||||
GM Gambia Banjul
|
||||
GN Guinea Conakry
|
||||
GP Guadeloupe Basse-Terre
|
||||
GQ Equatorial Guinea Ciudad de la Paz
|
||||
GR Greece Athens
|
||||
GS South Georgia and the South Sandwich Islands Grytviken
|
||||
GT Guatemala Guatemala City
|
||||
GU Guam Hagatna
|
||||
GW Guinea-Bissau Bissau
|
||||
GY Guyana Georgetown
|
||||
HK Hong Kong Hong Kong
|
||||
HM Heard Island and McDonald Islands
|
||||
HN Honduras Tegucigalpa
|
||||
HR Croatia Zagreb
|
||||
HT Haiti Port-au-Prince
|
||||
HU Hungary Budapest
|
||||
ID Indonesia Jakarta
|
||||
IE Ireland Dublin
|
||||
IL Israel Jerusalem
|
||||
IM Isle of Man Douglas
|
||||
IN India New Delhi
|
||||
IO British Indian Ocean Territory Diego Garcia
|
||||
IQ Iraq Baghdad
|
||||
IR Iran Tehran
|
||||
IS Iceland Reykjavik
|
||||
IT Italy Rome
|
||||
JE Jersey Saint Helier
|
||||
JM Jamaica Kingston
|
||||
JO Jordan Amman
|
||||
JP Japan Tokyo
|
||||
KE Kenya Nairobi
|
||||
KG Kyrgyzstan Bishkek
|
||||
KH Cambodia Phnom Penh
|
||||
KI Kiribati Tarawa
|
||||
KM Comoros Moroni
|
||||
KN Saint Kitts and Nevis Basseterre
|
||||
KP North Korea Pyongyang
|
||||
KR South Korea Seoul
|
||||
XK Kosovo Pristina
|
||||
KW Kuwait Kuwait City
|
||||
KY Cayman Islands George Town
|
||||
KZ Kazakhstan Nur-Sultan
|
||||
LA Laos Vientiane
|
||||
LB Lebanon Beirut
|
||||
LC Saint Lucia Castries
|
||||
LI Liechtenstein Vaduz
|
||||
LK Sri Lanka Colombo
|
||||
LR Liberia Monrovia
|
||||
LS Lesotho Maseru
|
||||
LT Lithuania Vilnius
|
||||
LU Luxembourg Luxembourg
|
||||
LV Latvia Riga
|
||||
LY Libya Tripoli
|
||||
MA Morocco Rabat
|
||||
MC Monaco Monaco
|
||||
MD Moldova Chisinau
|
||||
ME Montenegro Podgorica
|
||||
MF Saint Martin Marigot
|
||||
MG Madagascar Antananarivo
|
||||
MH Marshall Islands Majuro
|
||||
MK North Macedonia Skopje
|
||||
ML Mali Bamako
|
||||
MM Myanmar Nay Pyi Taw
|
||||
MN Mongolia Ulaanbaatar
|
||||
MO Macao Macao
|
||||
MP Northern Mariana Islands Saipan
|
||||
MQ Martinique Fort-de-France
|
||||
MR Mauritania Nouakchott
|
||||
MS Montserrat Plymouth
|
||||
MT Malta Valletta
|
||||
MU Mauritius Port Louis
|
||||
MV Maldives Male
|
||||
MW Malawi Lilongwe
|
||||
MX Mexico Mexico City
|
||||
MY Malaysia Kuala Lumpur
|
||||
MZ Mozambique Maputo
|
||||
NA Namibia Windhoek
|
||||
NC New Caledonia Noumea
|
||||
NE Niger Niamey
|
||||
NF Norfolk Island Kingston
|
||||
NG Nigeria Abuja
|
||||
NI Nicaragua Managua
|
||||
NL The Netherlands Amsterdam
|
||||
NO Norway Oslo
|
||||
NP Nepal Kathmandu
|
||||
NR Nauru Yaren
|
||||
NU Niue Alofi
|
||||
NZ New Zealand Wellington
|
||||
OM Oman Muscat
|
||||
PA Panama Panama City
|
||||
PE Peru Lima
|
||||
PF French Polynesia Papeete
|
||||
PG Papua New Guinea Port Moresby
|
||||
PH Philippines Manila
|
||||
PK Pakistan Islamabad
|
||||
PL Poland Warsaw
|
||||
PM Saint Pierre and Miquelon Saint-Pierre
|
||||
PN Pitcairn Adamstown
|
||||
PR Puerto Rico San Juan
|
||||
PS Palestinian Territory East Jerusalem
|
||||
PT Portugal Lisbon
|
||||
PW Palau Melekeok
|
||||
PY Paraguay Asuncion
|
||||
QA Qatar Doha
|
||||
RE Reunion Saint-Denis
|
||||
RO Romania Bucharest
|
||||
RS Serbia Belgrade
|
||||
RU Russia Moscow
|
||||
RW Rwanda Kigali
|
||||
SA Saudi Arabia Riyadh
|
||||
SB Solomon Islands Honiara
|
||||
SC Seychelles Victoria
|
||||
SD Sudan Khartoum
|
||||
SS South Sudan Juba
|
||||
SE Sweden Stockholm
|
||||
SG Singapore Singapore
|
||||
SH Saint Helena Jamestown
|
||||
SI Slovenia Ljubljana
|
||||
SJ Svalbard and Jan Mayen Longyearbyen
|
||||
SK Slovakia Bratislava
|
||||
SL Sierra Leone Freetown
|
||||
SM San Marino San Marino
|
||||
SN Senegal Dakar
|
||||
SO Somalia Mogadishu
|
||||
SR Suriname Paramaribo
|
||||
ST Sao Tome and Principe Sao Tome
|
||||
SV El Salvador San Salvador
|
||||
SX Sint Maarten Philipsburg
|
||||
SY Syria Damascus
|
||||
SZ Eswatini Mbabane
|
||||
TC Turks and Caicos Islands Cockburn Town
|
||||
TD Chad N'Djamena
|
||||
TF French Southern Territories Port-aux-Francais
|
||||
TG Togo Lome
|
||||
TH Thailand Bangkok
|
||||
TJ Tajikistan Dushanbe
|
||||
TK Tokelau
|
||||
TL Timor Leste Dili
|
||||
TM Turkmenistan Ashgabat
|
||||
TN Tunisia Tunis
|
||||
TO Tonga Nuku'alofa
|
||||
TR Turkey Ankara
|
||||
TT Trinidad and Tobago Port of Spain
|
||||
TV Tuvalu Funafuti
|
||||
TW Taiwan Taipei
|
||||
TZ Tanzania Dodoma
|
||||
UA Ukraine Kyiv
|
||||
UG Uganda Kampala
|
||||
UM United States Minor Outlying Islands
|
||||
US United States Washington
|
||||
UY Uruguay Montevideo
|
||||
UZ Uzbekistan Tashkent
|
||||
VA Vatican Vatican City
|
||||
VC Saint Vincent and the Grenadines Kingstown
|
||||
VE Venezuela Caracas
|
||||
VG British Virgin Islands Road Town
|
||||
VI U.S. Virgin Islands Charlotte Amalie
|
||||
VN Vietnam Hanoi
|
||||
VU Vanuatu Port Vila
|
||||
WF Wallis and Futuna Mata Utu
|
||||
WS Samoa Apia
|
||||
YE Yemen Sanaa
|
||||
YT Mayotte Mamoudzou
|
||||
ZA South Africa Pretoria
|
||||
ZM Zambia Lusaka
|
||||
ZW Zimbabwe Harare
|
||||
CS Serbia and Montenegro Belgrade
|
||||
AN Netherlands Antilles Willemstad
|
||||
|
193
news/summerizer/gazetteer.py
Normal file
193
news/summerizer/gazetteer.py
Normal file
|
|
@ -0,0 +1,193 @@
|
|||
"""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
|
||||
|
|
@ -26,6 +26,84 @@ _ARTICLE_RE = re.compile(r"^[ \t>*_#\-]*Article[ \t]+(\d{1,3})[ \t]*:", re.IGNOR
|
|||
_SCORE_RE = re.compile(r"Score:\s*(\d{1,3})", re.IGNORECASE)
|
||||
_IMPORTANCE_RE = re.compile(r"Importance:\s*(critical|high|medium|low|none)", re.IGNORECASE)
|
||||
_CATEGORY_RE = re.compile(r"Category:\s*(.+)", re.IGNORECASE)
|
||||
_LOCATION_RE = re.compile(r"Location:[ \t]*(.+)", re.IGNORECASE)
|
||||
_CONFIDENCE_RE = re.compile(
|
||||
r"Confidence:[ \t]*(exact|city|region|country|approx)", re.IGNORECASE
|
||||
)
|
||||
# Numeric token, optional degree sign, optional hemisphere letter. The
|
||||
# trailing lookahead keeps "12.3 South Sudan" from reading the S of a word
|
||||
# as a south marker (and from truncating the number to dodge it).
|
||||
_LAT_RE = re.compile(
|
||||
r"Lat:[ \t]*([+-]?\d+(?:\.\d+)?)[ \t]*°?[ \t]*([NS])?(?![A-Za-z\d.])", re.IGNORECASE
|
||||
)
|
||||
_LON_RE = re.compile(
|
||||
r"Lon:[ \t]*([+-]?\d+(?:\.\d+)?)[ \t]*°?[ \t]*([EW])?(?![A-Za-z\d.])", re.IGNORECASE
|
||||
)
|
||||
|
||||
LOCATION_NAME_MAX = 120
|
||||
_UNKNOWN_LOCATIONS = frozenset(
|
||||
{"unknown", "n/a", "none", "null", "unspecified", "not specified"}
|
||||
)
|
||||
GEO_CONFIDENCES = frozenset({"exact", "city", "region", "country", "approx"})
|
||||
|
||||
|
||||
def clean_location_name(raw) -> str | None:
|
||||
"""Normalise a model-written place name; Unknown/empty -> None.
|
||||
|
||||
Strips markdown decoration and trailing periods, caps the length.
|
||||
Never invents a place: a name the model did not write stays None.
|
||||
"""
|
||||
if not isinstance(raw, str):
|
||||
return None
|
||||
value = raw.strip().rstrip(".").strip().strip("*_`").strip()
|
||||
if not value:
|
||||
return None
|
||||
lowered = value.lower()
|
||||
if lowered in _UNKNOWN_LOCATIONS or lowered.startswith("unknown"):
|
||||
return None
|
||||
return value[:LOCATION_NAME_MAX]
|
||||
|
||||
|
||||
def _coord_from_block(text: str, kind: str) -> float | None:
|
||||
"""One Lat:/Lon: value from a block; hemisphere S/W negates."""
|
||||
match = (_LAT_RE if kind == "lat" else _LON_RE).search(text)
|
||||
if not match:
|
||||
return None
|
||||
try:
|
||||
value = float(match.group(1))
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
hemisphere = (match.group(2) or "").upper()
|
||||
if hemisphere in ("S", "W") and value > 0:
|
||||
value = -value
|
||||
return value
|
||||
|
||||
|
||||
def _geo_from_block(text: str) -> dict:
|
||||
"""Structured geo for one article block (pure).
|
||||
|
||||
Model coords are only trusted alongside a real place name — coords
|
||||
next to ``Location: Unknown`` are dropped (never invent a place).
|
||||
Missing/invalid coords leave lat/lon None for the offline gazetteer
|
||||
step; confidence defaults to "city" when the model gave coords but
|
||||
no Confidence line.
|
||||
"""
|
||||
loc_match = _LOCATION_RE.search(text)
|
||||
location_name = clean_location_name(loc_match.group(1) if loc_match else None)
|
||||
lat = lon = None
|
||||
confidence = None
|
||||
if location_name is not None:
|
||||
coords = clamp_coords(_coord_from_block(text, "lat"), _coord_from_block(text, "lon"))
|
||||
if coords is not None:
|
||||
lat, lon = coords
|
||||
conf_match = _CONFIDENCE_RE.search(text)
|
||||
confidence = conf_match.group(1).lower() if conf_match else "city"
|
||||
return {
|
||||
"location_name": location_name,
|
||||
"lat": lat,
|
||||
"lon": lon,
|
||||
"location_confidence": confidence,
|
||||
}
|
||||
|
||||
|
||||
def parse_reduce_json(raw: str) -> dict:
|
||||
|
|
@ -157,7 +235,14 @@ def parse_map_scores(
|
|||
Returns ``(blocks, stats)`` where each block is::
|
||||
|
||||
{"n", "article", "article_id", "score", "importance", "category",
|
||||
"location_name", "lat", "lon", "location_confidence",
|
||||
"text", "position"}
|
||||
|
||||
Geo is best-effort: ``location_name`` is the model's place name
|
||||
(Unknown -> None), ``lat``/``lon`` are clamp_coords-validated model
|
||||
coordinates (None when absent/invalid — the caller may resolve them
|
||||
via the offline gazetteer), ``location_confidence`` is the block's
|
||||
label or "city" when coords came without one.
|
||||
"""
|
||||
text = raw or ""
|
||||
matches = list(_ARTICLE_RE.finditer(text))
|
||||
|
|
@ -198,6 +283,7 @@ def parse_map_scores(
|
|||
"score": score,
|
||||
"importance": importance,
|
||||
"category": _category_from_block(block_text),
|
||||
**_geo_from_block(block_text),
|
||||
"text": block_text,
|
||||
"position": offset,
|
||||
}
|
||||
|
|
|
|||
|
|
@ -37,8 +37,12 @@ from zoneinfo import ZoneInfo
|
|||
|
||||
import psycopg2
|
||||
|
||||
from gazetteer import fill_block_geo
|
||||
from intel import (
|
||||
GEO_CONFIDENCES,
|
||||
article_url_for_row,
|
||||
clamp_coords,
|
||||
clean_location_name,
|
||||
dedupe_blocks,
|
||||
join_blocks,
|
||||
parse_map_scores,
|
||||
|
|
@ -176,7 +180,7 @@ Grade every article with this rubric before writing anything else in its block:
|
|||
For EACH article in the batch:
|
||||
1. Score: the integer 0-100 from the rubric above, first line of the block.
|
||||
2. Extract 2-4 key factual bullet points (who, what, when, where, numbers, quotes — stay very close to the text).
|
||||
3. Location: country/city/region or Unknown. If you can estimate coordinates, emit them as numbers; otherwise omit.
|
||||
3. Location: country/city/region or Unknown. If you can estimate coordinates, emit them as numbers; otherwise omit. Confidence: how precise that location is — exact (a specific site/address), city, region, or country. Never invent a place.
|
||||
4. Entities: list the key people, organizations, or governments mentioned (comma-separated, only names present in the text), else "None".
|
||||
5. Category: pick one — politics, military/conflict, economy, technology, environment/disaster, health, crime, society, sport, other.
|
||||
6. OSINT signal: if the article describes a breaking event with geopolitical, security, military, or disaster significance, say so in one short sentence. Otherwise write: "No notable OSINT signal."
|
||||
|
|
@ -192,6 +196,7 @@ Article 1:
|
|||
- Fact bullet 1
|
||||
- Fact bullet 2
|
||||
- Location: ...
|
||||
- Confidence: exact|city|region|country
|
||||
- Entities: ...
|
||||
- Category: ...
|
||||
- OSINT signal: ...
|
||||
|
|
@ -419,8 +424,15 @@ def ensure_tables() -> None:
|
|||
PRIMARY KEY (article_id, created_at)
|
||||
);
|
||||
ALTER TABLE article_scores ADD COLUMN IF NOT EXISTS duplicate_of INTEGER;
|
||||
ALTER TABLE article_scores ADD COLUMN IF NOT EXISTS location_name TEXT;
|
||||
ALTER TABLE article_scores ADD COLUMN IF NOT EXISTS lat DOUBLE PRECISION;
|
||||
ALTER TABLE article_scores ADD COLUMN IF NOT EXISTS lon DOUBLE PRECISION;
|
||||
ALTER TABLE article_scores ADD COLUMN IF NOT EXISTS location_confidence TEXT;
|
||||
CREATE INDEX IF NOT EXISTS ix_article_scores_summary
|
||||
ON article_scores (summary_id);
|
||||
CREATE INDEX IF NOT EXISTS ix_article_scores_geo_bbox
|
||||
ON article_scores (lon, lat)
|
||||
WHERE lat IS NOT NULL AND lon IS NOT NULL;
|
||||
"""
|
||||
try:
|
||||
conn = psycopg2.connect(**DB_CONFIG)
|
||||
|
|
@ -598,6 +610,9 @@ def persist_article_scores(
|
|||
Syndication duplicates are written too, with ``selected=false`` and
|
||||
``duplicate_of`` pointing at the surviving article id — the representative
|
||||
carries the selection even when the copy itself scores above the bar.
|
||||
Per-article geo (location_name/lat/lon/location_confidence) rides along
|
||||
for the /api/news/blips layer; coords are re-validated and confidence
|
||||
is restricted to the contract vocabulary at write time.
|
||||
Best-effort: a failure here is logged and never aborts the run.
|
||||
"""
|
||||
rows = []
|
||||
|
|
@ -608,6 +623,12 @@ def persist_article_scores(
|
|||
duplicate_of = block.get("duplicate_of")
|
||||
if not isinstance(duplicate_of, int):
|
||||
duplicate_of = None
|
||||
coords = clamp_coords(block.get("lat"), block.get("lon"))
|
||||
lat, lon = coords if coords is not None else (None, None)
|
||||
location_name = clean_location_name(block.get("location_name"))
|
||||
confidence = block.get("location_confidence")
|
||||
if lat is None or confidence not in GEO_CONFIDENCES:
|
||||
confidence = None
|
||||
rows.append(
|
||||
(
|
||||
article_id,
|
||||
|
|
@ -617,6 +638,10 @@ def persist_article_scores(
|
|||
bool(block.get("selected")) and duplicate_of is None,
|
||||
model,
|
||||
duplicate_of,
|
||||
location_name,
|
||||
lat,
|
||||
lon,
|
||||
confidence,
|
||||
)
|
||||
)
|
||||
if not rows:
|
||||
|
|
@ -626,17 +651,19 @@ def persist_article_scores(
|
|||
cur = conn.cursor()
|
||||
cur.executemany(
|
||||
"INSERT INTO article_scores "
|
||||
"(article_id, summary_id, score, category, selected, model, duplicate_of) "
|
||||
"VALUES (%s, %s, %s, %s, %s, %s, %s)",
|
||||
"(article_id, summary_id, score, category, selected, model, duplicate_of, "
|
||||
" location_name, lat, lon, location_confidence) "
|
||||
"VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)",
|
||||
rows,
|
||||
)
|
||||
conn.commit()
|
||||
cur.close()
|
||||
conn.close()
|
||||
logger.info(
|
||||
"article_scores persisted rows=%d selected=%d duplicates=%d summary_id=%s",
|
||||
"article_scores persisted rows=%d selected=%d duplicates=%d geo=%d summary_id=%s",
|
||||
len(rows), sum(1 for r in rows if r[4]),
|
||||
sum(1 for r in rows if r[6] is not None), summary_id,
|
||||
sum(1 for r in rows if r[6] is not None),
|
||||
sum(1 for r in rows if r[8] is not None), summary_id,
|
||||
)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.error("Error persisting article_scores (run continues): %s", exc)
|
||||
|
|
@ -726,10 +753,15 @@ def summarize_news() -> None:
|
|||
blocks, stats = parse_map_scores(
|
||||
response, articles=articles, batch_index=batch_index, batch_size=BATCH_SIZE
|
||||
)
|
||||
# Best-effort proximate geo: place-name-only blocks get offline
|
||||
# gazetteer coords (confidence "approx"); misses stay coord-less.
|
||||
for block in blocks:
|
||||
fill_block_geo(block)
|
||||
logger.info(
|
||||
"map batch %d graded %d/%d (score fallback=%d, unattributed=%d)",
|
||||
"map batch %d graded %d/%d (score fallback=%d, unattributed=%d, geo=%d)",
|
||||
batch_index + 1, stats["graded"], len(batch),
|
||||
stats["fallback"], stats["unattributed"],
|
||||
sum(1 for b in blocks if b.get("lat") is not None),
|
||||
)
|
||||
graded.extend(blocks)
|
||||
|
||||
|
|
|
|||
405
news/summerizer/tests/test_geo.py
Normal file
405
news/summerizer/tests/test_geo.py
Normal file
|
|
@ -0,0 +1,405 @@
|
|||
"""Per-article geo: map-block Location/Lat/Lon parsing + offline gazetteer.
|
||||
|
||||
Covers the blips pipeline (card t_bc15eb53): parse_map_scores extracts
|
||||
structured geo per graded block, clamp_coords rejects invalid values, and
|
||||
the vendored GeoNames gazetteer resolves place-name-only blocks to
|
||||
proximate coordinates with confidence "approx".
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
|
||||
import pytest
|
||||
|
||||
from intel import clamp_coords, parse_map_scores
|
||||
|
||||
|
||||
def _articles(n: int = 1, start: int = 100) -> list[dict]:
|
||||
return [
|
||||
{
|
||||
"id": start + i,
|
||||
"title": f"title {i}",
|
||||
"content": "body",
|
||||
"url": f"https://ex.com/{i}",
|
||||
"domain": "ex.com",
|
||||
}
|
||||
for i in range(n)
|
||||
]
|
||||
|
||||
|
||||
def _block(n: int, *lines: str, score: int = 55) -> str:
|
||||
return "\n".join([f"Article {n}:", f"- Score: {score}", *lines])
|
||||
|
||||
|
||||
# ── parse_map_scores: structured geo ──────────────────────────────────────
|
||||
|
||||
|
||||
def test_parses_location_lat_lon_and_confidence():
|
||||
raw = _block(
|
||||
1,
|
||||
"- Location: Kyiv, Ukraine",
|
||||
"- Lat: 50.45",
|
||||
"- Lon: 30.52",
|
||||
"- Confidence: city",
|
||||
"- Category: politics",
|
||||
)
|
||||
blocks, stats = parse_map_scores(raw, articles=_articles())
|
||||
assert stats["graded"] == 1
|
||||
b = blocks[0]
|
||||
assert b["location_name"] == "Kyiv, Ukraine"
|
||||
assert b["lat"] == pytest.approx(50.45)
|
||||
assert b["lon"] == pytest.approx(30.52)
|
||||
assert b["location_confidence"] == "city"
|
||||
|
||||
|
||||
def test_coords_without_confidence_default_to_city():
|
||||
raw = _block(1, "- Location: Kyiv", "- Lat: 50.45", "- Lon: 30.52")
|
||||
b = parse_map_scores(raw, articles=_articles())[0][0]
|
||||
assert b["location_confidence"] == "city"
|
||||
assert b["lat"] == pytest.approx(50.45)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("confidence", ["exact", "city", "region", "country"])
|
||||
def test_block_confidence_labels_pass_through(confidence):
|
||||
raw = _block(
|
||||
1, "- Location: somewhere", "- Lat: 10", "- Lon: 20",
|
||||
f"- Confidence: {confidence}",
|
||||
)
|
||||
b = parse_map_scores(raw, articles=_articles())[0][0]
|
||||
assert b["location_confidence"] == confidence
|
||||
|
||||
|
||||
def test_place_name_only_keeps_name_without_coords():
|
||||
raw = _block(1, "- Location: Odesa, Ukraine")
|
||||
b = parse_map_scores(raw, articles=_articles())[0][0]
|
||||
assert b["location_name"] == "Odesa, Ukraine"
|
||||
assert b["lat"] is None
|
||||
assert b["lon"] is None
|
||||
assert b["location_confidence"] is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("location", ["Unknown", "unknown", "N/A", "None", ""])
|
||||
def test_unknown_location_yields_no_geo(location):
|
||||
raw = _block(1, f"- Location: {location}", "- Lat: 50.45", "- Lon: 30.52")
|
||||
b = parse_map_scores(raw, articles=_articles())[0][0]
|
||||
assert b["location_name"] is None
|
||||
# No usable place name: model coords alone are not trusted either.
|
||||
assert b["lat"] is None
|
||||
assert b["lon"] is None
|
||||
assert b["location_confidence"] is None
|
||||
|
||||
|
||||
def test_no_location_line_yields_no_geo():
|
||||
b = parse_map_scores(_block(1, "- Category: politics"), articles=_articles())[0][0]
|
||||
assert b["location_name"] is None
|
||||
assert b["lat"] is None
|
||||
assert b["lon"] is None
|
||||
assert b["location_confidence"] is None
|
||||
|
||||
|
||||
def test_out_of_range_coords_are_dropped_but_name_kept():
|
||||
raw = _block(1, "- Location: Nowhere", "- Lat: 95.0", "- Lon: 30.52")
|
||||
b = parse_map_scores(raw, articles=_articles())[0][0]
|
||||
assert b["location_name"] == "Nowhere"
|
||||
assert b["lat"] is None
|
||||
assert b["lon"] is None
|
||||
assert b["location_confidence"] is None
|
||||
|
||||
|
||||
def test_lon_out_of_range_drops_both():
|
||||
raw = _block(1, "- Location: Nowhere", "- Lat: 10", "- Lon: 181")
|
||||
b = parse_map_scores(raw, articles=_articles())[0][0]
|
||||
assert b["lat"] is None and b["lon"] is None
|
||||
|
||||
|
||||
def test_missing_lon_drops_lat_too():
|
||||
raw = _block(1, "- Location: Kyiv", "- Lat: 50.45")
|
||||
b = parse_map_scores(raw, articles=_articles())[0][0]
|
||||
assert b["lat"] is None and b["lon"] is None
|
||||
|
||||
|
||||
def test_non_numeric_coords_drop_both():
|
||||
raw = _block(1, "- Location: Kyiv", "- Lat: about 50", "- Lon: 30.52")
|
||||
b = parse_map_scores(raw, articles=_articles())[0][0]
|
||||
assert b["lat"] is None and b["lon"] is None
|
||||
|
||||
|
||||
def test_hemisphere_suffixes_negate_south_and_west():
|
||||
raw = _block(
|
||||
1, "- Location: Sydney", "- Lat: 33.87 S", "- Lon: 151.21 E"
|
||||
)
|
||||
b = parse_map_scores(raw, articles=_articles())[0][0]
|
||||
assert b["lat"] == pytest.approx(-33.87)
|
||||
assert b["lon"] == pytest.approx(151.21)
|
||||
raw = _block(1, "- Location: Rio", "- Lat: 22.9 S", "- Lon: 43.2 W")
|
||||
b = parse_map_scores(raw, articles=_articles())[0][0]
|
||||
assert b["lat"] == pytest.approx(-22.9)
|
||||
assert b["lon"] == pytest.approx(-43.2)
|
||||
|
||||
|
||||
def test_hemisphere_letter_of_a_word_is_not_a_suffix():
|
||||
# "12.3 South Sudan" must NOT negate — the S belongs to a word.
|
||||
raw = _block(1, "- Location: Juba", "- Lat: 12.3 South Sudan", "- Lon: 31.6")
|
||||
b = parse_map_scores(raw, articles=_articles())[0][0]
|
||||
assert b["lat"] == pytest.approx(12.3)
|
||||
|
||||
|
||||
def test_location_name_is_cleaned_and_capped():
|
||||
raw = _block(1, "- Location: **Kyiv**.")
|
||||
b = parse_map_scores(raw, articles=_articles())[0][0]
|
||||
assert b["location_name"] == "Kyiv"
|
||||
raw = _block(1, "- Location: " + "x" * 300)
|
||||
b = parse_map_scores(raw, articles=_articles())[0][0]
|
||||
assert len(b["location_name"]) <= 120
|
||||
|
||||
|
||||
def test_each_block_gets_its_own_geo():
|
||||
raw = "\n\n".join(
|
||||
[
|
||||
_block(1, "- Location: Kyiv", "- Lat: 50.45", "- Lon: 30.52"),
|
||||
_block(2, "- Location: Tehran", "- Lat: 35.69", "- Lon: 51.39"),
|
||||
_block(3, "- Location: Unknown"),
|
||||
]
|
||||
)
|
||||
blocks, stats = parse_map_scores(raw, articles=_articles(3))
|
||||
assert stats["graded"] == 3
|
||||
assert blocks[0]["lat"] == pytest.approx(50.45)
|
||||
assert blocks[1]["location_name"] == "Tehran"
|
||||
assert blocks[1]["lon"] == pytest.approx(51.39)
|
||||
assert blocks[2]["location_name"] is None
|
||||
assert blocks[2]["lat"] is None
|
||||
|
||||
|
||||
def test_geo_fields_never_break_score_parsing():
|
||||
raw = _block(
|
||||
1, "- Location: Kyiv", "- Lat: 50.45", "- Lon: 30.52",
|
||||
"- Importance: high", score=83,
|
||||
)
|
||||
b = parse_map_scores(raw, articles=_articles())[0][0]
|
||||
assert b["score"] == 83
|
||||
assert b["importance"] == "high"
|
||||
|
||||
|
||||
# ── clamp_coords hardening ────────────────────────────────────────────────
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"lat,lon",
|
||||
[
|
||||
(90.1, 0), (-90.1, 0), (0, 180.1), (0, -180.1),
|
||||
(float("nan"), 0), (0, float("nan")),
|
||||
(float("inf"), 0), (0, float("-inf")),
|
||||
("abc", 0), (None, None),
|
||||
],
|
||||
)
|
||||
def test_clamp_coords_rejects_invalid(lat, lon):
|
||||
assert clamp_coords(lat, lon) is None
|
||||
|
||||
|
||||
def test_clamp_coords_accepts_boundaries():
|
||||
assert clamp_coords(90, 180) == (90.0, 180.0)
|
||||
assert clamp_coords(-90, -180) == (-90.0, -180.0)
|
||||
|
||||
|
||||
# ── Offline gazetteer ─────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def test_gazetteer_resolves_known_city():
|
||||
from gazetteer import resolve_place
|
||||
|
||||
coords = resolve_place("Kyiv")
|
||||
assert coords is not None
|
||||
lat, lon = coords
|
||||
assert lat == pytest.approx(50.45, abs=0.1)
|
||||
assert lon == pytest.approx(30.52, abs=0.1)
|
||||
|
||||
|
||||
def test_gazetteer_resolves_city_with_country_context():
|
||||
from gazetteer import resolve_place
|
||||
|
||||
coords = resolve_place("Kyiv, Ukraine")
|
||||
assert coords is not None
|
||||
assert coords[0] == pytest.approx(50.45, abs=0.1)
|
||||
|
||||
|
||||
def test_gazetteer_disambiguates_by_country():
|
||||
from gazetteer import resolve_place
|
||||
|
||||
france = resolve_place("Paris, France")
|
||||
texas = resolve_place("Paris, Texas")
|
||||
assert france is not None and texas is not None
|
||||
assert france[0] == pytest.approx(48.85, abs=0.2)
|
||||
assert texas[0] == pytest.approx(33.66, abs=0.3)
|
||||
assert france != texas
|
||||
|
||||
|
||||
def test_gazetteer_resolves_country_to_capital():
|
||||
from gazetteer import resolve_place
|
||||
|
||||
coords = resolve_place("Ukraine")
|
||||
assert coords is not None
|
||||
# Capital Kyiv.
|
||||
assert coords[0] == pytest.approx(50.45, abs=0.1)
|
||||
assert coords[1] == pytest.approx(30.52, abs=0.1)
|
||||
|
||||
|
||||
def test_gazetteer_handles_diacritics_and_case():
|
||||
from gazetteer import resolve_place
|
||||
|
||||
assert resolve_place("KYIV") is not None
|
||||
assert resolve_place("Tehrān") is not None or resolve_place("Tehran") is not None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("name", ["Unknown", "", None, " ", "Zzzqx Not A Real Place 999"])
|
||||
def test_gazetteer_misses_return_none(name):
|
||||
from gazetteer import resolve_place
|
||||
|
||||
assert resolve_place(name) is None
|
||||
|
||||
|
||||
def test_fill_block_geo_resolves_place_name_only_block():
|
||||
from gazetteer import fill_block_geo
|
||||
|
||||
raw = _block(1, "- Location: Kyiv, Ukraine")
|
||||
b = parse_map_scores(raw, articles=_articles())[0][0]
|
||||
fill_block_geo(b)
|
||||
assert b["lat"] == pytest.approx(50.45, abs=0.1)
|
||||
assert b["lon"] == pytest.approx(30.52, abs=0.1)
|
||||
assert b["location_confidence"] == "approx"
|
||||
assert b["location_name"] == "Kyiv, Ukraine"
|
||||
|
||||
|
||||
def test_fill_block_geo_keeps_model_coords():
|
||||
from gazetteer import fill_block_geo
|
||||
|
||||
raw = _block(1, "- Location: Kyiv", "- Lat: 50.45", "- Lon: 30.52")
|
||||
b = parse_map_scores(raw, articles=_articles())[0][0]
|
||||
fill_block_geo(b)
|
||||
assert b["lat"] == pytest.approx(50.45)
|
||||
assert b["location_confidence"] == "city"
|
||||
|
||||
|
||||
def test_fill_block_geo_omits_when_no_location():
|
||||
from gazetteer import fill_block_geo
|
||||
|
||||
raw = _block(1, "- Location: Unknown")
|
||||
b = parse_map_scores(raw, articles=_articles())[0][0]
|
||||
fill_block_geo(b)
|
||||
assert b["lat"] is None and b["lon"] is None
|
||||
assert b["location_confidence"] is None
|
||||
|
||||
|
||||
def test_fill_block_geo_omits_when_gazetteer_misses():
|
||||
from gazetteer import fill_block_geo
|
||||
|
||||
raw = _block(1, "- Location: Zzzqx Not A Real Place 999")
|
||||
b = parse_map_scores(raw, articles=_articles())[0][0]
|
||||
fill_block_geo(b)
|
||||
assert b["lat"] is None and b["lon"] is None
|
||||
assert b["location_confidence"] is None
|
||||
# The name the model actually wrote is still preserved.
|
||||
assert b["location_name"] == "Zzzqx Not A Real Place 999"
|
||||
|
||||
|
||||
# ── Persistence carries geo ───────────────────────────────────────────────
|
||||
|
||||
|
||||
def test_persist_article_scores_writes_geo_columns(monkeypatch):
|
||||
import summarizer
|
||||
|
||||
captured: list = []
|
||||
|
||||
class _Cur:
|
||||
def execute(self, sql, params=None):
|
||||
pass
|
||||
|
||||
def executemany(self, sql, rows):
|
||||
captured.append((" ".join(sql.split()), list(rows)))
|
||||
|
||||
def close(self):
|
||||
pass
|
||||
|
||||
class _Conn:
|
||||
def cursor(self):
|
||||
return _Cur()
|
||||
|
||||
def commit(self):
|
||||
pass
|
||||
|
||||
def close(self):
|
||||
pass
|
||||
|
||||
monkeypatch.setattr(summarizer.psycopg2, "connect", lambda **kw: _Conn())
|
||||
graded = [
|
||||
{
|
||||
"article_id": 1, "score": 80, "category": "politics",
|
||||
"selected": True, "location_name": "Kyiv, Ukraine",
|
||||
"lat": 50.45, "lon": 30.52, "location_confidence": "city",
|
||||
},
|
||||
{
|
||||
"article_id": 2, "score": 30, "category": "crime",
|
||||
"selected": False, "location_name": "Unknown",
|
||||
"lat": None, "lon": None, "location_confidence": None,
|
||||
},
|
||||
]
|
||||
summarizer.persist_article_scores(graded, summary_id=7, model="m")
|
||||
assert captured, "no executemany captured"
|
||||
sql, rows = captured[-1]
|
||||
for col in ("location_name", "lat", "lon", "location_confidence"):
|
||||
assert col in sql
|
||||
by_id = {row[0]: row for row in rows}
|
||||
assert by_id[1][7] == "Kyiv, Ukraine"
|
||||
assert by_id[1][8] == pytest.approx(50.45)
|
||||
assert by_id[1][9] == pytest.approx(30.52)
|
||||
assert by_id[1][10] == "city"
|
||||
assert by_id[2][7] is None
|
||||
assert by_id[2][8] is None
|
||||
assert by_id[2][9] is None
|
||||
assert by_id[2][10] is None
|
||||
|
||||
|
||||
def test_persist_article_scores_sanitizes_bad_geo(monkeypatch):
|
||||
import summarizer
|
||||
|
||||
captured: list = []
|
||||
|
||||
class _Cur:
|
||||
def execute(self, sql, params=None):
|
||||
pass
|
||||
|
||||
def executemany(self, sql, rows):
|
||||
captured.append(list(rows))
|
||||
|
||||
def close(self):
|
||||
pass
|
||||
|
||||
class _Conn:
|
||||
def cursor(self):
|
||||
return _Cur()
|
||||
|
||||
def commit(self):
|
||||
pass
|
||||
|
||||
def close(self):
|
||||
pass
|
||||
|
||||
monkeypatch.setattr(summarizer.psycopg2, "connect", lambda **kw: _Conn())
|
||||
graded = [
|
||||
{
|
||||
"article_id": 1, "score": 80, "selected": True,
|
||||
"location_name": "Kyiv", "lat": float("nan"), "lon": 30.52,
|
||||
"location_confidence": "bogus",
|
||||
},
|
||||
]
|
||||
summarizer.persist_article_scores(graded, summary_id=7, model="m")
|
||||
row = captured[-1][0]
|
||||
assert row[8] is None and row[9] is None # NaN lat drops the pair
|
||||
assert row[10] is None # confidence outside the contract vocabulary
|
||||
|
||||
|
||||
def test_map_prompt_asks_for_confidence():
|
||||
from summarizer import MAP_PROMPT_DEFAULT
|
||||
|
||||
assert "Confidence:" in MAP_PROMPT_DEFAULT
|
||||
assert "exact|city|region|country" in MAP_PROMPT_DEFAULT
|
||||
Loading…
Reference in a new issue