news: per-article proximate geolocation + GET /api/news/blips #64

Merged
sirius merged 1 commit from wt/t_bc15eb53 into master 2026-11-20 03:52:58 +00:00
16 changed files with 39639 additions and 10 deletions
Showing only changes of commit ca1c73e1a6 - Show all commits

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
Sirius DevOps 2026-11-19 22:50:59 -05:00

View file

@ -0,0 +1,40 @@
"""article_scores geo: per-article proximate location for /api/news/blips
Revision ID: 014_article_scores_geo
Revises: 013_article_scores_duplicate_of
Create Date: 2026-11-19
Additive nullable columns on article_scores (every graded article keeps
its grading row; geo rides along when derivable). Partial bbox index for
the blips endpoint's bbox= filter. Idempotent DDL mirrors the summarizer's
ensure_tables so either start order is safe.
"""
from alembic import op
revision = "014_article_scores_geo"
down_revision = "013_article_scores_duplicate_of"
branch_labels = None
depends_on = None
def upgrade() -> None:
op.execute("ALTER TABLE article_scores ADD COLUMN IF NOT EXISTS location_name TEXT")
op.execute("ALTER TABLE article_scores ADD COLUMN IF NOT EXISTS lat DOUBLE PRECISION")
op.execute("ALTER TABLE article_scores ADD COLUMN IF NOT EXISTS lon DOUBLE PRECISION")
op.execute(
"ALTER TABLE article_scores ADD COLUMN IF NOT EXISTS location_confidence TEXT"
)
op.execute(
"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"
)
def downgrade() -> None:
op.execute("DROP INDEX IF EXISTS ix_article_scores_geo_bbox")
op.execute("ALTER TABLE article_scores DROP COLUMN IF EXISTS location_confidence")
op.execute("ALTER TABLE article_scores DROP COLUMN IF EXISTS lon")
op.execute("ALTER TABLE article_scores DROP COLUMN IF EXISTS lat")
op.execute("ALTER TABLE article_scores DROP COLUMN IF EXISTS location_name")

View file

@ -96,6 +96,7 @@ PUBLIC_GET_EXACT = frozenset({
"/api/news/summaries",
"/api/news/ticker",
"/api/news/map",
"/api/news/blips",
# map / live layers
"/api/map/layers",
"/api/map/chokepoints",

View file

@ -37,13 +37,13 @@ from database import async_session, init_extensions
from auth import AdminAuthMiddleware, router as auth_router
from models import (
alerts, documents, entities, entity_events, events, feed_sources, fires,
articles, article_summaries, news_items,
articles, article_scores, article_summaries, news_items,
)
from schemas import (
AlertCreate, AlertOut, AlertSeverity, AlertType, AlertUpdate,
ConflictZoneOut, ConflictsOut,
DashboardSummary, EntityCreate, EntityKind, EntityOut,
EventCreate, EventOut, FireOut, NewsArticleOut, NewsMapItemOut,
EventCreate, EventOut, FireOut, NewsArticleOut, NewsBlipOut, NewsMapItemOut,
NewsSummaryOut, NewsTickerItemOut,
FeedSourceCreate, FeedSourceOut, FeedSourceUpdate,
KeyOut, KeyValueIn,
@ -1502,6 +1502,94 @@ async def list_news_map(
]
@app.get("/api/news/blips", response_model=list[NewsBlipOut])
async def list_news_blips(
bbox: str | None = Query(
None,
description="Comma-separated 'minlon,minlat,maxlon,maxlat' to bound the "
"result set by article coordinates. Omit for all blips.",
),
since: datetime | None = Query(
None,
description="Only gradings created at/after this UTC instant. "
"Defaults to the last 24 hours.",
),
limit: int = Query(1000, ge=1, le=5000),
):
"""Per-article proximate geo blips: EVERY graded article with a derivable
location (not just the critical/high map pins). Deduped by article id —
the latest grading's geo wins. Only finite lat/lon rows, newest first.
"""
if since is None:
since = datetime.now(timezone.utc) - timedelta(hours=24)
async with async_session() as session:
# DISTINCT ON (article_id) + ORDER BY article_id, created_at DESC
# keeps the latest grading per article; the outer query re-sorts
# newest-first and applies the limit. NaN is excluded explicitly:
# Postgres sorts NaN above every finite value, so range checks
# alone would let it through. prefix_with keeps this renderable on
# both SQLAlchemy 2.0 and 2.1 (requirements pin >=2.0).
stmt = (
select(
article_scores.c.article_id.label("id"),
articles.c.title.label("headline"),
articles.c.url,
articles.c.domain,
article_scores.c.location_name,
article_scores.c.lat,
article_scores.c.lon,
article_scores.c.location_confidence,
article_scores.c.category,
article_scores.c.score,
article_scores.c.created_at,
)
.select_from(
article_scores.join(articles, articles.c.id == article_scores.c.article_id)
)
.where(
article_scores.c.lat.isnot(None),
article_scores.c.lon.isnot(None),
article_scores.c.lat.between(-90, 90),
article_scores.c.lon.between(-180, 180),
text("article_scores.lat <> 'NaN'::double precision"),
text("article_scores.lon <> 'NaN'::double precision"),
article_scores.c.created_at >= since,
)
.prefix_with("DISTINCT ON (article_scores.article_id)")
.order_by(article_scores.c.article_id, article_scores.c.created_at.desc())
)
if bbox:
parts = [p.strip() for p in bbox.split(",")]
if len(parts) != 4:
raise HTTPException(
422, "bbox must be 'minlon,minlat,maxlon,maxlat' (4 comma-separated values)"
)
try:
minlon, minlat, maxlon, maxlat = (float(p) for p in parts)
except ValueError:
raise HTTPException(
422, "bbox values must be floats: 'minlon,minlat,maxlon,maxlat'"
)
stmt = stmt.where(
and_(
article_scores.c.lon >= minlon, article_scores.c.lon <= maxlon,
article_scores.c.lat >= minlat, article_scores.c.lat <= maxlat,
)
)
latest = stmt.subquery()
ordered = select(latest).order_by(latest.c.created_at.desc()).limit(limit)
rows = (await session.execute(ordered)).mappings().all()
return [
NewsBlipOut(
id=r["id"], headline=r["headline"] or "", url=r["url"], domain=r["domain"],
location_name=r["location_name"], lat=r["lat"], lon=r["lon"],
location_confidence=r["location_confidence"], category=r["category"],
score=r["score"], created_at=r["created_at"],
)
for r in rows
]
@app.get("/api/news/models", response_model=NewsModelsOut)
async def list_news_models():
"""Nous model catalog for the summarizer selector. Never 502s."""

View file

@ -4,7 +4,7 @@ from datetime import datetime, timezone
from uuid import uuid4
from sqlalchemy import (
Column, Enum, Float, Index, Integer, String, Text,
Boolean, Column, Enum, Float, Index, Integer, String, Text,
DateTime, JSON, func, Table, PrimaryKeyConstraint,
)
from sqlalchemy.dialects.postgresql import UUID, TSVECTOR
@ -242,3 +242,34 @@ news_items = Table(
Column("created_at", DateTime(timezone=True), server_default=func.now(), nullable=False),
)
Index("ix_news_items_kind_created", news_items.c.kind, news_items.c.created_at)
# Per-article map-phase grades (alembic 012/013/014). One row per graded
# article per run; PK (article_id, created_at) lets re-grades accumulate.
# Geo columns are nullable: only articles with a derivable location carry
# coordinates, served by GET /api/news/blips.
article_scores = Table(
"article_scores",
metadata,
Column("article_id", Integer, nullable=False),
Column("summary_id", Integer),
Column("score", Integer, nullable=False),
Column("category", Text),
Column("selected", Boolean, nullable=False),
Column("model", Text),
Column("duplicate_of", Integer),
Column("location_name", Text),
Column("lat", Float),
Column("lon", Float),
Column("location_confidence", Text),
Column("created_at", DateTime(timezone=True),
server_default=func.now(), nullable=False),
PrimaryKeyConstraint("article_id", "created_at"),
)
Index("ix_article_scores_summary", article_scores.c.summary_id)
Index(
"ix_article_scores_geo_bbox",
article_scores.c.lon, article_scores.c.lat,
postgresql_where=article_scores.c.lat.isnot(None)
& article_scores.c.lon.isnot(None),
)

View file

@ -314,6 +314,26 @@ class NewsMapItemOut(BaseModel):
created_at: datetime
class NewsBlipOut(BaseModel):
"""One per-article proximate geo blip as exposed by GET /api/news/blips.
Frozen wire contract (card t_bc15eb53): every graded article with a
derivable location, deduped by article id (latest grading wins).
Unlike /api/news/map this is NOT limited to critical/high items.
"""
id: int
headline: str
url: Optional[str] = None
domain: Optional[str] = None
location_name: Optional[str] = None
lat: float
lon: float
location_confidence: Optional[str] = None
category: Optional[str] = None
score: Optional[int] = None
created_at: datetime
class NewsModelId(BaseModel):
"""One model id as exposed by GET /api/news/models."""

View file

@ -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

View 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.

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View 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
1 AD Andorra Andorra la Vella
2 AE United Arab Emirates Abu Dhabi
3 AF Afghanistan Kabul
4 AG Antigua and Barbuda St. John's
5 AI Anguilla The Valley
6 AL Albania Tirana
7 AM Armenia Yerevan
8 AO Angola Luanda
9 AQ Antarctica
10 AR Argentina Buenos Aires
11 AS American Samoa Pago Pago
12 AT Austria Vienna
13 AU Australia Canberra
14 AW Aruba Oranjestad
15 AX Aland Islands Mariehamn
16 AZ Azerbaijan Baku
17 BA Bosnia and Herzegovina Sarajevo
18 BB Barbados Bridgetown
19 BD Bangladesh Dhaka
20 BE Belgium Brussels
21 BF Burkina Faso Ouagadougou
22 BG Bulgaria Sofia
23 BH Bahrain Manama
24 BI Burundi Gitega
25 BJ Benin Porto-Novo
26 BL Saint Barthelemy Gustavia
27 BM Bermuda Hamilton
28 BN Brunei Bandar Seri Begawan
29 BO Bolivia Sucre
30 BQ Bonaire, Saint Eustatius and Saba
31 BR Brazil Brasilia
32 BS Bahamas Nassau
33 BT Bhutan Thimphu
34 BV Bouvet Island
35 BW Botswana Gaborone
36 BY Belarus Minsk
37 BZ Belize Belmopan
38 CA Canada Ottawa
39 CC Cocos Islands West Island
40 CD Democratic Republic of the Congo Kinshasa
41 CF Central African Republic Bangui
42 CG Republic of the Congo Brazzaville
43 CH Switzerland Bern
44 CI Ivory Coast Yamoussoukro
45 CK Cook Islands Avarua
46 CL Chile Santiago
47 CM Cameroon Yaounde
48 CN China Beijing
49 CO Colombia Bogota
50 CR Costa Rica San Jose
51 CU Cuba Havana
52 CV Cabo Verde Praia
53 CW Curacao Willemstad
54 CX Christmas Island Flying Fish Cove
55 CY Cyprus Nicosia
56 CZ Czechia Prague
57 DE Germany Berlin
58 DJ Djibouti Djibouti
59 DK Denmark Copenhagen
60 DM Dominica Roseau
61 DO Dominican Republic Santo Domingo
62 DZ Algeria Algiers
63 EC Ecuador Quito
64 EE Estonia Tallinn
65 EG Egypt Cairo
66 EH Western Sahara El-Aaiun
67 ER Eritrea Asmara
68 ES Spain Madrid
69 ET Ethiopia Addis Ababa
70 FI Finland Helsinki
71 FJ Fiji Suva
72 FK Falkland Islands Stanley
73 FM Micronesia Palikir
74 FO Faroe Islands Torshavn
75 FR France Paris
76 GA Gabon Libreville
77 GB United Kingdom London
78 GD Grenada St. George's
79 GE Georgia Tbilisi
80 GF French Guiana Cayenne
81 GG Guernsey St Peter Port
82 GH Ghana Accra
83 GI Gibraltar Gibraltar
84 GL Greenland Nuuk
85 GM Gambia Banjul
86 GN Guinea Conakry
87 GP Guadeloupe Basse-Terre
88 GQ Equatorial Guinea Ciudad de la Paz
89 GR Greece Athens
90 GS South Georgia and the South Sandwich Islands Grytviken
91 GT Guatemala Guatemala City
92 GU Guam Hagatna
93 GW Guinea-Bissau Bissau
94 GY Guyana Georgetown
95 HK Hong Kong Hong Kong
96 HM Heard Island and McDonald Islands
97 HN Honduras Tegucigalpa
98 HR Croatia Zagreb
99 HT Haiti Port-au-Prince
100 HU Hungary Budapest
101 ID Indonesia Jakarta
102 IE Ireland Dublin
103 IL Israel Jerusalem
104 IM Isle of Man Douglas
105 IN India New Delhi
106 IO British Indian Ocean Territory Diego Garcia
107 IQ Iraq Baghdad
108 IR Iran Tehran
109 IS Iceland Reykjavik
110 IT Italy Rome
111 JE Jersey Saint Helier
112 JM Jamaica Kingston
113 JO Jordan Amman
114 JP Japan Tokyo
115 KE Kenya Nairobi
116 KG Kyrgyzstan Bishkek
117 KH Cambodia Phnom Penh
118 KI Kiribati Tarawa
119 KM Comoros Moroni
120 KN Saint Kitts and Nevis Basseterre
121 KP North Korea Pyongyang
122 KR South Korea Seoul
123 XK Kosovo Pristina
124 KW Kuwait Kuwait City
125 KY Cayman Islands George Town
126 KZ Kazakhstan Nur-Sultan
127 LA Laos Vientiane
128 LB Lebanon Beirut
129 LC Saint Lucia Castries
130 LI Liechtenstein Vaduz
131 LK Sri Lanka Colombo
132 LR Liberia Monrovia
133 LS Lesotho Maseru
134 LT Lithuania Vilnius
135 LU Luxembourg Luxembourg
136 LV Latvia Riga
137 LY Libya Tripoli
138 MA Morocco Rabat
139 MC Monaco Monaco
140 MD Moldova Chisinau
141 ME Montenegro Podgorica
142 MF Saint Martin Marigot
143 MG Madagascar Antananarivo
144 MH Marshall Islands Majuro
145 MK North Macedonia Skopje
146 ML Mali Bamako
147 MM Myanmar Nay Pyi Taw
148 MN Mongolia Ulaanbaatar
149 MO Macao Macao
150 MP Northern Mariana Islands Saipan
151 MQ Martinique Fort-de-France
152 MR Mauritania Nouakchott
153 MS Montserrat Plymouth
154 MT Malta Valletta
155 MU Mauritius Port Louis
156 MV Maldives Male
157 MW Malawi Lilongwe
158 MX Mexico Mexico City
159 MY Malaysia Kuala Lumpur
160 MZ Mozambique Maputo
161 NA Namibia Windhoek
162 NC New Caledonia Noumea
163 NE Niger Niamey
164 NF Norfolk Island Kingston
165 NG Nigeria Abuja
166 NI Nicaragua Managua
167 NL The Netherlands Amsterdam
168 NO Norway Oslo
169 NP Nepal Kathmandu
170 NR Nauru Yaren
171 NU Niue Alofi
172 NZ New Zealand Wellington
173 OM Oman Muscat
174 PA Panama Panama City
175 PE Peru Lima
176 PF French Polynesia Papeete
177 PG Papua New Guinea Port Moresby
178 PH Philippines Manila
179 PK Pakistan Islamabad
180 PL Poland Warsaw
181 PM Saint Pierre and Miquelon Saint-Pierre
182 PN Pitcairn Adamstown
183 PR Puerto Rico San Juan
184 PS Palestinian Territory East Jerusalem
185 PT Portugal Lisbon
186 PW Palau Melekeok
187 PY Paraguay Asuncion
188 QA Qatar Doha
189 RE Reunion Saint-Denis
190 RO Romania Bucharest
191 RS Serbia Belgrade
192 RU Russia Moscow
193 RW Rwanda Kigali
194 SA Saudi Arabia Riyadh
195 SB Solomon Islands Honiara
196 SC Seychelles Victoria
197 SD Sudan Khartoum
198 SS South Sudan Juba
199 SE Sweden Stockholm
200 SG Singapore Singapore
201 SH Saint Helena Jamestown
202 SI Slovenia Ljubljana
203 SJ Svalbard and Jan Mayen Longyearbyen
204 SK Slovakia Bratislava
205 SL Sierra Leone Freetown
206 SM San Marino San Marino
207 SN Senegal Dakar
208 SO Somalia Mogadishu
209 SR Suriname Paramaribo
210 ST Sao Tome and Principe Sao Tome
211 SV El Salvador San Salvador
212 SX Sint Maarten Philipsburg
213 SY Syria Damascus
214 SZ Eswatini Mbabane
215 TC Turks and Caicos Islands Cockburn Town
216 TD Chad N'Djamena
217 TF French Southern Territories Port-aux-Francais
218 TG Togo Lome
219 TH Thailand Bangkok
220 TJ Tajikistan Dushanbe
221 TK Tokelau
222 TL Timor Leste Dili
223 TM Turkmenistan Ashgabat
224 TN Tunisia Tunis
225 TO Tonga Nuku'alofa
226 TR Turkey Ankara
227 TT Trinidad and Tobago Port of Spain
228 TV Tuvalu Funafuti
229 TW Taiwan Taipei
230 TZ Tanzania Dodoma
231 UA Ukraine Kyiv
232 UG Uganda Kampala
233 UM United States Minor Outlying Islands
234 US United States Washington
235 UY Uruguay Montevideo
236 UZ Uzbekistan Tashkent
237 VA Vatican Vatican City
238 VC Saint Vincent and the Grenadines Kingstown
239 VE Venezuela Caracas
240 VG British Virgin Islands Road Town
241 VI U.S. Virgin Islands Charlotte Amalie
242 VN Vietnam Hanoi
243 VU Vanuatu Port Vila
244 WF Wallis and Futuna Mata Utu
245 WS Samoa Apia
246 YE Yemen Sanaa
247 YT Mayotte Mamoudzou
248 ZA South Africa Pretoria
249 ZM Zambia Lusaka
250 ZW Zimbabwe Harare
251 CS Serbia and Montenegro Belgrade
252 AN Netherlands Antilles Willemstad

View 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

View file

@ -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,
}

View file

@ -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)

View 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

View file

@ -0,0 +1,337 @@
"""Integration tests for GET /api/news/blips (per-article proximate geo).
DB-backed: marked `requires_db` and auto-skip when the test database is
unreachable (see tests/conftest.py). Seeding writes directly to `articles`
and `article_scores`, exactly as the summarizer's persist step would.
Frozen wire contract (card t_bc15eb53):
200 -> JSON array, EXACT keys: id, headline, url, domain, location_name,
lat, lon, location_confidence, category, score, created_at.
Only finite lat/lon; created_at DESC; dedup by article id (latest wins).
"""
from __future__ import annotations
import asyncio
import math
import os
from datetime import datetime, timedelta, timezone
from urllib.parse import quote
import asyncpg
import httpx
import pytest
from conftest import requires_db
from main import app
BASE = "http://test"
CONTRACT_KEYS = {
"id", "headline", "url", "domain", "location_name",
"lat", "lon", "location_confidence", "category", "score", "created_at",
}
def _conn_kwargs() -> dict:
return {
"host": os.environ["DB_HOST"],
"port": int(os.environ["DB_PORT"]),
"user": os.environ["DB_USER"],
"password": os.environ["DB_PASSWORD"],
"database": os.environ["DB_NAME"],
}
def _run(coro):
return asyncio.run(coro)
def _truncate() -> None:
async def run():
conn = await asyncpg.connect(**_conn_kwargs())
try:
await conn.execute("TRUNCATE articles, article_scores CASCADE")
finally:
await conn.close()
_run(run())
@pytest.fixture()
def clean_blips():
_truncate()
yield
_truncate()
def _seed_article(title: str, url: str | None, domain: str | None) -> int:
async def run() -> int:
conn = await asyncpg.connect(**_conn_kwargs())
try:
row = await conn.fetchrow(
"INSERT INTO articles (title, url, content, domain, timestamp) "
"VALUES ($1, $2, $3, $4, $5) RETURNING id",
title, url, "body text " * 20, domain,
datetime.now(timezone.utc),
)
return int(row["id"])
finally:
await conn.close()
return _run(run())
def _seed_score(
article_id: int,
*,
score: int = 50,
category: str | None = "politics",
location_name: str | None = "Kyiv, Ukraine",
lat: float | None = 50.45,
lon: float | None = 30.52,
location_confidence: str | None = "city",
created_at: datetime | None = None,
) -> None:
async def run():
conn = await asyncpg.connect(**_conn_kwargs())
try:
await conn.execute(
"INSERT INTO article_scores "
"(article_id, summary_id, score, category, selected, model, "
" duplicate_of, location_name, lat, lon, location_confidence, created_at) "
"VALUES ($1, NULL, $2, $3, false, 'test-model', NULL, $4, $5, $6, $7, $8)",
article_id, score, category, location_name, lat, lon,
location_confidence,
created_at or datetime.now(timezone.utc),
)
finally:
await conn.close()
_run(run())
async def _get(path: str) -> httpx.Response:
transport = httpx.ASGITransport(app=app)
async with httpx.AsyncClient(transport=transport, base_url=BASE) as client:
return await client.get(path)
def _get_sync(path: str) -> httpx.Response:
return _run(_get(path))
@requires_db
def test_blips_exact_contract_keys(clean_blips):
aid = _seed_article("Strike in Kyiv", "https://ex.com/1", "ex.com")
_seed_score(aid, score=82)
resp = _get_sync("/api/news/blips")
assert resp.status_code == 200
rows = resp.json()
assert len(rows) == 1
row = rows[0]
assert set(row.keys()) == CONTRACT_KEYS
assert row["id"] == aid
assert row["headline"] == "Strike in Kyiv"
assert row["url"] == "https://ex.com/1"
assert row["domain"] == "ex.com"
assert row["location_name"] == "Kyiv, Ukraine"
assert row["lat"] == pytest.approx(50.45)
assert row["lon"] == pytest.approx(30.52)
assert row["location_confidence"] == "city"
assert row["category"] == "politics"
assert row["score"] == 82
assert isinstance(row["created_at"], str)
datetime.fromisoformat(row["created_at"]) # ISO8601 parseable
@requires_db
def test_blips_nullable_fields(clean_blips):
aid = _seed_article("Untitled", None, None)
_seed_score(
aid, category=None, location_name=None, location_confidence=None,
lat=10.0, lon=20.0,
)
row = _get_sync("/api/news/blips").json()[0]
assert row["url"] is None
assert row["domain"] is None
assert row["location_name"] is None
assert row["location_confidence"] is None
assert row["category"] is None
assert row["headline"] == "Untitled"
@requires_db
def test_blips_dedup_by_article_id_latest_geo_wins(clean_blips):
aid = _seed_article("Regraded story", "https://ex.com/r", "ex.com")
now = datetime.now(timezone.utc)
_seed_score(
aid, lat=1.0, lon=2.0, location_name="Old place",
location_confidence="approx", created_at=now - timedelta(hours=3),
)
_seed_score(
aid, lat=50.45, lon=30.52, location_name="Kyiv",
location_confidence="city", created_at=now - timedelta(hours=1),
)
rows = _get_sync("/api/news/blips").json()
assert len(rows) == 1
assert rows[0]["id"] == aid
assert rows[0]["location_name"] == "Kyiv"
assert rows[0]["lat"] == pytest.approx(50.45)
assert rows[0]["location_confidence"] == "city"
@requires_db
def test_blips_dedup_latest_geo_wins_even_if_newer_row_has_none(clean_blips):
"""Latest grading without geo: the newest FINITE-geo row still blips.
The contract filters to finite lat/lon rows first, then dedups by id
(latest geo wins) — a coord-less re-grade does not erase an article's
last known location.
"""
aid = _seed_article("Keeps its place", "https://ex.com/x", "ex.com")
now = datetime.now(timezone.utc)
_seed_score(aid, lat=50.45, lon=30.52, created_at=now - timedelta(hours=3))
_seed_score(
aid, lat=None, lon=None, location_name=None,
location_confidence=None, created_at=now - timedelta(hours=1),
)
rows = _get_sync("/api/news/blips").json()
assert len(rows) == 1
assert rows[0]["id"] == aid
assert rows[0]["lat"] == pytest.approx(50.45)
@requires_db
def test_blips_only_finite_coords(clean_blips):
now = datetime.now(timezone.utc)
good = _seed_article("Good", "https://ex.com/g", "ex.com")
_seed_score(good, created_at=now)
bad_cases = [
{"lat": None, "lon": None},
{"lat": float("nan"), "lon": 30.52},
{"lat": 50.45, "lon": float("nan")},
{"lat": float("inf"), "lon": 30.52},
{"lat": 50.45, "lon": float("-inf")},
{"lat": 91.0, "lon": 30.52},
{"lat": 50.45, "lon": 181.0},
]
for i, geo in enumerate(bad_cases):
aid = _seed_article(f"Bad {i}", f"https://ex.com/b{i}", "ex.com")
_seed_score(aid, created_at=now - timedelta(minutes=i + 1), **geo)
rows = _get_sync("/api/news/blips").json()
assert [r["id"] for r in rows] == [good]
assert all(math.isfinite(r["lat"]) and math.isfinite(r["lon"]) for r in rows)
@requires_db
def test_blips_includes_non_critical_articles(clean_blips):
"""No importance/score filter: low-scored graded articles are blips too."""
now = datetime.now(timezone.utc)
ids = []
for i, score in enumerate((95, 78, 50, 30, 12)):
aid = _seed_article(f"Story {score}", f"https://ex.com/{i}", "ex.com")
_seed_score(aid, score=score, created_at=now - timedelta(minutes=i))
ids.append(aid)
rows = _get_sync("/api/news/blips").json()
assert {r["id"] for r in rows} == set(ids)
assert {r["score"] for r in rows} == {95, 78, 50, 30, 12}
@requires_db
def test_blips_order_created_at_desc(clean_blips):
now = datetime.now(timezone.utc)
ids = []
for i in range(4):
aid = _seed_article(f"Story {i}", f"https://ex.com/{i}", "ex.com")
_seed_score(aid, created_at=now - timedelta(hours=i + 1))
ids.append(aid)
rows = _get_sync("/api/news/blips").json()
assert [r["id"] for r in rows] == ids # newest first
stamps = [datetime.fromisoformat(r["created_at"]) for r in rows]
assert stamps == sorted(stamps, reverse=True)
@requires_db
def test_blips_bbox_filter(clean_blips):
now = datetime.now(timezone.utc)
kyiv = _seed_article("Kyiv story", "https://ex.com/k", "ex.com")
_seed_score(kyiv, lat=50.45, lon=30.52, created_at=now)
sydney = _seed_article("Sydney story", "https://ex.com/s", "ex.com")
_seed_score(sydney, lat=-33.87, lon=151.21, created_at=now)
rows = _get_sync("/api/news/blips?bbox=20,40,40,60").json()
assert [r["id"] for r in rows] == [kyiv]
rows = _get_sync("/api/news/blips?bbox=-180,-90,180,90").json()
assert {r["id"] for r in rows} == {kyiv, sydney}
assert _get_sync("/api/news/blips?bbox=0,0,1,1").json() == []
@requires_db
@pytest.mark.parametrize(
"bbox",
["1,2,3", "1,2,3,4,5", "a,b,c,d", "1,2,,4", "1,2,3,"],
)
def test_blips_bbox_malformed_422(clean_blips, bbox):
resp = _get_sync(f"/api/news/blips?bbox={bbox}")
assert resp.status_code == 422
@requires_db
def test_blips_bbox_empty_is_omitted(clean_blips):
"""Same semantics as /api/news/map: an empty bbox means 'no filter'."""
aid = _seed_article("Any place", "https://ex.com/a", "ex.com")
_seed_score(aid)
assert _get_sync("/api/news/blips?bbox=").status_code == 200
assert len(_get_sync("/api/news/blips?bbox=").json()) == 1
@requires_db
def test_blips_since_honored(clean_blips):
now = datetime.now(timezone.utc)
fresh = _seed_article("Fresh", "https://ex.com/f", "ex.com")
_seed_score(fresh, created_at=now - timedelta(hours=1))
stale = _seed_article("Stale", "https://ex.com/s", "ex.com")
_seed_score(stale, created_at=now - timedelta(hours=30))
# Default window is 24h: the 30h-old row is out.
rows = _get_sync("/api/news/blips").json()
assert [r["id"] for r in rows] == [fresh]
# Explicit since widens the window.
since = quote((now - timedelta(hours=48)).isoformat())
rows = _get_sync(f"/api/news/blips?since={since}").json()
assert {r["id"] for r in rows} == {fresh, stale}
# Explicit since narrows it.
since = quote((now - timedelta(minutes=30)).isoformat())
assert _get_sync(f"/api/news/blips?since={since}").json() == []
@requires_db
def test_blips_limit_honored_and_validated(clean_blips):
now = datetime.now(timezone.utc)
for i in range(5):
aid = _seed_article(f"Story {i}", f"https://ex.com/{i}", "ex.com")
_seed_score(aid, created_at=now - timedelta(minutes=i))
rows = _get_sync("/api/news/blips?limit=2").json()
assert len(rows) == 2
assert _get_sync("/api/news/blips?limit=0").status_code == 422
assert _get_sync("/api/news/blips?limit=5001").status_code == 422
assert _get_sync("/api/news/blips?limit=abc").status_code == 422
# Max boundary is accepted.
assert _get_sync("/api/news/blips?limit=5000").status_code == 200
@requires_db
def test_blips_empty_db_returns_empty_array(clean_blips):
resp = _get_sync("/api/news/blips")
assert resp.status_code == 200
assert resp.json() == []
@requires_db
def test_news_map_unchanged_by_blips(clean_blips):
"""Critical-pin layer keeps its own contract while blips exist."""
aid = _seed_article("Critical story", "https://ex.com/c", "ex.com")
_seed_score(aid, score=95)
resp = _get_sync("/api/news/map")
assert resp.status_code == 200
assert resp.json() == [] # no news_items seeded; blips do not leak in

View file

@ -144,6 +144,7 @@ def test_anonymous_can_read_public_allowlist(no_db):
"/api/news",
"/api/news/ticker",
"/api/news/map",
"/api/news/blips",
"/api/geofences",
"/api/geofence-alerts",
"/api/analytics/summary",
@ -168,6 +169,7 @@ SPEC_PUBLIC_READS = (
"/api/analytics/summary", "/api/analytics/timeline",
"/api/analytics/sentiment/by-source", "/api/cameras",
"/api/news", "/api/news/summaries", "/api/news/ticker", "/api/news/map",
"/api/news/blips",
"/api/map/layers", "/api/map/chokepoints", "/api/map/radar",
"/api/map/sentinel1", "/api/aircraft", "/api/aircraft/photo",
"/api/trains", "/api/vessels", "/api/tracks/range", "/api/geofences",