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:
Sirius DevOps 2026-11-19 22:50:59 -05:00
commit ca1c73e1a6
16 changed files with 39639 additions and 10 deletions

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)