Compare commits
23 changed files with 28 additions and 40595 deletions
|
|
@ -1,40 +0,0 @@
|
||||||
"""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")
|
|
||||||
|
|
@ -96,7 +96,6 @@ PUBLIC_GET_EXACT = frozenset({
|
||||||
"/api/news/summaries",
|
"/api/news/summaries",
|
||||||
"/api/news/ticker",
|
"/api/news/ticker",
|
||||||
"/api/news/map",
|
"/api/news/map",
|
||||||
"/api/news/blips",
|
|
||||||
# map / live layers
|
# map / live layers
|
||||||
"/api/map/layers",
|
"/api/map/layers",
|
||||||
"/api/map/chokepoints",
|
"/api/map/chokepoints",
|
||||||
|
|
|
||||||
|
|
@ -107,12 +107,3 @@ VESSELAPI_MAX_CALLS_PER_DAY = int(os.getenv("VESSELAPI_MAX_CALLS_PER_DAY", "5"))
|
||||||
# Run the VesselAPI poller inside the dashboard process (default on, like AIS).
|
# Run the VesselAPI poller inside the dashboard process (default on, like AIS).
|
||||||
VESSELAPI_IN_APP = os.getenv("VESSELAPI_IN_APP", "1").lower() in ("1", "true", "yes")
|
VESSELAPI_IN_APP = os.getenv("VESSELAPI_IN_APP", "1").lower() in ("1", "true", "yes")
|
||||||
VESSELAPI_IN_INGEST = os.getenv("VESSELAPI_IN_INGEST", "0").lower() in ("1", "true", "yes")
|
VESSELAPI_IN_INGEST = os.getenv("VESSELAPI_IN_INGEST", "0").lower() in ("1", "true", "yes")
|
||||||
|
|
||||||
# ADS-B (ADSB.lol, no key). The dashboard's refresh loop follows browser
|
|
||||||
# viewports; with no tab open it persisted nothing and aircraft_positions went
|
|
||||||
# silent for a day. ADSB_WATCH_ENABLED=1 makes the loop sweep the chokepoint
|
|
||||||
# presets while idle, so the hypertable keeps advancing unattended.
|
|
||||||
ADSB_REFRESH_INTERVAL = float(os.getenv("ADSB_REFRESH_INTERVAL", "8"))
|
|
||||||
ADSB_WATCH_ENABLED = os.getenv("ADSB_WATCH_ENABLED", "1").lower() in ("1", "true", "yes")
|
|
||||||
# Idle sweep cadence; 30 s over 5 preset boxes ≈ 0.17 req/s to ADSB.lol.
|
|
||||||
ADSB_WATCH_INTERVAL = float(os.getenv("ADSB_WATCH_INTERVAL", "30"))
|
|
||||||
|
|
|
||||||
131
app/main.py
131
app/main.py
|
|
@ -37,13 +37,13 @@ from database import async_session, init_extensions
|
||||||
from auth import AdminAuthMiddleware, router as auth_router
|
from auth import AdminAuthMiddleware, router as auth_router
|
||||||
from models import (
|
from models import (
|
||||||
alerts, documents, entities, entity_events, events, feed_sources, fires,
|
alerts, documents, entities, entity_events, events, feed_sources, fires,
|
||||||
articles, article_scores, article_summaries, news_items,
|
articles, article_summaries, news_items,
|
||||||
)
|
)
|
||||||
from schemas import (
|
from schemas import (
|
||||||
AlertCreate, AlertOut, AlertSeverity, AlertType, AlertUpdate,
|
AlertCreate, AlertOut, AlertSeverity, AlertType, AlertUpdate,
|
||||||
ConflictZoneOut, ConflictsOut,
|
ConflictZoneOut, ConflictsOut,
|
||||||
DashboardSummary, EntityCreate, EntityKind, EntityOut,
|
DashboardSummary, EntityCreate, EntityKind, EntityOut,
|
||||||
EventCreate, EventOut, FireOut, NewsArticleOut, NewsBlipOut, NewsMapItemOut,
|
EventCreate, EventOut, FireOut, NewsArticleOut, NewsMapItemOut,
|
||||||
NewsSummaryOut, NewsTickerItemOut,
|
NewsSummaryOut, NewsTickerItemOut,
|
||||||
FeedSourceCreate, FeedSourceOut, FeedSourceUpdate,
|
FeedSourceCreate, FeedSourceOut, FeedSourceUpdate,
|
||||||
KeyOut, KeyValueIn,
|
KeyOut, KeyValueIn,
|
||||||
|
|
@ -126,49 +126,14 @@ app.include_router(auth_router)
|
||||||
STATIC_DIR = Path(__file__).parent / "static"
|
STATIC_DIR = Path(__file__).parent / "static"
|
||||||
|
|
||||||
|
|
||||||
def _adsb_watch_boxes() -> list[tuple[float, float, float, float]]:
|
|
||||||
"""Chokepoint presets as viewport boxes (minlon, minlat, maxlon, maxlat).
|
|
||||||
|
|
||||||
Used only while no browser viewport is registered: without it the refresh
|
|
||||||
loop persists nothing and ``aircraft_positions`` silently stalls whenever
|
|
||||||
nobody has the map open.
|
|
||||||
"""
|
|
||||||
from chokepoints import chokepoints
|
|
||||||
|
|
||||||
out: list[tuple[float, float, float, float]] = []
|
|
||||||
for preset in chokepoints():
|
|
||||||
try:
|
|
||||||
# Preset bboxes are minlat,minlon,maxlat,maxlon (VesselAPI order).
|
|
||||||
minlat, minlon, maxlat, maxlon = (float(v) for v in str(preset["bbox"]).split(","))
|
|
||||||
except (KeyError, TypeError, ValueError):
|
|
||||||
continue
|
|
||||||
out.append((minlon, minlat, maxlon, maxlat))
|
|
||||||
return out
|
|
||||||
|
|
||||||
|
|
||||||
async def _adsb_refresh_loop() -> None:
|
async def _adsb_refresh_loop() -> None:
|
||||||
"""Poll ADSB.lol for connected viewports — never from GET /api/aircraft.
|
"""Poll ADSB.lol for connected viewports — never from GET /api/aircraft."""
|
||||||
|
|
||||||
When no client viewport is registered the loop sweeps the watch boxes
|
|
||||||
(chokepoint presets) at ``ADSB_WATCH_INTERVAL`` so aircraft ingest keeps
|
|
||||||
advancing with no map open.
|
|
||||||
"""
|
|
||||||
from ws_manager import manager
|
from ws_manager import manager
|
||||||
from live_layers import fetch_aircraft
|
from live_layers import fetch_aircraft
|
||||||
from config import ADSB_REFRESH_INTERVAL, ADSB_WATCH_ENABLED, ADSB_WATCH_INTERVAL
|
|
||||||
|
|
||||||
watch_boxes: list[tuple[float, float, float, float]] | None = None
|
|
||||||
|
|
||||||
while True:
|
while True:
|
||||||
interval = ADSB_REFRESH_INTERVAL
|
|
||||||
try:
|
try:
|
||||||
boxes = manager.viewports()
|
boxes = manager.viewports()
|
||||||
if not boxes and ADSB_WATCH_ENABLED:
|
|
||||||
if watch_boxes is None:
|
|
||||||
watch_boxes = _adsb_watch_boxes()
|
|
||||||
boxes = watch_boxes
|
|
||||||
interval = ADSB_WATCH_INTERVAL
|
|
||||||
logger.debug("adsb_idle_watch", boxes=len(boxes))
|
|
||||||
for box in boxes:
|
for box in boxes:
|
||||||
bbox = f"{box[0]},{box[1]},{box[2]},{box[3]}"
|
bbox = f"{box[0]},{box[1]},{box[2]},{box[3]}"
|
||||||
try:
|
try:
|
||||||
|
|
@ -177,7 +142,7 @@ async def _adsb_refresh_loop() -> None:
|
||||||
logger.warning("adsb_refresh_failed", error=str(exc))
|
logger.warning("adsb_refresh_failed", error=str(exc))
|
||||||
except Exception as exc: # noqa: BLE001
|
except Exception as exc: # noqa: BLE001
|
||||||
logger.warning("adsb_refresh_loop", error=str(exc))
|
logger.warning("adsb_refresh_loop", error=str(exc))
|
||||||
await asyncio.sleep(interval)
|
await asyncio.sleep(8)
|
||||||
|
|
||||||
|
|
||||||
class CachedStaticFiles(StaticFiles):
|
class CachedStaticFiles(StaticFiles):
|
||||||
|
|
@ -1537,94 +1502,6 @@ 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)
|
@app.get("/api/news/models", response_model=NewsModelsOut)
|
||||||
async def list_news_models():
|
async def list_news_models():
|
||||||
"""Nous model catalog for the summarizer selector. Never 502s."""
|
"""Nous model catalog for the summarizer selector. Never 502s."""
|
||||||
|
|
|
||||||
|
|
@ -4,7 +4,7 @@ from datetime import datetime, timezone
|
||||||
from uuid import uuid4
|
from uuid import uuid4
|
||||||
|
|
||||||
from sqlalchemy import (
|
from sqlalchemy import (
|
||||||
Boolean, Column, Enum, Float, Index, Integer, String, Text,
|
Column, Enum, Float, Index, Integer, String, Text,
|
||||||
DateTime, JSON, func, Table, PrimaryKeyConstraint,
|
DateTime, JSON, func, Table, PrimaryKeyConstraint,
|
||||||
)
|
)
|
||||||
from sqlalchemy.dialects.postgresql import UUID, TSVECTOR
|
from sqlalchemy.dialects.postgresql import UUID, TSVECTOR
|
||||||
|
|
@ -242,34 +242,3 @@ news_items = Table(
|
||||||
Column("created_at", DateTime(timezone=True), server_default=func.now(), nullable=False),
|
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)
|
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),
|
|
||||||
)
|
|
||||||
|
|
|
||||||
|
|
@ -56,11 +56,8 @@ async def producer_loop() -> None:
|
||||||
try:
|
try:
|
||||||
g = await ingest_gdelt(query=GDELT_QUERY, max_articles=50)
|
g = await ingest_gdelt(query=GDELT_QUERY, max_articles=50)
|
||||||
logger.info("GDELT -> %d articles", g)
|
logger.info("GDELT -> %d articles", g)
|
||||||
except Exception as exc: # noqa: BLE001
|
except Exception: # noqa: BLE001
|
||||||
# Quota/backoff cases are handled inside ingest_gdelt (one clean
|
logger.exception("GDELT fetch failed")
|
||||||
# line); anything reaching here is a real failure and a stack
|
|
||||||
# trace every 5 minutes is not actionable, so keep it to one line.
|
|
||||||
logger.warning("GDELT fetch failed: %s", exc)
|
|
||||||
if ENABLE_QUAKES:
|
if ENABLE_QUAKES:
|
||||||
try:
|
try:
|
||||||
q = await ingest_earthquakes()
|
q = await ingest_earthquakes()
|
||||||
|
|
|
||||||
|
|
@ -314,26 +314,6 @@ class NewsMapItemOut(BaseModel):
|
||||||
created_at: datetime
|
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):
|
class NewsModelId(BaseModel):
|
||||||
"""One model id as exposed by GET /api/news/models."""
|
"""One model id as exposed by GET /api/news/models."""
|
||||||
|
|
||||||
|
|
|
||||||
351
app/sources.py
351
app/sources.py
|
|
@ -2,15 +2,9 @@
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import html
|
|
||||||
import io
|
|
||||||
import json
|
import json
|
||||||
import logging
|
import logging
|
||||||
import os
|
from datetime import datetime, timezone
|
||||||
import re
|
|
||||||
import time
|
|
||||||
import zipfile
|
|
||||||
from datetime import datetime, timedelta, timezone
|
|
||||||
from email.utils import parsedate_to_datetime
|
from email.utils import parsedate_to_datetime
|
||||||
|
|
||||||
import httpx
|
import httpx
|
||||||
|
|
@ -149,61 +143,6 @@ def gdelt_params(query: str = "", max_articles: int = 50) -> dict[str, str]:
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
# GDELT 429 backoff state. GDELT sends no Retry-After, and its block window
|
|
||||||
# grows with request volume, so the only useful reaction to a 429 is to stop
|
|
||||||
# asking: skip whole producer cycles, doubling the wait from BASE to MAX.
|
|
||||||
GDELT_BACKOFF_BASE = int(os.getenv("GDELT_BACKOFF_BASE", "300"))
|
|
||||||
GDELT_BACKOFF_MAX = int(os.getenv("GDELT_BACKOFF_MAX", "1800"))
|
|
||||||
_gdelt_backoff_secs = 0
|
|
||||||
_gdelt_backoff_until = 0.0 # time.monotonic()
|
|
||||||
|
|
||||||
|
|
||||||
def gdelt_backoff_remaining() -> float:
|
|
||||||
"""Seconds left in the GDELT cooldown window (0 = ready to call)."""
|
|
||||||
return max(0.0, _gdelt_backoff_until - time.monotonic())
|
|
||||||
|
|
||||||
|
|
||||||
def _gdelt_backoff_until_iso() -> str:
|
|
||||||
return (
|
|
||||||
datetime.now(timezone.utc).replace(microsecond=0)
|
|
||||||
+ timedelta(seconds=gdelt_backoff_remaining())
|
|
||||||
).strftime("%Y-%m-%dT%H:%M:%SZ")
|
|
||||||
|
|
||||||
|
|
||||||
def _gdelt_start_backoff(retry_after: float | None = None) -> None:
|
|
||||||
global _gdelt_backoff_secs, _gdelt_backoff_until
|
|
||||||
wait = retry_after or min(
|
|
||||||
GDELT_BACKOFF_MAX, max(GDELT_BACKOFF_BASE, _gdelt_backoff_secs * 2)
|
|
||||||
)
|
|
||||||
_gdelt_backoff_secs = int(wait)
|
|
||||||
_gdelt_backoff_until = time.monotonic() + wait
|
|
||||||
|
|
||||||
|
|
||||||
def _gdelt_clear_backoff() -> None:
|
|
||||||
global _gdelt_backoff_secs, _gdelt_backoff_until
|
|
||||||
_gdelt_backoff_secs = 0
|
|
||||||
_gdelt_backoff_until = 0.0
|
|
||||||
|
|
||||||
|
|
||||||
def _gdelt_retry_after(resp: httpx.Response) -> float | None:
|
|
||||||
"""Retry-After as seconds (delta-seconds or HTTP-date); GDELT sends neither."""
|
|
||||||
raw = resp.headers.get("retry-after")
|
|
||||||
if not raw:
|
|
||||||
return None
|
|
||||||
raw = raw.strip()
|
|
||||||
try:
|
|
||||||
return max(1.0, float(raw))
|
|
||||||
except ValueError:
|
|
||||||
pass
|
|
||||||
try:
|
|
||||||
return max(
|
|
||||||
1.0,
|
|
||||||
(parsedate_to_datetime(raw) - datetime.now(timezone.utc)).total_seconds(),
|
|
||||||
)
|
|
||||||
except (TypeError, ValueError):
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
def _parse_gdelt_seendate(value: object) -> str:
|
def _parse_gdelt_seendate(value: object) -> str:
|
||||||
if isinstance(value, str) and len(value) >= 15:
|
if isinstance(value, str) and len(value) >= 15:
|
||||||
try:
|
try:
|
||||||
|
|
@ -236,59 +175,25 @@ def parse_gdelt_articles(data: dict) -> list[dict]:
|
||||||
return events
|
return events
|
||||||
|
|
||||||
|
|
||||||
async def _ingest_gdelt_doc(query: str = "", max_articles: int = 50):
|
async def ingest_gdelt(query: str = "", max_articles: int = 50):
|
||||||
"""Fetch articles from the GDELT DOC 2.0 API.
|
"""Fetch articles from the GDELT DOC 2.0 API."""
|
||||||
|
|
||||||
GDELT enforces a per-IP quota that answers ``429`` with a plain-text body
|
|
||||||
("Please limit requests to one every 5 seconds"), sends **no** Retry-After,
|
|
||||||
and widens the block window as request volume accumulates. So a 429 is not
|
|
||||||
retried: the ingester stops calling until a backoff window expires, and the
|
|
||||||
cycle is skipped with a single log line. See ``gdelt_backoff_remaining``.
|
|
||||||
"""
|
|
||||||
remaining = gdelt_backoff_remaining()
|
|
||||||
if remaining > 0:
|
|
||||||
logger.info(
|
|
||||||
"GDELT: cooling down (%ds left after 429); skipping this cycle", int(remaining)
|
|
||||||
)
|
|
||||||
return 0
|
|
||||||
|
|
||||||
params = gdelt_params(query=query, max_articles=max_articles)
|
params = gdelt_params(query=query, max_articles=max_articles)
|
||||||
|
data: dict = {"articles": []}
|
||||||
async with httpx.AsyncClient(
|
async with httpx.AsyncClient(
|
||||||
timeout=60, headers=_ua_headers(), follow_redirects=True,
|
timeout=60, headers=_ua_headers(), follow_redirects=True,
|
||||||
) as client:
|
) as client:
|
||||||
try:
|
try:
|
||||||
resp = await client.get(GDELT_API, params=params)
|
resp = await client.get(GDELT_API, params=params)
|
||||||
except httpx.TransportError as exc:
|
|
||||||
# gdeltproject.org certs have expired in the wild; HTTP fallback.
|
|
||||||
# Only transport failures (TLS/connect) get the fallback — an HTTP
|
|
||||||
# error status is a quota answer and retrying it just burns the
|
|
||||||
# same per-IP budget a second time.
|
|
||||||
logger.warning("GDELT HTTPS transport error (%s); retrying HTTP", exc)
|
|
||||||
http_url = GDELT_API.replace("https://", "http://", 1)
|
|
||||||
resp = await client.get(http_url, params=params)
|
|
||||||
|
|
||||||
if resp.status_code == 429:
|
|
||||||
_gdelt_start_backoff(_gdelt_retry_after(resp))
|
|
||||||
logger.warning(
|
|
||||||
"GDELT 429 (rate limited) -> backing off until %s",
|
|
||||||
_gdelt_backoff_until_iso(),
|
|
||||||
)
|
|
||||||
return 0
|
|
||||||
|
|
||||||
try:
|
|
||||||
resp.raise_for_status()
|
resp.raise_for_status()
|
||||||
data = resp.json()
|
data = resp.json()
|
||||||
except (httpx.HTTPStatusError, ValueError) as exc:
|
except (httpx.TransportError, httpx.HTTPStatusError) as exc:
|
||||||
# GDELT also signals errors/throttling as HTTP 200 + prose, so a
|
# gdeltproject.org certs have expired in the wild; HTTP fallback.
|
||||||
# JSON decode failure is "busy", not "no results".
|
logger.warning("GDELT HTTPS failed (%s); retrying HTTP", exc)
|
||||||
_gdelt_start_backoff(_gdelt_retry_after(resp))
|
http_url = GDELT_API.replace("https://", "http://", 1)
|
||||||
logger.warning(
|
resp = await client.get(http_url, params=params)
|
||||||
"GDELT unusable response (HTTP %s: %s) -> backing off until %s",
|
resp.raise_for_status()
|
||||||
resp.status_code, str(exc).splitlines()[0][:120], _gdelt_backoff_until_iso(),
|
data = resp.json()
|
||||||
)
|
|
||||||
return 0
|
|
||||||
|
|
||||||
_gdelt_clear_backoff()
|
|
||||||
events = parse_gdelt_articles(data if isinstance(data, dict) else {})
|
events = parse_gdelt_articles(data if isinstance(data, dict) else {})
|
||||||
for event in events:
|
for event in events:
|
||||||
await publish_event("events.gdelt", event)
|
await publish_event("events.gdelt", event)
|
||||||
|
|
@ -296,240 +201,6 @@ async def _ingest_gdelt_doc(query: str = "", max_articles: int = 50):
|
||||||
return len(events)
|
return len(events)
|
||||||
|
|
||||||
|
|
||||||
# ─── GDELT 2.0 15-minute bulk files (throttle-free) ─────────────────────
|
|
||||||
#
|
|
||||||
# The DOC 2.0 API is per-IP quota'd (429, no Retry-After). The same coverage is
|
|
||||||
# published every 15 minutes as static files under /gdeltv2/ with no key and no
|
|
||||||
# quota, indexed by ``lastupdate.txt``:
|
|
||||||
# *.export.CSV.zip events (CAMEO codes)
|
|
||||||
# *.mentions.CSV.zip event->article mentions (URL + confidence, no title)
|
|
||||||
# *.gkg.csv.zip Global Knowledge Graph, one row per article: URL, source
|
|
||||||
# domain, themes, locations with lat/lon, tone, and the
|
|
||||||
# page title in the V2ExtrasXML column
|
|
||||||
# GKG is the one that carries title + geo, so map a filtered row into the same
|
|
||||||
# event shape ``parse_gdelt_articles`` produces and let the existing
|
|
||||||
# ``events.gdelt`` NATS consumer + ``event_dedup`` (URL) keep working.
|
|
||||||
|
|
||||||
GDELT_BULK_ENABLED = os.getenv("GDELT_BULK_ENABLED", "1").lower() in ("1", "true", "yes")
|
|
||||||
GDELT_BULK_LASTUPDATE = os.getenv(
|
|
||||||
"GDELT_BULK_LASTUPDATE", "https://data.gdeltproject.org/gdeltv2/lastupdate.txt"
|
|
||||||
)
|
|
||||||
GDELT_BULK_MAX_EVENTS = int(os.getenv("GDELT_BULK_MAX_EVENTS", "100"))
|
|
||||||
|
|
||||||
# Newest bulk file already parsed; lastupdate.txt is re-read every cycle but the
|
|
||||||
# 15-minute file behind it only changes 4x/hour.
|
|
||||||
_gdelt_bulk_last_file: str | None = None
|
|
||||||
|
|
||||||
_PAGE_TITLE_RE = re.compile(r"<PAGE_TITLE>(.*?)</PAGE_TITLE>", re.DOTALL)
|
|
||||||
_PAGE_PUB_TS_RE = re.compile(r"<PAGE_PRECISEPUBTIMESTAMP>(\d{14})<")
|
|
||||||
|
|
||||||
|
|
||||||
def gdelt_query_terms(query: str = "") -> list[str]:
|
|
||||||
"""CONFIG GDELT query (``(unrest OR protest OR ...)``) -> plain terms.
|
|
||||||
|
|
||||||
Used to filter bulk rows against their GKG theme tokens instead of
|
|
||||||
publishing every article in the 15-minute window.
|
|
||||||
"""
|
|
||||||
q = (query or "").strip() or GDELT_DEFAULT_QUERY
|
|
||||||
terms: list[str] = []
|
|
||||||
for part in re.split(r"\s+OR\s+", q.strip().strip("()"), flags=re.IGNORECASE):
|
|
||||||
term = part.strip().strip('"').strip("'").strip().lower()
|
|
||||||
if term and term not in terms:
|
|
||||||
terms.append(term)
|
|
||||||
return terms
|
|
||||||
|
|
||||||
|
|
||||||
def _term_hits_themes(term: str, themes: str) -> bool:
|
|
||||||
"""Term matches when every word of it appears in the theme token list."""
|
|
||||||
words = [w for w in re.split(r"[\s_\-]+", term) if w]
|
|
||||||
return bool(words) and all(w in themes for w in words)
|
|
||||||
|
|
||||||
|
|
||||||
def select_gdelt_bulk_url(lastupdate_text: str) -> tuple[str, str] | None:
|
|
||||||
"""``(filename, https_url)`` of the newest GKG file in lastupdate.txt.
|
|
||||||
|
|
||||||
lastupdate.txt lists plain ``http://`` URLs, which 301 to https; normalise
|
|
||||||
so the fetch never follows a redirect into a stale mirror.
|
|
||||||
"""
|
|
||||||
for line in (lastupdate_text or "").splitlines():
|
|
||||||
parts = line.split()
|
|
||||||
if len(parts) < 3 or not parts[2].endswith(".gkg.csv.zip"):
|
|
||||||
continue
|
|
||||||
url = parts[2]
|
|
||||||
if url.startswith("http://"):
|
|
||||||
url = "https://" + url[len("http://"):]
|
|
||||||
return url.rsplit("/", 1)[-1], url
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
def _gkg_location(field: str) -> tuple[float | None, float | None, str | None]:
|
|
||||||
"""First location in a V2Locations field -> (lat, lon, name).
|
|
||||||
|
|
||||||
V2Locations is ``type#fullname#cc#adm1[#adm2]#lat#lon#featureid``; the
|
|
||||||
adm2 slot is sometimes dropped, so read the triple from the end.
|
|
||||||
"""
|
|
||||||
segment = (field or "").split(";", 1)[0]
|
|
||||||
parts = segment.split("#")
|
|
||||||
if len(parts) < 5:
|
|
||||||
return None, None, None
|
|
||||||
name = parts[1].strip() or None
|
|
||||||
try:
|
|
||||||
lat = float(parts[-3])
|
|
||||||
lon = float(parts[-2])
|
|
||||||
except (TypeError, ValueError):
|
|
||||||
return None, None, name
|
|
||||||
if not (-90 <= lat <= 90 and -180 <= lon <= 180):
|
|
||||||
return None, None, name
|
|
||||||
return lat, lon, name
|
|
||||||
|
|
||||||
|
|
||||||
def _gkg_tone(field: str) -> float | None:
|
|
||||||
try:
|
|
||||||
return _parse_gdelt_tone(field.split(",", 1)[0])
|
|
||||||
except (AttributeError, IndexError):
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
def _gkg_timestamp(row: list[str], extras: str) -> str:
|
|
||||||
"""Article publish time: PAGE_PRECISEPUBTIMESTAMP, else the GKG window stamp."""
|
|
||||||
stamps = []
|
|
||||||
pub = _PAGE_PUB_TS_RE.search(extras)
|
|
||||||
if pub is not None:
|
|
||||||
stamps.append(pub.group(1))
|
|
||||||
if len(row) > 1 and isinstance(row[1], str):
|
|
||||||
stamps.append(row[1][:14])
|
|
||||||
for stamp in stamps:
|
|
||||||
try:
|
|
||||||
return datetime.strptime(stamp, "%Y%m%d%H%M%S").replace(
|
|
||||||
tzinfo=timezone.utc
|
|
||||||
).isoformat()
|
|
||||||
except ValueError:
|
|
||||||
continue
|
|
||||||
return datetime.now(timezone.utc).isoformat()
|
|
||||||
|
|
||||||
|
|
||||||
def parse_gkg_row(row: list[str], terms: list[str], bulk_file: str = "") -> dict | None:
|
|
||||||
"""Map one GKG CSV row into the ``events.gdelt`` event shape.
|
|
||||||
|
|
||||||
Returns None when the row has no usable URL or matches none of ``terms``.
|
|
||||||
"""
|
|
||||||
if len(row) < 8:
|
|
||||||
return None
|
|
||||||
url = (row[4] or "").strip()
|
|
||||||
if not url.startswith(("http://", "https://")):
|
|
||||||
return None
|
|
||||||
|
|
||||||
raw_themes = row[7] or ""
|
|
||||||
themes = raw_themes.lower()
|
|
||||||
matched = [t for t in terms if _term_hits_themes(t, themes)]
|
|
||||||
if not matched:
|
|
||||||
return None
|
|
||||||
|
|
||||||
extras = row[-1] if isinstance(row[-1], str) else ""
|
|
||||||
title_match = _PAGE_TITLE_RE.search(extras)
|
|
||||||
title = html.unescape(title_match.group(1)).strip() if title_match else None
|
|
||||||
|
|
||||||
lat = lon = loc_name = None
|
|
||||||
for idx in (9, 10):
|
|
||||||
if idx < len(row):
|
|
||||||
lat, lon, loc_name = _gkg_location(row[idx])
|
|
||||||
if lat is not None:
|
|
||||||
break
|
|
||||||
|
|
||||||
theme_tokens = [t for t in raw_themes.split(";") if t]
|
|
||||||
tags = matched + [
|
|
||||||
t for t in theme_tokens
|
|
||||||
if any(w in t.lower() for w in matched)
|
|
||||||
]
|
|
||||||
tags = list(dict.fromkeys(tags))[:10]
|
|
||||||
|
|
||||||
return {
|
|
||||||
"source_type": "gdel-t2",
|
|
||||||
"title": title,
|
|
||||||
"body": (row[3] or "").strip() or None,
|
|
||||||
"url": url,
|
|
||||||
"location_lat": lat,
|
|
||||||
"location_lon": lon,
|
|
||||||
"location_name": loc_name,
|
|
||||||
"source_timestamp": _gkg_timestamp(row, extras),
|
|
||||||
"tags": tags,
|
|
||||||
"raw": {
|
|
||||||
"gkg_record_id": row[0],
|
|
||||||
"source_common_name": row[3],
|
|
||||||
"source_collection": row[2],
|
|
||||||
"themes": theme_tokens[:12],
|
|
||||||
"tone": _gkg_tone(row[15]) if len(row) > 15 else None,
|
|
||||||
"bulk_file": bulk_file,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
async def ingest_gdelt_bulk(query: str = "", max_events: int | None = None) -> int:
|
|
||||||
"""Publish new articles from the newest 15-minute GKG bulk file.
|
|
||||||
|
|
||||||
No API key, no per-IP quota, and the existing URL dedupe means re-reading
|
|
||||||
the same file after a restart publishes nothing new.
|
|
||||||
"""
|
|
||||||
global _gdelt_bulk_last_file
|
|
||||||
cap = GDELT_BULK_MAX_EVENTS if max_events is None else max_events
|
|
||||||
|
|
||||||
async with httpx.AsyncClient(
|
|
||||||
timeout=120, headers=_ua_headers(), follow_redirects=True,
|
|
||||||
) as client:
|
|
||||||
index = await client.get(GDELT_BULK_LASTUPDATE)
|
|
||||||
index.raise_for_status()
|
|
||||||
picked = select_gdelt_bulk_url(index.text)
|
|
||||||
if picked is None:
|
|
||||||
logger.warning("GDELT bulk: no .gkg file listed in lastupdate.txt")
|
|
||||||
return 0
|
|
||||||
filename, url = picked
|
|
||||||
if filename == _gdelt_bulk_last_file:
|
|
||||||
logger.debug("GDELT bulk: %s already ingested; nothing new", filename)
|
|
||||||
return 0
|
|
||||||
archive = await client.get(url)
|
|
||||||
archive.raise_for_status()
|
|
||||||
|
|
||||||
terms = gdelt_query_terms(query)
|
|
||||||
events: list[dict] = []
|
|
||||||
scanned = 0
|
|
||||||
with zipfile.ZipFile(io.BytesIO(archive.content)) as zf:
|
|
||||||
member = zf.namelist()[0]
|
|
||||||
with zf.open(member) as fh:
|
|
||||||
for line in io.TextIOWrapper(fh, encoding="utf-8", errors="replace"):
|
|
||||||
if not line.strip():
|
|
||||||
continue
|
|
||||||
scanned += 1
|
|
||||||
event = parse_gkg_row(line.rstrip("\r\n").split("\t"), terms, filename)
|
|
||||||
if event is not None and len(events) < cap:
|
|
||||||
events.append(event)
|
|
||||||
|
|
||||||
published = await _publish_unknown("events.gdelt", events)
|
|
||||||
_gdelt_bulk_last_file = filename
|
|
||||||
logger.info(
|
|
||||||
"GDELT bulk %s: %d/%d rows matched %s, %d new articles published",
|
|
||||||
filename, len(events), scanned, "/".join(terms), published,
|
|
||||||
)
|
|
||||||
return published
|
|
||||||
|
|
||||||
|
|
||||||
async def ingest_gdelt(query: str = "", max_articles: int = 50):
|
|
||||||
"""GDELT articles: throttle-free 15-minute bulk file first, DOC API fallback.
|
|
||||||
|
|
||||||
The bulk path carries the coverage; the DOC 2.0 call (with its 429 backoff)
|
|
||||||
only runs when the bulk fetch itself fails, so the per-IP quota is no longer
|
|
||||||
on the hot path.
|
|
||||||
"""
|
|
||||||
if GDELT_BULK_ENABLED:
|
|
||||||
try:
|
|
||||||
return await ingest_gdelt_bulk(query=query)
|
|
||||||
except Exception as exc: # noqa: BLE001 — any bulk failure falls back
|
|
||||||
logger.warning(
|
|
||||||
"GDELT bulk fetch failed (%s: %s); falling back to DOC API",
|
|
||||||
type(exc).__name__, str(exc)[:160],
|
|
||||||
)
|
|
||||||
return await _ingest_gdelt_doc(query=query, max_articles=max_articles)
|
|
||||||
|
|
||||||
|
|
||||||
def _parse_gdelt_tone(tone: str) -> float | None:
|
def _parse_gdelt_tone(tone: str) -> float | None:
|
||||||
"""Parse GDELT tone string to a -1..1 sentiment score."""
|
"""Parse GDELT tone string to a -1..1 sentiment score."""
|
||||||
try:
|
try:
|
||||||
|
|
|
||||||
|
|
@ -720,7 +720,7 @@
|
||||||
-webkit-mask-image: linear-gradient(90deg, transparent 0, #000 26px, #000 calc(100% - 26px), transparent 100%);
|
-webkit-mask-image: linear-gradient(90deg, transparent 0, #000 26px, #000 calc(100% - 26px), transparent 100%);
|
||||||
}
|
}
|
||||||
.tick-track { display: flex; width: max-content; animation: marquee 60s linear infinite; }
|
.tick-track { display: flex; width: max-content; animation: marquee 60s linear infinite; }
|
||||||
.ticker.news .tick-track { animation-duration: 240s; } /* fallback; JS sets constant px/s */
|
.ticker.news .tick-track { animation-duration: 90s; }
|
||||||
.tick-wrap:hover .tick-track, .tick-wrap:focus-within .tick-track { animation-play-state: paused; }
|
.tick-wrap:hover .tick-track, .tick-wrap:focus-within .tick-track { animation-play-state: paused; }
|
||||||
@keyframes marquee { from { transform: translateX(0); } to { transform: translateX(-50%); } }
|
@keyframes marquee { from { transform: translateX(0); } to { transform: translateX(-50%); } }
|
||||||
.tick-group { display: flex; align-items: center; }
|
.tick-group { display: flex; align-items: center; }
|
||||||
|
|
@ -1874,7 +1874,6 @@ function initMarketTicker() {
|
||||||
/* ═══════════════ NEWS FEED + TICKER ═══════════════ */
|
/* ═══════════════ NEWS FEED + TICKER ═══════════════ */
|
||||||
let newsInterval = null;
|
let newsInterval = null;
|
||||||
const NEWS_REFRESH_MS = 180000; // 3-min ticker/brief poll
|
const NEWS_REFRESH_MS = 180000; // 3-min ticker/brief poll
|
||||||
const NEWS_TICKER_PX_PER_S = 28; // constant readable scroll speed for the news ticker
|
|
||||||
let newsTickerBuilt = false;
|
let newsTickerBuilt = false;
|
||||||
|
|
||||||
function newsEsc(s) {
|
function newsEsc(s) {
|
||||||
|
|
@ -2017,13 +2016,6 @@ function renderNewsTicker(articles, summaries, tickerItems) {
|
||||||
items = `<span class="tick-item standby">No headlines yet — scraper idle</span>`;
|
items = `<span class="tick-item standby">No headlines yet — scraper idle</span>`;
|
||||||
}
|
}
|
||||||
track.innerHTML = `<span class="tick-group">${items}</span><span class="tick-group">${items}</span>`;
|
track.innerHTML = `<span class="tick-group">${items}</span><span class="tick-group">${items}</span>`;
|
||||||
// Constant pixel speed regardless of headline count: the marquee travels
|
|
||||||
// one group width (track = two identical copies, keyframe goes to -50%).
|
|
||||||
// Recomputed on every rebuild; market ticker keeps its own CSS duration.
|
|
||||||
const groupWidth = track.scrollWidth / 2;
|
|
||||||
track.style.animationDuration = groupWidth > 0
|
|
||||||
? `${(groupWidth / NEWS_TICKER_PX_PER_S).toFixed(2)}s`
|
|
||||||
: '';
|
|
||||||
newsTickerBuilt = true;
|
newsTickerBuilt = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -2357,7 +2349,7 @@ async function saveSummaryModel() {
|
||||||
let map = null, mapLayer = null, mapInitStarted = false;
|
let map = null, mapLayer = null, mapInitStarted = false;
|
||||||
let firesHeat = null, camsGroup = null, firesOn = false, camsOn = false;
|
let firesHeat = null, camsGroup = null, firesOn = false, camsOn = false;
|
||||||
let blipsGroup = null, blipsOn = false, blipsSince = '24h';
|
let blipsGroup = null, blipsOn = false, blipsSince = '24h';
|
||||||
let newsGroup = null, newsOn = false, newsReq = 0, newsRenderer = null;
|
let newsGroup = null, newsOn = false, newsReq = 0;
|
||||||
let articlesGroup = null, articlesOn = false, articlesReq = 0, articlesTimer = null, articlesRenderer = null;
|
let articlesGroup = null, articlesOn = false, articlesReq = 0, articlesTimer = null, articlesRenderer = null;
|
||||||
let firesOpacity = 0.65, firesColor = 'brightness', firesSince = '24h';
|
let firesOpacity = 0.65, firesColor = 'brightness', firesSince = '24h';
|
||||||
let camsOpacity = 1.0, baseOpacity = 1.0;
|
let camsOpacity = 1.0, baseOpacity = 1.0;
|
||||||
|
|
@ -2522,17 +2514,6 @@ function overlayFetch(url) {
|
||||||
return fetch(url, overlayAbort ? { signal: overlayAbort.signal } : {});
|
return fetch(url, overlayAbort ? { signal: overlayAbort.signal } : {});
|
||||||
}
|
}
|
||||||
function isAbort(e) { return e && e.name === 'AbortError'; }
|
function isAbort(e) { return e && e.name === 'AbortError'; }
|
||||||
/* Leaflet 1.9.4 race guard: a moveend-driven _updatePaths() calls _redraw()
|
|
||||||
directly, which nulls _redrawRequest WITHOUT cancelling an already-pending
|
|
||||||
animation frame. If the renderer is removed before that orphaned frame
|
|
||||||
fires (e.g. layer toggle-off), _redraw crashes on the deleted 2d context
|
|
||||||
("Cannot read properties of undefined (reading 'clearRect')"). No-op
|
|
||||||
redraws on detached renderers instead; live renderers are unaffected. */
|
|
||||||
const _canvasRedraw = L.Canvas.prototype._redraw;
|
|
||||||
L.Canvas.prototype._redraw = function () {
|
|
||||||
if (!this._ctx) return;
|
|
||||||
return _canvasRedraw.apply(this, arguments);
|
|
||||||
};
|
|
||||||
const pointCanvas = () => L.canvas({ padding: 0.5 });
|
const pointCanvas = () => L.canvas({ padding: 0.5 });
|
||||||
|
|
||||||
async function initMap() {
|
async function initMap() {
|
||||||
|
|
@ -2547,12 +2528,10 @@ async function initMap() {
|
||||||
const sel = document.getElementById('map-layer');
|
const sel = document.getElementById('map-layer');
|
||||||
sel.innerHTML = mapLayers.map(l =>
|
sel.innerHTML = mapLayers.map(l =>
|
||||||
`<option value="${l.id}">${l.title}</option>`).join('');
|
`<option value="${l.id}">${l.title}</option>`).join('');
|
||||||
// Blue Marble first: static, gap-free basemap. Satellite true-color
|
|
||||||
// (VIIRS/MODIS) has cloud/coverage gaps — still selectable below.
|
|
||||||
const preferred =
|
const preferred =
|
||||||
mapLayers.find(l => l.id === 'BlueMarble_ShadedRelief_Bathymetry')
|
mapLayers.find(l => l.id === 'VIIRS_SNPP_CorrectedReflectance_TrueColor')
|
||||||
|| mapLayers.find(l => l.id === 'VIIRS_SNPP_CorrectedReflectance_TrueColor')
|
|
||||||
|| mapLayers.find(l => l.id === 'MODIS_Terra_CorrectedReflectance_TrueColor')
|
|| mapLayers.find(l => l.id === 'MODIS_Terra_CorrectedReflectance_TrueColor')
|
||||||
|
|| mapLayers.find(l => l.id === 'BlueMarble_ShadedRelief_Bathymetry')
|
||||||
|| mapLayers.find(l => !l.has_time)
|
|| mapLayers.find(l => !l.has_time)
|
||||||
|| mapLayers[0];
|
|| mapLayers[0];
|
||||||
if (preferred) sel.value = preferred.id;
|
if (preferred) sel.value = preferred.id;
|
||||||
|
|
@ -3302,7 +3281,6 @@ async function toggleNewsPins() {
|
||||||
}
|
}
|
||||||
newsReq++;
|
newsReq++;
|
||||||
if (newsGroup && map) { map.removeLayer(newsGroup); newsGroup = null; }
|
if (newsGroup && map) { map.removeLayer(newsGroup); newsGroup = null; }
|
||||||
if (newsRenderer && map) { map.removeLayer(newsRenderer); newsRenderer = null; }
|
|
||||||
hudNewsCount = null;
|
hudNewsCount = null;
|
||||||
setLayerCount('lp-news-count', '0');
|
setLayerCount('lp-news-count', '0');
|
||||||
syncHud();
|
syncHud();
|
||||||
|
|
@ -3318,16 +3296,11 @@ async function loadNewsPins() {
|
||||||
const items = Array.isArray(data) ? data : [];
|
const items = Array.isArray(data) ? data : [];
|
||||||
if (newsGroup) map.removeLayer(newsGroup);
|
if (newsGroup) map.removeLayer(newsGroup);
|
||||||
const col = '#35e0ff';
|
const col = '#35e0ff';
|
||||||
// One persistent canvas renderer shared by ALL pins: L.Canvas
|
|
||||||
// hit-tests every drawn path, so each pin stays clickable (a fresh
|
|
||||||
// canvas per pin stacked empty siblings over all but the last), and
|
|
||||||
// reusing it across refreshes leaks no full-viewport containers.
|
|
||||||
const renderer = newsRenderer || (newsRenderer = L.canvas({ padding: 0.5 }));
|
|
||||||
const pins = items.filter(it => Number.isFinite(Number(it.lat)) && Number.isFinite(Number(it.lon)));
|
const pins = items.filter(it => Number.isFinite(Number(it.lat)) && Number.isFinite(Number(it.lon)));
|
||||||
newsGroup = L.layerGroup(pins.map(it => {
|
newsGroup = L.layerGroup(pins.map(it => {
|
||||||
return L.circleMarker([it.lat, it.lon], {
|
return L.circleMarker([it.lat, it.lon], {
|
||||||
radius: 6, weight: 1, color: col, fillColor: col, fillOpacity: 0.7,
|
radius: 6, weight: 1, color: col, fillColor: col, fillOpacity: 0.7,
|
||||||
renderer,
|
renderer: pointCanvas(),
|
||||||
})
|
})
|
||||||
.bindPopup(`<div class="blip-pop">` +
|
.bindPopup(`<div class="blip-pop">` +
|
||||||
`<div class="blip-src">◈ ${esc(it.importance || '')}${it.category ? ' · ' + esc(it.category) : ''}</div>` +
|
`<div class="blip-src">◈ ${esc(it.importance || '')}${it.category ? ' · ' + esc(it.category) : ''}</div>` +
|
||||||
|
|
|
||||||
|
|
@ -13,8 +13,7 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||||
COPY requirements.txt .
|
COPY requirements.txt .
|
||||||
RUN pip install --no-cache-dir -r requirements.txt
|
RUN pip install --no-cache-dir -r requirements.txt
|
||||||
|
|
||||||
COPY summarizer.py run_news_summarizer.py intel.py nous_client.py gazetteer.py ./
|
COPY summarizer.py run_news_summarizer.py intel.py nous_client.py ./
|
||||||
COPY data/ ./data/
|
|
||||||
|
|
||||||
# Security: run as a non-privileged user.
|
# Security: run as a non-privileged user.
|
||||||
RUN useradd -m summarizer_user
|
RUN useradd -m summarizer_user
|
||||||
|
|
|
||||||
|
|
@ -1,28 +0,0 @@
|
||||||
# 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
|
|
@ -1,252 +0,0 @@
|
||||||
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,193 +0,0 @@
|
||||||
"""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,84 +26,6 @@ _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)
|
_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)
|
_IMPORTANCE_RE = re.compile(r"Importance:\s*(critical|high|medium|low|none)", re.IGNORECASE)
|
||||||
_CATEGORY_RE = re.compile(r"Category:\s*(.+)", 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:
|
def parse_reduce_json(raw: str) -> dict:
|
||||||
|
|
@ -235,14 +157,7 @@ def parse_map_scores(
|
||||||
Returns ``(blocks, stats)`` where each block is::
|
Returns ``(blocks, stats)`` where each block is::
|
||||||
|
|
||||||
{"n", "article", "article_id", "score", "importance", "category",
|
{"n", "article", "article_id", "score", "importance", "category",
|
||||||
"location_name", "lat", "lon", "location_confidence",
|
|
||||||
"text", "position"}
|
"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 ""
|
text = raw or ""
|
||||||
matches = list(_ARTICLE_RE.finditer(text))
|
matches = list(_ARTICLE_RE.finditer(text))
|
||||||
|
|
@ -283,7 +198,6 @@ def parse_map_scores(
|
||||||
"score": score,
|
"score": score,
|
||||||
"importance": importance,
|
"importance": importance,
|
||||||
"category": _category_from_block(block_text),
|
"category": _category_from_block(block_text),
|
||||||
**_geo_from_block(block_text),
|
|
||||||
"text": block_text,
|
"text": block_text,
|
||||||
"position": offset,
|
"position": offset,
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -37,12 +37,8 @@ from zoneinfo import ZoneInfo
|
||||||
|
|
||||||
import psycopg2
|
import psycopg2
|
||||||
|
|
||||||
from gazetteer import fill_block_geo
|
|
||||||
from intel import (
|
from intel import (
|
||||||
GEO_CONFIDENCES,
|
|
||||||
article_url_for_row,
|
article_url_for_row,
|
||||||
clamp_coords,
|
|
||||||
clean_location_name,
|
|
||||||
dedupe_blocks,
|
dedupe_blocks,
|
||||||
join_blocks,
|
join_blocks,
|
||||||
parse_map_scores,
|
parse_map_scores,
|
||||||
|
|
@ -180,7 +176,7 @@ Grade every article with this rubric before writing anything else in its block:
|
||||||
For EACH article in the batch:
|
For EACH article in the batch:
|
||||||
1. Score: the integer 0-100 from the rubric above, first line of the block.
|
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).
|
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. Confidence: how precise that location is — exact (a specific site/address), city, region, or country. Never invent a place.
|
3. Location: country/city/region or Unknown. If you can estimate coordinates, emit them as numbers; otherwise omit.
|
||||||
4. Entities: list the key people, organizations, or governments mentioned (comma-separated, only names present in the text), else "None".
|
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.
|
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."
|
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."
|
||||||
|
|
@ -196,7 +192,6 @@ Article 1:
|
||||||
- Fact bullet 1
|
- Fact bullet 1
|
||||||
- Fact bullet 2
|
- Fact bullet 2
|
||||||
- Location: ...
|
- Location: ...
|
||||||
- Confidence: exact|city|region|country
|
|
||||||
- Entities: ...
|
- Entities: ...
|
||||||
- Category: ...
|
- Category: ...
|
||||||
- OSINT signal: ...
|
- OSINT signal: ...
|
||||||
|
|
@ -424,15 +419,8 @@ def ensure_tables() -> None:
|
||||||
PRIMARY KEY (article_id, created_at)
|
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 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
|
CREATE INDEX IF NOT EXISTS ix_article_scores_summary
|
||||||
ON article_scores (summary_id);
|
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:
|
try:
|
||||||
conn = psycopg2.connect(**DB_CONFIG)
|
conn = psycopg2.connect(**DB_CONFIG)
|
||||||
|
|
@ -610,9 +598,6 @@ def persist_article_scores(
|
||||||
Syndication duplicates are written too, with ``selected=false`` and
|
Syndication duplicates are written too, with ``selected=false`` and
|
||||||
``duplicate_of`` pointing at the surviving article id — the representative
|
``duplicate_of`` pointing at the surviving article id — the representative
|
||||||
carries the selection even when the copy itself scores above the bar.
|
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.
|
Best-effort: a failure here is logged and never aborts the run.
|
||||||
"""
|
"""
|
||||||
rows = []
|
rows = []
|
||||||
|
|
@ -623,12 +608,6 @@ def persist_article_scores(
|
||||||
duplicate_of = block.get("duplicate_of")
|
duplicate_of = block.get("duplicate_of")
|
||||||
if not isinstance(duplicate_of, int):
|
if not isinstance(duplicate_of, int):
|
||||||
duplicate_of = None
|
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(
|
rows.append(
|
||||||
(
|
(
|
||||||
article_id,
|
article_id,
|
||||||
|
|
@ -638,10 +617,6 @@ def persist_article_scores(
|
||||||
bool(block.get("selected")) and duplicate_of is None,
|
bool(block.get("selected")) and duplicate_of is None,
|
||||||
model,
|
model,
|
||||||
duplicate_of,
|
duplicate_of,
|
||||||
location_name,
|
|
||||||
lat,
|
|
||||||
lon,
|
|
||||||
confidence,
|
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
if not rows:
|
if not rows:
|
||||||
|
|
@ -651,19 +626,17 @@ def persist_article_scores(
|
||||||
cur = conn.cursor()
|
cur = conn.cursor()
|
||||||
cur.executemany(
|
cur.executemany(
|
||||||
"INSERT INTO article_scores "
|
"INSERT INTO article_scores "
|
||||||
"(article_id, summary_id, score, category, selected, model, duplicate_of, "
|
"(article_id, summary_id, score, category, selected, model, duplicate_of) "
|
||||||
" location_name, lat, lon, location_confidence) "
|
"VALUES (%s, %s, %s, %s, %s, %s, %s)",
|
||||||
"VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)",
|
|
||||||
rows,
|
rows,
|
||||||
)
|
)
|
||||||
conn.commit()
|
conn.commit()
|
||||||
cur.close()
|
cur.close()
|
||||||
conn.close()
|
conn.close()
|
||||||
logger.info(
|
logger.info(
|
||||||
"article_scores persisted rows=%d selected=%d duplicates=%d geo=%d summary_id=%s",
|
"article_scores persisted rows=%d selected=%d duplicates=%d summary_id=%s",
|
||||||
len(rows), sum(1 for r in rows if r[4]),
|
len(rows), sum(1 for r in rows if r[4]),
|
||||||
sum(1 for r in rows if r[6] is not None),
|
sum(1 for r in rows if r[6] is not None), summary_id,
|
||||||
sum(1 for r in rows if r[8] is not None), summary_id,
|
|
||||||
)
|
)
|
||||||
except Exception as exc: # noqa: BLE001
|
except Exception as exc: # noqa: BLE001
|
||||||
logger.error("Error persisting article_scores (run continues): %s", exc)
|
logger.error("Error persisting article_scores (run continues): %s", exc)
|
||||||
|
|
@ -753,15 +726,10 @@ def summarize_news() -> None:
|
||||||
blocks, stats = parse_map_scores(
|
blocks, stats = parse_map_scores(
|
||||||
response, articles=articles, batch_index=batch_index, batch_size=BATCH_SIZE
|
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(
|
logger.info(
|
||||||
"map batch %d graded %d/%d (score fallback=%d, unattributed=%d, geo=%d)",
|
"map batch %d graded %d/%d (score fallback=%d, unattributed=%d)",
|
||||||
batch_index + 1, stats["graded"], len(batch),
|
batch_index + 1, stats["graded"], len(batch),
|
||||||
stats["fallback"], stats["unattributed"],
|
stats["fallback"], stats["unattributed"],
|
||||||
sum(1 for b in blocks if b.get("lat") is not None),
|
|
||||||
)
|
)
|
||||||
graded.extend(blocks)
|
graded.extend(blocks)
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,405 +0,0 @@
|
||||||
"""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
|
|
||||||
|
|
@ -1,62 +0,0 @@
|
||||||
"""Tests for the idle ADS-B watch sweep.
|
|
||||||
|
|
||||||
Regression: the refresh loop only persisted aircraft for *connected browser
|
|
||||||
viewports*, so ``aircraft_positions`` went silent for a day whenever nobody had
|
|
||||||
the map open (observed 2026-11-20 04:58 -> 2026-11-21). When no viewport is
|
|
||||||
registered the loop must sweep the chokepoint presets instead.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import asyncio
|
|
||||||
|
|
||||||
from chokepoints import chokepoints
|
|
||||||
from live_layers import bbox_center_radius_nm, parse_bbox
|
|
||||||
from main import _adsb_watch_boxes, _adsb_refresh_loop
|
|
||||||
from ws_manager import manager
|
|
||||||
|
|
||||||
|
|
||||||
def test_watch_boxes_cover_every_chokepoint() -> None:
|
|
||||||
boxes = _adsb_watch_boxes()
|
|
||||||
assert len(boxes) == len(chokepoints())
|
|
||||||
for box in boxes:
|
|
||||||
minlon, minlat, maxlon, maxlat = box
|
|
||||||
# Preset catalog order is minlat,minlon,maxlat,maxlon: a lon/lat swap
|
|
||||||
# would put e.g. Hormuz at lat 56 lon 26.
|
|
||||||
assert -90 <= minlat < maxlat <= 90
|
|
||||||
assert -180 <= minlon < maxlon <= 180
|
|
||||||
# ADSB.lol 403s any dist > 250 nm; live_layer clamps to 150 nm.
|
|
||||||
assert bbox_center_radius_nm(minlon, minlat, maxlon, maxlat)[2] <= 150
|
|
||||||
|
|
||||||
|
|
||||||
def test_watch_box_order_matches_catalog() -> None:
|
|
||||||
hormuz = next(p for p in chokepoints() if p["id"] == "hormuz")
|
|
||||||
minlat, minlon, maxlat, maxlon = (float(v) for v in hormuz["bbox"].split(","))
|
|
||||||
assert (minlon, minlat, maxlon, maxlat) in _adsb_watch_boxes()
|
|
||||||
# parse_bbox (the app's viewport order) agrees with the converted box.
|
|
||||||
assert parse_bbox(f"{minlon},{minlat},{maxlon},{maxlat}") == (minlon, minlat, maxlon, maxlat)
|
|
||||||
|
|
||||||
|
|
||||||
def test_idle_loop_polls_watch_boxes(monkeypatch) -> None:
|
|
||||||
"""With no client viewport the loop must call fetch_aircraft(persist=True)."""
|
|
||||||
calls: list[tuple[str, bool]] = []
|
|
||||||
|
|
||||||
async def fake_fetch(bbox: str, limit: int = 2000, persist: bool = False):
|
|
||||||
calls.append((bbox, persist))
|
|
||||||
return []
|
|
||||||
|
|
||||||
monkeypatch.setattr("live_layers.fetch_aircraft", fake_fetch)
|
|
||||||
assert manager.viewports() == []
|
|
||||||
|
|
||||||
async def run() -> None:
|
|
||||||
try:
|
|
||||||
await asyncio.wait_for(_adsb_refresh_loop(), 0.5)
|
|
||||||
except asyncio.TimeoutError:
|
|
||||||
pass
|
|
||||||
|
|
||||||
asyncio.run(run())
|
|
||||||
assert calls, "idle loop persisted nothing"
|
|
||||||
assert all(persist for _, persist in calls)
|
|
||||||
assert {bbox for bbox, _ in calls} == {
|
|
||||||
f"{b[0]},{b[1]},{b[2]},{b[3]}" for b in _adsb_watch_boxes()
|
|
||||||
}
|
|
||||||
|
|
@ -1,337 +0,0 @@
|
||||||
"""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
|
|
||||||
|
|
@ -144,7 +144,6 @@ def test_anonymous_can_read_public_allowlist(no_db):
|
||||||
"/api/news",
|
"/api/news",
|
||||||
"/api/news/ticker",
|
"/api/news/ticker",
|
||||||
"/api/news/map",
|
"/api/news/map",
|
||||||
"/api/news/blips",
|
|
||||||
"/api/geofences",
|
"/api/geofences",
|
||||||
"/api/geofence-alerts",
|
"/api/geofence-alerts",
|
||||||
"/api/analytics/summary",
|
"/api/analytics/summary",
|
||||||
|
|
@ -169,7 +168,6 @@ SPEC_PUBLIC_READS = (
|
||||||
"/api/analytics/summary", "/api/analytics/timeline",
|
"/api/analytics/summary", "/api/analytics/timeline",
|
||||||
"/api/analytics/sentiment/by-source", "/api/cameras",
|
"/api/analytics/sentiment/by-source", "/api/cameras",
|
||||||
"/api/news", "/api/news/summaries", "/api/news/ticker", "/api/news/map",
|
"/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/layers", "/api/map/chokepoints", "/api/map/radar",
|
||||||
"/api/map/sentinel1", "/api/aircraft", "/api/aircraft/photo",
|
"/api/map/sentinel1", "/api/aircraft", "/api/aircraft/photo",
|
||||||
"/api/trains", "/api/vessels", "/api/tracks/range", "/api/geofences",
|
"/api/trains", "/api/vessels", "/api/tracks/range", "/api/geofences",
|
||||||
|
|
|
||||||
|
|
@ -1,199 +0,0 @@
|
||||||
"""GDELT DOC 2.0 quota handling: no http retry on 429, backoff, prose bodies.
|
|
||||||
|
|
||||||
GDELT answers ``429`` with a plain-text "Please limit requests to one every 5
|
|
||||||
seconds" body and no Retry-After header. The ingester must not spend a second
|
|
||||||
request from the same IP on a status error, and must stop calling until the
|
|
||||||
backoff window expires instead of raising a traceback every cycle.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import asyncio
|
|
||||||
|
|
||||||
import httpx
|
|
||||||
import pytest
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture(autouse=True)
|
|
||||||
def _reset_backoff(monkeypatch):
|
|
||||||
import sources
|
|
||||||
|
|
||||||
sources._gdelt_clear_backoff()
|
|
||||||
monkeypatch.setattr(sources, "GDELT_BACKOFF_BASE", 300)
|
|
||||||
monkeypatch.setattr(sources, "GDELT_BACKOFF_MAX", 1800)
|
|
||||||
# These tests cover the DOC 2.0 path, which is now the fallback behind the
|
|
||||||
# 15-minute bulk GKG file (tests/test_gdelt_bulk.py covers that path).
|
|
||||||
monkeypatch.setattr(sources, "GDELT_BULK_ENABLED", False)
|
|
||||||
yield
|
|
||||||
sources._gdelt_clear_backoff()
|
|
||||||
|
|
||||||
|
|
||||||
class _FakeClient:
|
|
||||||
"""Stands in for httpx.AsyncClient; records every GET it is asked for."""
|
|
||||||
|
|
||||||
def __init__(self, responses, calls):
|
|
||||||
self._responses = list(responses)
|
|
||||||
self._calls = calls
|
|
||||||
|
|
||||||
async def __aenter__(self):
|
|
||||||
return self
|
|
||||||
|
|
||||||
async def __aexit__(self, *exc):
|
|
||||||
return False
|
|
||||||
|
|
||||||
async def get(self, url, params=None):
|
|
||||||
self._calls.append(url)
|
|
||||||
resp = self._responses.pop(0)
|
|
||||||
resp.request = httpx.Request("GET", url)
|
|
||||||
return resp
|
|
||||||
|
|
||||||
|
|
||||||
def _install(monkeypatch, responses):
|
|
||||||
import sources
|
|
||||||
|
|
||||||
calls: list[str] = []
|
|
||||||
monkeypatch.setattr(
|
|
||||||
sources.httpx, "AsyncClient", lambda **kw: _FakeClient(responses, calls)
|
|
||||||
)
|
|
||||||
return calls
|
|
||||||
|
|
||||||
|
|
||||||
def _no_publish(monkeypatch):
|
|
||||||
import sources
|
|
||||||
|
|
||||||
published: list[str] = []
|
|
||||||
|
|
||||||
async def _fake(subject, event):
|
|
||||||
published.append(subject)
|
|
||||||
|
|
||||||
monkeypatch.setattr(sources, "publish_event", _fake)
|
|
||||||
return published
|
|
||||||
|
|
||||||
|
|
||||||
def test_429_does_not_retry_http_and_starts_backoff(monkeypatch):
|
|
||||||
import sources
|
|
||||||
|
|
||||||
calls = _install(
|
|
||||||
monkeypatch,
|
|
||||||
[httpx.Response(429, text="Please limit requests to one every 5 seconds")],
|
|
||||||
)
|
|
||||||
|
|
||||||
n = asyncio.run(sources.ingest_gdelt(query="protest", max_articles=5))
|
|
||||||
|
|
||||||
assert n == 0
|
|
||||||
assert calls == [sources.GDELT_API] # exactly one request, no http fallback
|
|
||||||
assert sources.gdelt_backoff_remaining() > 250
|
|
||||||
|
|
||||||
|
|
||||||
def test_cycle_skipped_while_backing_off(monkeypatch):
|
|
||||||
import sources
|
|
||||||
|
|
||||||
calls = _install(
|
|
||||||
monkeypatch, [httpx.Response(429, text="Please limit requests to one every 5 seconds")]
|
|
||||||
)
|
|
||||||
asyncio.run(sources.ingest_gdelt(query="protest", max_articles=5))
|
|
||||||
assert len(calls) == 1
|
|
||||||
|
|
||||||
# A second cycle inside the window must not touch the network at all.
|
|
||||||
n = asyncio.run(sources.ingest_gdelt(query="protest", max_articles=5))
|
|
||||||
assert n == 0
|
|
||||||
assert len(calls) == 1
|
|
||||||
|
|
||||||
|
|
||||||
def test_backoff_doubles_then_caps(monkeypatch):
|
|
||||||
import sources
|
|
||||||
|
|
||||||
sources._gdelt_start_backoff()
|
|
||||||
first = sources._gdelt_backoff_secs
|
|
||||||
sources._gdelt_start_backoff()
|
|
||||||
second = sources._gdelt_backoff_secs
|
|
||||||
for _ in range(6):
|
|
||||||
sources._gdelt_start_backoff()
|
|
||||||
|
|
||||||
assert first == 300
|
|
||||||
assert second == 600
|
|
||||||
assert sources._gdelt_backoff_secs == 1800
|
|
||||||
|
|
||||||
|
|
||||||
def test_retry_after_header_is_honoured(monkeypatch):
|
|
||||||
import sources
|
|
||||||
|
|
||||||
_install(monkeypatch, [httpx.Response(429, headers={"Retry-After": "45"}, text="busy")])
|
|
||||||
asyncio.run(sources.ingest_gdelt(query="protest", max_articles=5))
|
|
||||||
|
|
||||||
assert 40 <= sources.gdelt_backoff_remaining() <= 45
|
|
||||||
|
|
||||||
|
|
||||||
def test_200_prose_body_treated_as_throttle(monkeypatch):
|
|
||||||
import sources
|
|
||||||
|
|
||||||
calls = _install(
|
|
||||||
monkeypatch,
|
|
||||||
[httpx.Response(200, text="Please limit requests to one every 5 seconds")],
|
|
||||||
)
|
|
||||||
|
|
||||||
n = asyncio.run(sources.ingest_gdelt(query="protest", max_articles=5))
|
|
||||||
|
|
||||||
assert n == 0
|
|
||||||
assert len(calls) == 1
|
|
||||||
assert sources.gdelt_backoff_remaining() > 250
|
|
||||||
|
|
||||||
|
|
||||||
def test_success_publishes_and_clears_backoff(monkeypatch):
|
|
||||||
import sources
|
|
||||||
|
|
||||||
sources._gdelt_start_backoff()
|
|
||||||
sources._gdelt_clear_backoff()
|
|
||||||
published = _no_publish(monkeypatch)
|
|
||||||
_install(
|
|
||||||
monkeypatch,
|
|
||||||
[
|
|
||||||
httpx.Response(
|
|
||||||
200,
|
|
||||||
json={
|
|
||||||
"articles": [
|
|
||||||
{
|
|
||||||
"url": "https://example.com/a",
|
|
||||||
"title": "Protest",
|
|
||||||
"domain": "example.com",
|
|
||||||
"seendate": "20261121T120000Z",
|
|
||||||
"language": "English",
|
|
||||||
"sourcecountry": "United States",
|
|
||||||
}
|
|
||||||
]
|
|
||||||
},
|
|
||||||
)
|
|
||||||
],
|
|
||||||
)
|
|
||||||
|
|
||||||
n = asyncio.run(sources.ingest_gdelt(query="protest", max_articles=5))
|
|
||||||
|
|
||||||
assert n == 1
|
|
||||||
assert published == ["events.gdelt"]
|
|
||||||
assert sources.gdelt_backoff_remaining() == 0
|
|
||||||
|
|
||||||
|
|
||||||
def test_transport_error_still_falls_back_to_http(monkeypatch):
|
|
||||||
import sources
|
|
||||||
|
|
||||||
class _BoomClient(_FakeClient):
|
|
||||||
async def get(self, url, params=None):
|
|
||||||
self._calls.append(url)
|
|
||||||
if url.startswith("https://"):
|
|
||||||
raise httpx.ConnectError("tls handshake failed")
|
|
||||||
resp = self._responses.pop(0)
|
|
||||||
resp.request = httpx.Request("GET", url)
|
|
||||||
return resp
|
|
||||||
|
|
||||||
calls: list[str] = []
|
|
||||||
responses = [httpx.Response(200, json={"articles": []})]
|
|
||||||
monkeypatch.setattr(
|
|
||||||
sources.httpx, "AsyncClient", lambda **kw: _BoomClient(responses, calls)
|
|
||||||
)
|
|
||||||
_no_publish(monkeypatch)
|
|
||||||
|
|
||||||
n = asyncio.run(sources.ingest_gdelt(query="protest", max_articles=5))
|
|
||||||
|
|
||||||
assert n == 0
|
|
||||||
assert calls == [sources.GDELT_API, sources.GDELT_API.replace("https://", "http://", 1)]
|
|
||||||
assert sources.gdelt_backoff_remaining() == 0
|
|
||||||
|
|
@ -1,274 +0,0 @@
|
||||||
"""GDELT 15-minute bulk GKG ingest (throttle-free path).
|
|
||||||
|
|
||||||
The DOC 2.0 API is per-IP quota'd (429). The same article coverage is served as
|
|
||||||
static 15-minute files with no key and no quota. These tests pin the mapping
|
|
||||||
from a GKG row into the existing ``events.gdelt`` event shape, the CONFIG-term
|
|
||||||
filter that keeps volume bounded, and the DOC fallback contract.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import io
|
|
||||||
import zipfile
|
|
||||||
|
|
||||||
import httpx
|
|
||||||
import pytest
|
|
||||||
|
|
||||||
LASTUPDATE = """33287 99e984fd826497ae5765484af3b11521 http://data.gdeltproject.org/gdeltv2/20261121234500.export.CSV.zip
|
|
||||||
46052 c09f32f728f695f2bf753540aa92e6ce http://data.gdeltproject.org/gdeltv2/20261121234500.mentions.CSV.zip
|
|
||||||
2361330 0804c7df5b359f177aeff85cad63d539 http://data.gdeltproject.org/gdeltv2/20261121234500.gkg.csv.zip
|
|
||||||
"""
|
|
||||||
|
|
||||||
# GKG row shape (27 tab-separated fields): id, date, collection, common name,
|
|
||||||
# document id, V1Counts, V2Counts, V1Themes, V2Themes, V2Locations, ..., tone,
|
|
||||||
# ..., V2ExtrasXML.
|
|
||||||
GKG_ROW = "\t".join([
|
|
||||||
"20261121234500-11",
|
|
||||||
"20261121234500",
|
|
||||||
"1",
|
|
||||||
"dominicanrepublicpost.com",
|
|
||||||
"https://dominicanrepublicpost.com/protest-in-iowa/",
|
|
||||||
"PROTEST#29000##0######;",
|
|
||||||
"PROTEST#29000##0#######287;",
|
|
||||||
"PROTEST;TAX_FNCACT;VIOLENT_UNREST;",
|
|
||||||
"PROTEST,12;TAX_FNCACT,4;",
|
|
||||||
"",
|
|
||||||
"",
|
|
||||||
"",
|
|
||||||
"",
|
|
||||||
"",
|
|
||||||
"",
|
|
||||||
"-4.75,0.5,6.1,7.2,18.3,0,206",
|
|
||||||
"",
|
|
||||||
"",
|
|
||||||
"",
|
|
||||||
"",
|
|
||||||
"",
|
|
||||||
"",
|
|
||||||
"",
|
|
||||||
"",
|
|
||||||
"",
|
|
||||||
"",
|
|
||||||
"",
|
|
||||||
(
|
|
||||||
"<PAGE_AUTHORS>Gary Stevens</PAGE_AUTHORS>"
|
|
||||||
"<PAGE_PRECISEPUBTIMESTAMP>20261121211600</PAGE_PRECISEPUBTIMESTAMP>"
|
|
||||||
"<PAGE_TITLE>Protest in Iowa & Nebraska</PAGE_TITLE>"
|
|
||||||
),
|
|
||||||
])
|
|
||||||
|
|
||||||
LOCATIONS_ROW = "\t".join([
|
|
||||||
"20261121234500-12", "20261121234500", "1", "wkzo.com",
|
|
||||||
"https://wkzo.com/power-outage/",
|
|
||||||
"", "", "POWER_OUTAGE;CYBER_ATTACK;", "POWER_OUTAGE,9;", "",
|
|
||||||
"", "", "", "", "", "-2.0,0.1,1.0,1.0,1.0,0,10", "", "", "", "", "", "", "",
|
|
||||||
"", "", "", "<PAGE_TITLE>Power outage hits grid</PAGE_TITLE>",
|
|
||||||
])
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture(autouse=True)
|
|
||||||
def _reset_bulk_state(monkeypatch):
|
|
||||||
import sources
|
|
||||||
|
|
||||||
monkeypatch.setattr(sources, "_gdelt_bulk_last_file", None)
|
|
||||||
monkeypatch.setattr(sources, "GDELT_BULK_MAX_EVENTS", 100)
|
|
||||||
sources._gdelt_clear_backoff()
|
|
||||||
yield
|
|
||||||
sources._gdelt_clear_backoff()
|
|
||||||
|
|
||||||
|
|
||||||
def _gkg_zip(rows: list[str]) -> bytes:
|
|
||||||
buf = io.BytesIO()
|
|
||||||
with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf:
|
|
||||||
zf.writestr("20261121234500.gkg.csv", "\n".join(rows) + "\n")
|
|
||||||
return buf.getvalue()
|
|
||||||
|
|
||||||
|
|
||||||
class _FakeClient:
|
|
||||||
def __init__(self, index_text: str, archive: bytes | None, calls: list[str], fail_archive=False):
|
|
||||||
self._index_text = index_text
|
|
||||||
self._archive = archive
|
|
||||||
self._calls = calls
|
|
||||||
self._fail_archive = fail_archive
|
|
||||||
|
|
||||||
async def __aenter__(self):
|
|
||||||
return self
|
|
||||||
|
|
||||||
async def __aexit__(self, *exc):
|
|
||||||
return False
|
|
||||||
|
|
||||||
async def get(self, url, params=None, **kw):
|
|
||||||
self._calls.append(url)
|
|
||||||
request = httpx.Request("GET", url)
|
|
||||||
if url.endswith("lastupdate.txt"):
|
|
||||||
return httpx.Response(200, text=self._index_text, request=request)
|
|
||||||
if self._fail_archive:
|
|
||||||
raise httpx.TransportError("boom")
|
|
||||||
return httpx.Response(200, content=self._archive or b"", request=request)
|
|
||||||
|
|
||||||
|
|
||||||
def _install(monkeypatch, index_text=LASTUPDATE, archive=None, fail_archive=False):
|
|
||||||
import sources
|
|
||||||
|
|
||||||
calls: list[str] = []
|
|
||||||
monkeypatch.setattr(
|
|
||||||
sources.httpx, "AsyncClient",
|
|
||||||
lambda **kw: _FakeClient(index_text, archive, calls, fail_archive),
|
|
||||||
)
|
|
||||||
return calls
|
|
||||||
|
|
||||||
|
|
||||||
def _collect(monkeypatch):
|
|
||||||
import sources
|
|
||||||
|
|
||||||
published: list[dict] = []
|
|
||||||
|
|
||||||
async def _fake_publish(subject, events):
|
|
||||||
assert subject == "events.gdelt"
|
|
||||||
published.extend(events)
|
|
||||||
return len(events)
|
|
||||||
|
|
||||||
monkeypatch.setattr(sources, "_publish_unknown", _fake_publish)
|
|
||||||
return published
|
|
||||||
|
|
||||||
|
|
||||||
def _no_network(monkeypatch):
|
|
||||||
"""Fail the run if anything reaches the DOC 2.0 API."""
|
|
||||||
import sources
|
|
||||||
|
|
||||||
async def _boom(*a, **kw):
|
|
||||||
raise AssertionError("DOC API must not be called when bulk data lands")
|
|
||||||
|
|
||||||
monkeypatch.setattr(sources, "_ingest_gdelt_doc", _boom)
|
|
||||||
|
|
||||||
|
|
||||||
def test_query_terms_from_config_string():
|
|
||||||
import sources
|
|
||||||
|
|
||||||
assert sources.gdelt_query_terms("") == [
|
|
||||||
"unrest", "protest", "outage", "cyber", "power outage",
|
|
||||||
]
|
|
||||||
assert sources.gdelt_query_terms('(flood OR "power outage")') == [
|
|
||||||
"flood", "power outage",
|
|
||||||
]
|
|
||||||
|
|
||||||
|
|
||||||
def test_select_gdelt_bulk_url_picks_gkg_and_forces_https():
|
|
||||||
import sources
|
|
||||||
|
|
||||||
picked = sources.select_gdelt_bulk_url(LASTUPDATE)
|
|
||||||
assert picked == (
|
|
||||||
"20261121234500.gkg.csv.zip",
|
|
||||||
"https://data.gdeltproject.org/gdeltv2/20261121234500.gkg.csv.zip",
|
|
||||||
)
|
|
||||||
assert sources.select_gdelt_bulk_url("") is None
|
|
||||||
|
|
||||||
|
|
||||||
def test_parse_gkg_row_maps_into_event_shape():
|
|
||||||
import sources
|
|
||||||
|
|
||||||
terms = sources.gdelt_query_terms("")
|
|
||||||
event = sources.parse_gkg_row(GKG_ROW.split("\t"), terms, "20261121234500.gkg.csv.zip")
|
|
||||||
|
|
||||||
assert event["source_type"] == "gdel-t2"
|
|
||||||
assert event["url"] == "https://dominicanrepublicpost.com/protest-in-iowa/"
|
|
||||||
assert event["title"] == "Protest in Iowa & Nebraska"
|
|
||||||
assert event["body"] == "dominicanrepublicpost.com"
|
|
||||||
# Publish time comes from PAGE_PRECISEPUBTIMESTAMP, not the window stamp.
|
|
||||||
assert event["source_timestamp"] == "2026-11-21T21:16:00+00:00"
|
|
||||||
assert "protest" in event["tags"] and "VIOLENT_UNREST" in event["tags"]
|
|
||||||
assert event["raw"]["bulk_file"] == "20261121234500.gkg.csv.zip"
|
|
||||||
assert event["raw"]["tone"] == pytest.approx(-4.75 / 4249.0)
|
|
||||||
# No V2Locations in this row -> no fake geo.
|
|
||||||
assert event["location_lat"] is None and event["location_lon"] is None
|
|
||||||
|
|
||||||
|
|
||||||
def test_parse_gkg_row_reads_geo_from_v2locations():
|
|
||||||
import sources
|
|
||||||
|
|
||||||
row = GKG_ROW.split("\t")
|
|
||||||
row[9] = (
|
|
||||||
"4#Middletown, Iowa, United States#US#IA#40.8284#-91.259#-1834425"
|
|
||||||
";1#United States#US#US#39.8283#-98.5795#US"
|
|
||||||
)
|
|
||||||
event = sources.parse_gkg_row(row, sources.gdelt_query_terms(""))
|
|
||||||
assert event["location_lat"] == pytest.approx(40.8284)
|
|
||||||
assert event["location_lon"] == pytest.approx(-91.259)
|
|
||||||
assert event["location_name"] == "Middletown, Iowa, United States"
|
|
||||||
|
|
||||||
|
|
||||||
def test_gkg_location_tolerates_short_and_bad_forms():
|
|
||||||
import sources
|
|
||||||
|
|
||||||
# adm2 slot dropped: lat/lon are still the last two before the feature id.
|
|
||||||
assert sources._gkg_location("2#California, United States#US#USCA#36.17#-119.746#CA") == (
|
|
||||||
pytest.approx(36.17), pytest.approx(-119.746), "California, United States",
|
|
||||||
)
|
|
||||||
assert sources._gkg_location("")[0] is None
|
|
||||||
assert sources._gkg_location("1#Nowhere#US#US#999#999#X")[0] is None
|
|
||||||
|
|
||||||
|
|
||||||
def test_parse_gkg_row_drops_rows_without_query_terms():
|
|
||||||
import sources
|
|
||||||
|
|
||||||
row = GKG_ROW.split("\t")
|
|
||||||
row[7] = "SPORTS;ENTERTAINMENT;"
|
|
||||||
assert sources.parse_gkg_row(row, sources.gdelt_query_terms("")) is None
|
|
||||||
|
|
||||||
row = GKG_ROW.split("\t")
|
|
||||||
row[4] = ""
|
|
||||||
assert sources.parse_gkg_row(row, sources.gdelt_query_terms("")) is None
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
|
||||||
async def test_ingest_gdelt_bulk_publishes_filtered_rows_and_skips_repeat(monkeypatch):
|
|
||||||
import sources
|
|
||||||
|
|
||||||
_install(monkeypatch, archive=_gkg_zip([GKG_ROW, LOCATIONS_ROW]))
|
|
||||||
published = _collect(monkeypatch)
|
|
||||||
_no_network(monkeypatch)
|
|
||||||
|
|
||||||
count = await sources.ingest_gdelt()
|
|
||||||
assert count == 2
|
|
||||||
assert {e["url"] for e in published} == {
|
|
||||||
"https://dominicanrepublicpost.com/protest-in-iowa/",
|
|
||||||
"https://wkzo.com/power-outage/",
|
|
||||||
}
|
|
||||||
# Second cycle: same file, nothing new fetched or published.
|
|
||||||
before = len(published)
|
|
||||||
assert await sources.ingest_gdelt() == 0
|
|
||||||
assert len(published) == before
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
|
||||||
async def test_ingest_gdelt_bulk_caps_events_per_file(monkeypatch):
|
|
||||||
import sources
|
|
||||||
|
|
||||||
rows = []
|
|
||||||
for i in range(5):
|
|
||||||
row = GKG_ROW.split("\t")
|
|
||||||
row[0] = f"20261121234500-{i}"
|
|
||||||
row[4] = f"https://example.com/story-{i}"
|
|
||||||
rows.append("\t".join(row))
|
|
||||||
_install(monkeypatch, archive=_gkg_zip(rows))
|
|
||||||
published = _collect(monkeypatch)
|
|
||||||
_no_network(monkeypatch)
|
|
||||||
|
|
||||||
assert await sources.ingest_gdelt_bulk(max_events=2) == 2
|
|
||||||
assert len(published) == 2
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
|
||||||
async def test_ingest_gdelt_falls_back_to_doc_when_bulk_fails(monkeypatch):
|
|
||||||
import sources
|
|
||||||
|
|
||||||
_install(monkeypatch, fail_archive=True)
|
|
||||||
calls = {"doc": 0}
|
|
||||||
|
|
||||||
async def _doc(query="", max_articles=50):
|
|
||||||
calls["doc"] += 1
|
|
||||||
return 7
|
|
||||||
|
|
||||||
monkeypatch.setattr(sources, "_ingest_gdelt_doc", _doc)
|
|
||||||
assert await sources.ingest_gdelt() == 7
|
|
||||||
assert calls["doc"] == 1
|
|
||||||
Loading…
Reference in a new issue