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

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