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
92
app/main.py
92
app/main.py
|
|
@ -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."""
|
||||
|
|
|
|||
Loading…
Reference in a new issue