From 96590bc16d5cfe17b668e5dc0f233cb309b24b6d Mon Sep 17 00:00:00 2001 From: Sirius DevOps Date: Thu, 27 Aug 2026 22:21:26 -0400 Subject: [PATCH 01/79] test: add news summarizer intel parser tests + impl --- news/summerizer/intel.py | 90 +++++++++++++++++++++++++++++ news/summerizer/tests/test_intel.py | 42 ++++++++++++++ 2 files changed, 132 insertions(+) create mode 100644 news/summerizer/intel.py create mode 100644 news/summerizer/tests/test_intel.py diff --git a/news/summerizer/intel.py b/news/summerizer/intel.py new file mode 100644 index 0000000..d4bb1b7 --- /dev/null +++ b/news/summerizer/intel.py @@ -0,0 +1,90 @@ +"""Pure parser for the news-summarizer reduce JSON / geo / importance contract.""" + +from __future__ import annotations + +import json +import re + +_EMPTY = {"summary_en": "", "ticker": [], "map_items": []} +_KEEP = frozenset({"critical", "high"}) +_THINK_RE = re.compile(r".*?", re.DOTALL) +_FENCE_RE = re.compile(r"```(?:json)?", re.IGNORECASE) + +TICKER_HEADLINE_MAX = 140 +MAP_HEADLINE_MAX = 160 +TICKER_CAP = 12 + + +def parse_reduce_json(raw: str) -> dict: + try: + text = _THINK_RE.sub("", raw or "") + text = _FENCE_RE.sub("", text) + start = text.find("{") + end = text.rfind("}") + if start == -1 or end == -1 or end < start: + return dict(_EMPTY) + data = json.loads(text[start : end + 1]) + if not isinstance(data, dict): + return dict(_EMPTY) + summary = data.get("summary_en", "") + ticker = data.get("ticker", []) + map_items = data.get("map_items", []) + return { + "summary_en": summary if isinstance(summary, str) else "", + "ticker": ticker if isinstance(ticker, list) else [], + "map_items": map_items if isinstance(map_items, list) else [], + } + except Exception: + return dict(_EMPTY) + + +def clamp_coords(lat, lon) -> tuple[float, float] | None: + try: + lat_f = float(lat) + lon_f = float(lon) + except (TypeError, ValueError): + return None + if not (-90 <= lat_f <= 90 and -180 <= lon_f <= 180): + return None + return (lat_f, lon_f) + + +def _trimmed_headline(row: dict, limit: int) -> str: + headline = row.get("headline") or "" + if not isinstance(headline, str): + headline = str(headline) + return headline.strip()[:limit] + + +def select_ticker(rows: list) -> list: + out = [] + for row in rows: + if row.get("importance") not in _KEEP: + continue + headline = _trimmed_headline(row, TICKER_HEADLINE_MAX) + if not headline: + continue + item = dict(row) + item["headline"] = headline + out.append(item) + if len(out) >= TICKER_CAP: + break + return out + + +def select_map(items: list) -> list: + out = [] + for row in items: + if row.get("importance") not in _KEEP: + continue + headline = _trimmed_headline(row, MAP_HEADLINE_MAX) + if not headline: + continue + coords = clamp_coords(row.get("lat"), row.get("lon")) + if coords is None: + continue + item = dict(row) + item["headline"] = headline + item["lat"], item["lon"] = coords + out.append(item) + return out diff --git a/news/summerizer/tests/test_intel.py b/news/summerizer/tests/test_intel.py new file mode 100644 index 0000000..74f74c3 --- /dev/null +++ b/news/summerizer/tests/test_intel.py @@ -0,0 +1,42 @@ +from intel import parse_reduce_json, clamp_coords, select_ticker, select_map + +FENCED = """```json +{"summary_en": "Brief.", "ticker": [ + {"headline": "Blast in Kyiv", "importance": "critical", "url": "https://ex", "location_name": "Kyiv"} +], "map_items": [ + {"headline": "Blast in Kyiv", "importance": "critical", "location_name": "Kyiv, Ukraine", + "lat": 50.45, "lon": 30.52, "location_confidence": "city", "category": "military/conflict", "url": "https://ex"} +]} +```""" + +def test_parse_strips_fence_and_think_tags(): + raw = "nope\n" + FENCED + out = parse_reduce_json(raw) + assert out["summary_en"] == "Brief." + assert len(out["ticker"]) == 1 + +def test_parse_empty_and_garbage_returns_empty_struct(): + assert parse_reduce_json("")["summary_en"] == "" + assert parse_reduce_json("not json")["ticker"] == [] + +def test_clamp_coords_drops_out_of_range_and_unknown(): + assert clamp_coords(50.45, 30.52) == (50.45, 30.52) + assert clamp_coords(95.0, 10.0) is None + assert clamp_coords(None, 10.0) is None + assert clamp_coords("50.45", "30.52") == (50.45, 30.52) + +def test_select_ticker_keeps_critical_high_caps_12(): + rows = [{"headline": f"h{i}", "importance": "critical"} for i in range(15)] + rows.append({"headline": "skip", "importance": "low"}) + out = select_ticker(rows) + assert len(out) == 12 + assert all(r["importance"] in ("critical", "high") for r in out) + +def test_select_map_requires_valid_coords_and_flag(): + items = [ + {"headline": "A", "importance": "critical", "lat": 50.45, "lon": 30.52, "location_name": "Kyiv"}, + {"headline": "B", "importance": "critical", "lat": None, "lon": None, "location_name": "Unknown"}, + {"headline": "C", "importance": "low", "lat": 1.0, "lon": 2.0, "location_name": "x"}, + ] + out = select_map(items) + assert [r["headline"] for r in out] == ["A"] From 4b00eed5660131e83675242a78927f1cce530892 Mon Sep 17 00:00:00 2001 From: Sirius DevOps Date: Thu, 27 Aug 2026 22:30:50 -0400 Subject: [PATCH 02/79] feat: nous portal chat client for news summarizer --- news/summerizer/nous_client.py | 36 +++++++++ news/summerizer/tests/test_nous_client.py | 97 +++++++++++++++++++++++ 2 files changed, 133 insertions(+) create mode 100644 news/summerizer/nous_client.py create mode 100644 news/summerizer/tests/test_nous_client.py diff --git a/news/summerizer/nous_client.py b/news/summerizer/nous_client.py new file mode 100644 index 0000000..da0b2c4 --- /dev/null +++ b/news/summerizer/nous_client.py @@ -0,0 +1,36 @@ +"""HTTP client for the Nous inference chat completions API.""" + +from __future__ import annotations + +import os + +import httpx + +_DEFAULT_UA = "osint-dashboard-news-summarizer" +_DEFAULT_BASE = "https://inference-api.nousresearch.com/v1" + + +def chat(prompt, *, api_key, model, base_url, json_mode=False) -> str: + resolved = (base_url or os.environ.get("NOUS_BASE_URL", _DEFAULT_BASE)).rstrip("/") + url = f"{resolved}/chat/completions" + headers = { + "Authorization": f"Bearer {api_key}", + "User-Agent": os.environ.get("OSINT_USER_AGENT") or _DEFAULT_UA, + } + payload = { + "model": model, + "messages": [{"role": "user", "content": prompt}], + "temperature": 0.2, + "max_tokens": 4096, + } + if json_mode: + payload["response_format"] = {"type": "json_object"} + try: + with httpx.Client(timeout=60.0) as client: + resp = client.post(url, headers=headers, json=payload) + if resp.status_code == 401 or resp.status_code >= 500: + return "" + data = resp.json() + return data["choices"][0]["message"]["content"] + except Exception: + return "" diff --git a/news/summerizer/tests/test_nous_client.py b/news/summerizer/tests/test_nous_client.py new file mode 100644 index 0000000..002faa4 --- /dev/null +++ b/news/summerizer/tests/test_nous_client.py @@ -0,0 +1,97 @@ +from unittest.mock import MagicMock + +import httpx +from nous_client import chat + +DEFAULT_UA = "osint-dashboard-news-summarizer" +BASE = "https://inference-api.nousresearch.com/v1" + + +def _ok_response(content="hello"): + resp = MagicMock() + resp.status_code = 200 + resp.json.return_value = {"choices": [{"message": {"content": content}}]} + return resp + + +def _install_fake(monkeypatch, post_impl): + captured = {} + + class FakeClient: + def __init__(self, timeout=None, **kwargs): + captured["timeout"] = timeout + + def __enter__(self): + return self + + def __exit__(self, *exc): + return False + + def post(self, url, *, headers=None, json=None, **kwargs): + captured["url"] = url + captured["headers"] = headers + captured["json"] = json + return post_impl(url, headers, json) + + monkeypatch.setattr(httpx, "Client", FakeClient) + return captured + + +def test_posts_chat_completions_with_auth_body_and_returns_content(monkeypatch): + captured = _install_fake(monkeypatch, lambda *a: _ok_response("the-content")) + out = chat( + "summarize this", + api_key="secret-key", + model="hermes-3", + base_url=BASE, + ) + assert out == "the-content" + assert captured["url"] == f"{BASE}/chat/completions" + assert captured["headers"]["Authorization"] == "Bearer secret-key" + assert captured["headers"]["User-Agent"] == DEFAULT_UA + assert captured["json"]["model"] == "hermes-3" + assert captured["json"]["messages"] == [{"role": "user", "content": "summarize this"}] + assert captured["json"]["temperature"] == 0.2 + assert captured["json"]["max_tokens"] == 4096 + assert "response_format" not in captured["json"] + + +def test_user_agent_equals_osint_user_agent_env(monkeypatch): + monkeypatch.setenv("OSINT_USER_AGENT", "custom-ua/2.0") + captured = _install_fake(monkeypatch, lambda *a: _ok_response("ok")) + chat("p", api_key="k", model="m", base_url=BASE) + assert captured["headers"]["User-Agent"] == "custom-ua/2.0" + + +def test_json_mode_sets_response_format(monkeypatch): + captured = _install_fake(monkeypatch, lambda *a: _ok_response("{}")) + chat("p", api_key="k", model="m", base_url=BASE, json_mode=True) + assert captured["json"]["response_format"] == {"type": "json_object"} + + +def test_401_returns_empty_string(monkeypatch): + def post_impl(*a): + resp = MagicMock() + resp.status_code = 401 + return resp + + _install_fake(monkeypatch, post_impl) + assert chat("p", api_key="bad", model="m", base_url=BASE) == "" + + +def test_5xx_returns_empty_string(monkeypatch): + def post_impl(*a): + resp = MagicMock() + resp.status_code = 503 + return resp + + _install_fake(monkeypatch, post_impl) + assert chat("p", api_key="k", model="m", base_url=BASE) == "" + + +def test_timeout_returns_empty_string(monkeypatch): + def post_impl(*a): + raise httpx.TimeoutException("timed out") + + _install_fake(monkeypatch, post_impl) + assert chat("p", api_key="k", model="m", base_url=BASE) == "" From cbc573b83019ef0de9076d771be3ae766b85361b Mon Sep 17 00:00:00 2001 From: Sirius DevOps Date: Thu, 27 Aug 2026 22:40:50 -0400 Subject: [PATCH 03/79] feat: add news_items table and summary model column --- alembic/versions/005_news_items.py | 64 ++++++++++++++++++++++++++++++ app/models.py | 24 ++++++++++- 2 files changed, 86 insertions(+), 2 deletions(-) create mode 100644 alembic/versions/005_news_items.py diff --git a/alembic/versions/005_news_items.py b/alembic/versions/005_news_items.py new file mode 100644 index 0000000..08e9afc --- /dev/null +++ b/alembic/versions/005_news_items.py @@ -0,0 +1,64 @@ +"""news_items table + article_summaries.model + +Revision ID: 005_news_items +Revises: 004_camera_enum +Create Date: 2026-08-28 +""" + +from alembic import op + +# revision identifiers, used by Alembic. +revision = "005_news_items" +down_revision = "004_camera_enum" +branch_labels = None +depends_on = None + + +def upgrade() -> None: + # Idempotent DDL: ingest (summarizer ensure_tables) may create the same + # shapes first depending on container startup order. IF NOT EXISTS makes + # both orders safe — whichever runs first wins, the other no-ops. + # One statement per op.execute: asyncpg rejects multi-command prepared + # statements (same style as 003_news). + op.execute( + """ + ALTER TABLE article_summaries + ADD COLUMN IF NOT EXISTS model TEXT + """ + ) + op.execute( + """ + CREATE TABLE IF NOT EXISTS news_items ( + id SERIAL PRIMARY KEY, + summary_id INTEGER REFERENCES article_summaries(id) ON DELETE CASCADE, + kind TEXT NOT NULL, + headline TEXT NOT NULL, + importance TEXT NOT NULL, + location_name TEXT, + lat DOUBLE PRECISION, + lon DOUBLE PRECISION, + location_confidence TEXT, + category TEXT, + url TEXT, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() + ) + """ + ) + op.execute( + """ + CREATE INDEX IF NOT EXISTS ix_news_items_kind_created + ON news_items (kind, created_at DESC) + """ + ) + op.execute( + """ + CREATE INDEX IF NOT EXISTS ix_news_items_map_bbox + ON news_items (lon, lat) + WHERE kind = 'map' AND lat IS NOT NULL AND lon IS NOT NULL + """ + ) + + +def downgrade() -> None: + op.execute("DROP TABLE IF EXISTS news_items") + op.execute("ALTER TABLE article_summaries DROP COLUMN IF EXISTS model") diff --git a/app/models.py b/app/models.py index 706b5a2..b8ad2b2 100644 --- a/app/models.py +++ b/app/models.py @@ -185,8 +185,8 @@ Index("ix_fires_bbox", fires.c.longitude, fires.c.latitude) # ── News pipeline (scraper + summarizer) ────────────────────────────────── -# Written by the vendored news-scraper (Scrapy) / news-summarizer (Gemini) -# services; schema must match the idempotent alembic migration 003_news. +# Written by the vendored news-scraper (Scrapy) / news-summarizer services; +# schema must match the idempotent alembic migrations 003_news + 005_news_items. articles = Table( "articles", @@ -209,6 +209,26 @@ article_summaries = Table( Column("summary_text", Text, nullable=False), Column("batch_timestamp", DateTime(timezone=True), server_default=func.now(), nullable=False), + Column("model", Text), # LLM id used for this batch; nullable for old rows ) Index("ix_article_summaries_batch_timestamp", article_summaries.c.batch_timestamp) + + +news_items = Table( + "news_items", + metadata, + Column("id", Integer, primary_key=True, autoincrement=True), + Column("summary_id", Integer), + Column("kind", Text, nullable=False), + Column("headline", Text, nullable=False), + Column("importance", Text, nullable=False), + Column("location_name", Text), + Column("lat", Float), + Column("lon", Float), + Column("location_confidence", Text), + Column("category", Text), + Column("url", Text), + 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) From 5b2357830215f6219e91620082b3ded1637c5ff2 Mon Sep 17 00:00:00 2001 From: Sirius DevOps Date: Thu, 27 Aug 2026 22:49:59 -0400 Subject: [PATCH 04/79] feat: news ticker and map API contracts --- app/main.py | 102 +++++++++++++++++++++++++++++++++++-- app/schemas.py | 27 ++++++++++ tests/test_api_news.py | 113 +++++++++++++++++++++++++++++++++++++---- 3 files changed, 230 insertions(+), 12 deletions(-) diff --git a/app/main.py b/app/main.py index aad0663..6afd550 100644 --- a/app/main.py +++ b/app/main.py @@ -31,12 +31,13 @@ from sqlalchemy.ext.asyncio import AsyncSession from database import async_session, init_extensions from models import ( alerts, documents, entities, entity_events, events, feed_sources, fires, - articles, article_summaries, + articles, article_summaries, news_items, ) from schemas import ( AlertCreate, AlertOut, AlertSeverity, AlertType, AlertUpdate, DashboardSummary, EntityCreate, EntityKind, EntityOut, - EventCreate, EventOut, FireOut, NewsArticleOut, NewsSummaryOut, + EventCreate, EventOut, FireOut, NewsArticleOut, NewsMapItemOut, + NewsSummaryOut, NewsTickerItemOut, FeedSourceCreate, FeedSourceOut, KeyOut, KeyValueIn, SearchResult, SentimentSummary, SourceType, @@ -1128,7 +1129,102 @@ async def list_news_summaries( return [ NewsSummaryOut( id=r["id"], summary_text=r["summary_text"], - batch_timestamp=r["batch_timestamp"], + batch_timestamp=r["batch_timestamp"], model=r["model"], + ) + for r in rows + ] + + +_FLAGGED = ("critical", "high") + + +@app.get("/api/news/ticker", response_model=list[NewsTickerItemOut]) +async def list_news_ticker( + since: datetime | None = Query( + None, + description="Only ticker items created at/after this UTC instant.", + ), + limit: int = Query(20, ge=1, le=50), +): + """Flagged ticker rows (critical/high), newest first. No LLM required.""" + async with async_session() as session: + stmt = ( + select(news_items) + .where( + news_items.c.kind == "ticker", + news_items.c.importance.in_(_FLAGGED), + ) + .order_by(news_items.c.created_at.desc()) + ) + if since: + stmt = stmt.where(news_items.c.created_at >= since) + stmt = stmt.limit(limit) + rows = (await session.execute(stmt)).mappings().all() + return [ + NewsTickerItemOut( + id=r["id"], headline=r["headline"], importance=r["importance"], + location_name=r["location_name"], url=r["url"], + created_at=r["created_at"], + ) + for r in rows + ] + + +@app.get("/api/news/map", response_model=list[NewsMapItemOut]) +async def list_news_map( + bbox: str | None = Query( + None, + description="Comma-separated 'minlon,minlat,maxlon,maxlat' to bound the " + "result set by item coordinates. Omit for all flagged pins.", + ), + since: datetime | None = Query( + None, + description="Only map items created at/after this UTC instant. " + "Defaults to the last 24 hours.", + ), + limit: int = Query(200, ge=1, le=500), +): + """Flagged map pins (critical/high with coords). No zoom skip — world view.""" + if since is None: + since = datetime.now(timezone.utc) - timedelta(hours=24) + async with async_session() as session: + stmt = ( + select(news_items) + .where( + news_items.c.kind == "map", + news_items.c.lat.isnot(None), + news_items.c.lon.isnot(None), + news_items.c.importance.in_(_FLAGGED), + news_items.c.created_at >= since, + ) + .order_by(news_items.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_( + news_items.c.lon >= minlon, news_items.c.lon <= maxlon, + news_items.c.lat >= minlat, news_items.c.lat <= maxlat, + ) + ) + stmt = stmt.limit(limit) + rows = (await session.execute(stmt)).mappings().all() + return [ + NewsMapItemOut( + id=r["id"], headline=r["headline"], importance=r["importance"], + location_name=r["location_name"], lat=r["lat"], lon=r["lon"], + location_confidence=r["location_confidence"], category=r["category"], + url=r["url"], created_at=r["created_at"], ) for r in rows ] diff --git a/app/schemas.py b/app/schemas.py index e27b002..35bda45 100644 --- a/app/schemas.py +++ b/app/schemas.py @@ -273,6 +273,33 @@ class NewsSummaryOut(BaseModel): id: int summary_text: str batch_timestamp: datetime + model: Optional[str] = None + + +class NewsTickerItemOut(BaseModel): + """One flagged ticker row as exposed by GET /api/news/ticker.""" + + id: int + headline: str + importance: str + location_name: Optional[str] = None + url: Optional[str] = None + created_at: datetime + + +class NewsMapItemOut(BaseModel): + """One flagged map pin as exposed by GET /api/news/map.""" + + id: int + headline: str + importance: str + location_name: Optional[str] = None + lat: float + lon: float + location_confidence: Optional[str] = None + category: Optional[str] = None + url: Optional[str] = None + created_at: datetime # ─── Aggregations ──────────────────────────────────────────────────────── diff --git a/tests/test_api_news.py b/tests/test_api_news.py index 786d64e..340cbd0 100644 --- a/tests/test_api_news.py +++ b/tests/test_api_news.py @@ -1,9 +1,9 @@ -"""Integration tests for the news pipeline API (GET /api/news + summaries). +"""Integration tests for the news pipeline API (GET /api/news + summaries + intel). DB-backed: marked `requires_db` and auto-skip when the test database is unreachable (see tests/conftest.py). Seeding writes directly to the shared -`articles` / `article_summaries` tables, exactly as the scraper + summarizer -services would. +`articles` / `article_summaries` / `news_items` tables, exactly as the scraper ++ summarizer services would. """ from __future__ import annotations @@ -37,7 +37,9 @@ def _truncate() -> None: async def run(): conn = await asyncpg.connect(**_conn_kwargs()) try: - await conn.execute("TRUNCATE articles, article_summaries") + await conn.execute( + "TRUNCATE articles, article_summaries, news_items CASCADE" + ) finally: await conn.close() @@ -66,14 +68,45 @@ def _seed_article(title: str, url: str, domain: str, ts: str, content: str = "bo asyncio.run(run()) -def _seed_summary(text: str, ts: str) -> None: +def _seed_summary(text: str, ts: str, model: str | None = None) -> int: + async def run() -> int: + conn = await asyncpg.connect(**_conn_kwargs()) + try: + row = await conn.fetchrow( + "INSERT INTO article_summaries (summary_text, batch_timestamp, model) " + "VALUES ($1, $2, $3) RETURNING id", + text, datetime.fromisoformat(ts), model, + ) + return int(row["id"]) + finally: + await conn.close() + + return asyncio.run(run()) + + +def _seed_news_item( + summary_id: int, + kind: str, + headline: str, + importance: str, + *, + location_name: str | None = None, + lat: float | None = None, + lon: float | None = None, + location_confidence: str | None = None, + category: str | None = None, + url: str | None = None, +) -> None: async def run(): conn = await asyncpg.connect(**_conn_kwargs()) try: await conn.execute( - "INSERT INTO article_summaries (summary_text, batch_timestamp) " - "VALUES ($1, $2)", - text, datetime.fromisoformat(ts), + "INSERT INTO news_items " + "(summary_id, kind, headline, importance, location_name, " + " lat, lon, location_confidence, category, url) " + "VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)", + summary_id, kind, headline, importance, location_name, + lat, lon, location_confidence, category, url, ) finally: await conn.close() @@ -131,7 +164,7 @@ def test_api_news_summaries_contract(clean_news): assert isinstance(body, list) assert len(body) == 1 s = body[0] - assert set(s.keys()) == {"id", "summary_text", "batch_timestamp"} + assert set(s.keys()) == {"id", "summary_text", "batch_timestamp", "model"} assert s["summary_text"] == "master summary markdown…" assert s["batch_timestamp"].startswith("2026-08-24T18:05") @@ -140,3 +173,65 @@ def test_api_news_summaries_contract(clean_news): def test_api_news_empty(clean_news): assert _get("/api/news").json() == [] assert _get("/api/news/summaries").json() == [] + assert _get("/api/news/ticker").json() == [] + assert _get("/api/news/map").json() == [] + + +TICKER_KEYS = {"id", "headline", "importance", "location_name", "url", "created_at"} +MAP_KEYS = { + "id", "headline", "importance", "location_name", "lat", "lon", + "location_confidence", "category", "url", "created_at", +} + + +def _seed_flagged_items() -> None: + sid = _seed_summary("batch brief", "2026-08-27T18:05:00+00:00", "Hermes-4.3-36B") + _seed_news_item( + sid, "ticker", "Critical ticker", "critical", + location_name="Kyiv", url="https://example.com/ticker", + ) + _seed_news_item( + sid, "ticker", "Low ticker", "low", + location_name="Somewhere", url="https://example.com/low", + ) + _seed_news_item( + sid, "map", "Critical map", "critical", + location_name="Taipei", lat=25.03, lon=121.56, + location_confidence="high", category="conflict", + url="https://example.com/map", + ) + + +@requires_db +def test_api_news_ticker_returns_only_flagged(clean_news): + _seed_flagged_items() + resp = _get("/api/news/ticker") + assert resp.status_code == 200 + body = resp.json() + assert isinstance(body, list) + assert len(body) == 1 + item = body[0] + assert set(item.keys()) == TICKER_KEYS + assert item["headline"] == "Critical ticker" + assert item["importance"] == "critical" + assert item["location_name"] == "Kyiv" + assert item["url"] == "https://example.com/ticker" + + +@requires_db +def test_api_news_map_returns_only_flagged_with_coords(clean_news): + _seed_flagged_items() + resp = _get("/api/news/map") + assert resp.status_code == 200 + body = resp.json() + assert isinstance(body, list) + assert len(body) == 1 + item = body[0] + assert set(item.keys()) == MAP_KEYS + assert item["headline"] == "Critical map" + assert item["importance"] == "critical" + assert item["lat"] == 25.03 + assert item["lon"] == 121.56 + assert item["location_confidence"] == "high" + assert item["category"] == "conflict" + assert _get("/api/news/map?bbox=1,2,3").status_code == 422 From f50268ef819b06426b11ba53b26967df5da7e5d7 Mon Sep 17 00:00:00 2001 From: Sirius DevOps Date: Thu, 27 Aug 2026 22:55:51 -0400 Subject: [PATCH 05/79] feat: register NOUS_API_KEY in dashboard keystore --- app/keystore.py | 8 ++++---- app/static/index.html | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/app/keystore.py b/app/keystore.py index e2e5355..44c76d6 100644 --- a/app/keystore.py +++ b/app/keystore.py @@ -57,10 +57,10 @@ KEY_REGISTRY: dict[str, dict] = { "pattern": r"^[0-9a-fA-F]{32}$", "example": "32-char hex string (e.g. 5f3c…9a02)", }, - "GEMINI_API_KEY": { - "description": "Google Gemini API key — LLM event analysis / summarization.", - "pattern": r"^AIza[0-9A-Za-z_-]{35}$", - "example": "AIza… (Google API key, 39 chars)", + "NOUS_API_KEY": { + "description": "Nous Portal API key — hourly news summarizer (inference-api.nousresearch.com).", + "pattern": r"^.{16,}$", + "example": "key from https://portal.nousresearch.com (API keys page)", }, "TELEGRAM_TOKEN": { "description": "Telegram bot token — push alert notifications to a channel.", diff --git a/app/static/index.html b/app/static/index.html index d07f1ec..db5725a 100644 --- a/app/static/index.html +++ b/app/static/index.html @@ -955,7 +955,7 @@

⚿ API Keys

-

Keys used by ingest services (FIRMS, Gemini, Telegram, …). Stored in Postgres, never shown again — only status + last 4 chars.

+

Keys used by ingest services (FIRMS, Nous Portal, Telegram, AIS, …). Stored in Postgres, never shown again — only status + last 4 chars.

@@ -1486,7 +1486,7 @@ function sentimentBadge(label) { /* ═══════════════ API KEYS ═══════════════ */ const KEY_PATTERNS = { 'FIRMS_MAP_KEY': /^[0-9a-fA-F]{32}$/, - 'GEMINI_API_KEY': /^AIza[0-9A-Za-z_-]{35}$/, + 'NOUS_API_KEY': /^.{16,}$/, 'TELEGRAM_TOKEN': /^\d{8,10}:[0-9A-Za-z_-]{35}$/, }; async function loadKeys() { From 1616413e6592945afb7fafa8f3ef4f348cfb63ca Mon Sep 17 00:00:00 2001 From: Sirius DevOps Date: Thu, 27 Aug 2026 23:07:01 -0400 Subject: [PATCH 06/79] feat: persist summarizer model in app_settings --- app/main.py | 23 ++++ app/schemas.py | 38 ++++++- app/settings_store.py | 219 +++++++++++++++++++++++++++++++++++++ tests/test_api_settings.py | 172 +++++++++++++++++++++++++++++ 4 files changed, 451 insertions(+), 1 deletion(-) create mode 100644 app/settings_store.py create mode 100644 tests/test_api_settings.py diff --git a/app/main.py b/app/main.py index 6afd550..f08c0a7 100644 --- a/app/main.py +++ b/app/main.py @@ -40,6 +40,7 @@ from schemas import ( NewsSummaryOut, NewsTickerItemOut, FeedSourceCreate, FeedSourceOut, KeyOut, KeyValueIn, + NewsModelsOut, SettingsIn, SettingsOut, SearchResult, SentimentSummary, SourceType, SearchQuery, TimelinePoint, VesselBboxUpdate, GeofenceCreate, GeofenceUpdate, @@ -48,6 +49,7 @@ from ingestor import ingest_event, fetch_and_process from sources import ingest_rss_feed, ingest_gdelt, ingest_earthquakes, ingest_social_signals from fire_sources import ingest_fires from keystore import KeyFormatError, delete_key, list_keys, set_key +from settings_store import SettingsError, get_app_settings, list_models, set_summary_model from live_layers import ( fetch_aircraft, fetch_fire_incidents, fetch_fire_perimeters, fetch_radar_meta, fetch_storms, fetch_trains, fetch_vessels, @@ -634,6 +636,21 @@ async def remove_api_key(name: str): return {"ok": True} +@app.get("/api/settings", response_model=SettingsOut) +async def get_settings(): + """Summarizer model + read-only Nous base URL.""" + return await get_app_settings() + + +@app.put("/api/settings", response_model=SettingsOut) +async def put_settings(payload: SettingsIn): + """Persist SUMMARY_MODEL. ``nous_base_url`` is ignored even if sent.""" + try: + return await set_summary_model(payload.summary_model) + except SettingsError as exc: + raise HTTPException(status_code=422, detail=str(exc)) + + # ── Ingestion Triggers ─────────────────────────────────────────────────── @app.post("/api/ingest/rss") @@ -1230,6 +1247,12 @@ async def list_news_map( ] +@app.get("/api/news/models", response_model=NewsModelsOut) +async def list_news_models(): + """Nous model catalog for the summarizer selector. Never 502s.""" + return await list_models() + + # ── Frontend ────────────────────────────────────────────────────────────── @app.get("/", response_class=HTMLResponse) diff --git a/app/schemas.py b/app/schemas.py index 35bda45..b61e296 100644 --- a/app/schemas.py +++ b/app/schemas.py @@ -7,7 +7,7 @@ from enum import Enum from typing import Optional from uuid import UUID -from pydantic import BaseModel, Field +from pydantic import BaseModel, Field, field_validator # ─── Enums ─────────────────────────────────────────────────────────────── @@ -302,6 +302,42 @@ class NewsMapItemOut(BaseModel): created_at: datetime +class NewsModelId(BaseModel): + """One model id as exposed by GET /api/news/models.""" + + id: str + + +class NewsModelsOut(BaseModel): + """Catalog for the summarizer model selector.""" + + source: str + models: list[NewsModelId] + + +class SettingsIn(BaseModel): + """Body for PUT /api/settings. ``nous_base_url`` is not writable.""" + + summary_model: str = Field(..., min_length=1, max_length=128) + + @field_validator("summary_model") + @classmethod + def summary_model_not_blank(cls, v: str) -> str: + stripped = v.strip() + if not stripped: + raise ValueError("summary_model must be 1–128 chars, not whitespace-only") + if len(stripped) > 128: + raise ValueError("summary_model must be 1–128 chars, not whitespace-only") + return stripped + + +class SettingsOut(BaseModel): + """Current summarizer settings. ``nous_base_url`` is read-only.""" + + summary_model: str + nous_base_url: str + + # ─── Aggregations ──────────────────────────────────────────────────────── class SentimentSummary(BaseModel): diff --git a/app/settings_store.py b/app/settings_store.py new file mode 100644 index 0000000..314db42 --- /dev/null +++ b/app/settings_store.py @@ -0,0 +1,219 @@ +"""OSINT Dashboard — non-secret app settings (keyv-style Postgres table). + +Model choice lives here so the summarizer container can read it from Postgres. +Only whitelisted names are stored — this is not a generic dump. + +Storage: the table is created lazily with ``CREATE TABLE IF NOT EXISTS`` on +first use in each process (same bootstrap pattern as ``api_keys``). +""" + +from __future__ import annotations + +import asyncio +import os +import time +from datetime import datetime, timezone + +import httpx +from sqlalchemy import Column, DateTime, String, Table, Text, func, select, text + +import keystore +from database import async_session, engine, metadata + +DEFAULT_NOUS_BASE_URL = "https://inference-api.nousresearch.com/v1" +DEFAULT_SUMMARY_MODEL = "Hermes-4.3-36B" +SETTING_SUMMARY_MODEL = "SUMMARY_MODEL" +ALLOWED_SETTINGS = frozenset({SETTING_SUMMARY_MODEL}) +MODELS_CACHE_TTL_S = 600.0 +MODELS_TIMEOUT_S = 8.0 +DEFAULT_MODELS_USER_AGENT = "osint-dashboard-news-summarizer" + +FALLBACK_MODELS = [ + "Hermes-4.3-36B", + "Hermes-4-70B", + "google/gemini-2.5-flash", + "anthropic/claude-haiku-4.5", + "openai/gpt-4.1-mini", + "x-ai/grok-4", +] + +app_settings = Table( + "app_settings", + metadata, + Column("name", String(128), primary_key=True), + Column("value", Text, nullable=False), + Column("updated_at", DateTime(timezone=True), server_default=func.now(), nullable=False), +) + +_CREATE_TABLE_SQL = text( + """ + CREATE TABLE IF NOT EXISTS app_settings ( + name VARCHAR(128) PRIMARY KEY, + value TEXT NOT NULL, + updated_at TIMESTAMPTZ NOT NULL DEFAULT now() + ) + """ +) + +_ensure_lock = asyncio.Lock() +_ensured = False +_models_cache: tuple[float, dict] | None = None + + +class SettingsError(ValueError): + """Raised when a setting name or value fails validation.""" + + +async def ensure_app_settings_table() -> None: + """Create the app_settings table if it doesn't exist (idempotent, per process).""" + global _ensured + if _ensured: + return + async with _ensure_lock: + if _ensured: + return + async with engine.begin() as conn: + await conn.execute(_CREATE_TABLE_SQL) + _ensured = True + + +def nous_base_url() -> str: + """Read-only Nous inference base URL (env, never writable from the UI).""" + raw = (os.getenv("NOUS_BASE_URL") or "").strip().rstrip("/") + return raw or DEFAULT_NOUS_BASE_URL + + +def _validate_summary_model(value: str) -> str: + stripped = (value or "").strip() + if not stripped or len(stripped) > 128: + raise SettingsError("summary_model must be 1–128 chars, not whitespace-only") + return stripped + + +async def get_summary_model() -> str: + """Stored SUMMARY_MODEL, else env, else Hermes-4.3-36B.""" + await ensure_app_settings_table() + async with async_session() as session: + row = ( + await session.execute( + select(app_settings).where(app_settings.c.name == SETTING_SUMMARY_MODEL) + ) + ).mappings().one_or_none() + if row and row["value"]: + return row["value"] + return os.getenv("SUMMARY_MODEL", DEFAULT_SUMMARY_MODEL) + + +async def set_summary_model(value: str) -> dict: + """Upsert SUMMARY_MODEL and return the public settings payload.""" + value = _validate_summary_model(value) + now = datetime.now(timezone.utc) + + await ensure_app_settings_table() + async with async_session() as session: + existing = ( + await session.execute( + select(app_settings).where(app_settings.c.name == SETTING_SUMMARY_MODEL) + ) + ).mappings().one_or_none() + if existing: + await session.execute( + app_settings.update() + .where(app_settings.c.name == SETTING_SUMMARY_MODEL) + .values(value=value, updated_at=now) + ) + else: + await session.execute( + app_settings.insert().values( + name=SETTING_SUMMARY_MODEL, value=value, updated_at=now + ) + ) + await session.commit() + return await get_app_settings() + + +async def get_app_settings() -> dict: + return { + "summary_model": await get_summary_model(), + "nous_base_url": nous_base_url(), + } + + +def _fallback_payload() -> dict: + return { + "source": "fallback", + "models": [{"id": mid} for mid in FALLBACK_MODELS], + } + + +async def _nous_api_key() -> str | None: + """Keystore first, then env. Any lookup failure is treated as missing.""" + try: + stored = await keystore.get_api_key("NOUS_API_KEY") + except Exception: + stored = None + if stored and str(stored).strip(): + return str(stored).strip() + env = (os.getenv("NOUS_API_KEY") or "").strip() + return env or None + + +def _models_user_agent() -> str: + return os.getenv("OSINT_USER_AGENT") or DEFAULT_MODELS_USER_AGENT + + +def _parse_models_payload(body: object) -> list[dict[str, str]]: + if isinstance(body, dict): + raw = body.get("data", body.get("models", [])) + elif isinstance(body, list): + raw = body + else: + raw = [] + out: list[dict[str, str]] = [] + for item in raw or []: + if isinstance(item, str) and item.strip(): + out.append({"id": item.strip()}) + elif isinstance(item, dict): + mid = item.get("id") or item.get("name") + if mid: + out.append({"id": str(mid)}) + return out + + +async def _http_get(url: str, *, headers: dict[str, str], timeout: float) -> httpx.Response: + async with httpx.AsyncClient(timeout=timeout, headers=headers) as client: + return await client.get(url) + + +async def list_models() -> dict: + """Live ``GET {base}/models`` when a key is present; otherwise curated fallback. + + Never raises to the caller for missing key or upstream failure. + """ + global _models_cache + key = await _nous_api_key() + if not key: + return _fallback_payload() + + now = time.monotonic() + hit = _models_cache + if hit and now - hit[0] < MODELS_CACHE_TTL_S: + return hit[1] + + url = f"{nous_base_url()}/models" + headers = { + "Authorization": f"Bearer {key}", + "User-Agent": _models_user_agent(), + "Accept": "application/json", + } + try: + resp = await _http_get(url, headers=headers, timeout=MODELS_TIMEOUT_S) + resp.raise_for_status() + models = _parse_models_payload(resp.json()) + if not models: + return _fallback_payload() + payload = {"source": "live", "models": models} + _models_cache = (now, payload) + return payload + except Exception: + return _fallback_payload() diff --git a/tests/test_api_settings.py b/tests/test_api_settings.py new file mode 100644 index 0000000..6dad2f5 --- /dev/null +++ b/tests/test_api_settings.py @@ -0,0 +1,172 @@ +"""API tests for GET/PUT /api/settings and GET /api/news/models.""" + +from __future__ import annotations + +import asyncio +import os + +import asyncpg +import httpx +import pytest + +from conftest import requires_db + +from main import app + +BASE = "http://test" + + +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 _truncate_settings() -> None: + async def run(): + conn = await asyncpg.connect(**_conn_kwargs()) + try: + await conn.execute("DROP TABLE IF EXISTS app_settings") + finally: + await conn.close() + + asyncio.run(run()) + + +@pytest.fixture() +def clean_settings(): + import settings_store + settings_store._ensured = False + _truncate_settings() + yield + settings_store._ensured = False + _truncate_settings() + + +def _request(method: str, path: str, json: dict | None = None) -> httpx.Response: + async def _run() -> httpx.Response: + transport = httpx.ASGITransport(app=app) + async with httpx.AsyncClient(transport=transport, base_url=BASE) as client: + return await client.request(method, path, json=json) + + return asyncio.run(_run()) + + +def _get(path: str) -> httpx.Response: + return _request("GET", path) + + +def _put(path: str, json: dict) -> httpx.Response: + return _request("PUT", path, json=json) + + +def test_get_news_models_without_key_returns_fallback(monkeypatch): + monkeypatch.delenv("NOUS_API_KEY", raising=False) + monkeypatch.setattr("keystore.get_api_key", _missing_key) + + resp = _get("/api/news/models") + assert resp.status_code == 200 + body = resp.json() + assert body["source"] == "fallback" + ids = [m["id"] for m in body["models"]] + assert "Hermes-4.3-36B" in ids + from settings_store import FALLBACK_MODELS + assert ids == FALLBACK_MODELS + + +async def _missing_key(name: str): + return None + + +async def _present_key(name: str): + return "test-nous-api-key-1234" + + +def test_get_news_models_live_from_upstream(monkeypatch): + monkeypatch.setattr("keystore.get_api_key", _present_key) + monkeypatch.setenv("NOUS_BASE_URL", "https://inference-api.nousresearch.com/v1") + monkeypatch.delenv("OSINT_USER_AGENT", raising=False) + + captured: dict = {} + + class FakeResponse: + status_code = 200 + + def raise_for_status(self): + return None + + def json(self): + return {"data": [{"id": "live-model-a"}, {"id": "Hermes-4.3-36B"}]} + + async def fake_http_get(url, *, headers, timeout): + captured["url"] = url + captured["headers"] = headers + captured["timeout"] = timeout + return FakeResponse() + + import settings_store + monkeypatch.setattr(settings_store, "_http_get", fake_http_get) + settings_store._models_cache = None + + resp = _get("/api/news/models") + assert resp.status_code == 200 + body = resp.json() + assert body["source"] == "live" + ids = [m["id"] for m in body["models"]] + assert ids == ["live-model-a", "Hermes-4.3-36B"] + assert captured["url"] == "https://inference-api.nousresearch.com/v1/models" + assert captured["headers"]["User-Agent"] == "osint-dashboard-news-summarizer" + assert captured["headers"]["Authorization"] == "Bearer test-nous-api-key-1234" + timeout = captured["timeout"] + assert timeout == 8 or getattr(timeout, "read", timeout) == 8 or float(timeout) == 8.0 + + +def test_get_news_models_upstream_failure_returns_fallback(monkeypatch): + monkeypatch.setattr("keystore.get_api_key", _present_key) + + async def boom_http_get(url, *, headers, timeout): + raise httpx.ConnectError("upstream down") + + import settings_store + monkeypatch.setattr(settings_store, "_http_get", boom_http_get) + settings_store._models_cache = None + + resp = _get("/api/news/models") + assert resp.status_code == 200 + body = resp.json() + assert body["source"] == "fallback" + ids = [m["id"] for m in body["models"]] + assert "Hermes-4.3-36B" in ids + + +def test_put_settings_empty_returns_422(): + resp = _put("/api/settings", {"summary_model": ""}) + assert resp.status_code == 422 + + +def test_put_settings_whitespace_only_returns_422(): + resp = _put("/api/settings", {"summary_model": " "}) + assert resp.status_code == 422 + + +@requires_db +def test_put_settings_round_trip(clean_settings, monkeypatch): + monkeypatch.delenv("SUMMARY_MODEL", raising=False) + monkeypatch.delenv("NOUS_BASE_URL", raising=False) + + put_resp = _put("/api/settings", {"summary_model": "google/gemini-2.5-flash"}) + assert put_resp.status_code == 200 + put_body = put_resp.json() + assert put_body["summary_model"] == "google/gemini-2.5-flash" + assert put_body["nous_base_url"] == "https://inference-api.nousresearch.com/v1" + + get_resp = _get("/api/settings") + assert get_resp.status_code == 200 + get_body = get_resp.json() + assert get_body["summary_model"] == "google/gemini-2.5-flash" + assert get_body["nous_base_url"] == "https://inference-api.nousresearch.com/v1" + assert set(get_body.keys()) == {"summary_model", "nous_base_url"} From 8f3699f1333196b885085d00b37f0c91b99008da Mon Sep 17 00:00:00 2001 From: Sirius DevOps Date: Thu, 27 Aug 2026 23:17:45 -0400 Subject: [PATCH 07/79] feat: summarize hourly news via Nous portal into brief/ticker/map --- news/summerizer/run_news_summarizer.py | 7 +- news/summerizer/summarizer.py | 288 ++++++++++++++++++------- 2 files changed, 218 insertions(+), 77 deletions(-) diff --git a/news/summerizer/run_news_summarizer.py b/news/summerizer/run_news_summarizer.py index 27ba581..91740c6 100644 --- a/news/summerizer/run_news_summarizer.py +++ b/news/summerizer/run_news_summarizer.py @@ -10,7 +10,7 @@ The loop is serial, so a slow LLM pass never overlaps the next run. Env (all optional, 12-factor): NEWS_SUMMARIZE_MINUTE minute of the hour to fire (default 5) NEWS_SUMMARIZE_RUN_ON_START "1" to summarize once immediately on boot (default 1) - GEMINI_API_KEY required to do real work; unset = idle + NOUS_API_KEY optional in env; Keys UI / api_keys also works """ from __future__ import annotations @@ -46,10 +46,9 @@ def run_summarize() -> None: def main() -> None: - if not os.getenv("GEMINI_API_KEY", "").strip(): + if not os.getenv("NOUS_API_KEY", "").strip(): logger.warning( - "GEMINI_API_KEY not set — summarizer will idle (set it in .env and " - "recreate the service to enable)" + "NOUS_API_KEY unset in env — will read api_keys on each run; idle if both empty" ) logger.info( "news summarizer loop starting (minute=%s, run_on_start=%s)", diff --git a/news/summerizer/summarizer.py b/news/summerizer/summarizer.py index 993f71e..ea82a37 100644 --- a/news/summerizer/summarizer.py +++ b/news/summerizer/summarizer.py @@ -1,19 +1,25 @@ #!/usr/bin/env python3 -"""News summarizer — LLM (Gemini) map-reduce summarization of scraped articles. +"""News summarizer — Nous map-reduce of scraped articles into brief/ticker/map. Reads articles scraped within the last hour from the shared `articles` table, -summarizes them with Gemini (map phase per batch, reduce phase into one master -summary), and stores the result in `article_summaries` — both tables live in -the EXISTING osint-db (created by alembic migration 003_news, idempotent). +maps them with Nous (per-article English fact blocks), reduces to one JSON +object (summary_en + ticker + map_items), and stores the brief in +`article_summaries` plus flagged rows in `news_items`. Tables live in the +EXISTING osint-db (alembic 003_news + 005_news_items, idempotent). + +Everything is env-driven (12-factor). Secrets/config are resolved at the start +of each summarize_news() — env wins, else api_keys / app_settings: -Everything is env-driven (12-factor): DB_HOST / DB_NAME / DB_USER / DB_PASSWORD / DB_PORT PostgreSQL (osint-db) - GEMINI_API_KEY Google AI Studio key (required to actually run) - SUMMARY_MODEL Gemini model id (default gemini-2.0-flash) + NOUS_API_KEY Nous Portal key (else api_keys.name='NOUS_API_KEY') + NOUS_BASE_URL default https://inference-api.nousresearch.com/v1 + SUMMARY_MODEL default Hermes-4.3-36B (else app_settings) BATCH_SIZE articles per map-phase batch (default 50) SUMMARY_WINDOW_HOURS look-back window in hours (default 1) + OSINT_USER_AGENT default osint-dashboard-news-summarizer MAP_PROMPT override map-phase prompt (uses {batch_text}) SUMMARY_PROMPT override reduce-phase prompt (uses {final_input}) + NEWS_SUMMARIZE_FORCE "1" to ignore the current-UTC-hour idempotency skip INCLUDE_FUTURES "1" to prepend live futures prices (default 0) The futures/markets coupling from the original pipeline is gated behind @@ -30,6 +36,9 @@ from datetime import datetime import psycopg2 +from intel import parse_reduce_json, select_map, select_ticker +from nous_client import chat + logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s") logger = logging.getLogger("news.summarizer") @@ -42,8 +51,8 @@ DB_CONFIG = { "port": int(os.getenv("DB_PORT", "5432")), } -GEMINI_API_KEY = os.getenv("GEMINI_API_KEY", "").strip() -MODEL_NAME = os.getenv("SUMMARY_MODEL", "gemini-2.0-flash").strip() +DEFAULT_NOUS_BASE_URL = "https://inference-api.nousresearch.com/v1" +DEFAULT_SUMMARY_MODEL = "Hermes-4.3-36B" BATCH_SIZE = int(os.getenv("BATCH_SIZE", "50")) SUMMARY_WINDOW_HOURS = int(os.getenv("SUMMARY_WINDOW_HOURS", "1")) INCLUDE_FUTURES = os.getenv("INCLUDE_FUTURES", "0").lower() in ("1", "true", "yes") @@ -62,12 +71,15 @@ FUTURES_TICKERS = { MAP_PROMPT_DEFAULT = """\ You are a precise, factual OSINT news processor. Your ONLY source of information is the articles provided below. Do NOT add external knowledge, assumptions, training data, or invented facts. +Write every field in English. Translate if the article is not English. + For EACH article in the batch: 1. Extract 2-4 key factual bullet points (who, what, when, where, numbers, quotes — stay very close to the text). -2. Location: name the country / city / region mentioned if determinable from the text, else "Unknown". +2. Location: country/city/region or Unknown. If you can estimate coordinates, emit them as numbers; otherwise omit. 3. Entities: list the key people, organizations, or governments mentioned (comma-separated, only names present in the text), else "None". 4. Category: pick one — politics, military/conflict, economy, technology, environment/disaster, health, crime, society, sport, other. 5. OSINT signal: if the article describes an event with geopolitical, security, military, economic, or disaster significance, say so in one short sentence. Otherwise write: "No notable OSINT signal." +6. Importance: critical (breaking geopolitical/military/disaster with immediate impact), high, medium, low, none. If several articles cover the same story, add one short batch-level note at the end: "Batch theme: [one sentence]". @@ -80,6 +92,9 @@ Article 1: - Entities: ... - Category: ... - OSINT signal: ... +- Importance: ... +- Lat: ... +- Lon: ... Article 2: ... @@ -89,9 +104,21 @@ Articles in this batch: """ SUMMARY_PROMPT_DEFAULT = """\ -CRITICAL INSTRUCTION - REPEAT 3 TIMES: YOU MUST USE ONLY THE DATA PROVIDED BELOW. DO NOT INVENT, RECALL, OR ADD ANY EVENTS, NAMES, DATES, IMPLICATIONS, PROJECTS, OR DETAILS NOT EXPLICITLY PRESENT IN THE DATA. IF THE DATA HAS NO MAJOR GEOPOLITICAL/TECH/MILITARY/ECONOMIC/IMPACTFUL EVENTS OR UNUSUAL STORIES, OUTPUT ONLY: "No qualifying impactful or unusual events in the recent hourly news data." AND STOP. NO EXTERNAL KNOWLEDGE FROM TRAINING. +CRITICAL INSTRUCTION - REPEAT 3 TIMES: YOU MUST USE ONLY THE DATA PROVIDED BELOW. DO NOT INVENT, RECALL, OR ADD ANY EVENTS, NAMES, DATES, IMPLICATIONS, PROJECTS, OR DETAILS NOT EXPLICITLY PRESENT IN THE DATA. IF THE DATA HAS NO MAJOR GEOPOLITICAL/TECH/MILITARY/ECONOMIC/IMPACTFUL EVENTS OR UNUSUAL STORIES, set summary_en to exactly: "No qualifying impactful or unusual events in the recent hourly news data." and use empty ticker and map_items arrays. AND STOP. NO EXTERNAL KNOWLEDGE FROM TRAINING. -Write a concise executive summary of the most impactful items as a short markdown list, one line per story, using only the data. +All text in English. + +Demand a single JSON object (no markdown fences) with this exact shape: + +{ + "summary_en": "English markdown brief or the no-qualifying-events sentence", + "ticker": [{"headline": "", "importance": "critical", "url": "", "location_name": ""}], + "map_items": [{"headline": "", "importance": "critical", "location_name": "", "lat": 0, "lon": 0, "location_confidence": "city", "category": "military/conflict", "url": ""}] +} + +ticker: only critical and high, max 12, ≤140 chars, no markdown. +map_items: only critical and high where a real-world location is explicit in the data. Estimate lat/lon. If location is Unknown or not in the data, omit the item. Never invent a place. Max 20. +summary_en: English markdown brief for an operator HUD. DATA: {final_input} @@ -100,56 +127,52 @@ DATA: # ── LLM helpers ──────────────────────────────────────────────────────────── -_client = None +def _kv(conn, table, name) -> str: + cur = conn.cursor() + cur.execute(f"SELECT value FROM {table} WHERE name = %s", (name,)) + row = cur.fetchone() + return (row[0] or "").strip() if row else "" -def _get_client(): - """Lazily build the Gemini client (avoids import/init when key unset).""" - global _client - if _client is None: - from google import genai - - _client = genai.Client(api_key=GEMINI_API_KEY) - return _client - - -def _extract_text(resp) -> str: - """Defensively pull text out of the google-genai GenerateContentResponse. - - The modern SDK returns the response directly (``resp.text``); some older - wrappers exposed it as ``resp.response``. Handle both plus a candidates - fallback so a provider/SDK change degrades to "" instead of crashing. - """ - if not resp: - return "" - if hasattr(resp, "text") and resp.text: - return resp.text - inner = getattr(resp, "response", None) - if inner is not None and hasattr(inner, "text") and inner.text: - return inner.text +def resolve_api_key() -> str: + env = os.getenv("NOUS_API_KEY", "").strip() + if env: + return env try: - parts = [] - for cand in getattr(resp, "candidates", None) or []: - content = getattr(cand, "content", None) - for part in getattr(content, "parts", None) or []: - if getattr(part, "text", None): - parts.append(part.text) - return "\n".join(parts) + conn = psycopg2.connect(**DB_CONFIG) + try: + return _kv(conn, "api_keys", "NOUS_API_KEY") + finally: + conn.close() except Exception: # noqa: BLE001 - return str(resp) - - -def call_llm(prompt: str) -> str: - """Send a prompt to Gemini and return the text ("" on any failure).""" - if not GEMINI_API_KEY: - logger.warning("GEMINI_API_KEY not set — skipping LLM call") return "" + + +def resolve_model() -> str: + env = os.getenv("SUMMARY_MODEL", "").strip() + if env: + return env try: - resp = _get_client().models.generate_content(model=MODEL_NAME, contents=prompt) - return _extract_text(resp) - except Exception as exc: # noqa: BLE001 - logger.error("Gemini API error: %s", exc) + conn = psycopg2.connect(**DB_CONFIG) + try: + value = _kv(conn, "app_settings", "SUMMARY_MODEL") + return value or DEFAULT_SUMMARY_MODEL + finally: + conn.close() + except Exception: # noqa: BLE001 + return DEFAULT_SUMMARY_MODEL + + +def resolve_base_url() -> str: + return os.getenv("NOUS_BASE_URL", DEFAULT_NOUS_BASE_URL).strip() or DEFAULT_NOUS_BASE_URL + + +def call_llm(prompt: str, *, api_key: str, model: str, base_url: str, json_mode: bool = False) -> str: + """Send a prompt to Nous chat completions and return the text (\"\" on failure).""" + if not api_key: + logger.warning("NOUS_API_KEY not set — skipping LLM call") return "" + return chat(prompt, api_key=api_key, model=model, base_url=base_url, json_mode=json_mode) # ── Futures (legacy, gated) ──────────────────────────────────────────────── @@ -206,10 +229,11 @@ def build_futures_context() -> str: def ensure_tables() -> None: """Idempotently create the news tables if missing. - Normally created by alembic 003_news when the app container starts, but - this summarizer may boot before the app has run migrations (compose only - guarantees `db` is up, not that alembic has run). Mirrors the scraper - pipeline's own CREATE TABLE IF NOT EXISTS so either start order is safe. + Normally created by alembic 003_news + 005_news_items when the app + container starts, but this summarizer may boot before the app has run + migrations (compose only guarantees `db` is up, not that alembic has + run). Mirrors the scraper pipeline's own CREATE TABLE IF NOT EXISTS so + either start order is safe. """ ddl = """ CREATE TABLE IF NOT EXISTS articles ( @@ -225,6 +249,26 @@ def ensure_tables() -> None: summary_text TEXT NOT NULL, batch_timestamp TIMESTAMPTZ NOT NULL DEFAULT NOW() ); + ALTER TABLE article_summaries ADD COLUMN IF NOT EXISTS model TEXT; + CREATE TABLE IF NOT EXISTS news_items ( + id SERIAL PRIMARY KEY, + summary_id INTEGER REFERENCES article_summaries(id) ON DELETE CASCADE, + kind TEXT NOT NULL, + headline TEXT NOT NULL, + importance TEXT NOT NULL, + location_name TEXT, + lat DOUBLE PRECISION, + lon DOUBLE PRECISION, + location_confidence TEXT, + category TEXT, + url TEXT, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() + ); + CREATE INDEX IF NOT EXISTS ix_news_items_kind_created + ON news_items (kind, created_at DESC); + CREATE INDEX IF NOT EXISTS ix_news_items_map_bbox + ON news_items (lon, lat) + WHERE kind = 'map' AND lat IS NOT NULL AND lon IS NOT NULL; """ try: conn = psycopg2.connect(**DB_CONFIG) @@ -262,24 +306,90 @@ def get_recent_news() -> list[dict]: return [] -def save_summary_to_db(summary_text: str) -> None: - """Insert one master summary row (table created by alembic 003_news).""" - if not summary_text or len(summary_text.strip()) < 10: +def _already_summarized_this_hour() -> bool: + """True when article_summaries already has a row for the current UTC hour.""" + if os.getenv("NEWS_SUMMARIZE_FORCE", "") == "1": + return False + query = ( + "SELECT 1 FROM article_summaries " + "WHERE batch_timestamp >= date_trunc('hour', NOW() AT TIME ZONE 'utc')" + ) + try: + conn = psycopg2.connect(**DB_CONFIG) + cur = conn.cursor() + cur.execute(query) + row = cur.fetchone() + cur.close() + conn.close() + return row is not None + except Exception as exc: # noqa: BLE001 + logger.error("Error checking hourly idempotency: %s", exc) + return False + + +def save_batch(summary_en: str, model: str, ticker: list, map_items: list) -> None: + """Insert the master brief plus flagged ticker/map rows.""" + ticker_rows = select_ticker(ticker or []) + map_rows = select_map(map_items or []) + text = (summary_en or "").strip() + if len(text) < 10 and not ticker_rows and not map_rows: logger.info("Summary too short or empty. Skipping save.") return + insert_item = """ + INSERT INTO news_items ( + summary_id, kind, headline, importance, location_name, + lat, lon, location_confidence, category, url + ) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s) + """ try: conn = psycopg2.connect(**DB_CONFIG) cur = conn.cursor() cur.execute( - "INSERT INTO article_summaries (summary_text) VALUES (%s)", - (summary_text.strip(),), + "INSERT INTO article_summaries (summary_text, model) VALUES (%s, %s) RETURNING id", + (text, model), ) + summary_id = cur.fetchone()[0] + for row in ticker_rows: + cur.execute( + insert_item, + ( + summary_id, + "ticker", + row.get("headline"), + row.get("importance"), + row.get("location_name"), + None, + None, + None, + None, + row.get("url"), + ), + ) + for row in map_rows: + cur.execute( + insert_item, + ( + summary_id, + "map", + row.get("headline"), + row.get("importance"), + row.get("location_name"), + row.get("lat"), + row.get("lon"), + row.get("location_confidence"), + row.get("category"), + row.get("url"), + ), + ) conn.commit() - logger.info("Master summary saved to database successfully.") + logger.info( + "Master summary saved id=%s model=%s ticker=%d map=%d", + summary_id, model, len(ticker_rows), len(map_rows), + ) cur.close() conn.close() except Exception as exc: # noqa: BLE001 - logger.error("Error saving summary to DB: %s", exc) + logger.error("Error saving batch to DB: %s", exc) # ── Orchestration ────────────────────────────────────────────────────────── @@ -307,8 +417,22 @@ def build_master_prompt(final_input: str) -> str: def summarize_news() -> None: - """Map-reduce summarize recent articles and store the master summary.""" + """Map-reduce summarize recent articles and store brief + ticker + map.""" ensure_tables() + if _already_summarized_this_hour(): + logger.info( + "Skipping summarize: article_summaries already has a row this UTC hour " + "(set NEWS_SUMMARIZE_FORCE=1 to override)" + ) + return + + api_key = resolve_api_key() + model = resolve_model() + base_url = resolve_base_url() + if not api_key: + logger.warning("NOUS_API_KEY unset in env and api_keys — idle this run") + return + articles = get_recent_news() if not articles: logger.info("No new articles found in the last %sh.", SUMMARY_WINDOW_HOURS) @@ -316,14 +440,23 @@ def summarize_news() -> None: logger.info( "Processing %d articles with %s (batch_size=%d, futures=%s)...", - len(articles), MODEL_NAME, BATCH_SIZE, INCLUDE_FUTURES, + len(articles), model, BATCH_SIZE, INCLUDE_FUTURES, ) partial_summaries: list[str] = [] for i in range(0, len(articles), BATCH_SIZE): batch = articles[i : i + BATCH_SIZE] - logger.info("map batch %d/%d (%d articles)", i // BATCH_SIZE + 1, -(-len(articles) // BATCH_SIZE), len(batch)) - summary = call_llm(build_map_prompt(batch)) + logger.info( + "map batch %d/%d (%d articles)", + i // BATCH_SIZE + 1, -(-len(articles) // BATCH_SIZE), len(batch), + ) + summary = call_llm( + build_map_prompt(batch), + api_key=api_key, + model=model, + base_url=base_url, + json_mode=False, + ) if summary: partial_summaries.append(summary) @@ -333,9 +466,18 @@ def summarize_news() -> None: return logger.info("reduce phase over %d partial summaries", len(partial_summaries)) - master_summary = call_llm(build_master_prompt(final_input)) - if master_summary: - save_summary_to_db(master_summary) + master_raw = call_llm( + build_master_prompt(final_input), + api_key=api_key, + model=model, + base_url=base_url, + json_mode=True, + ) + if not master_raw: + logger.warning("Reduce phase returned empty — nothing to persist.") + return + parsed = parse_reduce_json(master_raw) + save_batch(parsed["summary_en"], model, parsed["ticker"], parsed["map_items"]) if __name__ == "__main__": From d93ad88956d9730c218ccdf0140706707efd763c Mon Sep 17 00:00:00 2001 From: Sirius DevOps Date: Thu, 27 Aug 2026 23:24:45 -0400 Subject: [PATCH 08/79] chore: point news-summarizer compose at Nous portal --- .env.example | 14 +++++++++----- docker-compose.yml | 8 +++++--- news/summerizer/requirements.txt | 6 +----- 3 files changed, 15 insertions(+), 13 deletions(-) diff --git a/.env.example b/.env.example index 7bf60b3..ad2d4ee 100644 --- a/.env.example +++ b/.env.example @@ -60,7 +60,7 @@ FIRMS_INTERVAL=900 INGEST_FIRES=1 # ── API keys (managed from the dashboard UI) ────────────────────────────── -# Keys such as GEMINI_API_KEY and TELEGRAM_TOKEN are stored in the Postgres +# Keys such as NOUS_API_KEY and TELEGRAM_TOKEN are stored in the Postgres # `api_keys` table and managed from the dashboard's "Keys" tab # (GET/POST/DELETE /api/keys/{name}) — see app/keystore.py. The FIRMS ingestor # currently reads FIRMS_MAP_KEY from .env (above); wiring the Keys-UI store as @@ -68,13 +68,15 @@ INGEST_FIRES=1 # ── News pipeline (scraper + summarizer, profile `ingest`) ──────────────── # Hourly: the scraper crawls 257 RSS sources at minute :00 and the summarizer -# runs the Gemini map-reduce at minute :05, both writing to the shared osint-db +# runs the Nous map-reduce at minute :05, both writing to the shared osint-db # (tables `articles` + `article_summaries`, created by alembic 003_news). # Consume via GET /api/news and GET /api/news/summaries. -# GEMINI_API_KEY is REQUIRED for summarization; unset = summarizer idles. -GEMINI_API_KEY= +# NOUS_API_KEY is also (preferably) set in the Keys UI; env is an override. +# Unset in both env and api_keys = summarizer logs and idles (never crashes). +NOUS_API_KEY= +NOUS_BASE_URL=https://inference-api.nousresearch.com/v1 # Optional LLM knobs -SUMMARY_MODEL=gemini-2.0-flash +SUMMARY_MODEL=Hermes-4.3-36B NEWS_BATCH_SIZE=50 SUMMARY_WINDOW_HOURS=1 # Futures/markets coupling from the upstream pipeline is OFF by default @@ -87,6 +89,8 @@ NEWS_SUMMARIZE_MINUTE=5 # scheduled minute. NEWS_SCRAPE_RUN_ON_START=1 NEWS_SUMMARIZE_RUN_ON_START=1 +# "1" ignores the current-UTC-hour idempotency skip (double-pins on recreate). +NEWS_SUMMARIZE_FORCE=0 NEWS_LOG_LEVEL=INFO # Reserved for the (out-of-scope) Telegram delivery bot. TELEGRAM_TOKEN= diff --git a/docker-compose.yml b/docker-compose.yml index b2a7cd6..a34365c 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -224,14 +224,16 @@ services: DB_HOST: db DB_PORT: ${DB_PORT:-5432} DB_NAME: ${DB_NAME:-osint_data} - # Required to do real work; unset → the loop logs and idles. - GEMINI_API_KEY: ${GEMINI_API_KEY:-} - SUMMARY_MODEL: ${SUMMARY_MODEL:-gemini-2.0-flash} + NOUS_API_KEY: ${NOUS_API_KEY:-} + NOUS_BASE_URL: ${NOUS_BASE_URL:-https://inference-api.nousresearch.com/v1} + SUMMARY_MODEL: ${SUMMARY_MODEL:-Hermes-4.3-36B} + OSINT_USER_AGENT: ${OSINT_USER_AGENT:-osint-dashboard-news-summarizer} BATCH_SIZE: ${NEWS_BATCH_SIZE:-50} SUMMARY_WINDOW_HOURS: ${SUMMARY_WINDOW_HOURS:-1} INCLUDE_FUTURES: ${INCLUDE_FUTURES:-0} NEWS_SUMMARIZE_MINUTE: ${NEWS_SUMMARIZE_MINUTE:-5} NEWS_SUMMARIZE_RUN_ON_START: ${NEWS_SUMMARIZE_RUN_ON_START:-1} + NEWS_SUMMARIZE_FORCE: ${NEWS_SUMMARIZE_FORCE:-0} command: ["python", "run_news_summarizer.py"] volumes: diff --git a/news/summerizer/requirements.txt b/news/summerizer/requirements.txt index 49aed17..30b9117 100644 --- a/news/summerizer/requirements.txt +++ b/news/summerizer/requirements.txt @@ -1,6 +1,2 @@ -# Database adapter for PostgreSQL (shared osint-db). psycopg2-binary==2.9.11 - -# Gemini LLM SDK (google-genai). yfinance is NOT a dependency: futures prices -# are gated behind INCLUDE_FUTURES=1 and lazy-imported (install it to enable). -google-genai +httpx==0.28.1 From 610666ef6a25de795d50a4b0620472e2db7ed8de Mon Sep 17 00:00:00 2001 From: Sirius DevOps Date: Thu, 27 Aug 2026 23:29:35 -0400 Subject: [PATCH 09/79] feat: settings model selector for news summarizer --- app/static/index.html | 79 +++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 76 insertions(+), 3 deletions(-) diff --git a/app/static/index.html b/app/static/index.html index db5725a..0e05168 100644 --- a/app/static/index.html +++ b/app/static/index.html @@ -979,6 +979,30 @@
+
+

News Summarizer

+

Takes effect on the next hourly run (:05). No container restart.

+
+ + Nous Portal (inference-api.nousresearch.com) +
+
+ + set in API Keys as NOUS_API_KEY (never shown here) +
+
+ + +
+
+ + — +
+
+ +
+
+

Map Defaults

Applied to the live map on load.

@@ -1025,7 +1049,7 @@
Active sources—
Open alerts—
Tracked entities—
-
News cycle15 min
+
News cyclehourly :05
Market feedSTANDBY
@@ -1051,7 +1075,7 @@
-
15-MIN CYCLE
+
HOURLY
@@ -1181,7 +1205,7 @@ function showView(name) { } if (name === 'news') loadNews(false); if (name === 'events') { loadSummary(); loadEvents(); } - if (name === 'settings') { loadSummary(); renderSysInfo(); } + if (name === 'settings') { loadSummary(); renderSysInfo(); loadSettings(); } window.scrollTo(0, 0); } @@ -1657,6 +1681,55 @@ function initSettings() { } } catch (e) {} } +async function loadSettings() { + const sel = document.getElementById('set-summary-model'); + const now = document.getElementById('set-summary-model-now'); + try { + const [setR, modR] = await Promise.all([ + fetch(`${API}/api/settings`), + fetch(`${API}/api/news/models`), + ]); + const settings = setR.ok ? await setR.json() : {}; + const catalog = modR.ok ? await modR.json() : {models: []}; + const saved = (settings.summary_model || '').trim(); + const ids = (catalog.models || []).map(m => m && m.id).filter(Boolean); + if (saved && ids.indexOf(saved) === -1) ids.unshift(saved); + if (sel) { + sel.innerHTML = ids.map(id => ``).join(''); + if (saved) sel.value = saved; + } + if (now) now.textContent = saved || '—'; + } catch (e) { + console.error('Settings load failed', e); + } +} +async function saveSummaryModel() { + const sel = document.getElementById('set-summary-model'); + const flash = document.getElementById('sum-saved'); + const now = document.getElementById('set-summary-model-now'); + const summary_model = ((sel && sel.value) || '').trim(); + if (!summary_model) { + if (flash) flash.textContent = 'Choose a model to save.'; + return; + } + try { + const r = await fetch(`${API}/api/settings`, { + method: 'PUT', + headers: {'Content-Type': 'application/json'}, + body: JSON.stringify({summary_model}), + }); + const d = await r.json().catch(() => ({})); + if (!r.ok) { + if (flash) flash.textContent = (typeof d.detail === 'string' ? d.detail : 'Save failed'); + return; + } + if (now) now.textContent = d.summary_model || summary_model; + if (sel && d.summary_model) sel.value = d.summary_model; + if (flash) flash.textContent = 'Model saved.'; + } catch (e) { + if (flash) flash.textContent = 'Network error.'; + } +} /* ═══════════════ MAP (NASA GIBS basemap + FIRMS + cameras + blips) ═══════ The satellite map core is production-proven — preserved verbatim. */ From 3b4dd4925301b4732d7c9ae636887a09f0e3f4fb Mon Sep 17 00:00:00 2001 From: Sirius DevOps Date: Thu, 27 Aug 2026 23:36:40 -0400 Subject: [PATCH 10/79] feat: news ticker shows flagged hourly items --- app/static/index.html | 68 ++++++++++++++++++++++++++++++------------- 1 file changed, 47 insertions(+), 21 deletions(-) diff --git a/app/static/index.html b/app/static/index.html index 0e05168..e3f987b 100644 --- a/app/static/index.html +++ b/app/static/index.html @@ -539,11 +539,14 @@ .tick-item .dom { font-family: 'Share Tech Mono', monospace; font-size: 0.64rem; color: var(--cyan); background: rgba(53,224,255,0.08); border: 1px solid rgba(53,224,255,0.22); border-radius: 3px; padding: 0.05rem 0.4rem; } .tick-item .tt { font-family: 'Share Tech Mono', monospace; font-size: 0.66rem; color: var(--muted); } .tick-item .sep { color: var(--line-hi); } + button.tick-item { cursor: pointer; background: transparent; border: 0; font: inherit; color: inherit; } .tick-item.brief { cursor: pointer; background: linear-gradient(90deg, rgba(255,46,151,0.12), transparent 70%); border-left: 2px solid var(--magenta); font-weight: 600; } - .tick-item.brief .b-tag { font-family: 'Share Tech Mono', monospace; font-size: 0.6rem; color: #1c0311; background: var(--magenta); border-radius: 2px; padding: 0.08rem 0.4rem; letter-spacing: 0.1em; } + .tick-item .b-tag { font-family: 'Share Tech Mono', monospace; font-size: 0.6rem; color: #1c0311; background: var(--magenta); border-radius: 2px; padding: 0.08rem 0.4rem; letter-spacing: 0.1em; } + .tick-item .b-tag.critical { background: var(--red); } + .tick-item .b-tag.high { background: var(--amber); } .tick-item.brief:hover { color: var(--magenta); } .tick-item.standby { color: var(--muted); opacity: 0.75; } .tick-item.standby .price { color: var(--muted); } @@ -827,7 +830,7 @@
Executive Summary WAITING
—
-
No executive summary yet — the Gemini summarizer is idle until GEMINI_API_KEY is set on the Pi.
+
No executive summary yet — the Nous summarizer is idle until NOUS_API_KEY is set on the Pi and a model is chosen in Settings.
@@ -1323,13 +1326,16 @@ async function loadNews(force) { if (upd) upd.textContent = 'updating…'; let articles = []; let summaries = []; + let tickerItems = []; try { - const [rArticles, rSumm] = await Promise.all([ + const [rArticles, rSumm, rTick] = await Promise.all([ fetch(`${API}/api/news?limit=100`), - fetch(`${API}/api/news/summaries?limit=1`) + fetch(`${API}/api/news/summaries?limit=1`), + fetch(`${API}/api/news/ticker?limit=20`), ]); if (rArticles.ok) articles = await rArticles.json(); if (rSumm.ok) summaries = await rSumm.json(); + if (rTick.ok) tickerItems = await rTick.json(); } catch (e) { const list = document.getElementById('news-list'); const body = document.getElementById('ns-body'); @@ -1341,7 +1347,7 @@ async function loadNews(force) { } renderNewsSummary(summaries); renderNewsList(articles); - renderNewsTicker(articles, summaries); + renderNewsTicker(articles, summaries, tickerItems); if (upd) upd.textContent = 'updated ' + new Date().toLocaleTimeString(); if (!newsInterval) { newsInterval = setInterval(() => loadNews(false), NEWS_REFRESH_MS); @@ -1353,7 +1359,7 @@ function renderNewsSummary(summaries) { const badgeEl = document.getElementById('ns-badge'); if (!bodyEl) return; if (!summaries || !summaries.length) { - bodyEl.innerHTML = '
No executive summary yet — the Gemini summarizer is idle until GEMINI_API_KEY is set on the Pi.
'; + bodyEl.innerHTML = '
No executive summary yet — the Nous summarizer is idle until NOUS_API_KEY is set on the Pi and a model is chosen in Settings.
'; timeEl.textContent = '—'; badgeEl.textContent = 'WAITING'; return; @@ -1381,25 +1387,45 @@ function renderNewsList(articles) { ''; }).join(''); } -function renderNewsTicker(articles, summaries) { +function renderNewsTicker(articles, summaries, tickerItems) { const track = document.getElementById('nt-track'); if (!track) return; let items = ''; - // LLM executive summary flash first (click → News view) - const summ = summaries && summaries.length ? summaries[0] : null; - if (summ && summ.summary_text) { - const brief = summ.summary_text.replace(/\s+/g, ' ').trim(); - items += ``; + const ticks = Array.isArray(tickerItems) ? tickerItems : []; + if (ticks.length) { + ticks.forEach(t => { + const imp = String(t.importance || '').toLowerCase(); + const tag = imp === 'critical' ? 'CRITICAL' : 'HIGH'; + const loc = (t.location_name || '').trim(); + const inner = + `${tag}` + + `${newsEsc((t.headline || '').trim())}` + + (loc ? `${newsEsc(loc)}` : '') + + `${newsTimeAgo(t.created_at)}▸`; + const url = (t.url || '').trim(); + if (url) { + items += `${inner}`; + } else { + items += ``; + } + }); + } else { + // Quiet hour: brief chip + article titles so the dock is never blank. + const summ = summaries && summaries.length ? summaries[0] : null; + const briefSrc = summ && (summ.summary_en || summ.summary_text); + if (briefSrc) { + const brief = String(briefSrc).replace(/\s+/g, ' ').trim(); + items += ``; + } + (articles || []).slice(0, 10).forEach(a => { + items += `` + + `${newsEsc(a.domain || '?')}` + + `${newsEsc((a.title || '').trim())}` + + `${newsTimeAgo(a.timestamp)}▸`; + }); } - // Top headlines - (articles || []).slice(0, 30).forEach(a => { - items += `` + - `${newsEsc(a.domain || '?')}` + - `${newsEsc((a.title || '').trim())}` + - `${newsTimeAgo(a.timestamp)}▸`; - }); if (!items) { items = `No headlines yet — scraper idle`; } From 496d13b8b001e3edc38b43acca6d39a4a31197b3 Mon Sep 17 00:00:00 2001 From: Sirius DevOps Date: Thu, 27 Aug 2026 23:43:36 -0400 Subject: [PATCH 11/79] feat: critical news pins on the osint map --- app/static/index.html | 69 ++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 68 insertions(+), 1 deletion(-) diff --git a/app/static/index.html b/app/static/index.html index e3f987b..db4fb01 100644 --- a/app/static/index.html +++ b/app/static/index.html @@ -264,6 +264,7 @@ .hud-chip .c.fires { background: #fb923c; box-shadow: 0 0 6px #fb923c; } .hud-chip .c.cams { background: #4ade80; box-shadow: 0 0 6px #4ade80; } .hud-chip .c.blips { background: var(--magenta); box-shadow: 0 0 6px var(--magenta); } + .hud-chip .c.news { background: var(--magenta); box-shadow: 0 0 6px var(--magenta); border-radius: 1px; transform: rotate(45deg); } .hud-chip.off { opacity: 0.4; } #dvr-bar { position: absolute; left: 50%; bottom: 12px; transform: translateX(-50%); @@ -319,6 +320,7 @@ .lp-dot.fires { background: #fb923c; box-shadow: 0 0 7px #fb923c; } .lp-dot.cams { background: #4ade80; box-shadow: 0 0 7px #4ade80; } .lp-dot.blips { background: var(--magenta); box-shadow: 0 0 7px var(--magenta); } + .lp-dot.news { background: var(--magenta); box-shadow: 0 0 7px var(--magenta); border-radius: 1px; transform: rotate(45deg); } .lp-dot.weather { background: var(--amber); box-shadow: 0 0 7px var(--amber); } .lp-dot.flights { background: #7dd3fc; box-shadow: 0 0 7px #7dd3fc; } .lp-dot.vessels { background: #2dd4bf; box-shadow: 0 0 7px #2dd4bf; } @@ -724,6 +726,13 @@
Geolocated events from the ingest pipeline. Color = source type.
+
+
+ + 0 +
+
LLM-estimated locations from the hourly brief. Pins only for critical/high.
+
@@ -804,6 +813,7 @@
FIRMS —
CAMS —
BLIPS —
+
NEWS —
@@ -1204,6 +1214,7 @@ function showView(name) { if (firesOn) loadFires(); if (camsOn) loadCams(); if (blipsOn) loadBlips(); + if (newsOn) loadNewsPins(); } } if (name === 'news') loadNews(false); @@ -1762,6 +1773,7 @@ async function saveSummaryModel() { let map = null, mapLayer = null, mapInitStarted = false; let firesHeat = null, camsGroup = null, firesOn = false, camsOn = false; let blipsGroup = null, blipsOn = false, blipsSince = '24h'; +let newsGroup = null, newsOn = false, newsReq = 0; let firesOpacity = 0.65, firesColor = 'brightness', firesSince = '24h'; let camsOpacity = 1.0, baseOpacity = 1.0; let camReq = 0, fireReq = 0, blipReq = 0; // stale-response guards (rapid zoom races) @@ -1954,6 +1966,7 @@ async function initMap() { if (firesOn) loadFires(); if (camsOn) loadCams(); if (blipsOn) loadBlips(); + if (newsOn) loadNewsPins(); refreshLiveOverlays(); sendLiveViewport(); }, 500); @@ -1965,6 +1978,7 @@ async function initMap() { firesOn = document.getElementById('lp-fires-on').checked; camsOn = document.getElementById('lp-cams-on').checked; blipsOn = document.getElementById('lp-blips-on').checked; + newsOn = document.getElementById('lp-news-on').checked; firesSince = document.getElementById('lp-fires-since').value; blipsSince = document.getElementById('lp-blips-since').value; radarOn = document.getElementById('lp-radar-on').checked; @@ -1979,6 +1993,7 @@ async function initMap() { if (firesOn) loadFires(); if (camsOn) loadCams(); if (blipsOn) loadBlips(); + if (newsOn) loadNewsPins(); refreshLiveOverlays(); connectLiveWs(); } catch(e) { @@ -2001,8 +2016,9 @@ function syncHud() { set('fires', firesOn ? (hudFiresCount) : '—', firesOn); set('cams', camsOn ? (hudCamsCount) : '—', camsOn); set('blips', blipsOn ? (hudBlipsCount) : '—', blipsOn); + set('news', newsOn ? (hudNewsCount) : '—', newsOn); } -let hudFiresCount = null, hudCamsCount = null, hudBlipsCount = null; +let hudFiresCount = null, hudCamsCount = null, hudBlipsCount = null, hudNewsCount = null; function setMapAttribution(text) { if (!map) return; @@ -2417,6 +2433,57 @@ async function loadBlips() { } } +/* ── CRITICAL NEWS (LLM-estimated locations, critical/high only) ── */ +async function toggleNewsPins() { + newsOn = document.getElementById('lp-news-on').checked; + if (newsOn) { + await loadNewsPins(); + return; + } + newsReq++; + if (newsGroup && map) { map.removeLayer(newsGroup); newsGroup = null; } + hudNewsCount = null; + const countEl = document.getElementById('lp-news-count'); + if (countEl) countEl.textContent = '0'; + syncHud(); +} +async function loadNewsPins() { + if (!map) return; + const req = ++newsReq; + try { + const url = `${API}/api/news/map?bbox=${currentBBox()}&limit=200`; + const r = await overlayFetch(url); + const data = await r.json(); + if (req !== newsReq) return; // superseded by a newer pan/zoom + const items = Array.isArray(data) ? data : []; + if (newsGroup) map.removeLayer(newsGroup); + const col = '#ff2e97'; + const pins = items.filter(it => Number.isFinite(Number(it.lat)) && Number.isFinite(Number(it.lon))); + newsGroup = L.layerGroup(pins.map(it => { + const icon = L.divIcon({ + className: '', + html: ``, + iconSize: [14, 14], iconAnchor: [7, 7], + }); + return L.marker([it.lat, it.lon], { icon }) + .bindPopup(`
` + + `
◈ ${esc(it.importance || '')}${it.category ? ' · ' + esc(it.category) : ''}
` + + `${esc(it.headline || '')}` + + `
${esc(it.location_name || '')}
` + + (it.url ? `source ↗` : '') + + `
`); + })); + newsGroup.addTo(map); + document.getElementById('lp-news-count').textContent = pins.length.toLocaleString(); + hudNewsCount = pins.length; + syncHud(); + } catch(e) { + if (isAbort(e)) return; + document.getElementById('map-hint').textContent = `News pins load failed: ${e.message || e}`; + console.error('News pins load failed', e); + } +} + /* ── Live overlays (radar / alerts / WFIGS / aircraft / trains / AIS / NHC) ── */ function refreshLiveOverlays() { if (!map) return; From 450de45bfcb21055830b25d863c4b4bfa8233589 Mon Sep 17 00:00:00 2001 From: Sirius DevOps Date: Thu, 27 Aug 2026 23:51:13 -0400 Subject: [PATCH 12/79] docs: nous portal news summarizer --- docs/news.md | 218 +++++++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 187 insertions(+), 31 deletions(-) diff --git a/docs/news.md b/docs/news.md index 75afc25..93084d0 100644 --- a/docs/news.md +++ b/docs/news.md @@ -1,10 +1,11 @@ -# News pipeline — scraper + summarizer +# News pipeline — scraper + Nous Portal summarizer The OSINT dashboard ingests ~257 global news RSS sources hourly and produces -LLM master summaries. Both services were vendored from the upstream -`~/Projects/newsPipeline` project and re-integrated here to replace the old -k8s CronJob choreography with in-compose scheduling against the EXISTING -osint-db — **no second Postgres**. +an English LLM brief plus flagged ticker/map rows. Both services were vendored +from the upstream `~/Projects/newsPipeline` project and re-integrated here to +replace the old k8s CronJob choreography with in-compose scheduling against +the EXISTING osint-db — **no second Postgres**. The LLM is **Nous Portal** +(`inference-api.nousresearch.com`) — not Gemini. ## Architecture @@ -15,10 +16,11 @@ osint-db — **no second Postgres**. news-scraper (Scrapy, hourly :00) ──► articles table (osint-db) │ │ │ ▼ -news-summarizer (Gemini map-reduce, hourly :05) ──► article_summaries table +news-summarizer (Nous Portal map-reduce, :05) ──► article_summaries + news_items │ ▼ - GET /api/news · GET /api/news/summaries + GET /api/news · /api/news/summaries · /api/news/ticker · /api/news/map + GET /api/news/models · GET/PUT /api/settings ``` | Component | Image | Container | Scheduling | @@ -29,6 +31,11 @@ news-summarizer (Gemini map-reduce, hourly :05) ──► article_summaries tabl Both services live under the `ingest` compose profile (same as the ingester and camera-scraper): `docker compose --profile ingest up -d`. +The summarizer is a batch sidecar, **not** a live overlay. Do **not** reuse +`GET /api/alerts` (dashboard entity/keyword alerts). Do **not** stuff news +into `overlay_catalog()` — `/api/map/layers` `overlays` stays live upstream +feeds (`GET /api/news` exact key set is unchanged on purpose). + ## Data flow 1. **Scraper** — `news/scraper/run_news_scraper.py` runs @@ -39,29 +46,52 @@ and camera-scraper): `docker compose --profile ingest up -d`. (`ON CONFLICT (url) DO NOTHING`). 2. **Summarizer** — `news/summerizer/run_news_summarizer.py` runs `summarizer.py` at :05 past each hour. It reads articles from the last - `SUMMARY_WINDOW_HOURS`, map-reduces them through Gemini - (`SUMMARY_MODEL`, default `gemini-2.0-flash`), and inserts one master - summary into `article_summaries`. + `SUMMARY_WINDOW_HOURS`, map-reduces them through Nous Portal + (`SUMMARY_MODEL` / Settings, default `Hermes-4.3-36B`), writes the English + brief to `article_summaries` (column `model` is the LLM id), and flagged + ticker/map rows to `news_items`. Scheduling is done with small in-compose wall-clock loops (not host cron): each loop runs once on boot (`*_RUN_ON_START=1`, seeds data fast) then sleeps until the next scheduled minute. The loop is serial, so a run that overruns its slot simply shifts to the next boundary — two crawls/summaries never overlap. +Hour-truncation idempotency: if `article_summaries` already has a row for the +current UTC hour, the summarizer **skips** (prevents double-pins on +`RUN_ON_START` recreate). Set `NEWS_SUMMARIZE_FORCE=1` to ignore that skip. + The `articles` and `article_summaries` tables are created by the idempotent alembic migration `003_news` (also created by the scraper's own -`CREATE TABLE IF NOT EXISTS`, so container startup order doesn't matter). +`CREATE TABLE IF NOT EXISTS`). `news_items` is alembic `005_news_items`. +Container startup order doesn't matter. + +## Keys and Settings + +- **`NOUS_API_KEY`** — paste in the dashboard **Keys** UI (`api_keys` / + `keystore.KEY_REGISTRY`). Env / `.env` is an **override** (env wins, same + as FIRMS). Never returned by any API; never emitted into `index.html`; + never proxied from the browser. +- **Idle without a key** — if env is unset **and** the keystore row is empty, + the summarizer logs and idles (never crashes). News intel APIs return `[]`. +- **Model** — non-secret. Settings UI model selector `PUT /api/settings` + `{ "summary_model": "…" }` stores `SUMMARY_MODEL` in `app_settings` (1–128 + chars). `GET /api/settings` echoes `{summary_model, nous_base_url}`. + `nous_base_url` is read-only. Default `Hermes-4.3-36B`. Live catalog is + best-effort `GET /api/news/models`. ## Endpoints ### GET /api/news — recent articles +Key set **unchanged** (no `lat`/`lon` on articles; geo lives on `/api/news/map`). + | Query param | Meaning | Default | |---|---|---| | `domain` | filter by source domain (e.g. `www.reuters.com`) | none | | `since` | only articles captured at/after this UTC instant (ISO-8601) | none | | `limit` | max rows | `50` (max `500`) | | `offset` | pagination offset | `0` | +| `include_content` | include full article body | `false` | ```json [ @@ -69,14 +99,14 @@ alembic migration `003_news` (also created by the scraper's own "id": 1, "title": "…", "url": "https://…", - "content": "full extracted article text…", + "content": null, "domain": "www.reuters.com", "timestamp": "2026-08-24T18:10:00Z" } ] ``` -### GET /api/news/summaries — master LLM summaries +### GET /api/news/summaries — master LLM briefs | Query param | Meaning | Default | |---|---|---| @@ -88,52 +118,178 @@ alembic migration `003_news` (also created by the scraper's own [ { "id": 1, - "summary_text": "master LLM summary (markdown)…", - "batch_timestamp": "2026-08-24T18:10:00Z" + "summary_text": "English markdown brief…", + "batch_timestamp": "2026-08-24T18:10:00Z", + "model": "Hermes-4.3-36B" } ] ``` +`model` is additive. Empty DB → `[]` (no crash). + +### GET /api/news/ticker — flagged HUD headlines + +Critical/high `news_items` with `kind=ticker` only. Do **not** reuse +`GET /api/alerts`. Bottom HUD `#nt-track` scrolls these rows, not a dump of +the whole brief. + +| Query param | Meaning | Default | +|---|---|---| +| `since` | only items created at/after this UTC instant | none | +| `limit` | max rows | `20` (max `50`) | + +```json +[ + { + "id": 1, + "headline": "…", + "importance": "critical", + "location_name": "Kyiv", + "url": "https://…", + "created_at": "2026-08-24T18:10:00Z" + } +] +``` + +### GET /api/news/map — geolocated critical/high pins + +Only rows with valid `lat`/`lon`. Optional bbox. **No zoom skip** — world +view is the point. Layer-panel toggle uses this dedicated path (same as +event blips), not `overlay_catalog`. + +| Query param | Meaning | Default | +|---|---|---| +| `bbox` | `minlon,minlat,maxlon,maxlat` | all flagged pins | +| `since` | only items created at/after this UTC instant | last 24 hours | +| `limit` | max rows | `200` (max `500`) | + +Malformed bbox → `422`. + +```json +[ + { + "id": 1, + "headline": "…", + "importance": "high", + "location_name": "Kyiv", + "lat": 50.45, + "lon": 30.52, + "location_confidence": "city", + "category": "military/conflict", + "url": "https://…", + "created_at": "2026-08-24T18:10:00Z" + } +] +``` + +Pins are LLM-estimated and clamped (`lat∈[-90,90]`, `lon∈[-180,180]`). No +Nominatim. No writes into `events`. + +### GET /api/news/models — Settings dropdown catalog + +Never 502s. `{ "source": "live"|"fallback", "models": [{"id": "…"}] }`. + +### GET /api/settings · PUT /api/settings + +```json +{ "summary_model": "Hermes-4.3-36B", "nous_base_url": "https://inference-api.nousresearch.com/v1" } +``` + +PUT body is `{ "summary_model": "<1–128 char id>" }`. `nous_base_url` is +ignored even if sent. + +## Reduce JSON contract + +Reduce phase (`response_format: json_object`, English only) must be a single +object. Parser (`intel.parse_reduce_json`) strips `…` and +markdown json fences, then brace-slices: + +```json +{ + "summary_en": "English markdown brief or the no-qualifying-events sentence", + "ticker": [ + {"headline": "", "importance": "critical", "url": "", "location_name": ""} + ], + "map_items": [ + { + "headline": "", + "importance": "critical", + "location_name": "", + "lat": 0, + "lon": 0, + "location_confidence": "city", + "category": "military/conflict", + "url": "" + } + ] +} +``` + +Persist ticker/map only for `importance` in `critical`/`high`. Map rows also +need valid coords; Unknown / invented places are dropped. Caps: 12 ticker +(≤140 chars, no markdown), 20 map. Empty ticker is allowed. `summary_en` +lands in `article_summaries.summary_text`. + ## Configuration (all via env / `.env`) | Var | Default | Notes | |---|---|---| -| `GEMINI_API_KEY` | *(blank)* | **Required for summaries.** Unset = summarizer logs and idles (never crashes). | -| `SUMMARY_MODEL` | `gemini-2.0-flash` | Gemini model id. | -| `NEWS_BATCH_SIZE` | `50` | Articles per map-phase batch. | +| `NOUS_API_KEY` | *(blank)* | **Required for summaries.** Prefer Keys UI; env overrides. Unset in **both** env and `api_keys` = summarizer logs and idles (never crashes); APIs return `[]`. | +| `NOUS_BASE_URL` | `https://inference-api.nousresearch.com/v1` | Read-only in Settings. | +| `SUMMARY_MODEL` | `Hermes-4.3-36B` | Compose default. Operator-facing choice is Settings → `app_settings.SUMMARY_MODEL`. | +| `NEWS_BATCH_SIZE` | `50` | Articles per map-phase batch (compose maps to container `BATCH_SIZE`). | | `SUMMARY_WINDOW_HOURS` | `1` | How far back the summarizer looks for new articles. | | `INCLUDE_FUTURES` | `0` | Legacy futures-prices coupling (upstream pipeline). OFF for OSINT; set `1` + install `yfinance` to enable. | | `NEWS_SCRAPE_MINUTE` | `0` | Wall-clock minute the scraper fires. | | `NEWS_SUMMARIZE_MINUTE` | `5` | Wall-clock minute the summarizer fires. | | `NEWS_SCRAPE_RUN_ON_START` | `1` | Run one scrape immediately on container start. | | `NEWS_SUMMARIZE_RUN_ON_START` | `1` | Run one summarize immediately on container start. | +| `NEWS_SUMMARIZE_FORCE` | `0` | `1` ignores the current-UTC-hour idempotency skip (double-pins on recreate). | | `NEWS_LOG_LEVEL` | `INFO` | Scrapy log level. | +| `OSINT_USER_AGENT` | `osint-dashboard-news-summarizer` | Sent on every outbound Nous call. | | `TELEGRAM_TOKEN` / `TELEGRAM_CHAT_ID` | *(blank)* | Reserved for the (out-of-scope) Telegram delivery bot. | DB_* for both services is mapped to the shared osint-db credentials (`DB_HOST=db`, same `DB_USER/DB_PASSWORD/DB_NAME` as the rest of the stack). +Nous chat: `POST {NOUS_BASE_URL}/chat/completions` via `news/summerizer/nous_client.py` +(`httpx`, no `openai` SDK). Auth is a Bearer token from `NOUS_API_KEY`. +No Hermes-4 reasoning system prompt. Reduce uses `json_mode=True`. + ## Prompts Both prompts are env-overridable — the default `MAP_PROMPT` is OSINT-neutral -(facts, locations, entities, category, OSINT signal per article) and the default -`SUMMARY_PROMPT` produces a concise executive summary of the most impactful -items (with a "no qualifying events" escape hatch). Upstream's futures/markets -prompt language is gated behind `INCLUDE_FUTURES=1`. +(facts, locations, entities, category, OSINT signal per article; English) and +the default `SUMMARY_PROMPT` demands the reduce JSON above (with a +"no qualifying events" escape hatch). Upstream's futures/markets prompt +language is gated behind `INCLUDE_FUTURES=1`. ## Tests -`tests/test_api_news.py` — DB-backed API contract tests (auto-skip without a -reachable test database, same as the FIRMS tests): - ```bash -DB_HOST=... DB_PORT=... DB_USER=osint DB_PASSWORD=... DB_NAME=osint_data \ - pytest tests/test_api_news.py -v +PYTHONPATH=news/summerizer pytest news/summerizer/tests -v +# intel + nous_client tests PASS (no network) + +PYTHONPATH=app pytest tests/test_api_news.py tests/test_api_news_intel.py \ + tests/test_api_settings.py tests/test_api_live_layers.py -v +# DB-marked tests skip without Postgres; live_layers must still PASS +# /api/map/layers overlays key set UNCHANGED ``` ## Live verification -End-to-end (real crawl → DB → API) is verified after deploy on the Pi: check -`docker compose --profile ingest logs -f news-scraper news-summarizer`, then -`curl -s localhost:8000/api/news | head`. Summaries additionally require -`GEMINI_API_KEY` to be set in `.env` on the Pi. +After deploy / compose rebuild of `news-summarizer` on the Pi: + +1. Keys UI: save `NOUS_API_KEY` → status `****last4`. +2. Settings: pick a model → Save → `GET /api/settings` echoes it. +3. `docker compose --profile ingest logs -f news-summarizer` — next run (or + `NEWS_SUMMARIZE_RUN_ON_START=1` recreate) logs `Processing N articles with `. +4. `curl -s localhost:8000/api/news/summaries?limit=1` — English `summary_text`, `model` set. +5. `curl -s localhost:8000/api/news/ticker` — flagged headlines only. +6. `curl -s localhost:8000/api/news/map` — only rows with lat/lon. +7. HUD: NEWS ticker scrolls flagged items; map overlay pins popup with location. +8. Unset key + empty keystore → summarizer logs idle, APIs return `[]`, no crash. + +**Operator action after merge:** paste a Nous Portal API key in API Keys; pick +a model in Settings if the default `Hermes-4.3-36B` is not wanted; rebuild +`osint-news-summarizer` on the Pi (`pi-app-deploy` / compose). From d2bf55183c844fd085a493d9bbdfa68c94f42635 Mon Sep 17 00:00:00 2001 From: Sirius DevOps Date: Fri, 28 Aug 2026 00:02:51 -0400 Subject: [PATCH 13/79] fix: let Settings model reach summarizer; cap map pins at 20 --- .env.example | 5 ++++- app/keystore.py | 2 +- app/main.py | 2 +- docker-compose.yml | 2 +- docs/news.md | 2 +- news/summerizer/intel.py | 3 +++ news/summerizer/tests/test_intel.py | 9 +++++++++ 7 files changed, 20 insertions(+), 5 deletions(-) diff --git a/.env.example b/.env.example index ad2d4ee..ac898a9 100644 --- a/.env.example +++ b/.env.example @@ -76,7 +76,10 @@ INGEST_FIRES=1 NOUS_API_KEY= NOUS_BASE_URL=https://inference-api.nousresearch.com/v1 # Optional LLM knobs -SUMMARY_MODEL=Hermes-4.3-36B +# SUMMARY_MODEL is an optional override. Leave unset so Settings +# (app_settings.SUMMARY_MODEL) can reach the summarizer. Code default +# Hermes-4.3-36B remains after a Postgres miss. Env wins when set. +# SUMMARY_MODEL= NEWS_BATCH_SIZE=50 SUMMARY_WINDOW_HOURS=1 # Futures/markets coupling from the upstream pipeline is OFF by default diff --git a/app/keystore.py b/app/keystore.py index 44c76d6..0eb49a4 100644 --- a/app/keystore.py +++ b/app/keystore.py @@ -214,7 +214,7 @@ async def get_api_key(name: str) -> str | None: """Read a stored key value — used by ingest services, never by the API. Returns the raw value (or None when unset) so producers can pass it to - external APIs (FIRMS, Gemini, Telegram, …). Reads live from Postgres, so a + external APIs (FIRMS, Nous, Telegram, …). Reads live from Postgres, so a key set via the dashboard is picked up on the next poll — no restart. """ await ensure_api_keys_table() diff --git a/app/main.py b/app/main.py index f08c0a7..a2e47ee 100644 --- a/app/main.py +++ b/app/main.py @@ -605,7 +605,7 @@ async def list_documents( async def list_api_keys(): """List known API keys with set/missing status — masked, never raw. - Registered keys (FIRMS_MAP_KEY, GEMINI_API_KEY, TELEGRAM_TOKEN) + Registered keys (FIRMS_MAP_KEY, NOUS_API_KEY, TELEGRAM_TOKEN) are always included. Any extra stored keys are appended. """ return await list_keys() diff --git a/docker-compose.yml b/docker-compose.yml index a34365c..aa674f7 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -226,7 +226,7 @@ services: DB_NAME: ${DB_NAME:-osint_data} NOUS_API_KEY: ${NOUS_API_KEY:-} NOUS_BASE_URL: ${NOUS_BASE_URL:-https://inference-api.nousresearch.com/v1} - SUMMARY_MODEL: ${SUMMARY_MODEL:-Hermes-4.3-36B} + SUMMARY_MODEL: ${SUMMARY_MODEL:-} OSINT_USER_AGENT: ${OSINT_USER_AGENT:-osint-dashboard-news-summarizer} BATCH_SIZE: ${NEWS_BATCH_SIZE:-50} SUMMARY_WINDOW_HOURS: ${SUMMARY_WINDOW_HOURS:-1} diff --git a/docs/news.md b/docs/news.md index 93084d0..43a39c0 100644 --- a/docs/news.md +++ b/docs/news.md @@ -270,7 +270,7 @@ language is gated behind `INCLUDE_FUTURES=1`. PYTHONPATH=news/summerizer pytest news/summerizer/tests -v # intel + nous_client tests PASS (no network) -PYTHONPATH=app pytest tests/test_api_news.py tests/test_api_news_intel.py \ +PYTHONPATH=app pytest tests/test_api_news.py \ tests/test_api_settings.py tests/test_api_live_layers.py -v # DB-marked tests skip without Postgres; live_layers must still PASS # /api/map/layers overlays key set UNCHANGED diff --git a/news/summerizer/intel.py b/news/summerizer/intel.py index d4bb1b7..d404f44 100644 --- a/news/summerizer/intel.py +++ b/news/summerizer/intel.py @@ -13,6 +13,7 @@ _FENCE_RE = re.compile(r"```(?:json)?", re.IGNORECASE) TICKER_HEADLINE_MAX = 140 MAP_HEADLINE_MAX = 160 TICKER_CAP = 12 +MAP_CAP = 20 def parse_reduce_json(raw: str) -> dict: @@ -87,4 +88,6 @@ def select_map(items: list) -> list: item["headline"] = headline item["lat"], item["lon"] = coords out.append(item) + if len(out) >= MAP_CAP: + break return out diff --git a/news/summerizer/tests/test_intel.py b/news/summerizer/tests/test_intel.py index 74f74c3..dde2b5c 100644 --- a/news/summerizer/tests/test_intel.py +++ b/news/summerizer/tests/test_intel.py @@ -40,3 +40,12 @@ def test_select_map_requires_valid_coords_and_flag(): ] out = select_map(items) assert [r["headline"] for r in out] == ["A"] + +def test_select_map_caps_20(): + items = [ + {"headline": f"h{i}", "importance": "critical", "lat": 1.0, "lon": 2.0} + for i in range(25) + ] + out = select_map(items) + assert len(out) == 20 + assert all(r["importance"] in ("critical", "high") for r in out) From 1b1f2d3b3af1645defc3c4b63a4c50705068e647 Mon Sep 17 00:00:00 2001 From: Sirius DevOps Date: Fri, 28 Aug 2026 18:29:06 -0400 Subject: [PATCH 14/79] fix: merge alembic heads so the dashboard stops crash-looping 005_phase2 and 005_news_items both revised 004_camera_enum. Entrypoint `alembic upgrade head` then failed and the app never bound :8000 (502 over Tailscale). Merge revision + `upgrade heads`. --- alembic/versions/006_merge_phase2_news.py | 24 +++++++++++++++++++++++ app/docker-entrypoint.sh | 4 +++- 2 files changed, 27 insertions(+), 1 deletion(-) create mode 100644 alembic/versions/006_merge_phase2_news.py diff --git a/alembic/versions/006_merge_phase2_news.py b/alembic/versions/006_merge_phase2_news.py new file mode 100644 index 0000000..0018728 --- /dev/null +++ b/alembic/versions/006_merge_phase2_news.py @@ -0,0 +1,24 @@ +"""merge 005_phase2 and 005_news_items + +Revision ID: 006_merge_heads +Revises: 005_phase2, 005_news_items +Create Date: 2026-08-28 + +Two PRs both parented 004_camera_enum (phase2 geofences + news_items). +`alembic upgrade head` then fails and crash-loops the dashboard. +""" + +from alembic import op # noqa: F401 + +revision = "006_merge_heads" +down_revision = ("005_phase2", "005_news_items") +branch_labels = None +depends_on = None + + +def upgrade() -> None: + pass + + +def downgrade() -> None: + pass diff --git a/app/docker-entrypoint.sh b/app/docker-entrypoint.sh index d424e23..e81ab44 100644 --- a/app/docker-entrypoint.sh +++ b/app/docker-entrypoint.sh @@ -4,7 +4,9 @@ set -e cd /app echo "[entrypoint] running migrations..." -alembic upgrade head +# `heads` (plural): parallel PRs can fork the chain (005_phase2 + 005_news_items). +# `upgrade head` then exits 255 and crash-loops the container. +alembic upgrade heads echo "[entrypoint] starting uvicorn..." exec uvicorn app.main:app --host 0.0.0.0 --port 8000 From 700f56ef51f4b7b5f50fb7d4d2d1e0034bcf46e3 Mon Sep 17 00:00:00 2001 From: Sirius DevOps Date: Fri, 28 Aug 2026 20:04:53 -0400 Subject: [PATCH 15/79] fix: hydrate camera popup from GET /api/cameras/{id} List payload is slim (no URLs). YouTube thumbs need source_url from the detail endpoint, so the popup fetches the full row before rendering. --- app/static/index.html | 50 +++++++++++++++++++++-------- tests/test_camera_popup_contract.py | 15 +++++++++ 2 files changed, 51 insertions(+), 14 deletions(-) create mode 100644 tests/test_camera_popup_contract.py diff --git a/app/static/index.html b/app/static/index.html index db4fb01..0226c13 100644 --- a/app/static/index.html +++ b/app/static/index.html @@ -1905,9 +1905,7 @@ async function initMap() { L.control.zoom({ position: 'topright' }).addTo(map); map.attributionControl.setPrefix(''); let activeHls = null; - map.on('popupopen', (e) => { - if (activeHls) { try { activeHls.destroy(); } catch (_) {} activeHls = null; } - const root = e.popup.getElement(); + const startHlsFrom = (root) => { const v = root && root.querySelector('video[data-hls]'); if (!v) return; const fallback = () => { @@ -1935,6 +1933,25 @@ async function initMap() { }; if (window.Hls) startHls(); else loadHls().then(startHls).catch(fallback); + }; + map.on('popupopen', (e) => { + if (activeHls) { try { activeHls.destroy(); } catch (_) {} activeHls = null; } + const root = e.popup.getElement(); + const box = root && root.querySelector('.cam-pop[data-cam-id]'); + if (box && box.dataset.loaded !== '1') { + fetch(`${API}/api/cameras/${box.dataset.camId}`) + .then(r => { if (!r.ok) throw new Error('camera detail'); return r.json(); }) + .then(c => { + box.outerHTML = camPopupHtml(c); + startHlsFrom(e.popup.getElement()); + }) + .catch(() => { + const ph = box.querySelector('.thumb.placeholder'); + if (ph) ph.textContent = 'preview unavailable'; + }); + return; + } + startHlsFrom(root); }); map.on('popupclose', () => { if (activeHls) { try { activeHls.destroy(); } catch (_) {} activeHls = null; } @@ -2305,6 +2322,20 @@ function camThumb(c) { ); return `camera preview`; } +function camPopupHtml(c) { + return `
` + + `${esc(c.location_name || 'Open camera')}` + + `${c.id ? camThumb(c) : '
no snapshot
'}` + + `` + + `` + + `` + + `` + + `` + + `` + + `
Vendor${esc(c.vendor || '?')} ${esc(c.device_type || '')}
Source${esc(c.discovery_source || '?')}
First seen${esc((c.first_seen||'').slice(0,16).replace('T',' '))}
Last seen${esc((c.last_seen||'').slice(0,16).replace('T',' '))}
Coords${(c.lat!=null&&c.lon!=null) ? c.lat.toFixed(3)+', '+c.lon.toFixed(3) : 'unknown'}
` + + camSourceLink(c) + + `
`; +} async function loadCams() { if (!map) return; if (tooZoomedOut()) { @@ -2340,18 +2371,9 @@ async function loadCams() { iconSize: [12, 12], iconAnchor: [6, 6], }); camsGroup.addLayer(L.marker([c.lat, c.lon], { icon }) - .bindPopup(() => `
` + + .bindPopup(() => `
` + `${esc(c.location_name || 'Open camera')}` + - `${c.id ? camThumb(c) : '
no snapshot
'}` + - `` + - `` + - `` + - `` + - `` + - `` + - `
Vendor${esc(c.vendor || '?')} ${esc(c.device_type || '')}
Source${esc(c.discovery_source || '?')}
First seen${esc((c.first_seen||'').slice(0,16).replace('T',' '))}
Last seen${esc((c.last_seen||'').slice(0,16).replace('T',' '))}
Coords${(c.lat!=null&&c.lon!=null) ? c.lat.toFixed(3)+', '+c.lon.toFixed(3) : 'unknown'}
` + - camSourceLink(c) + - `
`)); + `
loading feed…
`)); }); camsGroup.addTo(map); camsGroup.eachLayer(l => l.setOpacity && l.setOpacity(camsOpacity)); diff --git a/tests/test_camera_popup_contract.py b/tests/test_camera_popup_contract.py new file mode 100644 index 0000000..42f1bce --- /dev/null +++ b/tests/test_camera_popup_contract.py @@ -0,0 +1,15 @@ +"""Camera list is slim (no URLs). Popup must fetch GET /api/cameras/{id}.""" + +from pathlib import Path + +HTML = Path(__file__).resolve().parents[1] / "app/static/index.html" + + +def test_popupopen_fetches_camera_detail_row(): + html = HTML.read_text() + start = html.index("map.on('popupopen'") + end = html.index("map.on('popupclose'") + block = html[start:end] + assert "fetch(" in block + assert "/api/cameras/" in block + assert "camPopupHtml(" in block From b057ff48f9c8bf0c991a85d797d0323d531cc062 Mon Sep 17 00:00:00 2001 From: Sirius DevOps Date: Fri, 28 Aug 2026 20:35:31 -0400 Subject: [PATCH 16/79] fix(ci): recreate named compose containers without collisions CI ran `compose up --force-recreate` without the ingest profile, so compose tried to *create* osint-dashboard while the old name-pinned container was still running. down + rm -f the known names, then up --profile ingest. Volumes stay. --- .forgejo/workflows/build.yml | 8 ++++++- scripts/compose-reup.sh | 42 ++++++++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+), 1 deletion(-) create mode 100755 scripts/compose-reup.sh diff --git a/.forgejo/workflows/build.yml b/.forgejo/workflows/build.yml index 0eae41f..6116fdf 100644 --- a/.forgejo/workflows/build.yml +++ b/.forgejo/workflows/build.yml @@ -141,7 +141,13 @@ jobs: # osint-dashboard_osint-pgdata (pinned by `name:` in compose). docker compose build --no-cache app ingester camera-service news-scraper news-summarizer || \ docker compose build app ingester camera-service news-scraper news-summarizer - docker compose up -d --force-recreate + # Name-pinned containers (container_name: osint-dashboard, …) collide + # when compose tries to create instead of recreate — e.g. leftover from + # a different working_dir or a half-failed previous up. down + rm -f + # the known names, then up the full ingest profile. + chmod +x scripts/compose-reup.sh + COMPOSE_PROJECT_NAME=osint-dashboard COMPOSE_PROFILES=ingest \ + scripts/compose-reup.sh docker image prune -f echo "osint-dashboard deployed; images also on ${PUB}/${OWN}/" diff --git a/scripts/compose-reup.sh b/scripts/compose-reup.sh new file mode 100755 index 0000000..f279981 --- /dev/null +++ b/scripts/compose-reup.sh @@ -0,0 +1,42 @@ +#!/usr/bin/env bash +# Recreate the OSINT compose stack without container_name collisions. +# Named volumes (osint-dashboard_osint-pgdata, camera-snapshots) are kept — +# never pass -v to `compose down`. +# +# Usage: scripts/compose-reup.sh +# Env: COMPOSE_PROJECT_NAME (default osint-dashboard) +# COMPOSE_PROFILES (default ingest — nats/ingester/news/cameras) +set -euo pipefail + +ROOT="$(cd "$(dirname "$0")/.." && pwd)" +cd "$ROOT" + +export COMPOSE_PROJECT_NAME="${COMPOSE_PROJECT_NAME:-osint-dashboard}" +PROFILE="${COMPOSE_PROFILES:-ingest}" + +NAMES=( + osint-dashboard + osint-db + osint-nats + osint-ingester + osint-camera-scraper + osint-news-scraper + osint-news-summarizer +) + +echo "compose-reup: project=${COMPOSE_PROJECT_NAME} profile=${PROFILE} dir=${ROOT}" + +# Stop compose-owned containers first. Foreign/name-pinned leftovers survive this. +docker compose --profile "${PROFILE}" down --remove-orphans || true + +# Drop any leftover name-pinned containers compose does not own (the +# "Conflict. The container name is already in use" failure mode). +for c in "${NAMES[@]}"; do + if docker inspect "$c" >/dev/null 2>&1; then + echo "compose-reup: removing leftover ${c}" + docker rm -f "$c" >/dev/null + fi +done + +docker compose --profile "${PROFILE}" up -d --no-build "$@" +docker compose --profile "${PROFILE}" ps From 864315395440be5092e3a6bf4e4c2001310b2e45 Mon Sep 17 00:00:00 2001 From: Sirius DevOps Date: Fri, 28 Aug 2026 20:53:32 -0400 Subject: [PATCH 17/79] feat: continuous news scrape + 15-min analyst, expand urls.txt Scraper loops with NEWS_SCRAPE_INTERVAL_S (default 10s after each crawl). Summarizer runs every NEWS_SUMMARIZE_INTERVAL_S (default 900) over the last 15 minutes of articles. Feed list replaced from the k8s scrapy-urls configmap (334 sources). --- .env.example | 17 +- app/keystore.py | 2 +- app/main.py | 2 +- app/static/index.html | 12 +- docker-compose.yml | 8 +- docs/news.md | 60 +- .../newsScraper/spiders/news_spider.py | 2 +- news/scraper/run_news_scraper.py | 34 +- news/scraper/urls.txt | 593 ++++++++++-------- news/summerizer/run_news_summarizer.py | 28 +- news/summerizer/summarizer.py | 52 +- 11 files changed, 434 insertions(+), 376 deletions(-) diff --git a/.env.example b/.env.example index ac898a9..9e99921 100644 --- a/.env.example +++ b/.env.example @@ -67,10 +67,8 @@ INGEST_FIRES=1 # its lookup/fallback is a planned follow-up. # ── News pipeline (scraper + summarizer, profile `ingest`) ──────────────── -# Hourly: the scraper crawls 257 RSS sources at minute :00 and the summarizer -# runs the Nous map-reduce at minute :05, both writing to the shared osint-db -# (tables `articles` + `article_summaries`, created by alembic 003_news). -# Consume via GET /api/news and GET /api/news/summaries. +# Scraper crawls urls.txt continuously (default 10s between crawls). +# Summarizer runs Nous map-reduce every 15 min (NEWS_SUMMARIZE_INTERVAL_S=900). # NOUS_API_KEY is also (preferably) set in the Keys UI; env is an override. # Unset in both env and api_keys = summarizer logs and idles (never crashes). NOUS_API_KEY= @@ -81,18 +79,15 @@ NOUS_BASE_URL=https://inference-api.nousresearch.com/v1 # Hermes-4.3-36B remains after a Postgres miss. Env wins when set. # SUMMARY_MODEL= NEWS_BATCH_SIZE=50 -SUMMARY_WINDOW_HOURS=1 +SUMMARY_WINDOW_MINUTES=15 # Futures/markets coupling from the upstream pipeline is OFF by default # (irrelevant to OSINT). Set INCLUDE_FUTURES=1 + install yfinance to enable. INCLUDE_FUTURES=0 -# Wall-clock scheduling (k8s CronJob replacement): scrape minute, summarize minute -NEWS_SCRAPE_MINUTE=0 -NEWS_SUMMARIZE_MINUTE=5 -# Run once immediately on container start (seeds data fast), then align to the -# scheduled minute. +NEWS_SCRAPE_INTERVAL_S=10 +NEWS_SUMMARIZE_INTERVAL_S=900 NEWS_SCRAPE_RUN_ON_START=1 NEWS_SUMMARIZE_RUN_ON_START=1 -# "1" ignores the current-UTC-hour idempotency skip (double-pins on recreate). +# "1" ignores the interval idempotency skip (double-pins on recreate). NEWS_SUMMARIZE_FORCE=0 NEWS_LOG_LEVEL=INFO # Reserved for the (out-of-scope) Telegram delivery bot. diff --git a/app/keystore.py b/app/keystore.py index 0eb49a4..41ea782 100644 --- a/app/keystore.py +++ b/app/keystore.py @@ -58,7 +58,7 @@ KEY_REGISTRY: dict[str, dict] = { "example": "32-char hex string (e.g. 5f3c…9a02)", }, "NOUS_API_KEY": { - "description": "Nous Portal API key — hourly news summarizer (inference-api.nousresearch.com).", + "description": "Nous Portal API key — 15-min news summarizer (inference-api.nousresearch.com).", "pattern": r"^.{16,}$", "example": "key from https://portal.nousresearch.com (API keys page)", }, diff --git a/app/main.py b/app/main.py index a2e47ee..13d404f 100644 --- a/app/main.py +++ b/app/main.py @@ -1084,7 +1084,7 @@ async def camera_hls_segment(camera_id: UUID, u: str = Query(..., min_length=8)) # ── News pipeline (scraper + summarizer) ────────────────────────────────── # Backing data for the frontend news panel. Written by the vendored -# news-scraper (hourly Scrapy crawl) and news-summarizer (hourly Gemini +# news-scraper (continuous Scrapy crawl) and news-summarizer (15-min Nous # map-reduce) services into the shared osint-db. @app.get("/api/news", response_model=list[NewsArticleOut]) diff --git a/app/static/index.html b/app/static/index.html index 0226c13..25d35d5 100644 --- a/app/static/index.html +++ b/app/static/index.html @@ -731,7 +731,7 @@ 0
-
LLM-estimated locations from the hourly brief. Pins only for critical/high.
+
LLM-estimated locations from the 15-min brief. Pins only for critical/high.
@@ -828,7 +828,7 @@

◉ Global News Brief

-

Scraped on the 15-minute cycle · latest LLM executive summary pinned above

+

Scraped continuously · latest LLM executive summary pinned above

— @@ -994,7 +994,7 @@

News Summarizer

-

Takes effect on the next hourly run (:05). No container restart.

+

Takes effect on the next 15-min run. No container restart.

Nous Portal (inference-api.nousresearch.com) @@ -1062,7 +1062,7 @@
Active sources—
Open alerts—
Tracked entities—
-
News cyclehourly :05
+
News cycleanalyst 15m · scraper continuous
Market feedSTANDBY
@@ -1088,7 +1088,7 @@
-
HOURLY
+
15 MIN
@@ -1385,7 +1385,7 @@ function renderNewsList(articles) { if (!listEl) return; document.getElementById('news-count').textContent = articles.length + ' articles'; if (!articles || !articles.length) { - listEl.innerHTML = '
No articles scraped yet — the scraper runs hourly at :00. Check news-scraper logs.
'; + listEl.innerHTML = '
No articles scraped yet — the scraper runs continuously. Check news-scraper logs.
'; return; } listEl.innerHTML = articles.map(a => { diff --git a/docker-compose.yml b/docker-compose.yml index aa674f7..f810304 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -176,7 +176,7 @@ services: volumes: - camera-snapshots:/data/snapshots - # ── News pipeline: hourly scraper (:00) + summarizer (:05) ─────────────── + # ── News pipeline: continuous scraper + 15-min summarizer ─────────────── # Both services point at the EXISTING osint-db (tables articles + # article_summaries, created by idempotent alembic migration 003_news). # Scheduling replaces the upstream k8s CronJobs with in-compose wall-clock @@ -200,7 +200,7 @@ services: DB_PORT: ${DB_PORT:-5432} DB_NAME: ${DB_NAME:-osint_data} LOG_LEVEL: ${NEWS_LOG_LEVEL:-INFO} - NEWS_SCRAPE_MINUTE: ${NEWS_SCRAPE_MINUTE:-0} + NEWS_SCRAPE_INTERVAL_S: ${NEWS_SCRAPE_INTERVAL_S:-10} NEWS_SCRAPE_RUN_ON_START: ${NEWS_SCRAPE_RUN_ON_START:-1} # Override the image ENTRYPOINT ["scrapy"] with the scheduler loop. entrypoint: [] @@ -229,9 +229,9 @@ services: SUMMARY_MODEL: ${SUMMARY_MODEL:-} OSINT_USER_AGENT: ${OSINT_USER_AGENT:-osint-dashboard-news-summarizer} BATCH_SIZE: ${NEWS_BATCH_SIZE:-50} - SUMMARY_WINDOW_HOURS: ${SUMMARY_WINDOW_HOURS:-1} + SUMMARY_WINDOW_MINUTES: ${SUMMARY_WINDOW_MINUTES:-15} INCLUDE_FUTURES: ${INCLUDE_FUTURES:-0} - NEWS_SUMMARIZE_MINUTE: ${NEWS_SUMMARIZE_MINUTE:-5} + NEWS_SUMMARIZE_INTERVAL_S: ${NEWS_SUMMARIZE_INTERVAL_S:-900} NEWS_SUMMARIZE_RUN_ON_START: ${NEWS_SUMMARIZE_RUN_ON_START:-1} NEWS_SUMMARIZE_FORCE: ${NEWS_SUMMARIZE_FORCE:-0} command: ["python", "run_news_summarizer.py"] diff --git a/docs/news.md b/docs/news.md index 43a39c0..fe06f6c 100644 --- a/docs/news.md +++ b/docs/news.md @@ -1,22 +1,22 @@ # News pipeline — scraper + Nous Portal summarizer -The OSINT dashboard ingests ~257 global news RSS sources hourly and produces -an English LLM brief plus flagged ticker/map rows. Both services were vendored -from the upstream `~/Projects/newsPipeline` project and re-integrated here to -replace the old k8s CronJob choreography with in-compose scheduling against -the EXISTING osint-db — **no second Postgres**. The LLM is **Nous Portal** +The OSINT dashboard ingests a large curated feed list (`news/scraper/urls.txt`) +continuously and produces an English LLM brief plus flagged ticker/map rows +every 15 minutes. Both services were vendored from the upstream +`~/Projects/newsPipeline` project and re-integrated here against the EXISTING +osint-db — **no second Postgres**. The LLM is **Nous Portal** (`inference-api.nousresearch.com`) — not Gemini. ## Architecture ``` -257 RSS feeds (news/scraper/urls.txt) +urls.txt (RSS + homepages) │ ▼ -news-scraper (Scrapy, hourly :00) ──► articles table (osint-db) +news-scraper (Scrapy, continuous) ──► articles table (osint-db) │ │ │ ▼ -news-summarizer (Nous Portal map-reduce, :05) ──► article_summaries + news_items +news-summarizer (Nous Portal, every 15m) ──► article_summaries + news_items │ ▼ GET /api/news · /api/news/summaries · /api/news/ticker · /api/news/map @@ -25,8 +25,8 @@ news-summarizer (Nous Portal map-reduce, :05) ──► article_summaries + news | Component | Image | Container | Scheduling | |---|---|---|---| -| Scraper | `localhost/osint-news-scraper` | `osint-news-scraper` | wall-clock loop, minute `NEWS_SCRAPE_MINUTE` (default :00) | -| Summarizer | `localhost/osint-news-summarizer` | `osint-news-summarizer` | wall-clock loop, minute `NEWS_SUMMARIZE_MINUTE` (default :05) | +| Scraper | `localhost/osint-news-scraper` | `osint-news-scraper` | loop, `NEWS_SCRAPE_INTERVAL_S` (default 10s after each crawl) | +| Summarizer | `localhost/osint-news-summarizer` | `osint-news-summarizer` | loop, `NEWS_SUMMARIZE_INTERVAL_S` (default 900s) | Both services live under the `ingest` compose profile (same as the ingester and camera-scraper): `docker compose --profile ingest up -d`. @@ -39,26 +39,22 @@ feeds (`GET /api/news` exact key set is unchanged on purpose). ## Data flow 1. **Scraper** — `news/scraper/run_news_scraper.py` runs - `scrapy crawl articles` (spider `news/scraper/newsScraper/spiders/news_spider.py`) - at the top of each hour. The spider reads the RSS feed URLs from `urls.txt`, - follows each `` link, extracts the main article body, and the - `PostgresPipeline` writes to `articles` with URL-based dedup + `scrapy crawl articles` back-to-back (default 10s pause). The spider reads + URLs from `urls.txt` (homepages autodiscover RSS; feed URLs are parsed + directly), follows each `` link, extracts the main article body, and + the `PostgresPipeline` writes to `articles` with URL-based dedup (`ON CONFLICT (url) DO NOTHING`). 2. **Summarizer** — `news/summerizer/run_news_summarizer.py` runs - `summarizer.py` at :05 past each hour. It reads articles from the last - `SUMMARY_WINDOW_HOURS`, map-reduces them through Nous Portal - (`SUMMARY_MODEL` / Settings, default `Hermes-4.3-36B`), writes the English - brief to `article_summaries` (column `model` is the LLM id), and flagged - ticker/map rows to `news_items`. + `summarizer.py` every `NEWS_SUMMARIZE_INTERVAL_S` (default 900). It reads + articles from the last `SUMMARY_WINDOW_MINUTES` (default 15), map-reduces + them through Nous Portal (`SUMMARY_MODEL` / Settings, default + `Hermes-4.3-36B`), writes the English brief to `article_summaries` (column + `model` is the LLM id), and flagged ticker/map rows to `news_items`. -Scheduling is done with small in-compose wall-clock loops (not host cron): each -loop runs once on boot (`*_RUN_ON_START=1`, seeds data fast) then sleeps until -the next scheduled minute. The loop is serial, so a run that overruns its slot -simply shifts to the next boundary — two crawls/summaries never overlap. - -Hour-truncation idempotency: if `article_summaries` already has a row for the -current UTC hour, the summarizer **skips** (prevents double-pins on -`RUN_ON_START` recreate). Set `NEWS_SUMMARIZE_FORCE=1` to ignore that skip. +Loops are serial (two crawls/summaries never overlap). Interval idempotency: +if `article_summaries` already has a row in the last interval, the summarizer +**skips** (prevents double-pins on `RUN_ON_START` recreate). Set +`NEWS_SUMMARIZE_FORCE=1` to ignore that skip. The `articles` and `article_summaries` tables are created by the idempotent alembic migration `003_news` (also created by the scraper's own @@ -238,13 +234,13 @@ lands in `article_summaries.summary_text`. | `NOUS_BASE_URL` | `https://inference-api.nousresearch.com/v1` | Read-only in Settings. | | `SUMMARY_MODEL` | `Hermes-4.3-36B` | Compose default. Operator-facing choice is Settings → `app_settings.SUMMARY_MODEL`. | | `NEWS_BATCH_SIZE` | `50` | Articles per map-phase batch (compose maps to container `BATCH_SIZE`). | -| `SUMMARY_WINDOW_HOURS` | `1` | How far back the summarizer looks for new articles. | -| `INCLUDE_FUTURES` | `0` | Legacy futures-prices coupling (upstream pipeline). OFF for OSINT; set `1` + install `yfinance` to enable. | -| `NEWS_SCRAPE_MINUTE` | `0` | Wall-clock minute the scraper fires. | -| `NEWS_SUMMARIZE_MINUTE` | `5` | Wall-clock minute the summarizer fires. | +| `SUMMARY_WINDOW_MINUTES` | `15` | How far back the summarizer looks for new articles. | +| `NEWS_SCRAPE_INTERVAL_S` | `10` | Pause after each crawl before the next (scraper is otherwise continuous). | +| `NEWS_SUMMARIZE_INTERVAL_S` | `900` | Seconds between analyst runs (default 15 min). | | `NEWS_SCRAPE_RUN_ON_START` | `1` | Run one scrape immediately on container start. | | `NEWS_SUMMARIZE_RUN_ON_START` | `1` | Run one summarize immediately on container start. | -| `NEWS_SUMMARIZE_FORCE` | `0` | `1` ignores the current-UTC-hour idempotency skip (double-pins on recreate). | +| `NEWS_SUMMARIZE_FORCE` | `0` | `1` ignores the interval idempotency skip (double-pins on recreate). | +| `INCLUDE_FUTURES` | `0` | Legacy futures-prices coupling. OFF for OSINT; set `1` + install `yfinance` to enable. | | `NEWS_LOG_LEVEL` | `INFO` | Scrapy log level. | | `OSINT_USER_AGENT` | `osint-dashboard-news-summarizer` | Sent on every outbound Nous call. | | `TELEGRAM_TOKEN` / `TELEGRAM_CHAT_ID` | *(blank)* | Reserved for the (out-of-scope) Telegram delivery bot. | diff --git a/news/scraper/newsScraper/spiders/news_spider.py b/news/scraper/newsScraper/spiders/news_spider.py index 136f1b8..f29db33 100644 --- a/news/scraper/newsScraper/spiders/news_spider.py +++ b/news/scraper/newsScraper/spiders/news_spider.py @@ -8,7 +8,7 @@ import re class NewsRSSSpider(Spider): """Crawl the curated news sources in urls.txt and extract articles. - urls.txt contains 257 news HOMEPAGES (not feed URLs), so this spider + urls.txt contains curated news HOMEPAGES and RSS/Atom feeds, so this spider implements feed autodiscovery: it fetches each start URL, finds the RSS/Atom feed link (`` or a visible /rss|/feed link), follows it, and then follows each feed diff --git a/news/scraper/run_news_scraper.py b/news/scraper/run_news_scraper.py index 7fc9228..61aa551 100644 --- a/news/scraper/run_news_scraper.py +++ b/news/scraper/run_news_scraper.py @@ -1,18 +1,12 @@ #!/usr/bin/env python3 -"""Scheduler loop for the news scraper — hourly scrape at minute :00. +"""Scheduler loop for the news scraper — crawl continuously. -Replaces the k8s CronJob (`0 * * * *`) with an in-compose loop so the whole -news pipeline lives inside docker-compose. Each iteration: - - 1. (optionally, on first boot) runs the Scrapy crawl once to seed data fast - 2. sleeps until the next :NEWS_SCRAPE_MINUTE wall-clock boundary - -Because the loop is serial, a crawl that overruns its hour simply delays the -next run to the following boundary — two crawls never overlap. +As soon as one Scrapy pass finishes, wait NEWS_SCRAPE_INTERVAL_S seconds +and start the next. Two crawls never overlap (the loop is serial). Env (all optional, 12-factor): - NEWS_SCRAPE_MINUTE minute of the hour to fire (default 0) - NEWS_SCRAPE_RUN_ON_START "1" to crawl once immediately on boot (default 1) + NEWS_SCRAPE_INTERVAL_S seconds between crawls (default 10) + NEWS_SCRAPE_RUN_ON_START "1" to crawl immediately on boot (default 1) """ from __future__ import annotations @@ -27,19 +21,12 @@ import time logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s") logger = logging.getLogger("news.scraper") -MINUTE = int(os.getenv("NEWS_SCRAPE_MINUTE", "0")) +INTERVAL_S = max(0, int(os.getenv("NEWS_SCRAPE_INTERVAL_S", "10"))) RUN_ON_START = os.getenv("NEWS_SCRAPE_RUN_ON_START", "1").lower() in ("1", "true", "yes") CRAWL_CMD = ["scrapy", "crawl", "articles"] -def seconds_until_next(minute: int) -> float: - """Seconds until the next occurrence of ``minute`` past the hour (local time).""" - now = datetime.datetime.now() - nxt = now.replace(minute=minute, second=0, microsecond=0) + datetime.timedelta(hours=1) - return (nxt - now).total_seconds() - - def run_crawl() -> None: logger.info("scrape starting at %s", datetime.datetime.now().isoformat(timespec="seconds")) try: @@ -51,15 +38,14 @@ def run_crawl() -> None: def main() -> None: logger.info( - "news scraper loop starting (minute=%s, run_on_start=%s)", - MINUTE, RUN_ON_START, + "news scraper loop starting (interval_s=%s, run_on_start=%s)", + INTERVAL_S, RUN_ON_START, ) if RUN_ON_START: run_crawl() while True: - delay = seconds_until_next(MINUTE) - logger.info("next scrape at :%02d (in %.0fs)", MINUTE, delay) - time.sleep(delay) + logger.info("next scrape in %ss", INTERVAL_S) + time.sleep(INTERVAL_S) run_crawl() diff --git a/news/scraper/urls.txt b/news/scraper/urls.txt index 316d9f6..38ea5ed 100644 --- a/news/scraper/urls.txt +++ b/news/scraper/urls.txt @@ -1,257 +1,336 @@ -# --- NORTH AMERICA --- -# USA -https://www.npr.org -https://www.pbs.org/newshour -https://www.usatoday.com -https://www.cbsnews.com -https://www.nbcnews.com - -# Canada -https://www.cbc.ca/news -https://www.ctvnews.ca -https://globalnews.ca -https://nationalpost.com -https://www.thestar.com - -# Mexico -https://www.eluniversal.com.mx -https://www.milenio.com -https://www.jornada.com.mx -https://www.excelsior.com.mx -https://aristeguinoticias.com - -# --- SOUTH AMERICA --- -# Brazil -https://g1.globo.com -https://www.uol.com.br -https://agenciabrasil.ebc.com.br -https://www.metropoles.com -https://www.terra.com.br/noticias - -# Argentina -https://www.infobae.com -https://www.clarin.com -https://www.lanacion.com.ar -https://www.pagina12.com.ar -https://www.cronista.com - -# Colombia -https://www.eltiempo.com -https://www.elespectador.com -https://www.semana.com -https://www.bluradio.com -https://www.rcnradio.com - -# --- EUROPE --- -# United Kingdom -https://www.bbc.com/news -https://www.theguardian.com/uk -https://news.sky.com -https://www.independent.co.uk -https://metro.co.uk - -# France -https://www.france24.com/en -https://www.lefigaro.fr -https://www.20minutes.fr -https://www.francetvinfo.fr -https://www.lemonde.fr - -# Germany -https://www.dw.com/en -https://www.tagesschau.de -https://www.spiegel.de -https://www.zeit.de -https://www.bild.de - -# Spain -https://elpais.com -https://www.elmundo.es -https://www.rtve.es/noticias -https://www.20minutos.es -https://www.elconfidencial.com - -# Italy -https://www.ansa.it -https://www.corriere.it -https://www.repubblica.it -https://www.lastampa.it -https://tg24.sky.it - -# Russia (State & Independent mix) -https://tass.com -https://www.interfax.ru -https://www.rt.com -https://www.themoscowtimes.com -https://meduza.io/en - -# --- ASIA --- -# China -https://www.xinhuanet.com/english -https://www.chinadaily.com.cn -https://www.globaltimes.cn -https://www.cgtn.com -https://www.scmp.com - -# India -https://www.ndtv.com -https://timesofindia.indiatimes.com -https://indianexpress.com -https://www.thehindu.com -https://www.hindustantimes.com - -# Japan -https://www3.nhk.or.jp/nhkworld -https://www.japantimes.co.jp -https://www.asahi.com/ajw -https://mainichi.jp/english -https://english.kyodonews.net - -# South Korea -https://en.yna.co.kr -https://www.koreaherald.com -https://koreajoongangdaily.joins.com -https://www.donga.com/en -https://english.chosun.com - -# --- AFRICA --- -# South Africa -https://www.news24.com -https://www.iol.co.za -https://www.dailymaverick.co.za -https://www.sabcnews.com -https://www.timeslive.co.za - -# Nigeria -https://www.vanguardngr.com -https://punchng.com -https://dailypost.ng -https://saharareporters.com -https://thenationonlineng.net - -# --- MIDDLE EAST --- -# General Region -https://www.aljazeera.com -https://english.alarabiya.net -https://www.timesofisrael.com -https://www.tehrantimes.com -https://www.middleeasteye.net - -# --- OCEANIA --- -# Australia -https://www.abc.net.au/news -https://www.news.com.au -https://www.9news.com.au -https://www.smh.com.au -https://www.theage.com.au -# --- USA: MAJOR CITIES & LOCAL --- -https://www.latimes.com -https://www.chicagotribune.com -https://www.sfchronicle.com -https://www.bostonglobe.com -https://www.seattletimes.com -https://www.houstonchronicle.com -https://www.inquirer.com -https://www.denverpost.com -https://www.miamiherald.com -https://www.dallasnews.com -https://www.startribune.com -https://www.detroitnews.com -https://www.ajc.com -https://www.nydailynews.com -https://nypost.com -https://www.mercurynews.com -https://www.baltimoresun.com -https://www.oregonlive.com -https://www.cleveland.com -https://www.tampabay.com - -# --- EUROPE: LOCAL & INDEPENDENT --- -https://www.manchestereveningnews.co.uk -https://www.scotsman.com -https://www.belfasttelegraph.co.uk -https://www.irishtimes.com -https://www.berliner-zeitung.de -https://www.leparisien.fr -https://www.corriere.it -https://www.elperiodico.com -https://kyivindependent.com -https://www.pravda.com.ua/en -https://balkaninsight.com -https://www.ekathimerini.com -https://www.swissinfo.ch -https://www.thelocal.se -https://www.thelocal.fr -https://www.thelocal.de -https://www.novinite.com -https://www.romania-insider.com -https://hungarytoday.hu -https://polandin.com - -# --- MIDDLE EAST & CONFLICT ZONES --- -https://www.haaretz.com -https://www.jpost.com -https://www.timesofisrael.com -https://www.rudaw.net/english -https://www.kurdistan24.net/en -https://www.middleeasteye.net -https://www.al-monitor.com -https://www.dailysabah.com -https://www.duvarenglish.com -https://english.aawsat.com -https://www.arabnews.com -https://www.thenationalnews.com -https://www.jordantimes.com -https://www.naharnet.com -https://www.tehrantimes.com - -# --- ASIA: HOTSPOTS & LOCAL --- -https://www.taipeitimes.com -https://focustaiwan.tw -https://hongkongfp.com -https://www.bangkokpost.com -https://www.thejakartapost.com -https://www.straitstimes.com -https://www.khmertimeskh.com -https://www.irrawaddy.com -https://www.myanmarnow.org/en -https://www.rappler.com -https://www.philstar.com -https://english.hani.co.kr -https://www.japantoday.com -https://www.caixinglobal.com -https://thediplomat.com - -# --- LATIN AMERICA & AFRICA: LOCAL --- -https://buenosairesherald.com -https://riotimesonline.com -https://mercopress.com -https://www.elmostrador.cl -https://www.jornada.com.mx -https://www.theeastafrican.co.ke -https://allafrica.com -https://www.premiumtimesng.com -https://www.dailytrust.com -https://www.newtimes.co.rw -https://www.herald.co.zw -https://www.namibian.com.na -https://www.graphic.com.gh -https://www.thecitizen.co.tz -https://www.monitor.co.ug - -# --- ALTERNATIVE, INVESTIGATIVE & "FRINGE" --- -https://theintercept.com -https://www.propublica.org -https://www.democracynow.org -https://reason.com -https://www.motherjones.com -https://www.vox.com -https://slate.com -https://www.axios.com -https://www.politico.com -https://www.vice.com -https://www.bellingcat.com -https://www.project-syndicate.org -https://cryptonews.com -https://www.coindesk.com -https://techcrunch.com +https://www.investing.com/rss/news.rss +https://www.ftchinese.com/rss +https://www.alwatan.com +https://albiladpress.com +https://www.aletihad.ae/ +https://www.albayan.ae +https://www.aljazeera.com/xml/rss/all.xml +https://english.alarabiya.net/.mrss/en.xml +https://english.aawsat.com/home/rss +https://www.newarab.com/rss +https://www.skynewsarabia.com/rss/feeds/rss-1.xml +https://www.thenationalnews.com/arc/outboundfeeds/rss/ +https://www.arabnews.com/rss.xml +https://gulfnews.com/rss +https://www.kuwaittimes.com/feed/ +https://www.omanobserver.om/feed/ +https://www.khaleejtimes.com/rss/news +http://www.akhbar-alkhaleej.com/rss/all +https://today.lorientleyour.com/rss +https://www.annahar.com/english/rss +https://english.almayadeen.net/rss +https://english.ahram.org.eg/rss/0/Home.aspx +https://www.dailynewsegypt.com/feed/ +http://www.jordantimes.com/rss +https://www.alraimedia.com/rss +https://alghad.com/feed/ +https://nypost.com/feed/ +https://gothamist.com/feed/ +https://www.cityandstateny.com/rss +https://feeds.nytimes.com/nyt/rss/HomePage +https://www.thecity.nyc/rss/index.xml +https://brooklyneagle.com/feed/ +https://www.reutersagency.com/feed/ +https://newsatme.com/api/v1/rss/ap/world +https://feeds.bbci.co.uk/news/world/rss.xml +https://rss.dw.com/rdf/rss-en-all +https://www.france24.com/en/rss +https://www3.nhk.or.jp/rss/news/shakaitokushu.xml +https://www.cbc.ca/cctoc/rss/topstories.north +https://www.defensenews.com/arc/outboundfeeds/rss/ +https://therecord.media/feed +https://www.cfr.org/rss/newsletters/daily-news-brief +https://warontherocks.com/feed/ +https://www.thecipherbrief.com/feed +https://www.foreignaffairs.com/rss.xml +https://geopoliticalfutures.com/feed +# --- TACTICAL CYBER & VULNERABILITIES --- +https://www.bleepingcomputer.com/feed/ +https://www.cisa.gov/cybersecurity-advisory-feeds +https://krebsonsecurity.com/feed/ +https://thehackernews.com/feeds/posts/default +https://www.darkreading.com/rss.xml +https://www.mandiant.com/resources/blog/rss.xml +https://schneier.com/feed/atom/ +https://www.securityweek.com/feed/ +# --- REGIONAL THREAT LANDSCAPE --- +https://www.thenationalnews.com/rss/ +https://www.scmp.com/rss/91/feed +https://www.batimes.com.ar/rss +https://brazilian.report/feed/ +https://www.khon2.com/feed/ +https://www.staradvertiser.com/feed/ +https://www.westhawaiitoday.com/feed/ +https://mauinow.com/feed/ +https://www.idahofallsidaho.gov/RSSFeed.aspx?ModID=1&CID=All-newsflash.xml +https://www.eastidahonews.com/feed/ +https://localnews8.com/feed/ +https://www.boisestatepublicradio.org/news.rss +https://www.illinoistimes.com/springfield/Rss.xml +https://www.thecentersquare.com/search/?f=rss&t=article&l=20&s=start_time&fulltext=showtext&sd=desc&c%5B%5D=Illinois +https://chicago.suntimes.com/rss/index.xml +https://wgntv.com/feed/ +http://feeds.indiana.statenews.net/rss/7b3aa09cdd5d5eac +https://fox59.com/feed/ +https://www.nwitimes.com/search/?f=rss&t=article&c=news/local&l=50&s=start_time&sd=desc +https://www.wishtv.com/feed/ +https://www.kcci.com/topstories-rss +https://www.myiowainfo.com/feed/ +https://feeds.feedburner.com/radioiowanews +https://www.mississippivalleypublishing.com/search/?f=rss&t=article&c=the_hawk_eye&l=50&s=start_time&sd=desc +https://www.ksn.com/feed/ +https://www.ksnt.com/feed/ +https://www.hdnews.net/feed/ +https://themercury.com/search/?f=rss&t=article&c=news&l=50&s=start_time&sd=desc +https://www.wdrb.com/search/?f=rss&t=article&c=news&l=50&s=start_time&sd=desc +https://www.wtvq.com/feed/ +https://www.wnky.com/feed/ +https://www.wlky.com/topstories-rss +https://thehayride.com/feed/ +https://wgno.com/feed/ +https://feeds.feedburner.com/wbrz/news +https://thelensnola.org/feed/ +https://www.pressherald.com/news/feed/ +https://www.centralmaine.com/feed/ +https://www.bangordailynews.com/feed/ +https://www.sunjournal.com/news/feed/ +https://www.wbaltv.com/topstories-rss +https://www.manisteenews.com/news/feed/Latest-News-Feed-2564.php +https://www.theoaklandpress.com/feed/ +https://www.macombdaily.com/feed/ +https://www.startribune.com/local/index.rss2 +https://www.wctrib.com/index.rss +https://www.austindailyherald.com/feed/ +https://helenair.com/search/?f=rss&t=article&l=50&s=start_time&sd=desc +https://www.ktvq.com/news.rss +https://mtstandard.com/search/?f=rss&t=article&l=50&s=start_time&sd=desc +https://www.ketv.com/topstories-rss +https://nebraskaexaminer.com/feed/ +https://kearneyhub.com/rss +https://www.wowt.com/rss +https://thenevadaindependent.com/feed/ +https://www.8newsnow.com/feed/ +https://www.reviewjournal.com/feed/ +https://thisisreno.com/feed/ +https://www.conwaydailysun.com/search/?f=rss&t=article&c=berlin_sun/community/news&l=50&s=start_time&sd=desc +https://newhampshirebulletin.com/feed/ +https://www.nhgazette.com/feed/ +https://www.nhbr.com/feed/ +https://www.nj.com/arc/outboundfeeds/rss/?outputType=xml +https://www.njspotlightnews.org/feed/ +https://njmonthly.com/feed/ +https://www.trentonian.com/feed/ +https://www.krqe.com/feed/ +https://www.santafenewmexican.com/search/?f=rss&t=article&l=50&s=start_time&sd=desc +https://www.easternnewmexiconews.com/rss +https://www.koat.com/topstories-rss +https://rss.nytimes.com/services/xml/rss/nyt/HomePage.xml +https://www.thecity.nyc/feed/ +https://www.nbcnewyork.com/?rss=y +https://www.wral.com/news/rss/48/ +https://www.cbs17.com/news/north-carolina-news/feed/ +https://abc11.com/feed/ +https://myfox8.com/news/feed/ +https://www.kxnet.com/feed/ +https://www.wday.com/feed/ +https://www.jamestownsun.com/index.rss +https://www.inforum.com/index.rss +http://rssfeeds.wkyc.com/wkyc/news +https://theohiostar.com/feed/ +https://feeds.feedblitz.com/wtol/news +https://www.wcpo.com/news.rss +https://kfor.com/feed/ +https://oklahomawatch.org/feed/ +https://freepressokc.com/feed/ +https://osagenews.org/feed/ +http://rssfeeds.kgw.com/kgw/local +https://www.koin.com/feed/ +https://www.bendsource.com/bend/Rss.xml/feed +https://eugeneweekly.com/feed/ +https://www.wtae.com/topstories-rss +https://www.montgomerycountypa.gov/RSSFeed.aspx?ModID=76&CID=All-0 +https://www.mainlinemedianews.com/feed/ +https://www.dailylocal.com/feed/ +https://www.wpri.com/feed/ +https://www.abc6.com/feed/ +https://whdh.com/regional/rhode-island/feed/ +https://warwickpost.com/feed/ +https://www.wyff4.com/topstories-rss +https://www.wispolitics.com/feed/ +https://wiseye.org/feed/ +https://wisconsinexaminer.com/feed/ +https://trib.com/search/?f=rss&t=article&c=news/state-and-regional&l=50&s=start_time&sd=desc +https://wyofile.com/feed/ +https://www.wyomingnews.com/search/?f=rss&t=article&c=news&l=50&s=start_time&sd=desc +https://www.wyodaily.com/rss +https://www.wnct.com/news/north-carolina/feed/ +https://www.usnews.com/rss/news/north-carolina +https://indyweek.com/feed/ +https://portcitydaily.com/feed/ +https://www.theguardian.com/uk/rss +https://feeds.bbci.co.uk/news/england/rss.xml +https://www.lemonde.fr/rss/une.xml +https://www.ansa.it/sito/notizie/rss.xml +https://www.ilgiornale.it/feed +https://www.larepublica.it/rss/homepage/rss2.xml +https://www.sueddeutsche.de/rss +https://www.welt.de/feeds/top-news.rss +https://www.rfi.fr/en/rss +https://www.bangkokpost.com/rss +https://thephnompenhpost.com/rss +https://www.thejakartapost.com/rss +https://www.straitstimes.com/news/singapore/rss.xml +https://www.channelnewsasia.com/rss +https://www.antaranews.com/rss/ +https://www.irrawaddy.com/feed +https://news.abs-cbn.com/rss +https://www.hindustantimes.com/feeds/rss +https://www.africanews.com/feed/rss +https://www.clarin.com/rss +https://www.lanacion.com.ar/rss +https://www.eluniversal.com.mx/rss +https://www.excelsior.com.mx/rss +https://www.eltiempo.com/rss +https://www.elespectador.com/rss +https://www.larepublica.pe/rss +https://www.elcomercio.com/rss +https://www.abc.net.au/news/feed/ +https://www.smh.com.au/rss/world.xml +https://www.theage.com.au/rss +https://www.brisbanetimes.com.au/rss +https://www.stuff.co.nz/rss +https://www.nzherald.co.nz/arcio/rss/ +https://www.rnz.co.nz/rss +https://globalvoices.org/regions/africa/feed/ +https://globalvoices.org/regions/asia/feed/ +https://globalvoices.org/regions/latin-america/feed/ +https://globalvoices.org/regions/eastern-europe/feed/ +https://globalvoices.org/regions/middle-east-north-africa/feed/ +https://globalvoices.org/regions/south-asia/feed/ +https://globalvoices.org/regions/sub-saharan-africa/feed/ +https://globalvoices.org/regions/west-africa/feed/ +https://globalvoices.org/regions/east-asia/feed/ +https://globalvoices.org/regions/southeast-asia/feed/ +https://globalvoices.org/regions/central-asia/feed/ +https://globalvoices.org/regions/pacific/feed/ +https://globalvoices.org/regions/caribbean/feed/ +https://www.townandcountry-mo.gov/rss.aspx +https://feeds.smh.com.au/rssheadlines/national.xml +https://www.abc.net.au/local/rss/sydney/ +https://www.voanews.com/rssfeeds +https://rss.feedspot.com/southeast_asian_rss_feeds +https://www.crisisgroup.org/rss +https://news.panasonic.com/global/rss/area01/index.xml +https://news.panasonic.com/global/rss/area04/index.xml +https://allafrica.com/tools/headlines/rdf/latest/headlines.rdf +https://www.afro.who.int/rss-feeds +https://pressat.co.uk/rss-list +https://www.monitor.co.ug/rss +https://www.standardmedia.co.ke/rss +https://www.ft.com/rss/home +https://www.economist.com/rss/the-world-this-week +https://feeds.bloomberg.com/economics/news.rss +https://feeds.bloomberg.com/markets/news.rss +https://www.reuters.com/arc/outboundfeeds/newsroom/business/ +https://www.cnbc.com/id/10000113/device/rss/rss.html +https://feeds.a.dj.com/rss/RSSWorldBusiness.xml +https://www.marketwatch.com/rss/topstories +https://www.investing.com/rss/news_14.rss +https://feeds.bbci.co.uk/news/business/rss.xml +https://feeds.feedburner.com/TheHackersNews +https://www.darkreading.com/rss/all.xml +https://isc.sans.edu/rssfeed_full.xml +https://securelist.com/feed/ +https://feeds.feedburner.com/eset/blog +https://news.sophos.com/en-us/feed/ +https://www.schneier.com/feed/atom/ +https://www.securitymagazine.com/rss/topic/2236-cybersecurity-news +https://www.reuters.com/arc/outboundfeeds/rss/?outputType=xml +https://www.investing.com/rss/news_462.rss +https://www.investing.com/rss/news_1.rss +https://www.investing.com/rss/stock_Futures.rss +https://www.ecb.europa.eu/rss/fxref-ecbpress.en.xml +https://www.federalreserve.gov/feeds/news-events.xml +https://www.boj.or.jp/en/rss/whatsnew.xml +https://www.bankofengland.co.uk/rss/news +https://www.centralbanking.com/feeds/rss +https://oilprice.com/rss/ +https://www.spglobal.com/commodityinsights/en/rss +https://www.eia.gov/tools/rssfeeds/ +https://www.cmegroup.com/rss +https://globalvoices.org/-/topics/economics-business/feed/ +http://globalization.einnews.com/rss +https://financefeeds.com/feed/ +https://newsquawk.com/blog/feed.rss +https://www.coindesk.com/arc/outboundfeeds/rss/ +https://ishookfinance.com/feed/ +https://www.scmp.com/rss/92/feed +https://www.scmp.com/rss/93/feed +https://www.scmp.com/rss/94/feed +https://www.scmp.com/rss/317/feed +https://asia.nikkei.com/rss +https://www.caixin.com/rss/index_EN.xml +https://www.straitstimes.com/news/asia/rss.xml +https://www.straitstimes.com/business/rss.xml +https://www.reuters.com/arc/outboundfeeds/rss/?outputType=xml§ion=asia +https://www.reuters.com/arc/outboundfeeds/rss/?outputType=xml§ion=china +https://www.bloomberg.com/feeds/asia.rss +https://www.bloomberg.com/feeds/markets.rss +https://www.ft.com/asia-pacific?format=rss +https://www.ft.com/china?format=rss +https://english.kyodonews.net/rss/news.xml +https://en.yna.co.kr/RSS/news.xml +https://www.thejakartapost.com/rss/business +https://www.nationthailand.com/rss/business +https://www.aramco.com/api/v1/com/rss/news?sc_lang=en +https://www.worldoil.com/rss?feed=topic:saudi+arabia +https://www.worldoil.com/rss?feed=topic:iraq +https://www.worldoil.com/rss?feed=topic:uae +https://www.worldoil.com/rss?feed=topic:russia +https://www.worldoil.com/rss?feed=topic:canada +https://www.worldoil.com/rss?feed=topic:oil+sands +https://www.rigzone.com/news/europe_russia/production/rss/ +https://www.argusmedia.com/en/news-and-insights/latest-market-news/rss +https://www.eia.gov/rss/ +https://www.opec.org/opec_web/en/pressreleases.rss +https://www.opec.org +https://www.rosneft.com/press/news/rss/ +https://feeds.content.dowjones.io/public/rss/RSSMarketsMain +https://feeds.content.dowjones.io/public/rss/socialeconomyfeed +https://feeds.content.dowjones.io/public/rss/WSJcomUSBusiness +https://feeds.content.dowjones.io/public/rss/RSSWorldNews +http://feeds.feedburner.com/EconomicEventsAgriculture +http://feeds.feedburner.com/EconomicEventsEnergy +http://feeds.feedburner.com/EconomicEventsInterestRates +http://feeds.feedburner.com/mediaroom/CMsF +http://feeds.feedburner.com/CMEClearPortNoticesRss +http://feeds.feedburner.com/GlobexAdvisories +https://feeds.content.dowjones.io/public/rss/mw_topstories +https://feeds.content.dowjones.io/public/rss/mw_realtimeheadlines +http://feeds.marketwatch.com/marketwatch/bulletins +https://feeds.content.dowjones.io/public/rss/mw_marketpulse +https://www.nasdaqtrader.com/rss.aspx?feed=currentheadlines&categorylist=51 +https://www.nasdaqtrader.com/rss.aspx?feed=currentheadlines&categorylist=11 +https://www.investing.com/rss/stock_Options.rss +https://www.investing.com/rss/news_11.rss +https://www.investing.com/rss/news_25.rss +https://www.nasdaq.com/feed/rssoutbound?category=Markets +https://www.nasdaq.com/feed/rssoutbound?category=Commodities +https://www.barchart.com/news/rss/financials/options-news +https://www.barchart.com/news/rss/commodities/futures-news +https://www.spglobal.com/spdji/en/rss +https://www.litefinance.org/rss/analytics/ +https://www.mrt.com/arc/outboundfeeds/rss/category/business/oil/?outputType=xml +https://www.oaoa.com/category/local-news/inthepipeline/rss +https://pboilandgasmagazine.com/feed/ +https://www.rigzone.com/news/rss.asp +https://rbnenergy.com/blogcast.rss +https://www.eia.gov/rss/todayinenergy.xml +https://www.firstalert7.com/news/energy +https://www.energyvoice.com/feed/?category=oilandgas/north-sea +https://www.rigzone.com/news/rss/north_sea +https://www.oedigital.com/feeds/rss +https://www.sodir.no/en/whats-new/news/rss +https://www.worldoil.com/rss?feed=topic:offshore +https://oilandgas.einnews.com/rss/north-sea-offshore +https://www.energyvoice.com/feed/ diff --git a/news/summerizer/run_news_summarizer.py b/news/summerizer/run_news_summarizer.py index 91740c6..1032af7 100644 --- a/news/summerizer/run_news_summarizer.py +++ b/news/summerizer/run_news_summarizer.py @@ -1,14 +1,10 @@ #!/usr/bin/env python3 -"""Scheduler loop for the news summarizer — hourly summarize at minute :05. +"""Scheduler loop for the news summarizer — every NEWS_SUMMARIZE_INTERVAL_S. -Replaces the k8s CronJob (`5 * * * *`) with an in-compose loop. Runs once on -boot (catches up on any articles scraped since the last summary), then fires -at each :NEWS_SUMMARIZE_MINUTE wall-clock boundary. - -The loop is serial, so a slow LLM pass never overlaps the next run. +Default 900s (15 minutes). Serial: a slow LLM pass never overlaps the next. Env (all optional, 12-factor): - NEWS_SUMMARIZE_MINUTE minute of the hour to fire (default 5) + NEWS_SUMMARIZE_INTERVAL_S seconds between runs (default 900) NEWS_SUMMARIZE_RUN_ON_START "1" to summarize once immediately on boot (default 1) NOUS_API_KEY optional in env; Keys UI / api_keys also works """ @@ -25,17 +21,10 @@ import time logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s") logger = logging.getLogger("news.summarizer.scheduler") -MINUTE = int(os.getenv("NEWS_SUMMARIZE_MINUTE", "5")) +INTERVAL_S = max(1, int(os.getenv("NEWS_SUMMARIZE_INTERVAL_S", "900"))) RUN_ON_START = os.getenv("NEWS_SUMMARIZE_RUN_ON_START", "1").lower() in ("1", "true", "yes") -def seconds_until_next(minute: int) -> float: - """Seconds until the next occurrence of ``minute`` past the hour (local time).""" - now = datetime.datetime.now() - nxt = now.replace(minute=minute, second=0, microsecond=0) + datetime.timedelta(hours=1) - return (nxt - now).total_seconds() - - def run_summarize() -> None: logger.info("summarize starting at %s", datetime.datetime.now().isoformat(timespec="seconds")) try: @@ -51,15 +40,14 @@ def main() -> None: "NOUS_API_KEY unset in env — will read api_keys on each run; idle if both empty" ) logger.info( - "news summarizer loop starting (minute=%s, run_on_start=%s)", - MINUTE, RUN_ON_START, + "news summarizer loop starting (interval_s=%s, run_on_start=%s)", + INTERVAL_S, RUN_ON_START, ) if RUN_ON_START: run_summarize() while True: - delay = seconds_until_next(MINUTE) - logger.info("next summarize at :%02d (in %.0fs)", MINUTE, delay) - time.sleep(delay) + logger.info("next summarize in %ss", INTERVAL_S) + time.sleep(INTERVAL_S) run_summarize() diff --git a/news/summerizer/summarizer.py b/news/summerizer/summarizer.py index ea82a37..c57476f 100644 --- a/news/summerizer/summarizer.py +++ b/news/summerizer/summarizer.py @@ -1,7 +1,7 @@ #!/usr/bin/env python3 """News summarizer — Nous map-reduce of scraped articles into brief/ticker/map. -Reads articles scraped within the last hour from the shared `articles` table, +Reads articles scraped within the last SUMMARY_WINDOW_MINUTES from the shared `articles` table, maps them with Nous (per-article English fact blocks), reduces to one JSON object (summary_en + ticker + map_items), and stores the brief in `article_summaries` plus flagged rows in `news_items`. Tables live in the @@ -15,11 +15,8 @@ of each summarize_news() — env wins, else api_keys / app_settings: NOUS_BASE_URL default https://inference-api.nousresearch.com/v1 SUMMARY_MODEL default Hermes-4.3-36B (else app_settings) BATCH_SIZE articles per map-phase batch (default 50) - SUMMARY_WINDOW_HOURS look-back window in hours (default 1) - OSINT_USER_AGENT default osint-dashboard-news-summarizer - MAP_PROMPT override map-phase prompt (uses {batch_text}) - SUMMARY_PROMPT override reduce-phase prompt (uses {final_input}) - NEWS_SUMMARIZE_FORCE "1" to ignore the current-UTC-hour idempotency skip + SUMMARY_WINDOW_MINUTES look-back window (default 15; SUMMARY_WINDOW_HOURS wins if set) + NEWS_SUMMARIZE_FORCE "1" to ignore the interval idempotency skip INCLUDE_FUTURES "1" to prepend live futures prices (default 0) The futures/markets coupling from the original pipeline is gated behind @@ -54,7 +51,23 @@ DB_CONFIG = { DEFAULT_NOUS_BASE_URL = "https://inference-api.nousresearch.com/v1" DEFAULT_SUMMARY_MODEL = "Hermes-4.3-36B" BATCH_SIZE = int(os.getenv("BATCH_SIZE", "50")) -SUMMARY_WINDOW_HOURS = int(os.getenv("SUMMARY_WINDOW_HOURS", "1")) + + +def _summary_window_minutes() -> int: + hours = (os.getenv("SUMMARY_WINDOW_HOURS") or "").strip() + if hours: + return max(1, int(hours) * 60) + mins = (os.getenv("SUMMARY_WINDOW_MINUTES") or "").strip() + if mins: + return max(1, int(mins)) + return 15 + + +def _summarize_interval_seconds() -> int: + return max(1, int(os.getenv("NEWS_SUMMARIZE_INTERVAL_S", "900"))) + + +SUMMARY_WINDOW_MINUTES = _summary_window_minutes() INCLUDE_FUTURES = os.getenv("INCLUDE_FUTURES", "0").lower() in ("1", "true", "yes") # Only touched when INCLUDE_FUTURES=1 (legacy markets coupling, OSINT-off). @@ -282,18 +295,18 @@ def ensure_tables() -> None: def get_recent_news() -> list[dict]: - """Fetch articles from the last SUMMARY_WINDOW_HOURS (content > 100 chars).""" + """Fetch articles from the last SUMMARY_WINDOW_MINUTES (content > 100 chars).""" query = """ SELECT title, content, url, domain FROM articles - WHERE timestamp > NOW() - make_interval(hours => %s) + WHERE timestamp > NOW() - make_interval(mins => %s) AND content IS NOT NULL AND length(content) > 100 ORDER BY timestamp DESC; """ try: conn = psycopg2.connect(**DB_CONFIG) cur = conn.cursor() - cur.execute(query, (SUMMARY_WINDOW_HOURS,)) + cur.execute(query, (SUMMARY_WINDOW_MINUTES,)) rows = cur.fetchall() cur.close() conn.close() @@ -306,24 +319,24 @@ def get_recent_news() -> list[dict]: return [] -def _already_summarized_this_hour() -> bool: - """True when article_summaries already has a row for the current UTC hour.""" +def _already_summarized_this_interval() -> bool: + """True when article_summaries already has a row in the last interval.""" if os.getenv("NEWS_SUMMARIZE_FORCE", "") == "1": return False query = ( "SELECT 1 FROM article_summaries " - "WHERE batch_timestamp >= date_trunc('hour', NOW() AT TIME ZONE 'utc')" + "WHERE batch_timestamp >= NOW() - make_interval(secs => %s)" ) try: conn = psycopg2.connect(**DB_CONFIG) cur = conn.cursor() - cur.execute(query) + cur.execute(query, (_summarize_interval_seconds(),)) row = cur.fetchone() cur.close() conn.close() return row is not None except Exception as exc: # noqa: BLE001 - logger.error("Error checking hourly idempotency: %s", exc) + logger.error("Error checking interval idempotency: %s", exc) return False @@ -419,10 +432,11 @@ def build_master_prompt(final_input: str) -> str: def summarize_news() -> None: """Map-reduce summarize recent articles and store brief + ticker + map.""" ensure_tables() - if _already_summarized_this_hour(): + if _already_summarized_this_interval(): logger.info( - "Skipping summarize: article_summaries already has a row this UTC hour " - "(set NEWS_SUMMARIZE_FORCE=1 to override)" + "Skipping summarize: article_summaries already has a row in the last %ss " + "(set NEWS_SUMMARIZE_FORCE=1 to override)", + _summarize_interval_seconds(), ) return @@ -435,7 +449,7 @@ def summarize_news() -> None: articles = get_recent_news() if not articles: - logger.info("No new articles found in the last %sh.", SUMMARY_WINDOW_HOURS) + logger.info("No new articles found in the last %s min.", SUMMARY_WINDOW_MINUTES) return logger.info( From ca15885e7f9aba771c47c2d8b832d34df43ed071 Mon Sep 17 00:00:00 2001 From: Sirius DevOps Date: Fri, 28 Aug 2026 21:00:20 -0400 Subject: [PATCH 18/79] feat: classify aircraft/vessels as military vs civilian in popups Aircraft: readsb dbFlags bit0, then ICAO combat types / US-DoD hex / callsign. Popup shows type, operator, alt, vs, squawk, emitter class. Vessels: ITU ship type 35 = military, 50/51/55 = government; cargo/ tanker/passenger/etc otherwise. Popup shows kind, flag, dest, nav, IMO, size. Magenta glyphs = military, gold = law/gov. --- app/live_layers.py | 256 ++++++++++++++++++++++++++++++++++++-- app/static/index.html | 94 ++++++++++++-- tests/test_live_layers.py | 110 ++++++++++++++++ 3 files changed, 435 insertions(+), 25 deletions(-) diff --git a/app/live_layers.py b/app/live_layers.py index e5b9f0e..f3e15eb 100644 --- a/app/live_layers.py +++ b/app/live_layers.py @@ -309,6 +309,204 @@ def _heading(value: object) -> float | None: return num +def _s(value: object) -> str | None: + if value is None: + return None + text = str(value).strip() + return text or None + + +# ADS-B emitter category (DO-260B). A3 airliners, A5 heavies, A7 helicopters. +_EMITTER = { + "A0": "unknown", "A1": "light", "A2": "small", "A3": "large", + "A4": "high vortex", "A5": "heavy", "A6": "high performance", "A7": "rotorcraft", + "B0": "unknown", "B1": "glider", "B2": "airship", "B3": "parachute", + "B4": "ultralight", "B6": "UAV", "B7": "space", + "C0": "ground unknown", "C1": "emergency vehicle", "C2": "service vehicle", + "D0": "unknown", "D1": "emergency", +} + +# Combat / dedicated-military ICAO types. C-130/C-17 omitted — those also fly +# as fire tankers and civil contractors; dbFlags/hex catch the real mil ones. +_MIL_ICAO = frozenset({ + "F15", "F16", "F18", "FA18", "F22", "F35", "F117", "A10", "A10A", + "B1", "B1B", "B2", "B52", "AV8B", "F4", "F5", "F14", + "SU27", "SU30", "SU34", "SU35", "SU57", + "MG29", "MIG29", "MG31", "MIG31", "J10", "J11", "J15", "J16", "J20", + "EUFI", "RFAL", "TOR", "E3TF", "E3CF", "E6", "E8", "P8", + "MQ9", "MQ1", "RQ4", "V22", "AH64", "H64", +}) + +# US DoD Mode-S block AE0000–AEFFFF. +_US_DOD_HEX_LO, _US_DOD_HEX_HI = 0xAE0000, 0xAEFFFF + +_MIL_CS_PREFIX = ("RCH", "NAVY", "ARMY", "MARINE", "GOTOF", "REACH") + + +def classify_adsb(ac: dict) -> tuple[str, str]: + """Return (role, role_src). Prefer readsb dbFlags bit0, then type/hex/cs.""" + flags = ac.get("dbFlags") + try: + flags_i = int(flags) if flags is not None else 0 + except (TypeError, ValueError): + flags_i = 0 + if flags_i & 1: + return "military", "dbFlags" + icao = str(ac.get("t") or "").strip().upper() + if icao in _MIL_ICAO: + return "military", "type" + try: + hx = int(str(ac.get("hex") or "").strip(), 16) + except ValueError: + hx = -1 + if _US_DOD_HEX_LO <= hx <= _US_DOD_HEX_HI: + return "military", "hex" + cs = str(ac.get("flight") or "").strip().upper() + if cs.startswith(_MIL_CS_PREFIX): + return "military", "callsign" + return "civilian", "default" + + +def _adsb_extra(ac: dict, hex_id: str) -> dict[str, Any]: + role, src = classify_adsb(ac) + cat = str(ac.get("category") or "").strip().upper() + extra: dict[str, Any] = { + "hex": hex_id, + "reg": _s(ac.get("r")), + "type": _s(ac.get("t")), + "alt_baro": ac.get("alt_baro"), + "squawk": _s(ac.get("squawk")), + "emergency": _s(ac.get("emergency")), + "category": cat or None, + "emitter": _EMITTER.get(cat), + "seen_pos": ac.get("seen_pos"), + "role": role, + "role_src": src, + "src": "adsb.lol", + } + desc = _s(ac.get("desc")) + if desc: + extra["desc"] = desc + own = _s(ac.get("ownOp") or ac.get("ownOpName") or ac.get("ownop")) + if own: + extra["ownOp"] = own + if ac.get("alt_geom") is not None: + extra["alt_geom"] = ac.get("alt_geom") + vs = ac.get("baro_rate") + if vs is None: + vs = ac.get("geom_rate") + if vs is not None: + extra["vs"] = vs + try: + raw_flags = ac.get("dbFlags") + flags_i = int(raw_flags) if raw_flags is not None else 0 + except (TypeError, ValueError): + flags_i = 0 + if flags_i: + extra["dbFlags"] = flags_i + extra["interesting"] = bool(flags_i & 2) + return extra + + +_NAVSTAT = { + 0: "underway", + 1: "at anchor", + 2: "not under command", + 3: "restricted manoeuvre", + 4: "constrained by draught", + 5: "moored", + 6: "aground", + 7: "fishing", + 8: "sailing", + 14: "AIS-SART", + 15: "undefined", +} + +# Compact MID → country for the flags that actually show up on AIS. +_MID_COUNTRY = { + 211: "Germany", 218: "Germany", + 219: "Denmark", 220: "Denmark", + 224: "Spain", 225: "Spain", + 226: "France", 227: "France", 228: "France", + 232: "United Kingdom", 233: "United Kingdom", 234: "United Kingdom", 235: "United Kingdom", + 236: "Gibraltar", 237: "Greece", 239: "Greece", 240: "Greece", 241: "Greece", + 244: "Netherlands", 245: "Netherlands", 246: "Netherlands", + 247: "Italy", 249: "Malta", 250: "Ireland", 251: "Iceland", + 255: "Portugal", 256: "Malta", + 257: "Norway", 258: "Norway", 259: "Norway", + 261: "Poland", 263: "Portugal", 265: "Sweden", 266: "Sweden", + 271: "Turkey", 273: "Russia", 276: "Estonia", 277: "Lithuania", + 301: "Anguilla", 303: "United States", 310: "Bermuda", 316: "Canada", + 319: "Cayman Islands", 338: "United States", 339: "Jamaica", + 345: "Mexico", 352: "Panama", 353: "Panama", 354: "Panama", + 355: "Panama", 356: "Panama", 357: "Panama", + 366: "United States", 367: "United States", 368: "United States", 369: "United States", + 370: "Panama", 371: "Panama", 372: "Panama", 373: "Panama", 374: "Panama", + 375: "St Vincent", 376: "St Vincent", 377: "St Vincent", + 412: "China", 413: "China", 414: "China", 416: "Taiwan", + 419: "India", 431: "Japan", 432: "Japan", 440: "South Korea", 441: "South Korea", + 477: "Hong Kong", 503: "Australia", 525: "Indonesia", 533: "Malaysia", + 538: "Marshall Islands", 548: "Philippines", 563: "Singapore", + 564: "Singapore", 565: "Singapore", 566: "Singapore", 567: "Thailand", + 574: "Vietnam", 636: "Liberia", 637: "Liberia", + 710: "Brazil", 725: "Chile", 730: "Colombia", 760: "Peru", +} + + +def _mmsi_country(mmsi: object) -> str | None: + digits = "".join(ch for ch in str(mmsi or "") if ch.isdigit()) + if len(digits) < 3: + return None + try: + mid = int(digits[:3]) + except ValueError: + return None + return _MID_COUNTRY.get(mid) + + +def classify_ais_type(type_code: int | None) -> tuple[str, str]: + """Return (role, kind) from ITU-R M.1371 ship-and-cargo type.""" + if type_code is None: + return "civilian", "unknown" + t = int(type_code) + tens = t // 10 + if t == 35: + return "military", "military" + if t == 30: + return "civilian", "fishing" + if t in (31, 32, 52): + return "civilian", "tug" + if t == 33: + return "civilian", "dredger" + if t == 34: + return "civilian", "diving" + if t == 36: + return "civilian", "sailing" + if t == 37: + return "civilian", "pleasure" + if t == 50: + return "government", "pilot" + if t == 51: + return "government", "SAR" + if t == 55: + return "government", "law" + if t == 54: + return "government", "anti-pollution" + if t == 58: + return "government", "medical" + if tens == 4: + return "civilian", "HSC" + if tens == 6: + return "civilian", "passenger" + if tens == 7: + return "civilian", "cargo" + if tens == 8: + return "civilian", "tanker" + if tens in (5, 9) or t in (53, 56, 57, 59): + return "civilian", "special" + return "civilian", "other" + + def transform_adsb_lol(payload: dict | list | None) -> list[dict]: """Map ADSB.lol v2 aircraft list to shared markers. Dedup on hex.""" if payload is None: @@ -333,17 +531,7 @@ def transform_adsb_lol(payload: dict | list | None) -> list[dict]: heading=_heading(ac.get("track")), speed=_f(ac.get("gs")), label=flight, - extra={ - "hex": hex_id, - "reg": ac.get("r"), - "type": ac.get("t"), - "alt_baro": ac.get("alt_baro"), - "squawk": ac.get("squawk"), - "emergency": ac.get("emergency"), - "category": ac.get("category"), - "seen_pos": ac.get("seen_pos"), - "src": "adsb.lol", - }, + extra=_adsb_extra(ac, hex_id), )) return out @@ -405,6 +593,9 @@ def transform_ais_frame(frame: dict | None) -> dict | None: or {} ) extra: dict[str, Any] = {"src": "aisstream", "mmsi": mmsi} + country = _mmsi_country(mmsi) + if country: + extra["country"] = country if frame.get("MessageType") == "ShipStaticData": static = msg.get("ShipStaticData") or {} dest = str(static.get("Destination") or static.get("destination") or "").strip() @@ -412,6 +603,42 @@ def transform_ais_frame(frame: dict | None) -> dict | None: extra["static"] = True if not name: name = str(static.get("Name") or static.get("name") or "").strip() + cs = _s(static.get("CallSign") or static.get("callSign")) + if cs: + extra["callsign"] = cs + try: + imo = int(static.get("ImoNumber") or static.get("imoNumber") or 0) + except (TypeError, ValueError): + imo = 0 + if imo: + extra["imo"] = imo + type_code = static.get("Type") if "Type" in static else static.get("type") + try: + type_i = int(type_code) if type_code is not None else None + except (TypeError, ValueError): + type_i = None + if type_i is not None: + extra["type_code"] = type_i + role, kind = classify_ais_type(type_i) + extra["role"] = role + extra["kind"] = kind + dim = static.get("Dimension") or static.get("dimension") or {} + if isinstance(dim, dict): + a, b = _f(dim.get("A")), _f(dim.get("B")) + c, d = _f(dim.get("C")), _f(dim.get("D")) + if a is not None and b is not None: + extra["length"] = int(round(a + b)) + if c is not None and d is not None: + extra["beam"] = int(round(c + d)) + draught = _f(static.get("MaximumStaticDraught") or static.get("maximumStaticDraught")) + if draught is not None: + extra["draught"] = draught + eta = static.get("Eta") or static.get("eta") or {} + if isinstance(eta, dict) and eta.get("Month"): + extra["eta"] = ( + f"{int(eta.get('Month') or 0):02d}-{int(eta.get('Day') or 0):02d} " + f"{int(eta.get('Hour') or 0):02d}:{int(eta.get('Minute') or 0):02d}" + ) if lat is None or lon is None: # Static-only update: caller merges onto last-known by MMSI. return to_marker(str(mmsi), None, None, label=name or str(mmsi), extra=extra) @@ -421,8 +648,13 @@ def transform_ais_frame(frame: dict | None) -> dict | None: sog = pos.get("Sog") navstat = pos.get("NavigationalStatus") extra["navstat"] = navstat + try: + extra["nav"] = _NAVSTAT.get(int(navstat)) if navstat is not None else None + except (TypeError, ValueError): + extra["nav"] = None extra["cog"] = pos.get("Cog") - extra["dest"] = extra.get("dest") + if not extra.get("dest"): + extra.pop("dest", None) if lat is None or lon is None: return None return to_marker( diff --git a/app/static/index.html b/app/static/index.html index 0226c13..447e8b3 100644 --- a/app/static/index.html +++ b/app/static/index.html @@ -356,6 +356,16 @@ .cam-pop td { padding: 0.12rem 0.2rem; vertical-align: top; } .cam-pop td.k { color: var(--muted); text-transform: uppercase; font-size: 0.6rem; letter-spacing: 0.05em; white-space: nowrap; width: 34%; font-family: 'Share Tech Mono', monospace; } .cam-pop a { color: var(--cyan); word-break: break-all; } + .role-badge { + display: inline-block; font-family: 'Share Tech Mono', monospace; + font-size: 0.58rem; font-weight: 700; letter-spacing: 0.12em; + padding: 0.08rem 0.4rem; border-radius: 3px; margin-left: 0.4rem; + vertical-align: middle; + } + .role-badge.military { color: #f472b6; border: 1px solid #f472b6; background: rgba(244,114,182,0.12); } + .role-badge.civilian { color: #7dd3fc; border: 1px solid #38bdf8; background: rgba(56,189,248,0.1); } + .role-badge.government { color: #facc15; border: 1px solid #facc15; background: rgba(250,204,21,0.12); } + .role-badge.firefighter { color: #fb923c; border: 1px solid #fb923c; background: rgba(251,146,60,0.12); } .blip-pop { min-width: 200px; max-width: 260px; } .blip-pop .blip-src { font-family: 'Share Tech Mono', monospace; font-size: 0.62rem; color: var(--cyan); text-transform: uppercase; letter-spacing: 0.08em; } .blip-pop .blip-time { font-size: 0.7rem; color: var(--muted); font-family: 'Share Tech Mono', monospace; margin: 0.2rem 0 0.3rem; } @@ -771,6 +781,7 @@ 0
+
Magenta = military · orange = firefighting · else altitude. Click a plane for type / squawk / operator.
@@ -784,7 +795,7 @@ 0
-
Needs AISSTREAM_API_KEY in Keys.
+
Needs AISSTREAM_API_KEY. Magenta = military · gold = law/gov · teal = underway. Click for type / dest / IMO.
@@ -1855,9 +1866,13 @@ function applyLiveMarker(kind, p) { } } function acColor(p) { - const t = String(((p.extra || {}).type || '')).toUpperCase(); - if ((p.extra || {}).firefighter || firefighterHex.has(String(p.id)) || FF_ICAO.has(t)) return '#fb923c'; - return altColor((p.extra || {}).alt_baro); + const extra = p.extra || {}; + const t = String(extra.type || '').toUpperCase(); + const em = String(extra.emergency || '').toLowerCase(); + if (em && em !== 'none') return '#ff5d5d'; + if (extra.firefighter || firefighterHex.has(String(p.id)) || FF_ICAO.has(t)) return '#fb923c'; + if (extra.role === 'military') return '#f472b6'; + return altColor(extra.alt_baro); } function connectLiveWs() { if (liveWs && (liveWs.readyState === 0 || liveWs.readyState === 1)) return; @@ -2563,12 +2578,57 @@ function altColor(alt) { if (a >= 1000) return '#fbbf24'; return '#fb923c'; } +function _popVal(v) { + if (v == null || v === '' || v === 'none' || v === 'undefined') return null; + return v; +} function pointPopup(p) { const extra = p.extra || {}; - const rows = Object.keys(extra).filter(k => k !== 'stations' && extra[k] != null && extra[k] !== '') - .slice(0, 8) - .map(k => `${esc(k)}${esc(extra[k])}`).join(''); - return `
${esc(p.label || p.id)}${rows}
`; + const src = extra.src || ''; + const role = extra.firefighter ? 'firefighter' : extra.role; + const badge = role + ? ` ${esc(String(role).toUpperCase())}` + : ''; + const rows = []; + const add = (k, v) => { + const val = _popVal(v); + if (val == null) return; + rows.push(`${esc(k)}${esc(val)}`); + }; + if (src === 'adsb.lol') { + add('type', extra.type); + add('aircraft', extra.desc); + add('operator', extra.ownOp); + add('reg', extra.reg); + const alt = extra.alt_baro; + add('alt', alt != null ? `${alt} ft` : null); + add('vs', extra.vs != null ? `${extra.vs} fpm` : null); + add('gs', p.speed != null ? `${p.speed} kt` : null); + add('hdg', p.heading != null ? `${Math.round(p.heading)}°` : null); + add('squawk', extra.squawk); + add('emergency', extra.emergency); + add('class', extra.emitter); + add('hex', extra.hex); + } else if (src === 'aisstream') { + add('kind', extra.kind); + add('flag', extra.country); + add('dest', extra.dest); + add('nav', extra.nav); + add('callsign', extra.callsign); + add('imo', extra.imo); + add('mmsi', extra.mmsi); + if (extra.length && extra.beam) add('size', `${extra.length} × ${extra.beam} m`); + else add('length', extra.length != null ? `${extra.length} m` : null); + add('draught', extra.draught != null ? `${extra.draught} m` : null); + add('sog', p.speed != null ? `${p.speed} kt` : null); + add('hdg', p.heading != null ? `${Math.round(p.heading)}°` : null); + add('eta', extra.eta); + } else { + Object.keys(extra).filter(k => k !== 'stations' && extra[k] != null && extra[k] !== '') + .slice(0, 8) + .forEach(k => add(k, extra[k])); + } + return `
${esc(p.label || p.id)}${badge}${rows.join('')}
`; } /* ── Heading-aware live-feed glyph markers ─────────────────────────────── @@ -2617,15 +2677,19 @@ function feedIcon(feed, color, heading) { function makePointMarker(p, colorFn, feed, renderer) { if (p.lat == null || p.lon == null) return null; const col = sanitizeColor(colorFn(p), '#35e0ff'); + let m; if (feed) { const heading = Number(p.heading); const icon = feedIcon(feed, col, Number.isNaN(heading) ? null : heading); - return L.marker([p.lat, p.lon], { icon }).bindPopup(() => pointPopup(p)); + m = L.marker([p.lat, p.lon], { icon }); + } else { + m = L.circleMarker([p.lat, p.lon], { + radius: 5, color: col, fillColor: col, fillOpacity: 0.9, weight: 1, + renderer, + }); } - return L.circleMarker([p.lat, p.lon], { - radius: 5, color: col, fillColor: col, fillOpacity: 0.9, weight: 1, - renderer, - }).bindPopup(() => pointPopup(p)); + m._osintP = p; + return m.bindPopup(() => pointPopup(m._osintP || p)); } function renderPoints(existing, points, colorFn, cluster, feed) { const zoom = map.getZoom(); @@ -2662,6 +2726,7 @@ function renderPoints(existing, points, colorFn, cluster, feed) { const m = byId.get(id); if (m) { m.setLatLng([p.lat, p.lon]); + m._osintP = p; if (feed) m.setIcon(feedIcon(feed, col, p.heading)); else if (m.setStyle) m.setStyle({ color: col, fillColor: col }); } else { @@ -2920,6 +2985,9 @@ async function loadVessels() { const pts = await r.json(); if (req !== overlayReq.vessels) return; vesselsGroup = renderPoints(vesselsGroup, Array.isArray(pts) ? pts : [], p => { + const extra = p.extra || {}; + if (extra.role === 'military') return '#f472b6'; + if (extra.role === 'government') return '#facc15'; const sog = Number((p.speed) || 0); return sog > 0.5 ? '#2dd4bf' : '#64748b'; }, true, 'vessel'); diff --git a/tests/test_live_layers.py b/tests/test_live_layers.py index fedf6dd..0a1bf1b 100644 --- a/tests/test_live_layers.py +++ b/tests/test_live_layers.py @@ -362,3 +362,113 @@ def test_wfigs_params_requests_simplified_geometry(): # Envelope is the quantized cell, not the raw pan box. geom = params["geometry"] assert geom != "-84.5,33.8,-75.4,36.6" + + +def test_transform_adsb_lol_flags_military_from_dbflags(): + payload = { + "ac": [ + { + "hex": "ae01ab", + "flight": "RCH123 ", + "r": "04-1234", + "t": "C17", + "lat": 35.1, + "lon": -77.9, + "alt_baro": 24000, + "gs": 410, + "track": 90, + "squawk": "5101", + "emergency": "none", + "category": "A5", + "dbFlags": 1, + "baro_rate": 64, + "alt_geom": 24500, + "desc": "Boeing C-17A Globemaster III", + "ownOp": "USAF", + }, + { + "hex": "a1b2c3", + "flight": "AAL123", + "r": "N123AA", + "t": "B738", + "lat": 35.88, + "lon": -78.79, + "alt_baro": 32000, + "gs": 430, + "track": 87, + "squawk": "1200", + "emergency": "none", + "category": "A3", + }, + ] + } + rows = {r["id"]: r for r in transform_adsb_lol(payload)} + mil = rows["ae01ab"]["extra"] + civ = rows["a1b2c3"]["extra"] + assert mil["role"] == "military" + assert mil["role_src"] == "dbFlags" + assert mil["emitter"] == "heavy" + assert mil["desc"] == "Boeing C-17A Globemaster III" + assert mil["ownOp"] == "USAF" + assert mil["vs"] == 64 + assert mil["alt_geom"] == 24500 + assert civ["role"] == "civilian" + assert civ["emitter"] == "large" + + +def test_transform_adsb_lol_military_from_icao_type_and_hex(): + payload = { + "ac": [ + {"hex": "3b76aa", "flight": "FAF123", "t": "F16", "lat": 1, "lon": 2, "category": "A1"}, + {"hex": "ae1234", "flight": "BOXER1", "t": "C172", "lat": 1, "lon": 2, "category": "A1"}, + ] + } + rows = {r["id"]: r for r in transform_adsb_lol(payload)} + assert rows["3b76aa"]["extra"]["role"] == "military" + assert rows["3b76aa"]["extra"]["role_src"] == "type" + assert rows["ae1234"]["extra"]["role"] == "military" + assert rows["ae1234"]["extra"]["role_src"] == "hex" + + +def test_transform_ais_static_classifies_military_and_cargo(): + mil = transform_ais_frame({ + "MessageType": "ShipStaticData", + "MetaData": {"MMSI": 338123456, "ShipName": "USNS BOB", "Latitude": 32.7, "Longitude": -117.2}, + "Message": {"ShipStaticData": { + "Type": 35, "CallSign": "NBXX", "ImoNumber": 0, + "Destination": "SAN DIEGO", "MaximumStaticDraught": 8.2, + "Dimension": {"A": 80, "B": 20, "C": 8, "D": 8}, + "Eta": {"Month": 8, "Day": 29, "Hour": 14, "Minute": 0}, + }}, + }) + cargo = transform_ais_frame({ + "MessageType": "ShipStaticData", + "MetaData": {"MMSI": 477123456, "ShipName": "EVER GIVEN", "Latitude": 36.9, "Longitude": -76.3}, + "Message": {"ShipStaticData": { + "Type": 70, "CallSign": "VRXX", "ImoNumber": 9811000, + "Destination": "NORFOLK", "MaximumStaticDraught": 14.5, + "Dimension": {"A": 200, "B": 150, "C": 20, "D": 20}, + }}, + }) + assert mil is not None and cargo is not None + assert mil["extra"]["role"] == "military" + assert mil["extra"]["kind"] == "military" + assert mil["extra"]["callsign"] == "NBXX" + assert mil["extra"]["length"] == 100 + assert mil["extra"]["beam"] == 16 + assert mil["extra"]["dest"] == "SAN DIEGO" + assert mil["extra"]["country"] == "United States" + assert cargo["extra"]["role"] == "civilian" + assert cargo["extra"]["kind"] == "cargo" + assert cargo["extra"]["imo"] == 9811000 + + +def test_transform_ais_position_decodes_navstat(): + row = transform_ais_frame({ + "MessageType": "PositionReport", + "MetaData": {"MMSI": 366912810, "ShipName": "EVER GIVEN", "latitude": 36.9, "longitude": -76.3}, + "Message": {"PositionReport": {"Sog": 0.1, "Cog": 88.0, "TrueHeading": 90, "NavigationalStatus": 5}}, + }) + assert row is not None + assert row["extra"]["nav"] == "moored" + assert row["extra"]["navstat"] == 5 From d81ea68dec44d16293984ab34b2581060f31eeed Mon Sep 17 00:00:00 2001 From: Sirius DevOps Date: Fri, 28 Aug 2026 21:49:05 -0400 Subject: [PATCH 19/79] =?UTF-8?q?fix:=20pipeline=20reliability=20=E2=80=94?= =?UTF-8?q?=20WS,=20summarizer,=20ingest,=20health?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Stop the live HUD reconnect storm (nginx WS snippet + backoff), copy intel/nous_client into the summarizer image, and make event ingest idempotent on URL. GDELT uses the DOC API; NWS no longer sends bbox; FIRMS is one ON CONFLICT batch; GET /api/aircraft serves last-known. Health reports freshness without 503ing docker. EONET + CISA KEV added. --- alembic/versions/007_event_dedup.py | 115 +++++++ app/fire_sources.py | 12 +- app/ingestor.py | 58 +++- app/live_layers.py | 53 +++- app/main.py | 111 ++++++- app/models.py | 9 + app/run_ingester.py | 16 +- app/sources.py | 294 ++++++++++++++---- app/static/index.html | 39 ++- app/ws_manager.py | 3 + deploy/osint-ws.nginx.conf | 23 ++ news/scraper/newsScraper/feed_util.py | 32 ++ news/scraper/newsScraper/pipelines.py | 21 +- .../newsScraper/spiders/news_spider.py | 6 +- news/summerizer/Dockerfile | 2 +- pytest.ini | 3 + tests/test_cache_and_timeline.py | 21 ++ tests/test_event_ingest.py | 133 ++++++++ tests/test_fire_ingest.py | 44 +++ tests/test_fire_sources.py | 2 +- tests/test_frontend_reliability.py | 44 +++ tests/test_health_ready.py | 33 ++ tests/test_live_layers.py | 100 ++++++ tests/test_new_sources.py | 66 ++++ tests/test_news_scraper.py | 42 +++ tests/test_upstream_cache.py | 2 +- 26 files changed, 1169 insertions(+), 115 deletions(-) create mode 100644 alembic/versions/007_event_dedup.py create mode 100644 deploy/osint-ws.nginx.conf create mode 100644 news/scraper/newsScraper/feed_util.py create mode 100644 pytest.ini create mode 100644 tests/test_cache_and_timeline.py create mode 100644 tests/test_event_ingest.py create mode 100644 tests/test_frontend_reliability.py create mode 100644 tests/test_health_ready.py create mode 100644 tests/test_new_sources.py create mode 100644 tests/test_news_scraper.py diff --git a/alembic/versions/007_event_dedup.py b/alembic/versions/007_event_dedup.py new file mode 100644 index 0000000..f9b01e6 --- /dev/null +++ b/alembic/versions/007_event_dedup.py @@ -0,0 +1,115 @@ +"""event_dedup + Timescale compression/retention + +Revision ID: 007_event_dedup +Revises: 006_merge_heads +Create Date: 2026-08-28 +""" + +from alembic import op + +revision = "007_event_dedup" +down_revision = "006_merge_heads" +branch_labels = None +depends_on = None + + +def upgrade() -> None: + op.execute(""" + CREATE TABLE IF NOT EXISTS event_dedup ( + url TEXT PRIMARY KEY, + created_at TIMESTAMPTZ NOT NULL DEFAULT now() + ) + """) + + # Keep the earliest row per URL, drop the 10× USGS/camera dupes. + op.execute(""" + DELETE FROM events a + USING events b + WHERE a.url IS NOT NULL AND a.url <> '' + AND a.url = b.url + AND (a.ingested_at, a.id) > (b.ingested_at, b.id) + """) + op.execute(""" + INSERT INTO event_dedup (url) + SELECT DISTINCT url FROM events + WHERE url IS NOT NULL AND url <> '' + ON CONFLICT (url) DO NOTHING + """) + + # Compression + retention. Policies no-op if Timescale rejects (fresh PG). + op.execute(""" + DO $$ + BEGIN + PERFORM add_compression_policy('events', INTERVAL '7 days', if_not_exists => TRUE); + EXCEPTION WHEN OTHERS THEN + BEGIN + ALTER TABLE events SET ( + timescaledb.compress, + timescaledb.compress_segmentby = 'source_type', + timescaledb.compress_orderby = 'ingested_at DESC' + ); + PERFORM add_compression_policy('events', INTERVAL '7 days', if_not_exists => TRUE); + EXCEPTION WHEN OTHERS THEN + NULL; + END; + END + $$; + """) + op.execute(""" + DO $$ + BEGIN + PERFORM add_retention_policy('events', INTERVAL '180 days', if_not_exists => TRUE); + EXCEPTION WHEN OTHERS THEN + NULL; + END + $$; + """) + op.execute(""" + DO $$ + BEGIN + ALTER TABLE fires SET ( + timescaledb.compress, + timescaledb.compress_segmentby = 'satellite', + timescaledb.compress_orderby = 'acq_time DESC' + ); + PERFORM add_compression_policy('fires', INTERVAL '7 days', if_not_exists => TRUE); + PERFORM add_retention_policy('fires', INTERVAL '90 days', if_not_exists => TRUE); + EXCEPTION WHEN OTHERS THEN + NULL; + END + $$; + """) + op.execute(""" + DO $$ + BEGIN + ALTER TABLE aircraft_positions SET ( + timescaledb.compress, + timescaledb.compress_segmentby = 'hex', + timescaledb.compress_orderby = 'ts DESC' + ); + PERFORM add_compression_policy('aircraft_positions', INTERVAL '1 day', if_not_exists => TRUE); + PERFORM add_retention_policy('aircraft_positions', INTERVAL '14 days', if_not_exists => TRUE); + EXCEPTION WHEN OTHERS THEN + NULL; + END + $$; + """) + op.execute(""" + DO $$ + BEGIN + ALTER TABLE vessel_positions SET ( + timescaledb.compress, + timescaledb.compress_segmentby = 'mmsi', + timescaledb.compress_orderby = 'ts DESC' + ); + PERFORM add_compression_policy('vessel_positions', INTERVAL '1 day', if_not_exists => TRUE); + PERFORM add_retention_policy('vessel_positions', INTERVAL '14 days', if_not_exists => TRUE); + EXCEPTION WHEN OTHERS THEN + NULL; + END + $$; + """) + + +def downgrade() -> None: + op.execute("DROP TABLE IF EXISTS event_dedup") diff --git a/app/fire_sources.py b/app/fire_sources.py index 5faedd2..c27b0f7 100644 --- a/app/fire_sources.py +++ b/app/fire_sources.py @@ -162,6 +162,16 @@ async def publish_fire_batch(points: list[dict]) -> int: return len(points) +async def persist_hotspots(points: list[dict]) -> int: + """Write a FIRMS poll to Postgres in one ON CONFLICT batch. + + NATS-per-row was 93k commits + geofence/correlation per hotspot. + """ + from ingestor import ingest_fire_rows + + return await ingest_fire_rows(points) + + async def ingest_fires(bbox: str | None = None) -> int: """Fetch the FIRMS hotspot CSV for an area and publish it to NATS. @@ -206,7 +216,7 @@ async def ingest_fires(bbox: str | None = None) -> int: ) continue points = parse_firms_csv(text) - published = await publish_fire_batch(points) + published = await persist_hotspots(points) total_published += published logger.info( "FIRMS: fetched %d hotspot(s) for bbox=%s (%s), published %d", diff --git a/app/ingestor.py b/app/ingestor.py index 54d49cb..8d7eb97 100644 --- a/app/ingestor.py +++ b/app/ingestor.py @@ -14,7 +14,9 @@ from sqlalchemy.dialects.postgresql import insert as pg_insert from database import async_session from models import events as events_table from models import fires as fires_table +from models import event_dedup as event_dedup_table from config import NATS_URL +from sources import event_dedup_key logger = logging.getLogger("osint.ingestor") @@ -115,6 +117,42 @@ async def ingest_fire_row(msg: dict) -> bool: return inserted +async def ingest_fire_rows(msgs: list[dict]) -> int: + """Bulk-insert FIRMS hotspots: one INSERT, one ON CONFLICT, one commit.""" + rows = [] + for msg in msgs: + row = _fire_row_from_msg(msg) + if row is not None: + rows.append(row) + if not rows: + return 0 + async with async_session() as session: + stmt = ( + pg_insert(fires_table) + .values(rows) + .on_conflict_do_nothing(constraint="pk_fires_natural_key") + ) + result = await session.execute(stmt) + await session.commit() + inserted = int(result.rowcount or 0) + if inserted: + logger.info("bulk ingested %d/%d FIRMS hotspots", inserted, len(rows)) + from live_layers import aircraft_last_known + from fire_aircraft import correlate_and_notify + from tracks import recent_markers + acs = list(aircraft_last_known.values()) or await recent_markers("aircraft") + if acs: + fires = [ + { + "id": f"firms:{r['latitude']:.4f},{r['longitude']:.4f}", + "lat": r["latitude"], "lon": r["longitude"], "label": "FIRMS", + } + for r in rows[:500] + ] + await correlate_and_notify(fires, acs) + return inserted + + async def ingest_event(msg: dict): """Ingest a single event from NATS into PostgreSQL.""" # Active fire/hotspot messages carry a dedicated schema and land in the @@ -149,10 +187,26 @@ async def ingest_event(msg: dict): } # Parse timestamp if string - if isinstance(event_row["source_timestamp"], str): - event_row["source_timestamp"] = datetime.fromisoformat(event_row["source_timestamp"]) + ts = event_row["source_timestamp"] + if isinstance(ts, str): + ts = datetime.fromisoformat(ts.replace("Z", "+00:00")) + if isinstance(ts, datetime) and ts.tzinfo is None: + ts = ts.replace(tzinfo=timezone.utc) + event_row["source_timestamp"] = ts + key = event_dedup_key(event_row) async with async_session() as session: + if key: + dedup = ( + pg_insert(event_dedup_table) + .values(url=key) + .on_conflict_do_nothing(index_elements=["url"]) + ) + claimed = await session.execute(dedup) + if not claimed.rowcount: + await session.commit() + logger.info("skip duplicate event url=%s", key) + return None result = await session.execute(events_table.insert().values(**event_row)) await session.commit() event_id = result.inserted_primary_key[0] # type: ignore[union-attr] diff --git a/app/live_layers.py b/app/live_layers.py index f3e15eb..db1c0f7 100644 --- a/app/live_layers.py +++ b/app/live_layers.py @@ -12,6 +12,7 @@ or AIS poll. from __future__ import annotations import asyncio +import logging import math import time from datetime import datetime, timezone @@ -21,6 +22,8 @@ import httpx from config import OSINT_USER_AGENT +logger = logging.getLogger("osint.live_layers") + MARKER_FIELDS = ("id", "lat", "lon", "heading", "speed", "label", "extra") ADSB_LOL_BASE = "https://api.adsb.lol" @@ -800,8 +803,24 @@ async def _get_json(url: str, params: dict | None = None) -> Any: return resp.json() -async def fetch_aircraft(bbox: str, limit: int = DEFAULT_LIMIT) -> list[dict]: +async def fetch_aircraft( + bbox: str, limit: int = DEFAULT_LIMIT, persist: bool = False, +) -> list[dict]: + """Viewport ADS-B. + + GET path (persist=False) serves in-memory last-known and never writes + tracks/geofences. Background refresh (persist=True) hits ADSB.lol and + then persist_aircraft_snapshot. + """ minlon, minlat, maxlon, maxlat = parse_bbox(bbox) + if not persist: + cached = [ + dict(v) for v in aircraft_last_known.values() + if v.get("lat") is not None and v.get("lon") is not None + ] + filtered = filter_points_bbox(cached, minlon, minlat, maxlon, maxlat, limit) + if filtered: + return filtered qminlon, qminlat, qmaxlon, qmaxlat = quantize_bbox(minlon, minlat, maxlon, maxlat) lat, lon, radius = bbox_center_radius_nm(qminlon, qminlat, qmaxlon, qmaxlat) cache_key = f"adsb:{lat:.2f}:{lon:.2f}:{radius}" @@ -811,12 +830,20 @@ async def fetch_aircraft(bbox: str, limit: int = DEFAULT_LIMIT) -> list[dict]: return transform_adsb_lol(await _get_json(url)) rows = await _ttl_get(cache_key, 8.0, _load) + for m in rows: + aircraft_last_known[str(m.get("id"))] = m + if persist: + await persist_aircraft_snapshot(rows) + return filter_points_bbox(rows, minlon, minlat, maxlon, maxlat, limit) + + +async def persist_aircraft_snapshot(rows: list[dict]) -> None: + """Track / geofence / WS / fire correlation — never on the GET path.""" from ws_manager import manager from tracks import record_position from geofence import record_and_notify - aircraft_last_known.clear() + for m in rows: - aircraft_last_known[str(m.get("id"))] = m mlat, mlon = m.get("lat"), m.get("lon") if mlat is None or mlon is None: continue @@ -830,7 +857,6 @@ async def fetch_aircraft(bbox: str, limit: int = DEFAULT_LIMIT) -> list[dict]: if fire_last_known: from fire_aircraft import correlate_and_notify await correlate_and_notify(fire_last_known, rows) - return filter_points_bbox(rows, minlon, minlat, maxlon, maxlat, limit) async def fetch_trains(bbox: str | None, limit: int = DEFAULT_LIMIT) -> list[dict]: @@ -964,13 +990,16 @@ async def fetch_weather_alerts(area: str | None, bbox: str | None) -> dict: clip_box = None if area: nws_params["area"] = area.upper() - elif bbox: + if bbox: clip_box = quantize_bbox(*parse_bbox(bbox)) - nws_params["bbox"] = f"{clip_box[0]},{clip_box[1]},{clip_box[2]},{clip_box[3]}" + # NWS /alerts/active 400s on bbox= — never send it; clip locally. nws_fc: dict = {"features": []} + nws_ok = True try: nws_fc = await _get_json(NWS_ALERTS, nws_params) - except Exception: + except Exception as exc: + logger.warning("NWS alerts fetch failed: %s", exc) + nws_ok = False nws_fc = {"features": []} sbw_fc = await _ttl_get("iem:sbw", 45.0, _load_iem) features = [] @@ -988,11 +1017,15 @@ async def fetch_weather_alerts(area: str | None, bbox: str | None) -> dict: if "event" not in props: props["event"] = props.get("ps") or "Storm-based warning" features.append({**feat, "properties": slim_alert_properties(props)}) - merged = {"type": "FeatureCollection", "features": features} + merged = {"type": "FeatureCollection", "features": features, "nws_ok": nws_ok} if clip_box: - merged = clip_fc_to_bbox(merged, *clip_box) + clipped = clip_fc_to_bbox(merged, *clip_box) + clipped["nws_ok"] = nws_ok + merged = clipped elif bbox: - merged = clip_fc_to_bbox(merged, *parse_bbox(bbox)) + clipped = clip_fc_to_bbox(merged, *parse_bbox(bbox)) + clipped["nws_ok"] = nws_ok + merged = clipped return merged key = f"alerts:{area or ''}:{bbox_cell_key(bbox) if bbox else ''}" diff --git a/app/main.py b/app/main.py index 13d404f..355d379 100644 --- a/app/main.py +++ b/app/main.py @@ -72,12 +72,16 @@ async def _lifespan(app: FastAPI): pass from config import AISSTREAM_IN_APP ais_task = None + adsb_task = None if AISSTREAM_IN_APP: from ais_stream import run_ais_worker ais_task = asyncio.create_task(run_ais_worker()) + adsb_task = asyncio.create_task(_adsb_refresh_loop()) yield if ais_task is not None: ais_task.cancel() + if adsb_task is not None: + adsb_task.cancel() await close_http() @@ -92,6 +96,35 @@ app.add_middleware(GZipMiddleware, minimum_size=1024) STATIC_DIR = Path(__file__).parent / "static" +async def _adsb_refresh_loop() -> None: + """Poll ADSB.lol for connected viewports — never from GET /api/aircraft.""" + from ws_manager import manager + from live_layers import fetch_aircraft + + while True: + try: + boxes = manager.viewports() + for box in boxes: + bbox = f"{box[0]},{box[1]},{box[2]},{box[3]}" + try: + await fetch_aircraft(bbox, persist=True) + except Exception as exc: # noqa: BLE001 + logger.warning("adsb_refresh_failed", error=str(exc)) + except Exception as exc: # noqa: BLE001 + logger.warning("adsb_refresh_loop", error=str(exc)) + await asyncio.sleep(8) + + +class CachedStaticFiles(StaticFiles): + """Long-cache hashed/vendor Leaflet assets; index.html is served separately.""" + + async def get_response(self, path: str, scope): + resp = await super().get_response(path, scope) + if path.startswith("vendor/") or path.endswith((".js", ".css", ".woff2", ".png", ".svg")): + resp.headers["Cache-Control"] = "public, max-age=31536000, immutable" + return resp + + # ── Helpers ─────────────────────────────────────────────────────────────── def event_to_out(row: dict) -> EventOut: @@ -154,11 +187,65 @@ def alert_to_out(row: dict) -> AlertOut: @app.get("/api/health") async def health(): - """Health check with database connectivity.""" - async with async_session() as session: - result = await session.execute(select(func.now())) - db_time = result.scalar() - return {"status": "ok", "db_time": db_time.isoformat() if db_time else None} + """Liveness: process + DB. Pipeline freshness is in ``checks`` (HTTP 200 + unless DB is down, so docker healthcheck does not restart a working HUD). + """ + try: + async with async_session() as session: + result = await session.execute(select(func.now())) + db_time = result.scalar() + checks = await _pipeline_checks(session) + except Exception as exc: # noqa: BLE001 + logger.warning("health_db_failed", error=str(exc)) + return JSONResponse( + {"status": "down", "db_time": None, "checks": {"db": False}}, + status_code=503, + ) + checks["db"] = True + stale = [ + name for name, val in checks.items() + if isinstance(val, dict) and val.get("ok") is False + ] + status = "degraded" if stale else "ok" + return { + "status": status, + "db_time": db_time.isoformat() if db_time else None, + "checks": checks, + } + + +@app.get("/api/ready") +async def ready(): + """Readiness: 503 only when the database is unreachable.""" + payload = await health() + if isinstance(payload, JSONResponse): + return payload + return JSONResponse(payload, status_code=200) + + +async def _pipeline_checks(session) -> dict: + now = datetime.now(timezone.utc) + checks: dict = {} + + async def _age(sql: str, name: str, max_age_s: int) -> None: + try: + ts = (await session.execute(text(sql))).scalar() + except Exception: + checks[name] = {"ok": False, "age_s": None} + return + if ts is None: + checks[name] = {"ok": False, "age_s": None} + return + if getattr(ts, "tzinfo", None) is None: + ts = ts.replace(tzinfo=timezone.utc) + age = (now - ts).total_seconds() + checks[name] = {"ok": age <= max_age_s, "age_s": int(age)} + + await _age("SELECT max(ingested_at) FROM events", "events", 20 * 60) + await _age("SELECT max(ingested_at) FROM fires", "fires", 30 * 60) + await _age("SELECT max(timestamp) FROM articles", "articles", 2 * 3600) + await _age("SELECT max(batch_timestamp) FROM article_summaries", "summaries", 2 * 3600) + return checks def overlay_json(data, max_age: int) -> JSONResponse: @@ -821,17 +908,19 @@ async def get_timeline( """Event timeline: counts and avg sentiment per time bucket.""" async with async_session() as session: cutoff = datetime.now(timezone.utc) - timedelta(hours=hours) - # Use date_trunc for bucketing - buckets = await session.execute(text(f""" + bucket_s = bucket_hours * 3600 + buckets = await session.execute(text(""" SELECT - date_trunc('hour', source_timestamp) AS ts, + to_timestamp( + floor(extract(epoch FROM source_timestamp) / :bucket_s) * :bucket_s + ) AT TIME ZONE 'UTC' AS ts, COUNT(*) AS event_count, COALESCE(AVG(sentiment_score), 0) AS avg_sentiment FROM events WHERE source_timestamp >= :cutoff GROUP BY ts ORDER BY ts - """), {"cutoff": cutoff}) + """), {"cutoff": cutoff, "bucket_s": bucket_s}) rows = buckets.mappings().all() return [TimelinePoint(timestamp=r["ts"], event_count=r["event_count"], @@ -1319,7 +1408,7 @@ async def list_aircraft( ts = parse_timestamp(timestamp) if ts is not None: return overlay_json(await fetch_positions_at("aircraft", ts, bbox, limit), 5) - return overlay_json(await fetch_aircraft(bbox, limit), 5) + return overlay_json(await fetch_aircraft(bbox, limit, persist=False), 5) except ValueError as exc: raise HTTPException(422, str(exc)) from exc except Exception as exc: @@ -1550,7 +1639,7 @@ async def map_layer_times( return {"layer": layer, **domain} -app.mount("/static", StaticFiles(directory=str(STATIC_DIR)), name="static") +app.mount("/static", CachedStaticFiles(directory=str(STATIC_DIR)), name="static") if __name__ == "__main__": diff --git a/app/models.py b/app/models.py index b8ad2b2..dac5d0a 100644 --- a/app/models.py +++ b/app/models.py @@ -68,6 +68,15 @@ Index("ix_events_search_vector", events.c.search_vector, postgresql_using="gin") # Spatial index on location Index("ix_events_location", events.c.location_lat, events.c.location_lon) +# Timescale unique indexes must include the partition column, so URL +# idempotency lives on a regular table — not the events hypertable. +event_dedup = Table( + "event_dedup", + metadata, + Column("url", Text, primary_key=True), + Column("created_at", DateTime(timezone=True), server_default=func.now(), nullable=False), +) + # ── Entities (people, organizations, locations of interest) ────────────── diff --git a/app/run_ingester.py b/app/run_ingester.py index e2f0c18..293a2e5 100644 --- a/app/run_ingester.py +++ b/app/run_ingester.py @@ -25,7 +25,7 @@ import sys sys.path.insert(0, sys_path) from config import NATS_URL, FIRMS_INTERVAL, FIRMS_DATASET, AISSTREAM_IN_INGEST # noqa: E402 -from sources import ingest_rss_feed, ingest_gdelt, ingest_earthquakes # noqa: E402 +from sources import ingest_rss_feed, ingest_gdelt, ingest_earthquakes, ingest_eonet, ingest_cisa_kev # noqa: E402 from fire_sources import ingest_fires # noqa: E402 from ingestor import ingest_event, start_nats_consumer # noqa: E402 @@ -37,6 +37,8 @@ INTERVAL = int(os.getenv("INGEST_INTERVAL", "300")) GDELT_QUERY = os.getenv("GDELT_QUERY", "") ENABLE_QUAKES = os.getenv("INGEST_EARTHQUAKES", "1").lower() in ("1", "true", "yes") ENABLE_FIRES = os.getenv("INGEST_FIRES", "1").lower() in ("1", "true", "yes") +ENABLE_EONET = os.getenv("INGEST_EONET", "1").lower() in ("1", "true", "yes") +ENABLE_KEV = os.getenv("INGEST_KEV", "1").lower() in ("1", "true", "yes") NATS_STREAM = "events" @@ -62,6 +64,18 @@ async def producer_loop() -> None: logger.info("USGS -> %d events", q) except Exception: # noqa: BLE001 logger.exception("USGS fetch failed") + if ENABLE_EONET: + try: + n = await ingest_eonet() + logger.info("EONET -> %d events", n) + except Exception: # noqa: BLE001 + logger.exception("EONET fetch failed") + if ENABLE_KEV: + try: + k = await ingest_cisa_kev() + logger.info("CISA KEV -> %d events", k) + except Exception: # noqa: BLE001 + logger.exception("CISA KEV fetch failed") except Exception: # noqa: BLE001 logger.exception("producer cycle error") await asyncio.sleep(INTERVAL) diff --git a/app/sources.py b/app/sources.py index 804dea1..c12c303 100644 --- a/app/sources.py +++ b/app/sources.py @@ -11,7 +11,7 @@ import httpx import feedparser import nats -from config import NATS_URL +from config import NATS_URL, OSINT_USER_AGENT from upstream_cache import rss_cache logger = logging.getLogger("osint.sources") @@ -26,26 +26,46 @@ def _parse_rfc822(date_str: object) -> str | None: except (ValueError, TypeError): return None -# NATS connection + NATS_URLS = NATS_URL +_nc = None + + +async def _jetstream(): + """Reuse one NATS connection across publishes (no connect/close per event).""" + global _nc + if _nc is None or _nc.is_closed: + _nc = await nats.connect(NATS_URLS) + return _nc.jetstream() async def publish_event(subject: str, event: dict): """Publish an event to NATS JetStream.""" - nc = await nats.connect(NATS_URLS) - js = nc.jetstream() + js = await _jetstream() await js.publish(subject, json.dumps(event).encode()) - await nc.close() logger.debug("Published event to %s", subject) +def event_dedup_key(msg: dict) -> str | None: + """Natural key for generic events. URL when present; else None (always insert).""" + url = msg.get("url") + if not isinstance(url, str): + return None + url = url.strip() + return url or None + + +def _ua_headers() -> dict[str, str]: + return {"User-Agent": OSINT_USER_AGENT} + + # ─── RSS Feed Ingestor ────────────────────────────────────────────────── async def ingest_rss_feed(feed_url: str, source_id: str | None = None): """Fetch and parse an RSS feed, publish items to NATS.""" text = rss_cache.get(feed_url) if text is None: - async with httpx.AsyncClient(timeout=30) as client: + async with httpx.AsyncClient(timeout=30, headers=_ua_headers()) as client: resp = await client.get(feed_url) resp.raise_for_status() text = resp.text @@ -76,51 +96,80 @@ async def ingest_rss_feed(feed_url: str, source_id: str | None = None): return count -# ─── GDELT 2.0 Ingestor ───────────────────────────────────────────────── +# ─── GDELT 2.0 DOC API ────────────────────────────────────────────────── -GDELT_API = "https://api.gdeltproject.org/gdeltv2" +GDELT_API = "https://api.gdeltproject.org/api/v2/doc/doc" +GDELT_DEFAULT_QUERY = '(unrest OR protest OR outage OR cyber OR "power outage")' + + +def gdelt_params(query: str = "", max_articles: int = 50) -> dict[str, str]: + """DOC 2.0 query string (not the retired gdeltv2 ``search`` param).""" + q = (query or "").strip() or GDELT_DEFAULT_QUERY + return { + "query": q, + "mode": "ArtList", + "format": "json", + "maxrecords": str(int(max_articles)), + "timespan": "1d", + } + + +def _parse_gdelt_seendate(value: object) -> str: + if isinstance(value, str) and len(value) >= 15: + try: + return datetime.strptime(value[:15], "%Y%m%dT%H%M%S").replace( + tzinfo=timezone.utc + ).isoformat() + except ValueError: + pass + return datetime.now(timezone.utc).isoformat() + + +def parse_gdelt_articles(data: dict) -> list[dict]: + events = [] + for article in data.get("articles") or []: + if not isinstance(article, dict): + continue + url = article.get("url") + if not url: + continue + events.append({ + "source_type": "gdel-t2", + "title": article.get("title"), + "body": article.get("domain") or article.get("language"), + "url": url, + "location_name": article.get("sourcecountry"), + "source_timestamp": _parse_gdelt_seendate(article.get("seendate")), + "tags": [t for t in (article.get("language"), article.get("sourcecountry")) if t], + "raw": article, + }) + return events async def ingest_gdelt(query: str = "", max_articles: int = 50): - """Fetch articles from GDELT 2.0 API.""" - params = { - "mode": "artlist", - "format": "json", - "maxrecords": max_articles, - "mode": "artlist", - } - if query: - params["search"] = query + """Fetch articles from the GDELT DOC 2.0 API.""" + params = gdelt_params(query=query, max_articles=max_articles) + data: dict = {"articles": []} + async with httpx.AsyncClient( + timeout=60, headers=_ua_headers(), follow_redirects=True, + ) as client: + try: + resp = await client.get(GDELT_API, params=params) + resp.raise_for_status() + data = resp.json() + except (httpx.TransportError, httpx.HTTPStatusError) as exc: + # gdeltproject.org certs have expired in the wild; HTTP fallback. + logger.warning("GDELT HTTPS failed (%s); retrying HTTP", exc) + http_url = GDELT_API.replace("https://", "http://", 1) + resp = await client.get(http_url, params=params) + resp.raise_for_status() + data = resp.json() - async with httpx.AsyncClient(timeout=60) as client: - resp = await client.get(GDELT_API, params=params) - resp.raise_for_status() - data = resp.json() - - count = 0 - for article in data.get("articles", []): - event = { - "source_type": "gdel-t2", - "title": article.get("title"), - "body": article.get("articleBody"), - "url": article.get("url"), - "sentiment_score": _parse_gdelt_tone(article.get("Tone", "0")), - "location_lat": article.get("Latitude"), - "location_lon": article.get("Longitude"), - "location_name": article.get("Location"), - "source_timestamp": article.get("FirstCreated"), - "entities": [ - {"name": e.get("Topic"), "type": "topic"} - for e in article.get("Mentions", []) - if e.get("Topic") - ], - "raw": article, - } + events = parse_gdelt_articles(data if isinstance(data, dict) else {}) + for event in events: await publish_event("events.gdelt", event) - count += 1 - - logger.info("Ingested %d articles from GDELT", count) - return count + logger.info("Ingested %d articles from GDELT", len(events)) + return len(events) def _parse_gdelt_tone(tone: str) -> float | None: @@ -137,34 +186,45 @@ def _parse_gdelt_tone(tone: str) -> float | None: USGS_API = "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_hour.geojson" +def parse_usgs_feature(feature: dict) -> dict: + """Map one USGS GeoJSON feature, keeping the stable event id.""" + props = feature.get("properties") or {} + geometry = (feature.get("geometry") or {}).get("coordinates") or [] + usgs_id = feature.get("id") + url = props.get("url") or ( + f"https://earthquake.usgs.gov/earthquakes/eventpage/{usgs_id}" if usgs_id else None + ) + raw = dict(props) + raw["usgs_id"] = usgs_id + return { + "source_type": "earthquake", + "title": props.get("title"), + "body": props.get("description"), + "url": url, + "location_lat": geometry[1] if len(geometry) > 1 else None, + "location_lon": geometry[0] if len(geometry) > 0 else None, + "location_name": props.get("place"), + "sentiment_label": "neutral", + "tags": [f"magnitude:{props.get('mag')}"] if props.get("mag") else [], + "source_timestamp": ( + datetime.utcfromtimestamp(props.get("time", 0) / 1000) + .replace(tzinfo=timezone.utc) + .isoformat() + ), + "raw": raw, + } + + async def ingest_earthquakes(): """Fetch recent earthquakes from USGS.""" - async with httpx.AsyncClient(timeout=30) as client: + async with httpx.AsyncClient(timeout=30, headers=_ua_headers()) as client: resp = await client.get(USGS_API) resp.raise_for_status() data = resp.json() count = 0 for feature in data.get("features", []): - props = feature.get("properties", {}) - geometry = feature.get("geometry", {}).get("coordinates", []) - event = { - "source_type": "earthquake", - "title": props.get("title"), - "body": props.get("description"), - "url": props.get("url"), - "location_lat": geometry[1] if len(geometry) > 1 else None, - "location_lon": geometry[0] if len(geometry) > 0 else None, - "location_name": props.get("place"), - "sentiment_label": "neutral", - "tags": [f"magnitude:{props.get('mag')}"] if props.get("mag") else [], - "source_timestamp": ( - datetime.utcfromtimestamp(props.get("time", 0) / 1000) - .replace(tzinfo=timezone.utc) - .isoformat() - ), - "raw": props, - } + event = parse_usgs_feature(feature) await publish_event("events.earthquake", event) count += 1 @@ -172,6 +232,110 @@ async def ingest_earthquakes(): return count +# ─── NASA EONET v3 ────────────────────────────────────────────────────── + +EONET_API = "https://eonet.gsfc.nasa.gov/api/v3/events" + + +def parse_eonet_events(payload: dict) -> list[dict]: + events = [] + for item in payload.get("events") or []: + if not isinstance(item, dict): + continue + eid = item.get("id") + geoms = item.get("geometry") or [] + point = None + for g in geoms: + if isinstance(g, dict) and g.get("type") == "Point": + point = g + if point is None: + continue + coords = point.get("coordinates") or [] + if len(coords) < 2: + continue + lon, lat = float(coords[0]), float(coords[1]) + cats = item.get("categories") or [] + tags = [] + for c in cats: + if isinstance(c, dict) and c.get("id"): + tags.append(str(c["id"])) + url = item.get("link") or (f"https://eonet.gsfc.nasa.gov/api/v3/events/{eid}" if eid else None) + ts = point.get("date") or datetime.now(timezone.utc).isoformat() + events.append({ + "source_type": "disaster", + "title": item.get("title"), + "body": ", ".join(tags) if tags else None, + "url": url, + "location_lat": lat, + "location_lon": lon, + "location_name": item.get("title"), + "tags": tags, + "source_timestamp": ts, + "raw": {**item, "eonet_id": eid}, + }) + return events + + +async def ingest_eonet(): + """Volcanoes, storms, floods, drought — gaps USGS/FIRMS don't cover.""" + async with httpx.AsyncClient(timeout=30, headers=_ua_headers()) as client: + resp = await client.get(EONET_API, params={"status": "open", "limit": 100}) + resp.raise_for_status() + data = resp.json() + events = parse_eonet_events(data if isinstance(data, dict) else {}) + for event in events: + await publish_event("events.disaster", event) + logger.info("Ingested %d EONET events", len(events)) + return len(events) + + +# ─── CISA KEV ─────────────────────────────────────────────────────────── + +CISA_KEV_API = ( + "https://www.cisa.gov/sites/default/files/feeds/known_exploited_vulnerabilities.json" +) + + +def parse_cisa_kev(payload: dict) -> list[dict]: + events = [] + for row in payload.get("vulnerabilities") or []: + if not isinstance(row, dict): + continue + cve = row.get("cveID") + if not cve: + continue + title = row.get("vulnerabilityName") or cve + vendor = row.get("vendorProject") or "" + product = row.get("product") or "" + events.append({ + "source_type": "disaster", + "title": f"{cve}: {title}", + "body": row.get("shortDescription") or f"{vendor} {product}".strip(), + "url": f"https://nvd.nist.gov/vuln/detail/{cve}", + "location_lat": None, + "location_lon": None, + "location_name": None, + "tags": ["cisa-kev", cve, "ransomware" if row.get("knownRansomwareCampaignUse") == "Known" else None], + "source_timestamp": row.get("dateAdded") or datetime.now(timezone.utc).isoformat(), + "raw": {**row, "cveID": cve}, + }) + events[-1]["tags"] = [t for t in events[-1]["tags"] if t] + return events + + +async def ingest_cisa_kev(): + """Exploited-in-the-wild CVEs. No fake map coords — ticker/events only.""" + async with httpx.AsyncClient(timeout=30, headers=_ua_headers(), follow_redirects=True) as client: + resp = await client.get(CISA_KEV_API) + resp.raise_for_status() + data = resp.json() + events = parse_cisa_kev(data if isinstance(data, dict) else {}) + for event in events: + await publish_event("events.disaster", event) + logger.info("Ingested %d CISA KEV rows", len(events)) + return len(events) + + # ─── Social Signals (Twitter/X-like placeholder) ──────────────────────── async def ingest_social_signals(query: str = "", max_items: int = 50): diff --git a/app/static/index.html b/app/static/index.html index 0bb8963..9974edb 100644 --- a/app/static/index.html +++ b/app/static/index.html @@ -1149,9 +1149,12 @@ async function checkHealth() { try { const r = await fetch(`${API}/api/health`); const d = await r.json(); - if (r.ok) { + if (r.ok && d && d.status === 'ok') { dot.className = 'dot ok'; txt.textContent = 'SYSTEMS OK'; + } else if (r.ok) { + dot.className = 'dot bad'; + txt.textContent = 'DEGRADED'; } else { dot.className = 'dot bad'; txt.textContent = 'DEGRADED'; @@ -1307,8 +1310,7 @@ function initMarketTicker() { loadMarketSymbols(); buildMarketTrack(true); setMarketTag('standby'); - probeMarket(); - setInterval(probeMarket, MARKET_POLL_MS); + // GET /api/market is not wired — do not 404-poll every 15s. } /* ═══════════════ NEWS FEED + TICKER ═══════════════ */ @@ -1813,6 +1815,7 @@ function bboxCell() { return currentBBox().split(',').map(n => Number(n).toFixed(2)).join(',') + '@' + map.getZoom(); } let liveWs = null; +let wsRetryMs = 1000; const FF_ICAO = new Set(['AT802','AT8T','AT8P','C130','C30J','C130J','DC10','MD10','MD87','S64','UH60','S70','CL415','CL215','B350','OV10','C208']); let firefighterHex = new Set(); let dvrTs = null; @@ -1876,15 +1879,25 @@ function acColor(p) { } function connectLiveWs() { if (liveWs && (liveWs.readyState === 0 || liveWs.readyState === 1)) return; - try { liveWs = new WebSocket(liveWsUrl()); } catch (e) { return; } - liveWs.onopen = () => sendLiveViewport(); + try { liveWs = new WebSocket(liveWsUrl()); } catch (e) { + const delay = wsRetryMs; + wsRetryMs = Math.min(wsRetryMs * 2, 60000); + setTimeout(connectLiveWs, delay); + return; + } + liveWs.onopen = () => { wsRetryMs = 1000; sendLiveViewport(); }; liveWs.onmessage = (ev) => { try { const msg = JSON.parse(ev.data); applyLiveMarker(msg.type, msg.payload); } catch (e) { /* ignore malformed */ } }; - liveWs.onclose = () => { liveWs = null; setTimeout(connectLiveWs, 4000); }; + liveWs.onclose = () => { + liveWs = null; + const delay = wsRetryMs; + wsRetryMs = Math.min(wsRetryMs * 2, 60000); + setTimeout(connectLiveWs, delay); + }; } function overlayFetch(url) { return fetch(url, overlayAbort ? { signal: overlayAbort.signal } : {}); @@ -2022,12 +2035,16 @@ async function initMap() { trainsOn = document.getElementById('lp-trains-on').checked; vesselsOn = document.getElementById('lp-vessels-on').checked; stormsOn = document.getElementById('lp-storms-on').checked; - if (firesOn) loadFires(); - if (camsOn) loadCams(); - if (blipsOn) loadBlips(); - if (newsOn) loadNewsPins(); - refreshLiveOverlays(); connectLiveWs(); + requestAnimationFrame(() => { + if (firesOn) loadFires(); + setTimeout(() => { + if (camsOn) loadCams(); + if (blipsOn) loadBlips(); + if (newsOn) loadNewsPins(); + refreshLiveOverlays(); + }, 250); + }); } catch(e) { hint.textContent = `Failed to load map layers: ${e.message || e}`; console.error('Map init failed', e); diff --git a/app/ws_manager.py b/app/ws_manager.py index b46a6b6..f91657c 100644 --- a/app/ws_manager.py +++ b/app/ws_manager.py @@ -43,6 +43,9 @@ class ConnectionManager: def viewport_of(self, client_id: str) -> BBox | None: return self._viewports.get(client_id) + def viewports(self) -> list[BBox]: + return list(self._viewports.values()) + def has_clients(self) -> bool: return bool(self._queues) diff --git a/deploy/osint-ws.nginx.conf b/deploy/osint-ws.nginx.conf new file mode 100644 index 0000000..4426e6e --- /dev/null +++ b/deploy/osint-ws.nginx.conf @@ -0,0 +1,23 @@ +# osint.rpi.local — WebSocket upgrade for /ws/live +# +# GitOps: this file is the source of truth. On the Pi: +# sudo cp deploy/osint-ws.nginx.conf /etc/nginx/snippets/osint-ws.conf +# then `include snippets/osint-ws.conf;` inside the osint.rpi.local server +# block (before `location /`), `nginx -t && systemctl reload nginx`. +# +# Without these headers nginx proxies GET /ws/live as HTTP/1.0 → FastAPI 404 +# and the HUD reconnects every few seconds. + +location /ws/ { + proxy_pass http://127.0.0.1:8000; + proxy_http_version 1.1; + proxy_set_header Upgrade $http_upgrade; + proxy_set_header Connection "upgrade"; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_read_timeout 3600s; + proxy_send_timeout 3600s; + proxy_buffering off; +} diff --git a/news/scraper/newsScraper/feed_util.py b/news/scraper/newsScraper/feed_util.py new file mode 100644 index 0000000..1cffa17 --- /dev/null +++ b/news/scraper/newsScraper/feed_util.py @@ -0,0 +1,32 @@ +"""Feed helpers shared by the news spider (no Scrapy import).""" + +from __future__ import annotations + +import datetime +from email.utils import parsedate_to_datetime +from urllib.parse import urlparse + +AUDIO_EXT = (".mp3", ".m4a", ".ogg", ".wav", ".aac", ".flac", ".opus") + + +def is_audio_url(url: str) -> bool: + path = urlparse(url or "").path.lower() + return any(path.endswith(ext) for ext in AUDIO_EXT) + + +def article_timestamp(pub_date: str | None) -> datetime.datetime: + """Prefer the feed's pubDate/published; fall back to now (UTC).""" + if pub_date: + try: + return parsedate_to_datetime(pub_date).astimezone(datetime.timezone.utc) + except (TypeError, ValueError, IndexError): + pass + try: + raw = pub_date.replace("Z", "+00:00") + ts = datetime.datetime.fromisoformat(raw) + if ts.tzinfo is None: + ts = ts.replace(tzinfo=datetime.timezone.utc) + return ts + except ValueError: + pass + return datetime.datetime.now(datetime.timezone.utc) diff --git a/news/scraper/newsScraper/pipelines.py b/news/scraper/newsScraper/pipelines.py index 209607c..68cad97 100644 --- a/news/scraper/newsScraper/pipelines.py +++ b/news/scraper/newsScraper/pipelines.py @@ -3,7 +3,7 @@ # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html -import logging +import logging import psycopg2 import os from scrapy.exceptions import DropItem @@ -53,8 +53,10 @@ class PostgresPipeline: self.connection.commit() def process_item(self, item, spider): - if item ['url'] in self.seen_urls: - raise DropItem() + url = item['url'] + if url in self.seen_urls: + raise DropItem(f"Duplicate URL (in-memory): {url}") + self.seen_urls.add(url) try: self.cur.execute(""" INSERT INTO articles (title, url, content, domain, timestamp) @@ -68,15 +70,16 @@ class PostgresPipeline: item['timestamp'] )) if self.cur.rowcount == 0: - e = DropItem("Duplicate URL (database conflict)") - e.log_level = logging.DEBUG - raise e + raise DropItem(f"Duplicate URL (database): {url}") self.connection.commit() - return item + return item + except DropItem: + self.connection.rollback() + raise except Exception as e: spider.logger.error(f"Error saving to Postgres: {e}") self.connection.rollback() - raise + raise def close_spider(self, spider): self.cur.close() @@ -88,5 +91,3 @@ from itemadapter import ItemAdapter class NewsscraperPipeline: def process_item(self, item, spider): return item - - diff --git a/news/scraper/newsScraper/spiders/news_spider.py b/news/scraper/newsScraper/spiders/news_spider.py index f29db33..11d9996 100644 --- a/news/scraper/newsScraper/spiders/news_spider.py +++ b/news/scraper/newsScraper/spiders/news_spider.py @@ -4,6 +4,8 @@ from urllib.parse import urljoin, urlparse import datetime import re +from newsScraper.feed_util import article_timestamp, is_audio_url + class NewsRSSSpider(Spider): """Crawl the curated news sources in urls.txt and extract articles. @@ -87,6 +89,8 @@ class NewsRSSSpider(Spider): or node.xpath('updated/text()').get() ) if link: + if is_audio_url(link): + continue yield scrapy.Request( link, callback=self.parse_article, @@ -112,5 +116,5 @@ class NewsRSSSpider(Spider): 'url': response.url, 'text': pure_text, 'domain': urlparse(response.url).netloc, - 'timestamp': datetime.datetime.now().isoformat() + 'timestamp': article_timestamp(response.meta.get('date')).isoformat() } diff --git a/news/summerizer/Dockerfile b/news/summerizer/Dockerfile index 4638617..3b795c2 100644 --- a/news/summerizer/Dockerfile +++ b/news/summerizer/Dockerfile @@ -13,7 +13,7 @@ RUN apt-get update && apt-get install -y --no-install-recommends \ COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt -COPY summarizer.py run_news_summarizer.py ./ +COPY summarizer.py run_news_summarizer.py intel.py nous_client.py ./ # Security: run as a non-privileged user. RUN useradd -m summarizer_user diff --git a/pytest.ini b/pytest.ini new file mode 100644 index 0000000..27eec68 --- /dev/null +++ b/pytest.ini @@ -0,0 +1,3 @@ +[pytest] +testpaths = tests +python_files = test_*.py diff --git a/tests/test_cache_and_timeline.py b/tests/test_cache_and_timeline.py new file mode 100644 index 0000000..73f4f4e --- /dev/null +++ b/tests/test_cache_and_timeline.py @@ -0,0 +1,21 @@ +"""Timeline bucket_hours + static Cache-Control.""" + +from __future__ import annotations + +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent + + +def test_timeline_uses_bucket_hours(): + src = (ROOT / "app/main.py").read_text() + fn = src.split("async def get_timeline")[1].split("async def sentiment_by_source")[0] + assert "bucket_hours" in fn + assert "date_trunc('hour'" not in fn or "bucket" in fn.lower() + # Must not ignore the query param. + assert ":bucket" in fn or "bucket_hours" in fn.split("text(")[1][:800] + + +def test_static_vendor_cache_control(): + src = (ROOT / "app/main.py").read_text() + assert "max-age=31536000" in src or "immutable" in src.lower() diff --git a/tests/test_event_ingest.py b/tests/test_event_ingest.py new file mode 100644 index 0000000..d280d25 --- /dev/null +++ b/tests/test_event_ingest.py @@ -0,0 +1,133 @@ +"""Generic event ingest: idempotency, USGS ids, GDELT DOC URL.""" + +from __future__ import annotations + +import asyncio +from datetime import datetime, timezone + + +def test_event_dedup_key_prefers_url(): + from sources import event_dedup_key + + assert event_dedup_key({"url": "https://earthquake.usgs.gov/earthquakes/eventpage/ci1"}) == ( + "https://earthquake.usgs.gov/earthquakes/eventpage/ci1" + ) + assert event_dedup_key({"url": " "}) is None + assert event_dedup_key({}) is None + + +def test_usgs_feature_keeps_id_and_url(): + from sources import parse_usgs_feature + + feature = { + "id": "ci39818991", + "properties": { + "title": "M 2.1 - 5 km W of", + "url": "https://earthquake.usgs.gov/earthquakes/eventpage/ci39818991", + "place": "5 km W of", + "mag": 2.1, + "time": 1_700_000_000_000, + }, + "geometry": {"coordinates": [-118.5, 34.1, 10.0]}, + } + event = parse_usgs_feature(feature) + assert event["url"] == "https://earthquake.usgs.gov/earthquakes/eventpage/ci39818991" + assert event["raw"]["usgs_id"] == "ci39818991" + assert event["location_lat"] == 34.1 + assert event["location_lon"] == -118.5 + assert event["source_type"] == "earthquake" + + +def test_gdelt_uses_doc_api_and_query_param(): + from sources import GDELT_API, gdelt_params + + assert GDELT_API == "https://api.gdeltproject.org/api/v2/doc/doc" + params = gdelt_params(query="unrest", max_articles=50) + assert params["query"] == "unrest" + assert "search" not in params + assert params["mode"] == "ArtList" + assert params["format"] == "json" + assert int(params["maxrecords"]) == 50 + + +def test_gdelt_default_query_when_empty(): + from sources import gdelt_params + + params = gdelt_params(query="", max_articles=25) + assert params["query"] + assert "unrest" in params["query"].lower() or "cyber" in params["query"].lower() + + +def test_parse_gdelt_articles_maps_doc_payload(): + from sources import parse_gdelt_articles + + payload = { + "articles": [ + { + "url": "https://example.com/a", + "title": "Outage", + "seendate": "20240101T120000Z", + "domain": "example.com", + "language": "English", + "sourcecountry": "US", + } + ] + } + events = parse_gdelt_articles(payload) + assert len(events) == 1 + assert events[0]["source_type"] == "gdel-t2" + assert events[0]["url"] == "https://example.com/a" + assert events[0]["title"] == "Outage" + + +def test_ingest_event_skips_duplicate_url(monkeypatch): + """Second insert with the same url must not hit events_table.insert.""" + from ingestor import ingest_event + + calls = {"insert": 0, "dedup": 0} + + class _Result: + rowcount = 1 + inserted_primary_key = ["evt-1"] + + class _Session: + async def execute(self, stmt): + sql = str(stmt).lower() + if "event_dedup" in sql or "on conflict" in sql: + calls["dedup"] += 1 + self_result = _Result() + if calls["dedup"] > 1: + self_result.rowcount = 0 + return self_result + calls["insert"] += 1 + return _Result() + + async def commit(self): + return None + + async def __aenter__(self): + return self + + async def __aexit__(self, *a): + return False + + import ingestor + + monkeypatch.setattr(ingestor, "async_session", lambda: _Session()) + + msg = { + "source_type": "earthquake", + "title": "M 2.1", + "url": "https://earthquake.usgs.gov/earthquakes/eventpage/ci1", + "source_timestamp": datetime(2026, 1, 1, tzinfo=timezone.utc).isoformat(), + } + + async def run(): + first = await ingest_event(msg) + second = await ingest_event(msg) + return first, second + + first, second = asyncio.run(run()) + assert first is not None + assert second is None + assert calls["insert"] == 1 diff --git a/tests/test_fire_ingest.py b/tests/test_fire_ingest.py index b6e7dc1..29a1950 100644 --- a/tests/test_fire_ingest.py +++ b/tests/test_fire_ingest.py @@ -169,3 +169,47 @@ def test_ingest_fire_row_correlates_from_hypertable_when_last_known_empty(monkey assert len(correlated) == 1 assert correlated[0][1][0]["id"] == "acf001" assert correlated[0][0][0]["lat"] == 39.45678 + + +def test_ingest_fire_rows_one_execute_one_commit(monkeypatch): + """93k FIRMS points must not be 93k commits.""" + from ingestor import ingest_fire_rows + + class _Session: + def __init__(self): + self.executes = 0 + self.commits = 0 + self.rowcount = 3 + + async def execute(self, *a, **k): + self.executes += 1 + return self + + async def commit(self): + self.commits += 1 + + async def __aenter__(self): + return self + + async def __aexit__(self, *a): + return False + + session = _Session() + import ingestor + monkeypatch.setattr(ingestor, "async_session", lambda: session) + + msgs = [ + make_fire_msg(latitude=39.1 + i * 0.01, longitude=-121.1) + for i in range(3) + ] + + async def no_corr(*a, **k): + return [] + + monkeypatch.setattr("fire_aircraft.correlate_and_notify", no_corr) + monkeypatch.setattr("geofence.record_and_notify", no_corr) + + inserted = asyncio.run(ingest_fire_rows(msgs)) + assert inserted == 3 + assert session.executes == 1 + assert session.commits == 1 diff --git a/tests/test_fire_sources.py b/tests/test_fire_sources.py index c787ec2..24fcf94 100644 --- a/tests/test_fire_sources.py +++ b/tests/test_fire_sources.py @@ -123,7 +123,7 @@ def test_ingest_fires_uses_keystore_key(monkeypatch): published.extend(points) return len(points) - monkeypatch.setattr("fire_sources.publish_fire_batch", fake_publish) + monkeypatch.setattr("fire_sources.persist_hotspots", fake_publish) assert asyncio.run(ingest_fires()) == 10 # NOAA-20 + NOAA-21 dual-write assert "a" * 32 in captured["url"] diff --git a/tests/test_frontend_reliability.py b/tests/test_frontend_reliability.py new file mode 100644 index 0000000..7735d5b --- /dev/null +++ b/tests/test_frontend_reliability.py @@ -0,0 +1,44 @@ +"""HUD load-time: no market 404 poll, deferred overlays, WS backoff, nginx snippet.""" + +from __future__ import annotations + +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +HTML = (ROOT / "app/static/index.html").read_text() + + +def test_summarizer_dockerfile_copies_intel_modules(): + df = (ROOT / "news/summerizer/Dockerfile").read_text() + assert "intel.py" in df + assert "nous_client.py" in df + + +def test_nginx_ws_snippet_has_upgrade_headers(): + conf = (ROOT / "deploy/osint-ws.nginx.conf").read_text() + assert "proxy_http_version 1.1" in conf + assert "Upgrade" in conf + assert "Connection" in conf + assert "/ws/" in conf + + +def test_market_ticker_does_not_poll_unwired_endpoint(): + assert "setInterval(probeMarket" not in HTML + assert "initMarketTicker()" not in HTML or "probeMarket();" not in HTML.split("function initMarketTicker")[1][:400] + + +def test_startup_defers_nonessential_overlays(): + init = HTML.split("function initMap")[1].split("function readMapPrefs")[0] + # Must not fire all four DB loads + live overlays in the same tick. + assert "setTimeout" in init or "requestAnimationFrame" in init + + +def test_ws_reconnect_uses_backoff(): + assert "setTimeout(connectLiveWs, 4000)" not in HTML + ws = HTML.split("function connectLiveWs")[1][:1200] + assert "backoff" in ws.lower() or "wsRetry" in ws or "wsDelay" in ws + + +def test_check_health_treats_degraded_status(): + fn = HTML.split("async function checkHealth")[1].split("/* ═══════════════ NAV")[0] + assert "degraded" in fn.lower() or "d.status" in fn diff --git a/tests/test_health_ready.py b/tests/test_health_ready.py new file mode 100644 index 0000000..c2acdfc --- /dev/null +++ b/tests/test_health_ready.py @@ -0,0 +1,33 @@ +"""Liveness stays up; readiness/freshness is explicit.""" + +from __future__ import annotations + +import asyncio + +import httpx + +from main import app + +BASE = "http://test" + + +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 test_health_includes_checks_even_when_db_ok(monkeypatch): + """HUD must be able to show degraded without docker killing the container.""" + body = asyncio.run(_get("/api/health")).json() + assert "status" in body + assert "checks" in body + assert "db" in body["checks"] + + +def test_ready_endpoint_exists(): + resp = asyncio.run(_get("/api/ready")) + assert resp.status_code in (200, 503) + body = resp.json() + assert "checks" in body + assert "status" in body diff --git a/tests/test_live_layers.py b/tests/test_live_layers.py index 0a1bf1b..4ff214d 100644 --- a/tests/test_live_layers.py +++ b/tests/test_live_layers.py @@ -472,3 +472,103 @@ def test_transform_ais_position_decodes_navstat(): assert row is not None assert row["extra"]["nav"] == "moored" assert row["extra"]["navstat"] == 5 + + +def test_nws_alerts_does_not_send_bbox_param(monkeypatch): + """api.weather.gov/alerts/active 400s on bbox — clip locally instead.""" + import asyncio + + from live_layers import fetch_weather_alerts, _cache + + seen = [] + + async def fake_get(url, params=None): + seen.append((url, dict(params or {}))) + if "weather.gov" in url: + return { + "type": "FeatureCollection", + "features": [{ + "type": "Feature", + "properties": {"event": "Tornado Warning", "severity": "Extreme"}, + "geometry": {"type": "Point", "coordinates": [-78.7, 35.8]}, + }], + } + return {"type": "FeatureCollection", "features": []} + + monkeypatch.setattr("live_layers._get_json", fake_get) + _cache.clear() + fc = asyncio.run(fetch_weather_alerts(None, "-79.0,35.5,-78.0,36.0")) + nws_calls = [p for u, p in seen if "weather.gov" in u] + assert nws_calls, "NWS should still be fetched" + assert "bbox" not in nws_calls[0] + assert fc.get("nws_ok") is True + assert len(fc["features"]) == 1 + + +def test_nws_alerts_failure_is_flagged(monkeypatch): + import asyncio + + from live_layers import fetch_weather_alerts, _cache + + async def fake_get(url, params=None): + if "weather.gov" in url: + raise RuntimeError("400 Bad Request") + return {"type": "FeatureCollection", "features": []} + + monkeypatch.setattr("live_layers._get_json", fake_get) + _cache.clear() + fc = asyncio.run(fetch_weather_alerts(None, None)) + assert fc.get("nws_ok") is False + + +def test_fetch_aircraft_get_path_does_not_persist(monkeypatch): + """GET /api/aircraft must serve last-known without track/geofence writes.""" + import asyncio + + from live_layers import ( + aircraft_last_known, fetch_aircraft, persist_aircraft_snapshot, _cache, + ) + + aircraft_last_known.clear() + aircraft_last_known["abc"] = { + "id": "abc", "lat": 35.8, "lon": -78.7, "heading": 90, "speed": 400, + "label": "ABC", "extra": {}, + } + writes = {"n": 0} + + async def boom(*a, **k): + writes["n"] += 1 + raise AssertionError("GET path must not persist") + + monkeypatch.setattr("tracks.record_position", boom) + monkeypatch.setattr("geofence.record_and_notify", boom) + _cache.clear() + rows = asyncio.run(fetch_aircraft("-79,35,-78,36", persist=False)) + assert writes["n"] == 0 + assert any(r["id"] == "abc" for r in rows) + + +def test_persist_aircraft_snapshot_writes_tracks(monkeypatch): + import asyncio + + from live_layers import persist_aircraft_snapshot + + recorded = [] + + async def fake_record(kind, marker): + recorded.append((kind, marker["id"])) + return True + + async def fake_gf(**kw): + return 0 + + monkeypatch.setattr("tracks.record_position", fake_record) + monkeypatch.setattr("geofence.record_and_notify", fake_gf) + monkeypatch.setattr("ws_manager.manager.has_clients", lambda: False) + + rows = [{ + "id": "abc", "lat": 35.8, "lon": -78.7, "heading": 90, "speed": 400, + "label": "ABC", "extra": {}, + }] + asyncio.run(persist_aircraft_snapshot(rows)) + assert recorded == [("aircraft", "abc")] diff --git a/tests/test_new_sources.py b/tests/test_new_sources.py new file mode 100644 index 0000000..9cd0b85 --- /dev/null +++ b/tests/test_new_sources.py @@ -0,0 +1,66 @@ +"""NASA EONET + CISA KEV parsers (no network).""" + +from __future__ import annotations + + +def test_parse_eonet_keeps_stable_ids_and_points(): + from sources import parse_eonet_events + + payload = { + "events": [ + { + "id": "EONET_6363", + "title": "Etna Volcano", + "categories": [{"id": "volcanoes", "title": "Volcanoes"}], + "geometry": [ + {"date": "2024-01-01T00:00:00Z", "type": "Point", "coordinates": [15.0, 37.7]}, + ], + "link": "https://eonet.gsfc.nasa.gov/api/v3/events/EONET_6363", + }, + { + "id": "EONET_skip", + "title": "No geometry", + "categories": [], + "geometry": [], + "link": "https://eonet.gsfc.nasa.gov/api/v3/events/EONET_skip", + }, + ] + } + events = parse_eonet_events(payload) + assert len(events) == 1 + ev = events[0] + assert ev["url"] == "https://eonet.gsfc.nasa.gov/api/v3/events/EONET_6363" + assert ev["source_type"] == "disaster" + assert ev["location_lat"] == 37.7 + assert ev["location_lon"] == 15.0 + assert ev["raw"]["eonet_id"] == "EONET_6363" + assert "volcanoes" in ev["tags"] + + +def test_parse_cisa_kev_emits_cve_url_no_coords(): + from sources import parse_cisa_kev + + payload = { + "vulnerabilities": [ + { + "cveID": "CVE-2024-1234", + "vendorProject": "Acme", + "product": "Widget", + "vulnerabilityName": "RCE", + "dateAdded": "2024-06-01", + "shortDescription": "Remote code execution", + "requiredAction": "Apply updates", + "dueDate": "2024-06-22", + "knownRansomwareCampaignUse": "Known", + } + ] + } + events = parse_cisa_kev(payload) + assert len(events) == 1 + ev = events[0] + assert ev["url"] == "https://nvd.nist.gov/vuln/detail/CVE-2024-1234" + assert ev["location_lat"] is None + assert ev["location_lon"] is None + assert "cisa-kev" in ev["tags"] + assert "CVE-2024-1234" in ev["tags"] + assert ev["raw"]["cveID"] == "CVE-2024-1234" diff --git a/tests/test_news_scraper.py b/tests/test_news_scraper.py new file mode 100644 index 0000000..b2b3817 --- /dev/null +++ b/tests/test_news_scraper.py @@ -0,0 +1,42 @@ +"""News spider/pipeline: skip audio, use pubDate, don't log dupes as errors.""" + +from __future__ import annotations + +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +_SCRAPER = ROOT / "news/scraper" +if str(_SCRAPER) not in sys.path: + sys.path.insert(0, str(_SCRAPER)) + + +def test_is_audio_enclosure(): + from newsScraper.feed_util import is_audio_url + + assert is_audio_url("https://cdn.example/podcast.mp3") is True + assert is_audio_url("https://cdn.example/show.m4a?x=1") is True + assert is_audio_url("https://www.example.com/world/story") is False + + +def test_article_timestamp_prefers_pubdate(): + from newsScraper.feed_util import article_timestamp + + ts = article_timestamp("Tue, 01 Apr 2025 12:00:00 GMT") + assert ts.tzinfo is not None + assert ts.year == 2025 + assert ts.month == 4 + assert ts.day == 1 + + +def test_pipeline_does_not_wrap_dropitem_as_error(): + src = (ROOT / "news/scraper/newsScraper/pipelines.py").read_text() + assert "except DropItem" in src + assert "seen_urls.add" in src or "self.seen_urls.add" in src + + +def test_spider_skips_audio_before_request(): + src = (ROOT / "news/scraper/newsScraper/spiders/news_spider.py").read_text() + assert "is_audio_url" in src + assert "article_timestamp" in src + assert "datetime.datetime.now()" not in src diff --git a/tests/test_upstream_cache.py b/tests/test_upstream_cache.py index 040527b..249d2f4 100644 --- a/tests/test_upstream_cache.py +++ b/tests/test_upstream_cache.py @@ -55,7 +55,7 @@ def test_ingest_fires_hits_http_once_within_ttl(monkeypatch): async def fake_publish(points): return len(points) - monkeypatch.setattr("fire_sources.publish_fire_batch", fake_publish) + monkeypatch.setattr("fire_sources.persist_hotspots", fake_publish) assert asyncio.run(ingest_fires()) == 5 assert asyncio.run(ingest_fires()) == 5 From 5302e261d7ec8b7581148a59799597c9589aa335 Mon Sep 17 00:00:00 2001 From: Sirius DevOps Date: Fri, 28 Aug 2026 22:22:12 -0400 Subject: [PATCH 20/79] fix: chunk FIRMS bulk inserts under asyncpg 32767 bind cap A ~90k-row INSERT ... ON CONFLICT dies with InterfaceError, so fire_loop fails every poll and /api/health stays degraded (fires age > 30 min). Chunk 2000 rows per statement, still one commit per poll. --- app/ingestor.py | 22 +++++++++++------ tests/test_fire_ingest.py | 52 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 67 insertions(+), 7 deletions(-) diff --git a/app/ingestor.py b/app/ingestor.py index 8d7eb97..ac0bcbd 100644 --- a/app/ingestor.py +++ b/app/ingestor.py @@ -20,6 +20,11 @@ from sources import event_dedup_key logger = logging.getLogger("osint.ingestor") +# asyncpg rejects statements with >32767 bind params. A FIRMS poll is ~90k +# rows × 14 columns. Chunk inserts; still one transaction / one commit. +FIRE_ROW_BIND_PARAMS = 14 +FIRE_INSERT_CHUNK = 2000 + # NATS connection settings NATS_URLS = NATS_URL NATS_STREAM = "events" @@ -126,15 +131,18 @@ async def ingest_fire_rows(msgs: list[dict]) -> int: rows.append(row) if not rows: return 0 + inserted = 0 async with async_session() as session: - stmt = ( - pg_insert(fires_table) - .values(rows) - .on_conflict_do_nothing(constraint="pk_fires_natural_key") - ) - result = await session.execute(stmt) + for i in range(0, len(rows), FIRE_INSERT_CHUNK): + chunk = rows[i:i + FIRE_INSERT_CHUNK] + stmt = ( + pg_insert(fires_table) + .values(chunk) + .on_conflict_do_nothing(constraint="pk_fires_natural_key") + ) + result = await session.execute(stmt) + inserted += int(result.rowcount or 0) await session.commit() - inserted = int(result.rowcount or 0) if inserted: logger.info("bulk ingested %d/%d FIRMS hotspots", inserted, len(rows)) from live_layers import aircraft_last_known diff --git a/tests/test_fire_ingest.py b/tests/test_fire_ingest.py index 29a1950..51c41a4 100644 --- a/tests/test_fire_ingest.py +++ b/tests/test_fire_ingest.py @@ -213,3 +213,55 @@ def test_ingest_fire_rows_one_execute_one_commit(monkeypatch): assert inserted == 3 assert session.executes == 1 assert session.commits == 1 + + +def test_fire_insert_chunk_stays_under_asyncpg_bind_limit(): + """asyncpg caps bind params at 32767 — a 93k-row INSERT dies.""" + from ingestor import FIRE_INSERT_CHUNK, FIRE_ROW_BIND_PARAMS + + assert FIRE_INSERT_CHUNK * FIRE_ROW_BIND_PARAMS < 32767 + assert FIRE_INSERT_CHUNK >= 500 + + +def test_ingest_fire_rows_chunks_when_over_limit(monkeypatch): + from ingestor import ingest_fire_rows + import ingestor + + class _Session: + def __init__(self): + self.executes = 0 + self.commits = 0 + self.rowcount = 0 + + async def execute(self, *a, **k): + self.executes += 1 + self.rowcount = 2 if self.executes < 3 else 1 + return self + + async def commit(self): + self.commits += 1 + + async def __aenter__(self): + return self + + async def __aexit__(self, *a): + return False + + session = _Session() + monkeypatch.setattr(ingestor, "async_session", lambda: session) + monkeypatch.setattr(ingestor, "FIRE_INSERT_CHUNK", 2) + + async def no_corr(*a, **k): + return [] + + monkeypatch.setattr("fire_aircraft.correlate_and_notify", no_corr) + monkeypatch.setattr("geofence.record_and_notify", no_corr) + + msgs = [ + make_fire_msg(latitude=39.1 + i * 0.01, longitude=-121.1) + for i in range(5) + ] + inserted = asyncio.run(ingest_fire_rows(msgs)) + assert inserted == 5 + assert session.executes == 3 + assert session.commits == 1 From 49ee5fe7a3c040242bdbbb24ca7bb5dceb8b1bcd Mon Sep 17 00:00:00 2001 From: Sirius DevOps Date: Fri, 28 Aug 2026 22:53:31 -0400 Subject: [PATCH 21/79] feat: 23:00 daily news recap; prompts drop futures Summarizer still runs the 15-min analyst, plus a 24h breaking-news recap at 23:00 America/New_York. HUD pins kind=daily_recap. Prompts ignore futures/market tape. --- alembic/versions/008_summary_kind.py | 26 ++++ app/main.py | 9 ++ app/models.py | 1 + app/schemas.py | 1 + app/static/index.html | 11 +- docker-compose.yml | 3 + docs/news.md | 37 +++--- news/summerizer/Dockerfile | 2 +- news/summerizer/run_news_summarizer.py | 106 +++++++++++++--- news/summerizer/summarizer.py | 153 +++++++++++++++++------ news/summerizer/tests/conftest.py | 11 ++ news/summerizer/tests/test_prompts.py | 32 +++++ news/summerizer/tests/test_scheduler.py | 42 +++++++ news/summerizer/tests/test_summarizer.py | 45 +++++++ tests/test_api_news.py | 22 +++- tests/test_frontend_reliability.py | 5 + 16 files changed, 431 insertions(+), 75 deletions(-) create mode 100644 alembic/versions/008_summary_kind.py create mode 100644 news/summerizer/tests/conftest.py create mode 100644 news/summerizer/tests/test_prompts.py create mode 100644 news/summerizer/tests/test_scheduler.py create mode 100644 news/summerizer/tests/test_summarizer.py diff --git a/alembic/versions/008_summary_kind.py b/alembic/versions/008_summary_kind.py new file mode 100644 index 0000000..e5bced4 --- /dev/null +++ b/alembic/versions/008_summary_kind.py @@ -0,0 +1,26 @@ +"""article_summaries.kind — interval vs daily_recap + +Revision ID: 008_summary_kind +Revises: 007_event_dedup +Create Date: 2026-08-28 +""" + +from alembic import op + +revision = "008_summary_kind" +down_revision = "007_event_dedup" +branch_labels = None +depends_on = None + + +def upgrade() -> None: + op.execute( + """ + ALTER TABLE article_summaries + ADD COLUMN IF NOT EXISTS kind TEXT + """ + ) + + +def downgrade() -> None: + op.execute("ALTER TABLE article_summaries DROP COLUMN IF EXISTS kind") diff --git a/app/main.py b/app/main.py index 355d379..5b31141 100644 --- a/app/main.py +++ b/app/main.py @@ -1220,22 +1220,31 @@ async def list_news_summaries( None, description="Only summaries generated at/after this UTC instant.", ), + kind: str | None = Query( + None, + description="Filter: interval or daily_recap. Omit for all.", + ), limit: int = Query(20, ge=1, le=100), offset: int = Query(0, ge=0), ): """Most recent master LLM summaries (newest first).""" + if kind is not None and kind not in ("interval", "daily_recap"): + raise HTTPException(422, "kind must be interval or daily_recap") async with async_session() as session: stmt = select(article_summaries).order_by( article_summaries.c.batch_timestamp.desc().nullslast() ) if since: stmt = stmt.where(article_summaries.c.batch_timestamp >= since) + if kind is not None: + stmt = stmt.where(article_summaries.c.kind == kind) stmt = stmt.limit(limit).offset(offset) rows = (await session.execute(stmt)).mappings().all() return [ NewsSummaryOut( id=r["id"], summary_text=r["summary_text"], batch_timestamp=r["batch_timestamp"], model=r["model"], + kind=r["kind"], ) for r in rows ] diff --git a/app/models.py b/app/models.py index dac5d0a..f3b528d 100644 --- a/app/models.py +++ b/app/models.py @@ -219,6 +219,7 @@ article_summaries = Table( Column("batch_timestamp", DateTime(timezone=True), server_default=func.now(), nullable=False), Column("model", Text), # LLM id used for this batch; nullable for old rows + Column("kind", Text), # interval | daily_recap; nullable for old rows ) Index("ix_article_summaries_batch_timestamp", article_summaries.c.batch_timestamp) diff --git a/app/schemas.py b/app/schemas.py index b61e296..799aeb3 100644 --- a/app/schemas.py +++ b/app/schemas.py @@ -274,6 +274,7 @@ class NewsSummaryOut(BaseModel): summary_text: str batch_timestamp: datetime model: Optional[str] = None + kind: Optional[str] = None class NewsTickerItemOut(BaseModel): diff --git a/app/static/index.html b/app/static/index.html index 9974edb..efd9e61 100644 --- a/app/static/index.html +++ b/app/static/index.html @@ -1350,15 +1350,18 @@ async function loadNews(force) { if (upd) upd.textContent = 'updating…'; let articles = []; let summaries = []; + let recaps = []; let tickerItems = []; try { - const [rArticles, rSumm, rTick] = await Promise.all([ + const [rArticles, rSumm, rRecap, rTick] = await Promise.all([ fetch(`${API}/api/news?limit=100`), fetch(`${API}/api/news/summaries?limit=1`), + fetch(`${API}/api/news/summaries?kind=daily_recap&limit=1`), fetch(`${API}/api/news/ticker?limit=20`), ]); if (rArticles.ok) articles = await rArticles.json(); if (rSumm.ok) summaries = await rSumm.json(); + if (rRecap.ok) recaps = await rRecap.json(); if (rTick.ok) tickerItems = await rTick.json(); } catch (e) { const list = document.getElementById('news-list'); @@ -1369,7 +1372,7 @@ async function loadNews(force) { console.error('News load failed', e); return; } - renderNewsSummary(summaries); + renderNewsSummary(recaps.length ? recaps : summaries, recaps.length > 0); renderNewsList(articles); renderNewsTicker(articles, summaries, tickerItems); if (upd) upd.textContent = 'updated ' + new Date().toLocaleTimeString(); @@ -1377,7 +1380,7 @@ async function loadNews(force) { newsInterval = setInterval(() => loadNews(false), NEWS_REFRESH_MS); } } -function renderNewsSummary(summaries) { +function renderNewsSummary(summaries, isRecap) { const bodyEl = document.getElementById('ns-body'); const timeEl = document.getElementById('ns-time'); const badgeEl = document.getElementById('ns-badge'); @@ -1389,7 +1392,7 @@ function renderNewsSummary(summaries) { return; } const s = summaries[0]; - badgeEl.textContent = 'LATEST'; + badgeEl.textContent = isRecap || s.kind === 'daily_recap' ? 'DAILY RECAP' : 'LATEST'; timeEl.textContent = s.batch_timestamp ? 'Batch: ' + new Date(s.batch_timestamp).toLocaleString() : '—'; bodyEl.innerHTML = newsSimpleMD(s.summary_text || ''); } diff --git a/docker-compose.yml b/docker-compose.yml index f810304..e854010 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -234,6 +234,9 @@ services: NEWS_SUMMARIZE_INTERVAL_S: ${NEWS_SUMMARIZE_INTERVAL_S:-900} NEWS_SUMMARIZE_RUN_ON_START: ${NEWS_SUMMARIZE_RUN_ON_START:-1} NEWS_SUMMARIZE_FORCE: ${NEWS_SUMMARIZE_FORCE:-0} + TZ: ${TZ:-America/New_York} + NEWS_RECAP_HOUR: ${NEWS_RECAP_HOUR:-23} + NEWS_RECAP_MINUTE: ${NEWS_RECAP_MINUTE:-0} command: ["python", "run_news_summarizer.py"] volumes: diff --git a/docs/news.md b/docs/news.md index fe06f6c..5ac373b 100644 --- a/docs/news.md +++ b/docs/news.md @@ -16,7 +16,7 @@ urls.txt (RSS + homepages) news-scraper (Scrapy, continuous) ──► articles table (osint-db) │ │ │ ▼ -news-summarizer (Nous Portal, every 15m) ──► article_summaries + news_items +news-summarizer (Nous Portal, every 15m + 23:00 recap) ──► article_summaries + news_items │ ▼ GET /api/news · /api/news/summaries · /api/news/ticker · /api/news/map @@ -45,11 +45,13 @@ feeds (`GET /api/news` exact key set is unchanged on purpose). the `PostgresPipeline` writes to `articles` with URL-based dedup (`ON CONFLICT (url) DO NOTHING`). 2. **Summarizer** — `news/summerizer/run_news_summarizer.py` runs - `summarizer.py` every `NEWS_SUMMARIZE_INTERVAL_S` (default 900). It reads - articles from the last `SUMMARY_WINDOW_MINUTES` (default 15), map-reduces - them through Nous Portal (`SUMMARY_MODEL` / Settings, default - `Hermes-4.3-36B`), writes the English brief to `article_summaries` (column - `model` is the LLM id), and flagged ticker/map rows to `news_items`. + `summarizer.py` every `NEWS_SUMMARIZE_INTERVAL_S` (default 900) over the + last `SUMMARY_WINDOW_MINUTES` (default 15), and again at 23:00 + `America/New_York` (`TZ`) over the last 24 hours as a daily recap + (`kind=daily_recap`). Both map-reduce through Nous Portal (`SUMMARY_MODEL` + / Settings, default `Hermes-4.3-36B`), write the English brief to + `article_summaries` (column `model` is the LLM id; `kind` is + `interval` or `daily_recap`), and flagged ticker/map rows to `news_items`. Loops are serial (two crawls/summaries never overlap). Interval idempotency: if `article_summaries` already has a row in the last interval, the summarizer @@ -116,12 +118,15 @@ Key set **unchanged** (no `lat`/`lon` on articles; geo lives on `/api/news/map`) "id": 1, "summary_text": "English markdown brief…", "batch_timestamp": "2026-08-24T18:10:00Z", - "model": "Hermes-4.3-36B" + "model": "Hermes-4.3-36B", + "kind": "daily_recap" } ] ``` -`model` is additive. Empty DB → `[]` (no crash). +`model` and `kind` are additive (`interval` | `daily_recap` | `null` for old rows). +`?kind=daily_recap` pins the nightly 24h recap. Empty DB → `[]` (no crash). +Malformed `kind` → `422`. ### GET /api/news/ticker — flagged HUD headlines @@ -237,10 +242,13 @@ lands in `article_summaries.summary_text`. | `SUMMARY_WINDOW_MINUTES` | `15` | How far back the summarizer looks for new articles. | | `NEWS_SCRAPE_INTERVAL_S` | `10` | Pause after each crawl before the next (scraper is otherwise continuous). | | `NEWS_SUMMARIZE_INTERVAL_S` | `900` | Seconds between analyst runs (default 15 min). | +| `TZ` | `America/New_York` | Timezone for the 23:00 daily recap. | +| `NEWS_RECAP_HOUR` | `23` | Local hour of the daily 24h recap. | +| `NEWS_RECAP_MINUTE` | `0` | Local minute of the daily recap. | | `NEWS_SCRAPE_RUN_ON_START` | `1` | Run one scrape immediately on container start. | | `NEWS_SUMMARIZE_RUN_ON_START` | `1` | Run one summarize immediately on container start. | -| `NEWS_SUMMARIZE_FORCE` | `0` | `1` ignores the interval idempotency skip (double-pins on recreate). | -| `INCLUDE_FUTURES` | `0` | Legacy futures-prices coupling. OFF for OSINT; set `1` + install `yfinance` to enable. | +| `NEWS_SUMMARIZE_FORCE` | `0` | `1` ignores the interval/recap idempotency skip (double-pins on recreate). | +| `INCLUDE_FUTURES` | `0` | Legacy. Ignored — prompts never inject futures/market tape. | | `NEWS_LOG_LEVEL` | `INFO` | Scrapy log level. | | `OSINT_USER_AGENT` | `osint-dashboard-news-summarizer` | Sent on every outbound Nous call. | | `TELEGRAM_TOKEN` / `TELEGRAM_CHAT_ID` | *(blank)* | Reserved for the (out-of-scope) Telegram delivery bot. | @@ -254,11 +262,10 @@ No Hermes-4 reasoning system prompt. Reduce uses `json_mode=True`. ## Prompts -Both prompts are env-overridable — the default `MAP_PROMPT` is OSINT-neutral -(facts, locations, entities, category, OSINT signal per article; English) and -the default `SUMMARY_PROMPT` demands the reduce JSON above (with a -"no qualifying events" escape hatch). Upstream's futures/markets prompt -language is gated behind `INCLUDE_FUTURES=1`. +Both prompts are env-overridable. Defaults focus on **breaking important news** +and explicitly ignore futures, commodity tape, and routine market moves. +`RECAP_PROMPT` (23:00, 24h window) is the daily recap; `SUMMARY_PROMPT` is the +15-min analyst. `INCLUDE_FUTURES` is ignored. ## Tests diff --git a/news/summerizer/Dockerfile b/news/summerizer/Dockerfile index 3b795c2..19a145b 100644 --- a/news/summerizer/Dockerfile +++ b/news/summerizer/Dockerfile @@ -7,7 +7,7 @@ WORKDIR /app # libpq-dev + gcc for psycopg2 build/adapters; keep the image lean. RUN apt-get update && apt-get install -y --no-install-recommends \ - libpq-dev gcc \ + libpq-dev gcc tzdata \ && rm -rf /var/lib/apt/lists/* COPY requirements.txt . diff --git a/news/summerizer/run_news_summarizer.py b/news/summerizer/run_news_summarizer.py index 1032af7..dca6d68 100644 --- a/news/summerizer/run_news_summarizer.py +++ b/news/summerizer/run_news_summarizer.py @@ -1,37 +1,97 @@ #!/usr/bin/env python3 -"""Scheduler loop for the news summarizer — every NEWS_SUMMARIZE_INTERVAL_S. +"""Scheduler loop for the news summarizer. -Default 900s (15 minutes). Serial: a slow LLM pass never overlaps the next. +15-minute analyst (NEWS_SUMMARIZE_INTERVAL_S, default 900s) plus a daily +recap at 23:00 in TZ (default America/New_York) over the last 24 hours. + +Serial: a slow LLM pass never overlaps the next. Env (all optional, 12-factor): - NEWS_SUMMARIZE_INTERVAL_S seconds between runs (default 900) + NEWS_SUMMARIZE_INTERVAL_S seconds between analyst runs (default 900) NEWS_SUMMARIZE_RUN_ON_START "1" to summarize once immediately on boot (default 1) + NEWS_RECAP_HOUR / MINUTE wall-clock recap time (default 23:00) + TZ IANA tz (default America/New_York) NOUS_API_KEY optional in env; Keys UI / api_keys also works """ from __future__ import annotations -import datetime import logging import os import subprocess import sys import time +from datetime import datetime, timedelta +from zoneinfo import ZoneInfo logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s") logger = logging.getLogger("news.summarizer.scheduler") INTERVAL_S = max(1, int(os.getenv("NEWS_SUMMARIZE_INTERVAL_S", "900"))) RUN_ON_START = os.getenv("NEWS_SUMMARIZE_RUN_ON_START", "1").lower() in ("1", "true", "yes") +DEFAULT_TZ = "America/New_York" +DEFAULT_RECAP_HOUR = 23 +DEFAULT_RECAP_MINUTE = 0 -def run_summarize() -> None: - logger.info("summarize starting at %s", datetime.datetime.now().isoformat(timespec="seconds")) +def _tz() -> ZoneInfo: + name = (os.getenv("TZ") or DEFAULT_TZ).strip() or DEFAULT_TZ + return ZoneInfo(name) + + +def recap_hour_minute() -> tuple[int, int]: + hour = int(os.getenv("NEWS_RECAP_HOUR", str(DEFAULT_RECAP_HOUR))) + minute = int(os.getenv("NEWS_RECAP_MINUTE", str(DEFAULT_RECAP_MINUTE))) + return hour, minute + + +def next_recap_datetime( + now: datetime, hour: int | None = None, minute: int | None = None +) -> datetime: + """Next 23:00 (or hour/minute) strictly after *now* in now's timezone.""" + if now.tzinfo is None: + now = now.replace(tzinfo=_tz()) + env_h, env_m = recap_hour_minute() + hour = env_h if hour is None else hour + minute = env_m if minute is None else minute + candidate = now.replace(hour=hour, minute=minute, second=0, microsecond=0) + if now >= candidate: + candidate += timedelta(days=1) + return candidate + + +def next_event( + now: datetime, + last_periodic: datetime | None, + interval_s: int, + hour: int = DEFAULT_RECAP_HOUR, + minute: int = DEFAULT_RECAP_MINUTE, +) -> tuple[datetime, str]: + """Return (when, 'recap'|'interval') for the sooner of recap vs interval.""" + recap_at = next_recap_datetime(now, hour=hour, minute=minute) + periodic_at = now if last_periodic is None else last_periodic + timedelta(seconds=interval_s) + if recap_at <= periodic_at: + return recap_at, "recap" + return periodic_at, "interval" + + +def run_summarize(*, recap: bool = False) -> None: + kind = "recap" if recap else "interval" + logger.info( + "%s starting at %s", kind, datetime.now().isoformat(timespec="seconds") + ) + env = os.environ.copy() + if recap: + env["NEWS_RECAP"] = "1" + else: + env.pop("NEWS_RECAP", None) try: - proc = subprocess.run([sys.executable, "summarizer.py"], cwd="/app") - logger.info("summarize finished rc=%s", proc.returncode) + proc = subprocess.run( + [sys.executable, "summarizer.py"], cwd="/app", env=env + ) + logger.info("%s finished rc=%s", kind, proc.returncode) except Exception: # noqa: BLE001 — keep the loop alive across failures - logger.exception("summarize failed") + logger.exception("%s failed", kind) def main() -> None: @@ -39,16 +99,32 @@ def main() -> None: logger.warning( "NOUS_API_KEY unset in env — will read api_keys on each run; idle if both empty" ) + tz = _tz() + hour, minute = recap_hour_minute() logger.info( - "news summarizer loop starting (interval_s=%s, run_on_start=%s)", - INTERVAL_S, RUN_ON_START, + "news summarizer loop starting (interval_s=%s, run_on_start=%s, recap=%02d:%02d %s)", + INTERVAL_S, RUN_ON_START, hour, minute, tz, ) + last_periodic: datetime | None = None if RUN_ON_START: - run_summarize() + run_summarize(recap=False) + last_periodic = datetime.now(tz) while True: - logger.info("next summarize in %ss", INTERVAL_S) - time.sleep(INTERVAL_S) - run_summarize() + now = datetime.now(tz) + when, kind = next_event( + now, last_periodic, INTERVAL_S, hour=hour, minute=minute + ) + sleep_s = max(1, (when - now).total_seconds()) + logger.info("next %s in %ss", kind, int(sleep_s)) + time.sleep(sleep_s) + now = datetime.now(tz) + if kind == "recap": + run_summarize(recap=True) + # Recap covers the 15-min window; don't immediately fire interval. + last_periodic = now + else: + run_summarize(recap=False) + last_periodic = now if __name__ == "__main__": diff --git a/news/summerizer/summarizer.py b/news/summerizer/summarizer.py index c57476f..82c624a 100644 --- a/news/summerizer/summarizer.py +++ b/news/summerizer/summarizer.py @@ -16,13 +16,10 @@ of each summarize_news() — env wins, else api_keys / app_settings: SUMMARY_MODEL default Hermes-4.3-36B (else app_settings) BATCH_SIZE articles per map-phase batch (default 50) SUMMARY_WINDOW_MINUTES look-back window (default 15; SUMMARY_WINDOW_HOURS wins if set) - NEWS_SUMMARIZE_FORCE "1" to ignore the interval idempotency skip - INCLUDE_FUTURES "1" to prepend live futures prices (default 0) - -The futures/markets coupling from the original pipeline is gated behind -INCLUDE_FUTURES and OFF by default — it is irrelevant to the OSINT dashboard -and pulled yfinance into the image. Re-enable by installing yfinance and -setting INCLUDE_FUTURES=1. + NEWS_RECAP "1" for the 23:00 daily recap (24h window, recap prompt) + NEWS_SUMMARIZE_FORCE "1" to ignore the interval/recap idempotency skip + TZ IANA tz for recap-day bounds (default America/New_York) + INCLUDE_FUTURES legacy; ignored — prompts never inject futures data """ from __future__ import annotations @@ -30,6 +27,7 @@ from __future__ import annotations import logging import os from datetime import datetime +from zoneinfo import ZoneInfo import psycopg2 @@ -67,6 +65,18 @@ def _summarize_interval_seconds() -> int: return max(1, int(os.getenv("NEWS_SUMMARIZE_INTERVAL_S", "900"))) +def is_recap_run() -> bool: + return os.getenv("NEWS_RECAP", "0").lower() in ("1", "true", "yes") + + +def effective_window_minutes(*, recap: bool | None = None) -> int: + if recap is None: + recap = is_recap_run() + if recap: + return 24 * 60 + return _summary_window_minutes() + + SUMMARY_WINDOW_MINUTES = _summary_window_minutes() INCLUDE_FUTURES = os.getenv("INCLUDE_FUTURES", "0").lower() in ("1", "true", "yes") @@ -84,6 +94,8 @@ FUTURES_TICKERS = { MAP_PROMPT_DEFAULT = """\ You are a precise, factual OSINT news processor. Your ONLY source of information is the articles provided below. Do NOT add external knowledge, assumptions, training data, or invented facts. +Focus on breaking important news (geopolitical, military/conflict, security, disasters, major political developments). Ignore futures prices, commodity tape, ticker chatter, and routine market moves unless they themselves are the breaking event. + Write every field in English. Translate if the article is not English. For EACH article in the batch: @@ -91,7 +103,7 @@ For EACH article in the batch: 2. Location: country/city/region or Unknown. If you can estimate coordinates, emit them as numbers; otherwise omit. 3. Entities: list the key people, organizations, or governments mentioned (comma-separated, only names present in the text), else "None". 4. Category: pick one — politics, military/conflict, economy, technology, environment/disaster, health, crime, society, sport, other. -5. OSINT signal: if the article describes an event with geopolitical, security, military, economic, or disaster significance, say so in one short sentence. Otherwise write: "No notable OSINT signal." +5. 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. Importance: critical (breaking geopolitical/military/disaster with immediate impact), high, medium, low, none. If several articles cover the same story, add one short batch-level note at the end: "Batch theme: [one sentence]". @@ -117,10 +129,12 @@ Articles in this batch: """ SUMMARY_PROMPT_DEFAULT = """\ -CRITICAL INSTRUCTION - REPEAT 3 TIMES: YOU MUST USE ONLY THE DATA PROVIDED BELOW. DO NOT INVENT, RECALL, OR ADD ANY EVENTS, NAMES, DATES, IMPLICATIONS, PROJECTS, OR DETAILS NOT EXPLICITLY PRESENT IN THE DATA. IF THE DATA HAS NO MAJOR GEOPOLITICAL/TECH/MILITARY/ECONOMIC/IMPACTFUL EVENTS OR UNUSUAL STORIES, set summary_en to exactly: "No qualifying impactful or unusual events in the recent hourly news data." and use empty ticker and map_items arrays. AND STOP. NO EXTERNAL KNOWLEDGE FROM TRAINING. +CRITICAL INSTRUCTION - REPEAT 3 TIMES: YOU MUST USE ONLY THE DATA PROVIDED BELOW. DO NOT INVENT, RECALL, OR ADD ANY EVENTS, NAMES, DATES, IMPLICATIONS, PROJECTS, OR DETAILS NOT EXPLICITLY PRESENT IN THE DATA. IF THE DATA HAS NO BREAKING IMPORTANT NEWS, set summary_en to exactly: "No qualifying breaking news in the recent news data." and use empty ticker and map_items arrays. AND STOP. NO EXTERNAL KNOWLEDGE FROM TRAINING. All text in English. +Focus on breaking important news (geopolitical, military/conflict, security, disasters, major political developments). Ignore futures, commodity prices, and routine market data — do not treat price ticks as news. + Demand a single JSON object (no markdown fences) with this exact shape: { @@ -131,7 +145,32 @@ Demand a single JSON object (no markdown fences) with this exact shape: ticker: only critical and high, max 12, ≤140 chars, no markdown. map_items: only critical and high where a real-world location is explicit in the data. Estimate lat/lon. If location is Unknown or not in the data, omit the item. Never invent a place. Max 20. -summary_en: English markdown brief for an operator HUD. +summary_en: English markdown brief of breaking important news for an operator HUD. + +DATA: +{final_input} +""" + +RECAP_PROMPT_DEFAULT = """\ +You are writing a daily recap of the last 24 hours of news for an OSINT operator HUD. + +CRITICAL INSTRUCTION: YOU MUST USE ONLY THE DATA PROVIDED BELOW. DO NOT INVENT, RECALL, OR ADD ANY EVENTS, NAMES, DATES, IMPLICATIONS, PROJECTS, OR DETAILS NOT EXPLICITLY PRESENT IN THE DATA. IF THE DATA HAS NO BREAKING IMPORTANT NEWS, set summary_en to exactly: "No qualifying breaking news in the last 24 hours." and use empty ticker and map_items arrays. AND STOP. NO EXTERNAL KNOWLEDGE FROM TRAINING. + +All text in English. + +Focus on breaking important news from the last 24 hours (geopolitical, military/conflict, security, disasters, major political developments). Ignore futures, commodity prices, and routine market data — do not treat price ticks as news. + +Demand a single JSON object (no markdown fences) with this exact shape: + +{ + "summary_en": "English markdown daily recap or the no-qualifying-events sentence", + "ticker": [{"headline": "", "importance": "critical", "url": "", "location_name": ""}], + "map_items": [{"headline": "", "importance": "critical", "location_name": "", "lat": 0, "lon": 0, "location_confidence": "city", "category": "military/conflict", "url": ""}] +} + +ticker: only critical and high, max 12, ≤140 chars, no markdown. +map_items: only critical and high where a real-world location is explicit in the data. Estimate lat/lon. If location is Unknown or not in the data, omit the item. Never invent a place. Max 20. +summary_en: English markdown daily recap of the last 24 hours of breaking important news. DATA: {final_input} @@ -263,6 +302,7 @@ def ensure_tables() -> None: batch_timestamp TIMESTAMPTZ NOT NULL DEFAULT NOW() ); ALTER TABLE article_summaries ADD COLUMN IF NOT EXISTS model TEXT; + ALTER TABLE article_summaries ADD COLUMN IF NOT EXISTS kind TEXT; CREATE TABLE IF NOT EXISTS news_items ( id SERIAL PRIMARY KEY, summary_id INTEGER REFERENCES article_summaries(id) ON DELETE CASCADE, @@ -294,8 +334,9 @@ def ensure_tables() -> None: logger.error("Error ensuring news tables: %s", exc) -def get_recent_news() -> list[dict]: - """Fetch articles from the last SUMMARY_WINDOW_MINUTES (content > 100 chars).""" +def get_recent_news(window_minutes: int | None = None) -> list[dict]: + """Fetch articles from the look-back window (content > 100 chars).""" + mins = window_minutes if window_minutes is not None else effective_window_minutes() query = """ SELECT title, content, url, domain FROM articles @@ -306,7 +347,7 @@ def get_recent_news() -> list[dict]: try: conn = psycopg2.connect(**DB_CONFIG) cur = conn.cursor() - cur.execute(query, (SUMMARY_WINDOW_MINUTES,)) + cur.execute(query, (mins,)) rows = cur.fetchall() cur.close() conn.close() @@ -340,7 +381,34 @@ def _already_summarized_this_interval() -> bool: return False -def save_batch(summary_en: str, model: str, ticker: list, map_items: list) -> None: +def _already_recapped_today() -> bool: + """True when a daily_recap row already exists for the local calendar day.""" + if os.getenv("NEWS_SUMMARIZE_FORCE", "") == "1": + return False + tz_name = (os.getenv("TZ") or "America/New_York").strip() or "America/New_York" + start = datetime.now(ZoneInfo(tz_name)).replace( + hour=0, minute=0, second=0, microsecond=0 + ) + query = ( + "SELECT 1 FROM article_summaries " + "WHERE kind = 'daily_recap' AND batch_timestamp >= %s" + ) + try: + conn = psycopg2.connect(**DB_CONFIG) + cur = conn.cursor() + cur.execute(query, (start,)) + row = cur.fetchone() + cur.close() + conn.close() + return row is not None + except Exception as exc: # noqa: BLE001 + logger.error("Error checking recap idempotency: %s", exc) + return False + + +def save_batch( + summary_en: str, model: str, ticker: list, map_items: list, *, kind: str = "interval" +) -> None: """Insert the master brief plus flagged ticker/map rows.""" ticker_rows = select_ticker(ticker or []) map_rows = select_map(map_items or []) @@ -358,8 +426,8 @@ def save_batch(summary_en: str, model: str, ticker: list, map_items: list) -> No conn = psycopg2.connect(**DB_CONFIG) cur = conn.cursor() cur.execute( - "INSERT INTO article_summaries (summary_text, model) VALUES (%s, %s) RETURNING id", - (text, model), + "INSERT INTO article_summaries (summary_text, model, kind) VALUES (%s, %s, %s) RETURNING id", + (text, model, kind), ) summary_id = cur.fetchone()[0] for row in ticker_rows: @@ -396,8 +464,8 @@ def save_batch(summary_en: str, model: str, ticker: list, map_items: list) -> No ) conn.commit() logger.info( - "Master summary saved id=%s model=%s ticker=%d map=%d", - summary_id, model, len(ticker_rows), len(map_rows), + "Master summary saved id=%s model=%s kind=%s ticker=%d map=%d", + summary_id, model, kind, len(ticker_rows), len(map_rows), ) cur.close() conn.close() @@ -413,26 +481,35 @@ def build_map_prompt(batch: list[dict]) -> str: for a in batch ) template = os.getenv("MAP_PROMPT", MAP_PROMPT_DEFAULT) - prefix = build_futures_context() + "\n" if INCLUDE_FUTURES else "" try: - return prefix + template.format(batch_text=batch_text) + return template.format(batch_text=batch_text) except KeyError: - return prefix + template + return template -def build_master_prompt(final_input: str) -> str: - template = os.getenv("SUMMARY_PROMPT", SUMMARY_PROMPT_DEFAULT) - prefix = build_futures_context() + "\n" if INCLUDE_FUTURES else "" - try: - return prefix + template.format(final_input=final_input) - except KeyError: - return prefix + template +def build_master_prompt(final_input: str, recap: bool = False) -> str: + if recap: + template = os.getenv("RECAP_PROMPT", RECAP_PROMPT_DEFAULT) + else: + template = os.getenv("SUMMARY_PROMPT", SUMMARY_PROMPT_DEFAULT) + if "{final_input}" in template: + return template.replace("{final_input}", final_input) + return template def summarize_news() -> None: """Map-reduce summarize recent articles and store brief + ticker + map.""" + recap = is_recap_run() + window = effective_window_minutes(recap=recap) ensure_tables() - if _already_summarized_this_interval(): + if recap: + if _already_recapped_today(): + logger.info( + "Skipping recap: article_summaries already has daily_recap today " + "(set NEWS_SUMMARIZE_FORCE=1 to override)" + ) + return + elif _already_summarized_this_interval(): logger.info( "Skipping summarize: article_summaries already has a row in the last %ss " "(set NEWS_SUMMARIZE_FORCE=1 to override)", @@ -447,14 +524,14 @@ def summarize_news() -> None: logger.warning("NOUS_API_KEY unset in env and api_keys — idle this run") return - articles = get_recent_news() + articles = get_recent_news(window) if not articles: - logger.info("No new articles found in the last %s min.", SUMMARY_WINDOW_MINUTES) + logger.info("No new articles found in the last %s min.", window) return logger.info( - "Processing %d articles with %s (batch_size=%d, futures=%s)...", - len(articles), model, BATCH_SIZE, INCLUDE_FUTURES, + "Processing %d articles with %s (batch_size=%d, recap=%s, window_min=%s)...", + len(articles), model, BATCH_SIZE, recap, window, ) partial_summaries: list[str] = [] @@ -481,7 +558,7 @@ def summarize_news() -> None: logger.info("reduce phase over %d partial summaries", len(partial_summaries)) master_raw = call_llm( - build_master_prompt(final_input), + build_master_prompt(final_input, recap=recap), api_key=api_key, model=model, base_url=base_url, @@ -491,7 +568,13 @@ def summarize_news() -> None: logger.warning("Reduce phase returned empty — nothing to persist.") return parsed = parse_reduce_json(master_raw) - save_batch(parsed["summary_en"], model, parsed["ticker"], parsed["map_items"]) + save_batch( + parsed["summary_en"], + model, + parsed["ticker"], + parsed["map_items"], + kind="daily_recap" if recap else "interval", + ) if __name__ == "__main__": diff --git a/news/summerizer/tests/conftest.py b/news/summerizer/tests/conftest.py new file mode 100644 index 0000000..8cb64cd --- /dev/null +++ b/news/summerizer/tests/conftest.py @@ -0,0 +1,11 @@ +"""Keep summarizer unit tests importable without Postgres drivers.""" + +from __future__ import annotations + +import sys +from types import ModuleType + +if "psycopg2" not in sys.modules: + fake = ModuleType("psycopg2") + fake.connect = lambda **kwargs: None # type: ignore[attr-defined] + sys.modules["psycopg2"] = fake diff --git a/news/summerizer/tests/test_prompts.py b/news/summerizer/tests/test_prompts.py new file mode 100644 index 0000000..e6ca187 --- /dev/null +++ b/news/summerizer/tests/test_prompts.py @@ -0,0 +1,32 @@ +"""Default prompts: breaking news, ignore futures/market tape.""" + +from summarizer import MAP_PROMPT_DEFAULT, RECAP_PROMPT_DEFAULT, SUMMARY_PROMPT_DEFAULT + + +def _assert_breaking_not_futures(prompt: str) -> None: + p = prompt.lower() + assert "breaking" in p + assert "futures" in p + assert "ignore" in p or "do not" in p or "not" in p + assert "es=f" not in p + assert "yfinance" not in p + + +def test_map_prompt_focuses_on_breaking_news_not_futures(): + _assert_breaking_not_futures(MAP_PROMPT_DEFAULT) + + +def test_summary_prompt_focuses_on_breaking_news_not_futures(): + _assert_breaking_not_futures(SUMMARY_PROMPT_DEFAULT) + p = SUMMARY_PROMPT_DEFAULT.lower() + assert "commodity" in p or "market" in p + + +def test_recap_prompt_is_daily_24h_breaking_news(): + p = RECAP_PROMPT_DEFAULT.lower() + _assert_breaking_not_futures(RECAP_PROMPT_DEFAULT) + assert "daily" in p + assert "24" in p + assert "summary_en" in p + assert "ticker" in p + assert "map_items" in p diff --git a/news/summerizer/tests/test_scheduler.py b/news/summerizer/tests/test_scheduler.py new file mode 100644 index 0000000..b2ef43c --- /dev/null +++ b/news/summerizer/tests/test_scheduler.py @@ -0,0 +1,42 @@ +"""Wall-clock scheduling: 15-min analyst + 23:00 America/New_York recap.""" + +from datetime import datetime, timedelta +from zoneinfo import ZoneInfo + +from run_news_summarizer import next_event, next_recap_datetime + +TZ = ZoneInfo("America/New_York") + + +def test_next_recap_is_11pm_same_day_before_2300(): + now = datetime(2026, 8, 28, 15, 4, tzinfo=TZ) + got = next_recap_datetime(now) + assert got == datetime(2026, 8, 28, 23, 0, tzinfo=TZ) + + +def test_next_recap_is_11pm_next_day_at_or_after_2300(): + now = datetime(2026, 8, 28, 23, 0, tzinfo=TZ) + got = next_recap_datetime(now) + assert got == datetime(2026, 8, 29, 23, 0, tzinfo=TZ) + + +def test_next_recap_honors_custom_hour(): + now = datetime(2026, 8, 28, 10, 0, tzinfo=TZ) + got = next_recap_datetime(now, hour=22, minute=30) + assert got == datetime(2026, 8, 28, 22, 30, tzinfo=TZ) + + +def test_next_event_picks_recap_when_sooner_than_interval(): + now = datetime(2026, 8, 28, 22, 50, tzinfo=TZ) + last_periodic = now - timedelta(seconds=100) + when, kind = next_event(now, last_periodic=last_periodic, interval_s=900) + assert kind == "recap" + assert when == datetime(2026, 8, 28, 23, 0, tzinfo=TZ) + + +def test_next_event_picks_interval_when_recap_is_hours_away(): + now = datetime(2026, 8, 28, 10, 0, tzinfo=TZ) + last_periodic = now + when, kind = next_event(now, last_periodic=last_periodic, interval_s=900) + assert kind == "interval" + assert when == now + timedelta(seconds=900) diff --git a/news/summerizer/tests/test_summarizer.py b/news/summerizer/tests/test_summarizer.py new file mode 100644 index 0000000..117044f --- /dev/null +++ b/news/summerizer/tests/test_summarizer.py @@ -0,0 +1,45 @@ +"""Summarizer window, recap flag, and no futures injection into prompts.""" + +from summarizer import ( + build_map_prompt, + build_master_prompt, + effective_window_minutes, + is_recap_run, +) + + +def test_interval_window_defaults_to_15_minutes(monkeypatch): + monkeypatch.delenv("NEWS_RECAP", raising=False) + monkeypatch.delenv("SUMMARY_WINDOW_HOURS", raising=False) + monkeypatch.setenv("SUMMARY_WINDOW_MINUTES", "15") + assert is_recap_run() is False + assert effective_window_minutes() == 15 + + +def test_recap_window_is_24_hours(monkeypatch): + monkeypatch.setenv("NEWS_RECAP", "1") + monkeypatch.setenv("SUMMARY_WINDOW_MINUTES", "15") + assert is_recap_run() is True + assert effective_window_minutes() == 24 * 60 + + +def test_build_map_prompt_does_not_inject_futures(): + prompt = build_map_prompt( + [{"title": "Blast", "domain": "ex.com", "url": "https://ex.com/1", "content": "x" * 120}] + ) + assert "FUTURES PRICES" not in prompt + assert "ES=F" not in prompt + assert "Blast" in prompt + + +def test_build_master_prompt_interval_uses_summary_not_recap(): + prompt = build_master_prompt("partial facts", recap=False) + assert "partial facts" in prompt + assert "daily recap" not in prompt.lower() + + +def test_build_master_prompt_recap_uses_daily_template(): + prompt = build_master_prompt("partial facts", recap=True) + assert "partial facts" in prompt + assert "daily recap" in prompt.lower() + assert "24" in prompt diff --git a/tests/test_api_news.py b/tests/test_api_news.py index 340cbd0..0ba569d 100644 --- a/tests/test_api_news.py +++ b/tests/test_api_news.py @@ -68,14 +68,14 @@ def _seed_article(title: str, url: str, domain: str, ts: str, content: str = "bo asyncio.run(run()) -def _seed_summary(text: str, ts: str, model: str | None = None) -> int: +def _seed_summary(text: str, ts: str, model: str | None = None, kind: str | None = None) -> int: async def run() -> int: conn = await asyncpg.connect(**_conn_kwargs()) try: row = await conn.fetchrow( - "INSERT INTO article_summaries (summary_text, batch_timestamp, model) " - "VALUES ($1, $2, $3) RETURNING id", - text, datetime.fromisoformat(ts), model, + "INSERT INTO article_summaries (summary_text, batch_timestamp, model, kind) " + "VALUES ($1, $2, $3, $4) RETURNING id", + text, datetime.fromisoformat(ts), model, kind, ) return int(row["id"]) finally: @@ -164,9 +164,21 @@ def test_api_news_summaries_contract(clean_news): assert isinstance(body, list) assert len(body) == 1 s = body[0] - assert set(s.keys()) == {"id", "summary_text", "batch_timestamp", "model"} + assert set(s.keys()) == {"id", "summary_text", "batch_timestamp", "model", "kind"} assert s["summary_text"] == "master summary markdown…" assert s["batch_timestamp"].startswith("2026-08-24T18:05") + assert s["kind"] is None + + +@requires_db +def test_api_news_summaries_kind_filter(clean_news): + _seed_summary("interval brief", "2026-08-28T22:05:00+00:00", kind="interval") + _seed_summary("daily recap", "2026-08-28T03:00:00+00:00", kind="daily_recap") + recap = _get("/api/news/summaries?kind=daily_recap").json() + assert len(recap) == 1 + assert recap[0]["summary_text"] == "daily recap" + assert recap[0]["kind"] == "daily_recap" + assert _get("/api/news/summaries?kind=nope").status_code == 422 @requires_db diff --git a/tests/test_frontend_reliability.py b/tests/test_frontend_reliability.py index 7735d5b..908f779 100644 --- a/tests/test_frontend_reliability.py +++ b/tests/test_frontend_reliability.py @@ -14,6 +14,11 @@ def test_summarizer_dockerfile_copies_intel_modules(): assert "nous_client.py" in df +def test_news_panel_pins_daily_recap(): + assert "kind=daily_recap" in HTML + assert "DAILY RECAP" in HTML + + def test_nginx_ws_snippet_has_upgrade_headers(): conf = (ROOT / "deploy/osint-ws.nginx.conf").read_text() assert "proxy_http_version 1.1" in conf From 665aaec22fa17f805ab003a5b8e8492bd7fdd4a1 Mon Sep 17 00:00:00 2001 From: Sirius DevOps Date: Fri, 28 Aug 2026 22:58:04 -0400 Subject: [PATCH 22/79] feat(aircraft): planespotters.net photo in aircraft popup Add planespotters.net latest-photo lookup for ADS-B aircraft. - app/live_layers.py: fetch_planespotters_photo() (hex preferred, reg fallback) + _normalize_planespotter_photo(); 24h TTL cache (their ToS cap). - app/main.py: GET /api/aircraft/photo?hex=...|reg=... (422/404/502). - app/static/index.html: .ps-photo block in ADS-B popup; lazy load on popupopen; thumbnail links to photo page + photographer credit. Server-side proxy, not browser fetch(): planespotters 403s any request carrying an Origin header (every browser fetch() sends one). The thumbnail binary is loaded by the browser straight from their CDN, never re-hosted. Tests: 4 unit + 4 API contract (38 pass in the two files). --- app/live_layers.py | 55 +++++++++++++++++++++++++++ app/main.py | 24 ++++++++++-- app/static/index.html | 51 ++++++++++++++++++++++++- tests/test_api_live_layers.py | 32 ++++++++++++++++ tests/test_live_layers.py | 70 +++++++++++++++++++++++++++++++++++ 5 files changed, 228 insertions(+), 4 deletions(-) diff --git a/app/live_layers.py b/app/live_layers.py index db1c0f7..ace617e 100644 --- a/app/live_layers.py +++ b/app/live_layers.py @@ -19,6 +19,7 @@ from datetime import datetime, timezone from typing import Any, Awaitable, Callable import httpx +from urllib.parse import quote from config import OSINT_USER_AGENT @@ -27,6 +28,9 @@ logger = logging.getLogger("osint.live_layers") MARKER_FIELDS = ("id", "lat", "lon", "heading", "speed", "label", "extra") ADSB_LOL_BASE = "https://api.adsb.lol" +PLANESPOTTERS_PHOTO = "https://api.planespotters.net/pub/photos" +# Planespotters ToS cap server-side JSON caching at 24 hours. +PLANESPOTTERS_CACHE_TTL = 24 * 3600 AMTRAKER_TRAINS = "https://api.amtraker.com/v3/trains" RAINVIEWER_MAPS = "https://api.rainviewer.com/public/weather-maps.json" NWS_ALERTS = "https://api.weather.gov/alerts/active" @@ -803,6 +807,57 @@ async def _get_json(url: str, params: dict | None = None) -> Any: return resp.json() +def _normalize_planespotter_photo(photo: dict) -> dict | None: + """Slim a planespotters.net photo object for the aircraft popup. + + Image binaries are never proxied/re-hosted: we return the CDN ``src`` + and the browser loads it directly (per ToS). + """ + if not isinstance(photo, dict): + return None + large = photo.get("thumbnail_large") or {} + small = photo.get("thumbnail") or {} + src = large.get("src") or small.get("src") + if not src: + return None + size = large.get("size") or small.get("size") or {} + return { + "id": str(photo.get("id") or ""), + "src": src, + "width": size.get("width"), + "height": size.get("height"), + "link": photo.get("link") or "", + "photographer": photo.get("photographer") or "", + } + + +async def fetch_planespotters_photo( + hex_code: str | None = None, reg: str | None = None, +) -> dict | None: + """Latest photo for an aircraft from planespotters.net (hex preferred). + + Server-side only: planespotters 403s any request carrying an ``Origin`` + header (browser fetch() always sends one), so the browser can never reach + it directly. We fetch here with the identifying UA, cache the JSON ≤24h, + and hand the CDN image URL back for the browser to load. + """ + if hex_code: + key = f"psp-hex:{hex_code.strip().lower()}" + url = f"{PLANESPOTTERS_PHOTO}/hex/{quote(hex_code.strip())}" + elif reg: + key = f"psp-reg:{reg.strip().lower()}" + url = f"{PLANESPOTTERS_PHOTO}/reg/{quote(reg.strip())}" + else: + return None + + async def _load() -> dict | None: + data = await _get_json(url) + photos = data.get("photos") or [] + return _normalize_planespotter_photo(photos[0]) if photos else None + + return await _ttl_get(key, PLANESPOTTERS_CACHE_TTL, _load) + + async def fetch_aircraft( bbox: str, limit: int = DEFAULT_LIMIT, persist: bool = False, ) -> list[dict]: diff --git a/app/main.py b/app/main.py index 5b31141..80c5133 100644 --- a/app/main.py +++ b/app/main.py @@ -18,6 +18,7 @@ from contextlib import asynccontextmanager from datetime import datetime, timedelta, timezone from decimal import Decimal from pathlib import Path +from typing import NoReturn from uuid import UUID import structlog @@ -52,8 +53,8 @@ from keystore import KeyFormatError, delete_key, list_keys, set_key from settings_store import SettingsError, get_app_settings, list_models, set_summary_model from live_layers import ( fetch_aircraft, fetch_fire_incidents, fetch_fire_perimeters, - fetch_radar_meta, fetch_storms, fetch_trains, fetch_vessels, - fetch_weather_alerts, overlay_catalog, parse_bbox, + fetch_planespotters_photo, fetch_radar_meta, fetch_storms, fetch_trains, + fetch_vessels, fetch_weather_alerts, overlay_catalog, parse_bbox, ) logging.basicConfig(level=logging.INFO) @@ -1390,7 +1391,7 @@ async def map_layers(): return {"layers": MAP_LAYERS, "overlays": overlay_catalog()} -def _upstream_or_502(exc: Exception, name: str): +def _upstream_or_502(exc: Exception, name: str) -> NoReturn: logger.warning("live_layer_upstream_failed", layer=name, error=str(exc)) raise HTTPException(502, f"{name} upstream unavailable: {exc}") from exc @@ -1424,6 +1425,23 @@ async def list_aircraft( _upstream_or_502(exc, "aircraft") +@app.get("/api/aircraft/photo") +async def aircraft_photo( + hex_code: str | None = Query(None, alias="hex", pattern="^[0-9a-fA-F]{6}$"), + reg: str | None = Query(None, min_length=1, max_length=12), +): + """Latest planespotters.net photo for an aircraft (hex preferred, reg fallback).""" + if not hex_code and not reg: + raise HTTPException(422, "hex or reg required") + try: + photo = await fetch_planespotters_photo(hex_code=hex_code, reg=reg) + except Exception as exc: + _upstream_or_502(exc, "planespotters") + if photo is None: + raise HTTPException(404, "no photo") + return overlay_json(photo, 86400) + + @app.get("/api/trains") async def list_trains( bbox: str | None = Query(None, description="minlon,minlat,maxlon,maxlat"), diff --git a/app/static/index.html b/app/static/index.html index efd9e61..4d2622e 100644 --- a/app/static/index.html +++ b/app/static/index.html @@ -356,6 +356,12 @@ .cam-pop td { padding: 0.12rem 0.2rem; vertical-align: top; } .cam-pop td.k { color: var(--muted); text-transform: uppercase; font-size: 0.6rem; letter-spacing: 0.05em; white-space: nowrap; width: 34%; font-family: 'Share Tech Mono', monospace; } .cam-pop a { color: var(--cyan); word-break: break-all; } + .cam-pop .ps-photo { margin-top: 0.35rem; } + .cam-pop .ps-photo a.ps-link { display: block; } + .cam-pop .ps-thumb { width: 100%; height: auto; max-height: 220px; object-fit: contain; border-radius: 4px; border: 1px solid var(--line); background: var(--bg-0); display: block; } + .cam-pop .ps-credit { font-size: 0.68rem; color: var(--muted); margin-top: 0.2rem; } + .cam-pop .ps-credit a { color: var(--cyan); } + .cam-pop .ps-loading { font-size: 0.68rem; color: var(--muted); margin-top: 0.35rem; } .role-badge { display: inline-block; font-family: 'Share Tech Mono', monospace; font-size: 0.58rem; font-weight: 700; letter-spacing: 0.12em; @@ -1984,6 +1990,7 @@ async function initMap() { } startHlsFrom(root); }); + map.on('popupopen', (e) => { loadPlanePhoto(e.popup.getElement()); }); map.on('popupclose', () => { if (activeHls) { try { activeHls.destroy(); } catch (_) {} activeHls = null; } }); @@ -2648,7 +2655,49 @@ function pointPopup(p) { .slice(0, 8) .forEach(k => add(k, extra[k])); } - return `
${esc(p.label || p.id)}${badge}${rows.join('')}
`; + let photoBlock = ''; + if (src === 'adsb.lol' && (extra.hex || extra.reg)) { + photoBlock = `
`; + } + return `
${esc(p.label || p.id)}${badge}${rows.join('')}
${photoBlock}
`; +} + +/* ── Planespotters.net aircraft photos ──────────────────────────────────── + Lazy-loaded into the ADS-B popup. Server-side endpoint (/api/aircraft/photo) + proxies the JSON (planespotters 403s any Origin-bearing request, which every + browser fetch() sends), but the thumbnail binary is always loaded by the + browser straight from the planespotters CDN — never re-hosted. */ +function loadPlanePhoto(root) { + if (!root) return; + root.querySelectorAll('.ps-photo').forEach(box => { + if (box.dataset.loaded === '1' || box.dataset.loading === '1') return; + const hex = (box.dataset.hex || '').trim(); + const reg = (box.dataset.reg || '').trim(); + if (!hex && !reg) { box.remove(); return; } + box.dataset.loading = '1'; + box.innerHTML = `
photo…
`; + const q = hex ? `hex=${encodeURIComponent(hex)}` : `reg=${encodeURIComponent(reg)}`; + fetch(`${API}/api/aircraft/photo?${q}`, { headers: { 'Accept': 'application/json' } }) + .then(r => { + if (r.status === 404) throw new Error('none'); + if (!r.ok) throw new Error('http ' + r.status); + return r.json(); + }) + .then(ph => { + if (!ph || !ph.src) { box.remove(); return; } + const link = esc(ph.link || ''); + const alt = `Photo of ${esc(reg || hex)}`; + const credit = ph.photographer ? `© ${esc(ph.photographer)}` : ''; + box.dataset.loaded = '1'; + box.innerHTML = + `` + + `${alt}` + + (credit ? `` : ''); + }) + .catch(() => { box.remove(); }); + }); } /* ── Heading-aware live-feed glyph markers ─────────────────────────────── diff --git a/tests/test_api_live_layers.py b/tests/test_api_live_layers.py index 83f200c..7349fd8 100644 --- a/tests/test_api_live_layers.py +++ b/tests/test_api_live_layers.py @@ -75,3 +75,35 @@ def test_vessels_subscribe_rejects_bad_bbox(): assert resp.status_code == 422, bad # Explicit null bbox is the "reset to env default" path (still 200). assert asyncio.run(_post("/api/vessels/subscribe", {"bbox": None})).status_code == 200 + + +def test_aircraft_photo_requires_hex_or_reg(): + assert asyncio.run(_get("/api/aircraft/photo")).status_code == 422 + + +def test_aircraft_photo_rejects_bad_hex(): + # hex must be exactly 6 hex chars + resp = asyncio.run(_get("/api/aircraft/photo?hex=xyz1234")) + assert resp.status_code == 422 + + +def test_aircraft_photo_returns_photo(monkeypatch): + async def fake(hex_code=None, reg=None): + return {"id": "1", "src": "https://t.plnspttrs.net/a_280.jpg", + "link": "https://www.planespotters.net/photo/1/x", "photographer": "A"} + + monkeypatch.setattr("main.fetch_planespotters_photo", fake) + resp = asyncio.run(_get("/api/aircraft/photo?hex=e8027e")) + assert resp.status_code == 200 + body = resp.json() + assert body["src"].startswith("https://t.plnspttrs.net/") + assert "max-age" in (resp.headers.get("cache-control") or "").lower() + + +def test_aircraft_photo_404_when_no_photo(monkeypatch): + async def fake(hex_code=None, reg=None): + return None + + monkeypatch.setattr("main.fetch_planespotters_photo", fake) + resp = asyncio.run(_get("/api/aircraft/photo?reg=D-ABCD")) + assert resp.status_code == 404 diff --git a/tests/test_live_layers.py b/tests/test_live_layers.py index 4ff214d..6982c87 100644 --- a/tests/test_live_layers.py +++ b/tests/test_live_layers.py @@ -572,3 +572,73 @@ def test_persist_aircraft_snapshot_writes_tracks(monkeypatch): }] asyncio.run(persist_aircraft_snapshot(rows)) assert recorded == [("aircraft", "abc")] + + +# ── Planespotters.net photo lookup ──────────────────────────────────────── + +def test_normalize_planespotter_photo_prefers_large_thumbnail(): + from live_layers import _normalize_planespotter_photo + + out = _normalize_planespotter_photo({ + "id": "1053982", + "thumbnail": {"src": "https://t.plnspttrs.net/x_t.jpg", "size": {"width": 200, "height": 141}}, + "thumbnail_large": {"src": "https://t.plnspttrs.net/x_280.jpg", "size": {"width": 395, "height": 280}}, + "link": "https://www.planespotters.net/photo/1053982/foo", + "photographer": "Günther Feniuk", + }) + assert out["id"] == "1053982" + assert out["src"] == "https://t.plnspttrs.net/x_280.jpg" + assert out["width"] == 395 + assert out["height"] == 280 + assert out["photographer"] == "Günther Feniuk" + assert "planespotters.net" in out["link"] + + +def test_normalize_planespotter_photo_empty_or_malformed_returns_none(): + from live_layers import _normalize_planespotter_photo + + assert _normalize_planespotter_photo({}) is None + assert _normalize_planespotter_photo({"thumbnail": {}}) is None + assert _normalize_planespotter_photo(None) is None + assert _normalize_planespotter_photo("not-a-dict") is None + + +def test_fetch_planespotters_photo_hex_builds_url_and_normalizes(monkeypatch): + import asyncio + + from live_layers import fetch_planespotters_photo, _cache + + seen = [] + + async def fake_get(url, params=None): + seen.append(url) + return {"photos": [{ + "id": "1", "thumbnail": {"src": "https://t.plnspttrs.net/a_t.jpg"}, + "thumbnail_large": {"src": "https://t.plnspttrs.net/a_280.jpg"}, + "link": "https://www.planespotters.net/photo/1/x", "photographer": "A", + }]} + + monkeypatch.setattr("live_layers._get_json", fake_get) + _cache.clear() + out = asyncio.run(fetch_planespotters_photo(hex_code="e8027e")) + assert out["src"] == "https://t.plnspttrs.net/a_280.jpg" + assert seen == ["https://api.planespotters.net/pub/photos/hex/e8027e"] + + +def test_fetch_planespotters_photo_reg_fallback_and_no_result(monkeypatch): + import asyncio + + from live_layers import fetch_planespotters_photo, _cache + + seen = [] + + async def fake_get(url, params=None): + seen.append(url) + return {"photos": []} + + monkeypatch.setattr("live_layers._get_json", fake_get) + _cache.clear() + assert asyncio.run(fetch_planespotters_photo(reg="D-ABCD")) is None + assert seen == ["https://api.planespotters.net/pub/photos/reg/D-ABCD"] + # no hex and no reg → no upstream call at all + assert asyncio.run(fetch_planespotters_photo()) is None From 7822d45f37c7768042cb71693dd34e74716b1a45 Mon Sep 17 00:00:00 2001 From: Sirius DevOps Date: Fri, 28 Aug 2026 23:20:40 -0400 Subject: [PATCH 23/79] fix: stop summarizer from bailing to a canned empty brief MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The reduce/recap prompts told the model to AND STOP with "No qualifying…" whenever nothing looked breaking enough, so full article batches became one sentence. Always write summary_en from the provided stories; ticker and map may still be empty. Futures/market tape stay ignored. --- docs/news.md | 5 +++-- news/summerizer/summarizer.py | 22 ++++++++++------------ news/summerizer/tests/test_prompts.py | 22 +++++++++++++++++++++- 3 files changed, 34 insertions(+), 15 deletions(-) diff --git a/docs/news.md b/docs/news.md index 5ac373b..d94d29f 100644 --- a/docs/news.md +++ b/docs/news.md @@ -262,8 +262,9 @@ No Hermes-4 reasoning system prompt. Reduce uses `json_mode=True`. ## Prompts -Both prompts are env-overridable. Defaults focus on **breaking important news** -and explicitly ignore futures, commodity tape, and routine market moves. +Both prompts are env-overridable. Defaults recap the articles actually +provided, ranked by breaking important news, and ignore futures / commodity +tape. ticker/map may be empty; `summary_en` must still be a real brief. `RECAP_PROMPT` (23:00, 24h window) is the daily recap; `SUMMARY_PROMPT` is the 15-min analyst. `INCLUDE_FUTURES` is ignored. diff --git a/news/summerizer/summarizer.py b/news/summerizer/summarizer.py index 82c624a..73f9cb6 100644 --- a/news/summerizer/summarizer.py +++ b/news/summerizer/summarizer.py @@ -129,48 +129,46 @@ Articles in this batch: """ SUMMARY_PROMPT_DEFAULT = """\ -CRITICAL INSTRUCTION - REPEAT 3 TIMES: YOU MUST USE ONLY THE DATA PROVIDED BELOW. DO NOT INVENT, RECALL, OR ADD ANY EVENTS, NAMES, DATES, IMPLICATIONS, PROJECTS, OR DETAILS NOT EXPLICITLY PRESENT IN THE DATA. IF THE DATA HAS NO BREAKING IMPORTANT NEWS, set summary_en to exactly: "No qualifying breaking news in the recent news data." and use empty ticker and map_items arrays. AND STOP. NO EXTERNAL KNOWLEDGE FROM TRAINING. +You are writing an English operator HUD brief from the article facts in DATA below. Use ONLY that data. Do not invent events, names, dates, places, or implications. -All text in English. +Always write a real summary_en that recaps the most important stories present in DATA. Rank geopolitics, military/conflict, security, disasters, and major political developments first. Ignore futures prices, commodity tape, ticker chatter, and routine market data — do not treat price ticks as news. -Focus on breaking important news (geopolitical, military/conflict, security, disasters, major political developments). Ignore futures, commodity prices, and routine market data — do not treat price ticks as news. +ticker and map_items may be empty if nothing is critical or high. Never replace summary_en with a canned empty-brief sentence when DATA contains article facts. Demand a single JSON object (no markdown fences) with this exact shape: { - "summary_en": "English markdown brief or the no-qualifying-events sentence", + "summary_en": "English markdown brief of the provided stories", "ticker": [{"headline": "", "importance": "critical", "url": "", "location_name": ""}], "map_items": [{"headline": "", "importance": "critical", "location_name": "", "lat": 0, "lon": 0, "location_confidence": "city", "category": "military/conflict", "url": ""}] } ticker: only critical and high, max 12, ≤140 chars, no markdown. map_items: only critical and high where a real-world location is explicit in the data. Estimate lat/lon. If location is Unknown or not in the data, omit the item. Never invent a place. Max 20. -summary_en: English markdown brief of breaking important news for an operator HUD. +summary_en: English markdown brief of breaking important news for an operator HUD (bullets or short paragraphs). Cover the actual stories in DATA. DATA: {final_input} """ RECAP_PROMPT_DEFAULT = """\ -You are writing a daily recap of the last 24 hours of news for an OSINT operator HUD. +You are writing a daily recap of the last 24 hours of news for an OSINT operator HUD, using ONLY the article facts in DATA below. Do not invent events, names, dates, places, or implications. -CRITICAL INSTRUCTION: YOU MUST USE ONLY THE DATA PROVIDED BELOW. DO NOT INVENT, RECALL, OR ADD ANY EVENTS, NAMES, DATES, IMPLICATIONS, PROJECTS, OR DETAILS NOT EXPLICITLY PRESENT IN THE DATA. IF THE DATA HAS NO BREAKING IMPORTANT NEWS, set summary_en to exactly: "No qualifying breaking news in the last 24 hours." and use empty ticker and map_items arrays. AND STOP. NO EXTERNAL KNOWLEDGE FROM TRAINING. +Always write a real summary_en daily recap of the most important stories in DATA. Rank geopolitics, military/conflict, security, disasters, and major political developments first. Ignore futures prices, commodity tape, ticker chatter, and routine market data — do not treat price ticks as news. -All text in English. - -Focus on breaking important news from the last 24 hours (geopolitical, military/conflict, security, disasters, major political developments). Ignore futures, commodity prices, and routine market data — do not treat price ticks as news. +ticker and map_items may be empty if nothing is critical or high. Never replace summary_en with a canned empty-brief sentence when DATA contains article facts. Demand a single JSON object (no markdown fences) with this exact shape: { - "summary_en": "English markdown daily recap or the no-qualifying-events sentence", + "summary_en": "English markdown daily recap of the provided stories", "ticker": [{"headline": "", "importance": "critical", "url": "", "location_name": ""}], "map_items": [{"headline": "", "importance": "critical", "location_name": "", "lat": 0, "lon": 0, "location_confidence": "city", "category": "military/conflict", "url": ""}] } ticker: only critical and high, max 12, ≤140 chars, no markdown. map_items: only critical and high where a real-world location is explicit in the data. Estimate lat/lon. If location is Unknown or not in the data, omit the item. Never invent a place. Max 20. -summary_en: English markdown daily recap of the last 24 hours of breaking important news. +summary_en: English markdown daily recap of the last 24 hours of breaking important news. Cover the actual stories in DATA. DATA: {final_input} diff --git a/news/summerizer/tests/test_prompts.py b/news/summerizer/tests/test_prompts.py index e6ca187..e5d4374 100644 --- a/news/summerizer/tests/test_prompts.py +++ b/news/summerizer/tests/test_prompts.py @@ -22,7 +22,27 @@ def test_summary_prompt_focuses_on_breaking_news_not_futures(): assert "commodity" in p or "market" in p -def test_recap_prompt_is_daily_24h_breaking_news(): +def test_summary_prompt_does_not_bail_out_with_canned_empty_brief(): + p = SUMMARY_PROMPT_DEFAULT + assert "AND STOP" not in p + assert "REPEAT 3 TIMES" not in p + assert "No qualifying" not in p + assert "no-qualifying" not in p.lower() + low = p.lower() + assert "always" in low + assert "recap" in low or "summar" in low + + +def test_recap_prompt_does_not_bail_out_with_canned_empty_brief(): + p = RECAP_PROMPT_DEFAULT + assert "AND STOP" not in p + assert "No qualifying" not in p + assert "no-qualifying" not in p.lower() + low = p.lower() + assert "always" in low + assert "daily" in low + assert "24" in low + p = RECAP_PROMPT_DEFAULT.lower() _assert_breaking_not_futures(RECAP_PROMPT_DEFAULT) assert "daily" in p From 20a266563c581181893c04b919aa1ab030de6b82 Mon Sep 17 00:00:00 2001 From: Sirius DevOps Date: Fri, 28 Aug 2026 23:28:28 -0400 Subject: [PATCH 24/79] fix(aircraft): show planespotters photo in overlay popup Planespotters 403s server clients whose User-Agent has no contact email; compose default UA lacked one. Leaflet popup.update() also re-ran the bindPopup factory and wiped the thumbnail after load. - Send a contact UA on planespotters lookups; align compose default. - Resize the popup without re-rendering content. - Keep hex/src on live firefighter upserts so they get a photo too. --- app/live_layers.py | 22 ++++++++++++++++---- app/static/index.html | 42 +++++++++++++++++++++++++++------------ docker-compose.yml | 4 ++-- tests/test_live_layers.py | 18 +++++++++++++---- 4 files changed, 63 insertions(+), 23 deletions(-) diff --git a/app/live_layers.py b/app/live_layers.py index ace617e..4e3b1fd 100644 --- a/app/live_layers.py +++ b/app/live_layers.py @@ -751,6 +751,18 @@ def _headers() -> dict[str, str]: return {"User-Agent": OSINT_USER_AGENT, "Accept": "application/json"} +def _planespotters_headers() -> dict[str, str]: + """Planespotters 403s server clients whose UA has no contact URL/email.""" + ua = (OSINT_USER_AGENT or "").strip() + if ua and ("@" in ua or "http://" in ua.lower() or "https://" in ua.lower()): + return {"User-Agent": ua, "Accept": "application/json"} + base = ua or "osint-dashboard/1.0" + return { + "User-Agent": f"{base} (lancewalters94@gmail.com)", + "Accept": "application/json", + } + + async def _lock_for(key: str) -> asyncio.Lock: async with _key_locks_guard: lock = _key_locks.get(key) @@ -794,15 +806,17 @@ async def close_http() -> None: _http = None -async def _get_json(url: str, params: dict | None = None) -> Any: +async def _get_json( + url: str, params: dict | None = None, headers: dict | None = None, +) -> Any: if _http is None: async with httpx.AsyncClient( timeout=_HTTP_TIMEOUT, follow_redirects=True, headers=_headers(), ) as client: - resp = await client.get(url, params=params) + resp = await client.get(url, params=params, headers=headers) resp.raise_for_status() return resp.json() - resp = await _http.get(url, params=params) + resp = await _http.get(url, params=params, headers=headers) resp.raise_for_status() return resp.json() @@ -851,7 +865,7 @@ async def fetch_planespotters_photo( return None async def _load() -> dict | None: - data = await _get_json(url) + data = await _get_json(url, headers=_planespotters_headers()) photos = data.get("photos") or [] return _normalize_planespotter_photo(photos[0]) if photos else None diff --git a/app/static/index.html b/app/static/index.html index 4d2622e..07cfd7f 100644 --- a/app/static/index.html +++ b/app/static/index.html @@ -356,9 +356,13 @@ .cam-pop td { padding: 0.12rem 0.2rem; vertical-align: top; } .cam-pop td.k { color: var(--muted); text-transform: uppercase; font-size: 0.6rem; letter-spacing: 0.05em; white-space: nowrap; width: 34%; font-family: 'Share Tech Mono', monospace; } .cam-pop a { color: var(--cyan); word-break: break-all; } - .cam-pop .ps-photo { margin-top: 0.35rem; } + .cam-pop .ps-photo { margin-top: 0.45rem; } .cam-pop .ps-photo a.ps-link { display: block; } - .cam-pop .ps-thumb { width: 100%; height: auto; max-height: 220px; object-fit: contain; border-radius: 4px; border: 1px solid var(--line); background: var(--bg-0); display: block; } + .cam-pop .ps-thumb { + width: 100%; height: auto; max-height: 220px; object-fit: contain; + border-radius: 4px; border: 1px solid var(--line); background: var(--bg-0); + display: block; box-shadow: 0 0 10px rgba(53,224,255,0.2); + } .cam-pop .ps-credit { font-size: 0.68rem; color: var(--muted); margin-top: 0.2rem; } .cam-pop .ps-credit a { color: var(--cyan); } .cam-pop .ps-loading { font-size: 0.68rem; color: var(--muted); margin-top: 0.35rem; } @@ -1872,7 +1876,7 @@ function applyLiveMarker(kind, p) { if (acOn && p.aircraft_lat != null) { acGroup = upsertLivePoint(acGroup, { id: p.aircraft_hex, lat: p.aircraft_lat, lon: p.aircraft_lon, - label: p.label || p.aircraft_hex, extra: { type: p.aircraft_type, firefighter: true }, + label: p.label || p.aircraft_hex, extra: { type: p.aircraft_type, firefighter: true, hex: p.aircraft_hex, src: 'adsb.lol' }, }, q => acColor(q), 'ac'); } } @@ -1990,7 +1994,7 @@ async function initMap() { } startHlsFrom(root); }); - map.on('popupopen', (e) => { loadPlanePhoto(e.popup.getElement()); }); + map.on('popupopen', (e) => { loadPlanePhoto(e.popup); }); map.on('popupclose', () => { if (activeHls) { try { activeHls.destroy(); } catch (_) {} activeHls = null; } }); @@ -2656,18 +2660,19 @@ function pointPopup(p) { .forEach(k => add(k, extra[k])); } let photoBlock = ''; - if (src === 'adsb.lol' && (extra.hex || extra.reg)) { - photoBlock = `
`; + const hex = extra.hex || p.id || ''; + if (src === 'adsb.lol' && (hex || extra.reg)) { + photoBlock = `
`; } return `
${esc(p.label || p.id)}${badge}${rows.join('')}
${photoBlock}
`; } /* ── Planespotters.net aircraft photos ──────────────────────────────────── - Lazy-loaded into the ADS-B popup. Server-side endpoint (/api/aircraft/photo) - proxies the JSON (planespotters 403s any Origin-bearing request, which every - browser fetch() sends), but the thumbnail binary is always loaded by the - browser straight from the planespotters CDN — never re-hosted. */ -function loadPlanePhoto(root) { + Lazy-loaded into the ADS-B popup. Server-side /api/aircraft/photo looks up + JSON (their ToS requires a contact User-Agent on server clients). The + thumbnail binary is loaded by the browser from their CDN — never re-hosted. */ +function loadPlanePhoto(popup) { + const root = popup && (popup.getElement ? popup.getElement() : popup); if (!root) return; root.querySelectorAll('.ps-photo').forEach(box => { if (box.dataset.loaded === '1' || box.dataset.loading === '1') return; @@ -2676,6 +2681,13 @@ function loadPlanePhoto(root) { if (!hex && !reg) { box.remove(); return; } box.dataset.loading = '1'; box.innerHTML = `
photo…
`; + const bump = () => { + if (!popup || !popup._map) return; + // popup.update() re-runs bindPopup()'s factory and wipes the . + if (popup._updateLayout) popup._updateLayout(); + if (popup._updatePosition) popup._updatePosition(); + if (popup._adjustPan) popup._adjustPan(); + }; const q = hex ? `hex=${encodeURIComponent(hex)}` : `reg=${encodeURIComponent(reg)}`; fetch(`${API}/api/aircraft/photo?${q}`, { headers: { 'Accept': 'application/json' } }) .then(r => { @@ -2684,7 +2696,7 @@ function loadPlanePhoto(root) { return r.json(); }) .then(ph => { - if (!ph || !ph.src) { box.remove(); return; } + if (!ph || !ph.src) { box.remove(); bump(); return; } const link = esc(ph.link || ''); const alt = `Photo of ${esc(reg || hex)}`; const credit = ph.photographer ? `© ${esc(ph.photographer)}` : ''; @@ -2695,8 +2707,11 @@ function loadPlanePhoto(root) { (ph.width ? ` width="${esc(ph.width)}"` : '') + (ph.height ? ` height="${esc(ph.height)}"` : '') + `>` + (credit ? `` : ''); + const img = box.querySelector('img'); + if (img && !img.complete) img.addEventListener('load', bump, { once: true }); + else bump(); }) - .catch(() => { box.remove(); }); + .catch(() => { box.remove(); bump(); }); }); } @@ -2988,6 +3003,7 @@ async function loadAircraft() { acGroup = renderPoints(acGroup, Array.isArray(pts) ? pts : [], p => acColor(p), true, 'ac'); document.getElementById('lp-ac-count').textContent = (pts.length || 0).toLocaleString(); addExtraAttrib('ADSB.lol ODbL'); + addExtraAttrib('Photo © planespotters.net'); } catch (e) { if (isAbort(e)) return; console.error('Aircraft load failed', e); diff --git a/docker-compose.yml b/docker-compose.yml index e854010..00fd71c 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -93,7 +93,7 @@ services: FIRMS_DATASETS: ${FIRMS_DATASETS:-VIIRS_NOAA20_NRT,VIIRS_NOAA21_NRT} FIRMS_BBOX: ${FIRMS_BBOX:--180,-60,180,75} FIRMS_INTERVAL: ${FIRMS_INTERVAL:-900} - OSINT_USER_AGENT: ${OSINT_USER_AGENT:-osint-dashboard/1.0 (self-hosted)} + OSINT_USER_AGENT: ${OSINT_USER_AGENT:-osint-dashboard/1.0 (self-hosted; lancewalters94@gmail.com)} AISSTREAM_API_KEY: ${AISSTREAM_API_KEY:-} AISSTREAM_BBOX: ${AISSTREAM_BBOX:-24,-125,50,-66} AISSTREAM_IN_INGEST: ${AISSTREAM_IN_INGEST:-0} @@ -127,7 +127,7 @@ services: FIRMS_DATASET: ${FIRMS_DATASET:-VIIRS_NOAA20_NRT} FIRMS_DATASETS: ${FIRMS_DATASETS:-VIIRS_NOAA20_NRT,VIIRS_NOAA21_NRT} FIRMS_BBOX: ${FIRMS_BBOX:--180,-60,180,75} - OSINT_USER_AGENT: ${OSINT_USER_AGENT:-osint-dashboard/1.0 (self-hosted)} + OSINT_USER_AGENT: ${OSINT_USER_AGENT:-osint-dashboard/1.0 (self-hosted; lancewalters94@gmail.com)} AISSTREAM_API_KEY: ${AISSTREAM_API_KEY:-} AISSTREAM_BBOX: ${AISSTREAM_BBOX:-24,-125,50,-66} AISSTREAM_IN_APP: ${AISSTREAM_IN_APP:-1} diff --git a/tests/test_live_layers.py b/tests/test_live_layers.py index 6982c87..ff70c8a 100644 --- a/tests/test_live_layers.py +++ b/tests/test_live_layers.py @@ -610,8 +610,8 @@ def test_fetch_planespotters_photo_hex_builds_url_and_normalizes(monkeypatch): seen = [] - async def fake_get(url, params=None): - seen.append(url) + async def fake_get(url, params=None, headers=None): + seen.append((url, (headers or {}).get("User-Agent", ""))) return {"photos": [{ "id": "1", "thumbnail": {"src": "https://t.plnspttrs.net/a_t.jpg"}, "thumbnail_large": {"src": "https://t.plnspttrs.net/a_280.jpg"}, @@ -622,7 +622,8 @@ def test_fetch_planespotters_photo_hex_builds_url_and_normalizes(monkeypatch): _cache.clear() out = asyncio.run(fetch_planespotters_photo(hex_code="e8027e")) assert out["src"] == "https://t.plnspttrs.net/a_280.jpg" - assert seen == ["https://api.planespotters.net/pub/photos/hex/e8027e"] + assert seen[0][0] == "https://api.planespotters.net/pub/photos/hex/e8027e" + assert "@" in seen[0][1] or "http" in seen[0][1] def test_fetch_planespotters_photo_reg_fallback_and_no_result(monkeypatch): @@ -632,7 +633,7 @@ def test_fetch_planespotters_photo_reg_fallback_and_no_result(monkeypatch): seen = [] - async def fake_get(url, params=None): + async def fake_get(url, params=None, headers=None): seen.append(url) return {"photos": []} @@ -642,3 +643,12 @@ def test_fetch_planespotters_photo_reg_fallback_and_no_result(monkeypatch): assert seen == ["https://api.planespotters.net/pub/photos/reg/D-ABCD"] # no hex and no reg → no upstream call at all assert asyncio.run(fetch_planespotters_photo()) is None + + +def test_planespotters_headers_add_contact_when_ua_is_generic(monkeypatch): + import live_layers + + monkeypatch.setattr(live_layers, "OSINT_USER_AGENT", "osint-dashboard/1.0 (self-hosted)") + ua = live_layers._planespotters_headers()["User-Agent"] + assert "osint-dashboard" in ua + assert "@" in ua From 1f23083351b4db3987aa74ddfe00b9fba663ae6b Mon Sep 17 00:00:00 2001 From: Sirius DevOps Date: Sat, 29 Aug 2026 00:18:49 -0400 Subject: [PATCH 25/79] feat(vessels): VesselAPI quota-capped AIS poller for Middle East blind spot Add a server-side REST poller for VesselAPI (free tier 150 calls/mo) that upserts last-known positions into the shared vessel_last_known store when AISStream is unset. Default box is the Strait of Hormuz (span 3.6 <= 4 deg), never CONUS/NC (AISStream owns US coasts). - app/vesselapi.py: worker loop, 4deg span validator, position->marker transform (skip suspected_glitch), durable Postgres daily-quota table. - Local hard cap 5 successful 2xx/UTC day (VESSELAPI_MAX_CALLS_PER_DAY), monthly floor from X-RateLimit-Remaining, single request limit=50, no nextToken, no filter.sat, no retry-storm. - keystore VESSELAPI_API_KEY registry entry; config + compose env passthrough (app + ingest); wired next to AISStream in main.py lifespan + run_ingester. - GET /api/vessels docstring notes AISStream and/or VesselAPI cache. - tests/test_vesselapi.py: 20 unit tests (no network/DB). --- .env.example | 16 ++ app/config.py | 16 ++ app/keystore.py | 5 + app/main.py | 16 +- app/run_ingester.py | 5 +- app/vesselapi.py | 443 ++++++++++++++++++++++++++++++++++++++++ docker-compose.yml | 10 + tests/test_vesselapi.py | 298 +++++++++++++++++++++++++++ 8 files changed, 806 insertions(+), 3 deletions(-) create mode 100644 app/vesselapi.py create mode 100644 tests/test_vesselapi.py diff --git a/.env.example b/.env.example index 9e99921..50cf113 100644 --- a/.env.example +++ b/.env.example @@ -59,6 +59,22 @@ FIRMS_INTERVAL=900 # Set to 0 to disable the fire loop entirely. INGEST_FIRES=1 +# ── VesselAPI (quota-capped REST AIS poller — free tier 150 calls/mo) ───── +# AISStream keeps US coasts live; VesselAPI fills the Middle East blind spot. +# The poller idles when VESSELAPI_API_KEY is unset. Never called from the map +# pans (GET /api/vessels serves the shared last-known cache only). +VESSELAPI_API_KEY= +# Bounding box(es) as minlat,minlon,maxlat,maxlon (lat/lon order). Semicolon- +# separated for multiple boxes. Default = Strait of Hormuz (span 3.6 ≤ 4° cap). +VESSELAPI_BBOX=25.5,55.4,27.3,57.2 +# Poll cadence in seconds (17280 = 4.8h → 5 polls/day = 150/mo). +VESSELAPI_INTERVAL=17280 +# Local hard cap on successful 2xx calls per UTC day (persisted in Postgres). +VESSELAPI_MAX_CALLS_PER_DAY=5 +# 1 = run the poller inside the dashboard process (default); ingester off. +VESSELAPI_IN_APP=1 +VESSELAPI_IN_INGEST=0 + # ── API keys (managed from the dashboard UI) ────────────────────────────── # Keys such as NOUS_API_KEY and TELEGRAM_TOKEN are stored in the Postgres # `api_keys` table and managed from the dashboard's "Keys" tab diff --git a/app/config.py b/app/config.py index be6ffec..8b8fd82 100644 --- a/app/config.py +++ b/app/config.py @@ -81,3 +81,19 @@ AISSTREAM_BBOX = os.getenv("AISSTREAM_BBOX", "24,-125,50,-66") # without the ingest profile). Set 0 if the ingester owns the only connection. AISSTREAM_IN_APP = os.getenv("AISSTREAM_IN_APP", "1").lower() in ("1", "true", "yes") AISSTREAM_IN_INGEST = os.getenv("AISSTREAM_IN_INGEST", "0").lower() in ("1", "true", "yes") + +# VesselAPI (quota-capped REST AIS poller — free tier 150 calls/mo). +# AISStream keeps US coasts; VesselAPI fills the Middle East blind spot. The +# poller idles when VESSELAPI_API_KEY is unset (never from GET /api/vessels). +VESSELAPI_API_KEY = os.getenv("VESSELAPI_API_KEY", "") +# Bounding box(es) as minlat,minlon,maxlat,maxlon — note lat/lon order (same as +# AISSTREAM_BBOX). Semicolon-separated for multiple boxes. Default: Strait of +# Hormuz (|dLat|+|dLon| = 3.6 ≤ 4° span cap). VesselAPI 400s any box over 4°. +VESSELAPI_BBOX = os.getenv("VESSELAPI_BBOX", "25.5,55.4,27.3,57.2") +# Poll cadence in seconds. 17280 = 4.8h → 5 polls/day (150/mo free tier). +VESSELAPI_INTERVAL = int(os.getenv("VESSELAPI_INTERVAL", "17280")) +# Local hard cap on successful 2xx calls per UTC day (persisted in Postgres). +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). +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") diff --git a/app/keystore.py b/app/keystore.py index 41ea782..c196e8e 100644 --- a/app/keystore.py +++ b/app/keystore.py @@ -72,6 +72,11 @@ KEY_REGISTRY: dict[str, dict] = { "pattern": r"^.{8,}$", "example": "key from https://aisstream.io/account (GitHub login)", }, + "VESSELAPI_API_KEY": { + "description": "VesselAPI REST AIS (150 calls/mo free; server-side poller).", + "pattern": r"^.{8,}$", + "example": "Bearer token from https://dashboard.vesselapi.com/", + }, "OPENSKY_CLIENT_ID": { "description": "OpenSky OAuth client id — optional ADS-B fallback (unused until enabled).", "example": "client id from opensky-network.org account", diff --git a/app/main.py b/app/main.py index 80c5133..7131fc4 100644 --- a/app/main.py +++ b/app/main.py @@ -71,18 +71,26 @@ async def _lifespan(app: FastAPI): await refresh_cache() except Exception: pass - from config import AISSTREAM_IN_APP + from config import AISSTREAM_IN_APP, VESSELAPI_IN_APP ais_task = None + vesselapi_task = None adsb_task = None if AISSTREAM_IN_APP: from ais_stream import run_ais_worker ais_task = asyncio.create_task(run_ais_worker()) + if VESSELAPI_IN_APP: + from vesselapi import run_vesselapi_worker + vesselapi_task = asyncio.create_task(run_vesselapi_worker()) adsb_task = asyncio.create_task(_adsb_refresh_loop()) yield if ais_task is not None: ais_task.cancel() + if vesselapi_task is not None: + vesselapi_task.cancel() if adsb_task is not None: adsb_task.cancel() + from vesselapi import close_client + await close_client() await close_http() @@ -1464,7 +1472,11 @@ async def list_vessels( limit: int = Query(2000, ge=1, le=5000), timestamp: str | None = Query(None, description="ISO time — DVR 1-min tracks instead of live"), ): - """AIS last-known from the server-side AISStream worker. Empty without a key.""" + """AIS last-known from the AISStream worker and/or the VesselAPI poller. + + Empty without either key / until the first successful poll. VesselAPI + positions upsert into the same store (extra.src = "vesselapi"). + """ if bbox: _parse_bbox_query(bbox) try: diff --git a/app/run_ingester.py b/app/run_ingester.py index 293a2e5..5d94389 100644 --- a/app/run_ingester.py +++ b/app/run_ingester.py @@ -24,7 +24,7 @@ import sys sys.path.insert(0, sys_path) -from config import NATS_URL, FIRMS_INTERVAL, FIRMS_DATASET, AISSTREAM_IN_INGEST # noqa: E402 +from config import NATS_URL, FIRMS_INTERVAL, FIRMS_DATASET, AISSTREAM_IN_INGEST, VESSELAPI_IN_INGEST # noqa: E402 from sources import ingest_rss_feed, ingest_gdelt, ingest_earthquakes, ingest_eonet, ingest_cisa_kev # noqa: E402 from fire_sources import ingest_fires # noqa: E402 from ingestor import ingest_event, start_nats_consumer # noqa: E402 @@ -134,6 +134,9 @@ async def main() -> None: if AISSTREAM_IN_INGEST: from ais_stream import run_ais_worker # noqa: E402 tasks.append(asyncio.create_task(run_ais_worker())) + if VESSELAPI_IN_INGEST: + from vesselapi import run_vesselapi_worker # noqa: E402 + tasks.append(asyncio.create_task(run_vesselapi_worker())) await asyncio.gather(producer_loop(), consumer_loop(), *tasks) diff --git a/app/vesselapi.py b/app/vesselapi.py new file mode 100644 index 0000000..266e3e9 --- /dev/null +++ b/app/vesselapi.py @@ -0,0 +1,443 @@ +"""VesselAPI REST poller — quota-capped AIS fallback (free tier 150 calls/mo). + +AISStream (WebSocket) keeps US coasts live; VesselAPI fills the Middle East +blind spot (Strait of Hormuz default box). This worker polls the REST +``GET /v1/location/vessels/bounding-box`` endpoint at most +``VESSELAPI_MAX_CALLS_PER_DAY`` (default 5) *successful 2xx* calls per UTC day +and upserts the results into the shared ``vessel_last_known`` store. + +Idle (no crash) when VESSELAPI_API_KEY is unset. Never called from the GET +/api/vessels path — map pans must not hit upstream. One request per poll, +``pagination.limit=50``, never follow ``nextToken``, never send ``filter.sat``. +""" + +from __future__ import annotations + +import asyncio +import calendar +import logging +import os +from datetime import date, datetime, timezone + +import httpx +from sqlalchemy import Column, Date, DateTime, Integer, Table, func, select, text + +from config import ( + OSINT_USER_AGENT, + VESSELAPI_API_KEY, + VESSELAPI_BBOX, + VESSELAPI_INTERVAL, + VESSELAPI_MAX_CALLS_PER_DAY, +) +from database import async_session, engine, metadata +from live_layers import to_marker, upsert_vessel + +logger = logging.getLogger("osint.vesselapi") + +BASE_URL = "https://api.vesselapi.com/v1" +ENDPOINT = f"{BASE_URL}/location/vessels/bounding-box" +MAX_SPAN_DEG = 4.0 # |dLat| + |dLon| — VesselAPI 400s above this. +PAGE_LIMIT = 50 # pagination.limit; never follow nextToken on the free tier. + +_client: httpx.AsyncClient | None = None +_client_lock = asyncio.Lock() + + +# ── Box parsing / span validation ───────────────────────────────────────── + +class BboxError(ValueError): + """A configured VesselAPI box violates the 4° span rule or is malformed.""" + + +def validate_bbox_span( + minlat: float, minlon: float, maxlat: float, maxlon: float, +) -> None: + """Reject boxes VesselAPI would 400 on (span > 4°, bad order, bad range).""" + if not (-90 <= minlat <= 90 and -90 <= maxlat <= 90 + and -180 <= minlon <= 180 and -180 <= maxlon <= 180): + raise BboxError("coordinates out of range") + if minlat >= maxlat or minlon >= maxlon: + raise BboxError("bbox must have min < max on both axes") + dlat = abs(maxlat - minlat) + dlon = abs(maxlon - minlon) + if dlat + dlon > MAX_SPAN_DEG: + raise BboxError( + f"span |dLat|+|dLon| = {dlat + dlon:.2f}° exceeds {MAX_SPAN_DEG}° cap" + ) + + +def parse_boxes(raw: str) -> list[tuple[float, float, float, float]]: + """Env format: ``minlat,minlon,maxlat,maxlon[; ...]`` (lat/lon order).""" + out: list[tuple[float, float, float, float]] = [] + for chunk in (raw or "").split(";"): + parts = [p.strip() for p in chunk.split(",") if p.strip()] + if len(parts) != 4: + continue + try: + minlat = float(parts[0]) + minlon = float(parts[1]) + maxlat = float(parts[2]) + maxlon = float(parts[3]) + except ValueError: + continue + out.append((minlat, minlon, maxlat, maxlon)) + return out + + +def parse_boxes_validated(raw: str) -> list[tuple[float, float, float, float]]: + """Parse boxes, log + skip any that violate the span/order/range rules.""" + valid: list[tuple[float, float, float, float]] = [] + for box in parse_boxes(raw): + try: + validate_bbox_span(*box) + valid.append(box) + except BboxError as exc: + logger.warning("VesselAPI bbox %r skipped: %s", box, exc) + return valid + + +# ── Position → marker transform ─────────────────────────────────────────── + +def _f(value: object) -> float | None: + if value is None or value == "": + return None + try: + return float(value) + except (TypeError, ValueError): + return None + + +def _s(value: object) -> str | None: + if value is None: + return None + text = str(value).strip() + return text or None + + +def transform_vesselapi_position(obj: dict | None) -> dict | None: + """Map one VesselAPI position object to the shared marker contract. + + Returns None for glitch rows, missing MMSI, or missing coordinates. + """ + if not obj or not isinstance(obj, dict): + return None + if obj.get("suspected_glitch") is True: + return None + mmsi = obj.get("mmsi") + if mmsi is None: + return None + lat = _f(obj.get("latitude")) + lon = _f(obj.get("longitude")) + if lat is None or lon is None: + return None + mmsi_s = str(mmsi) + name = _s(obj.get("vessel_name") or obj.get("name")) + heading = _f(obj.get("heading")) + if heading is None: + heading = _f(obj.get("cog")) + sog = _f(obj.get("sog")) + extra: dict = { + "src": "vesselapi", + "mmsi": mmsi_s, + "cog": obj.get("cog"), + "sog": obj.get("sog"), + "navstat": obj.get("nav_status"), + } + imo = obj.get("imo") + if imo: + extra["imo"] = imo + dest = _s(obj.get("dest") or obj.get("destination")) + if dest: + extra["dest"] = dest + ts = obj.get("timestamp") or obj.get("processed_timestamp") + if ts: + extra["timestamp"] = ts + return to_marker( + mmsi_s, lat, lon, + heading=heading, + speed=sog, + label=name or mmsi_s, + extra=extra, + ) + + +def transform_vesselapi_payload(payload: dict | None) -> list[dict]: + """Flatten a bounding-box response ``{vessels: [...]}`` to markers.""" + if not payload or not isinstance(payload, dict): + return [] + rows = payload.get("vessels") or [] + out = [] + for row in rows: + marker = transform_vesselapi_position(row) + if marker: + out.append(marker) + return out + + +# ── Durable daily quota (Postgres, survives restarts) ───────────────────── +# Mirrors keystore.api_keys: lazy CREATE TABLE IF NOT EXISTS, no alembic fork. + +vesselapi_quota = Table( + "vesselapi_quota", + metadata, + Column("day", Date, primary_key=True), + Column("calls", Integer, nullable=False, server_default="0"), + Column("remaining", Integer, nullable=True), + Column("updated_at", DateTime(timezone=True), server_default=func.now(), nullable=False), +) + +_CREATE_QUOTA_SQL = text( + """ + CREATE TABLE IF NOT EXISTS vesselapi_quota ( + day DATE PRIMARY KEY, + calls INTEGER NOT NULL DEFAULT 0, + remaining INTEGER, + updated_at TIMESTAMPTZ NOT NULL DEFAULT now() + ) + """ +) + +_quota_lock = asyncio.Lock() +_quota_ensured = False + + +async def ensure_quota_table() -> None: + global _quota_ensured + if _quota_ensured: + return + async with _quota_lock: + if _quota_ensured: + return + async with engine.begin() as conn: + await conn.execute(_CREATE_QUOTA_SQL) + _quota_ensured = True + + +class PgQuotaStore: + """Postgres-backed daily call counter. Injected for tests.""" + + async def calls_today(self, day: date) -> int: + await ensure_quota_table() + async with async_session() as session: + row = (await session.execute( + select(vesselapi_quota.c.calls).where(vesselapi_quota.c.day == day) + )).scalar() + return int(row) if row else 0 + + async def remaining_today(self, day: date) -> int | None: + await ensure_quota_table() + async with async_session() as session: + row = (await session.execute( + select(vesselapi_quota.c.remaining).where(vesselapi_quota.c.day == day) + )).scalar() + return int(row) if row is not None else None + + async def bump(self, day: date, remaining: int | None) -> int: + await ensure_quota_table() + now = datetime.now(timezone.utc) + async with async_session() as session: + existing = (await session.execute( + select(vesselapi_quota.c.calls).where(vesselapi_quota.c.day == day) + )).scalar() + if existing is None: + await session.execute( + vesselapi_quota.insert().values( + day=day, calls=1, remaining=remaining, updated_at=now, + ) + ) + else: + await session.execute( + vesselapi_quota.update() + .where(vesselapi_quota.c.day == day) + .values( + calls=vesselapi_quota.c.calls + 1, + remaining=remaining, + updated_at=now, + ) + ) + await session.commit() + return (int(existing) if existing else 0) + 1 + + +# ── Budget / scheduling (pure, unit-testable) ───────────────────────────── + +def days_left_in_month(now: datetime) -> int: + """UTC days remaining in the current month, inclusive of today.""" + _, last = calendar.monthrange(now.year, now.month) + return last - now.day + 1 + + +def budget_allows( + calls_today: int, + remaining: int | None, + days_left: int, + max_per_day: int, +) -> bool: + """True if another poll is permitted today. + + Local hard cap: fewer than ``max_per_day`` successful calls today. + Monthly floor: if ``X-RateLimit-Remaining`` is known, keep at least + ``max_per_day * days_left`` in reserve for the rest of the month. + """ + if calls_today >= max_per_day: + return False + if remaining is not None and remaining <= max_per_day * days_left: + return False + return True + + +def choose_box( + boxes: list[tuple[float, float, float, float]], + calls_today: int, + max_per_day: int, +) -> int: + """Index into ``boxes`` for the next poll. + + Prefer refreshing the first (primary) box rather than spraying one call + across every region — round-robin only when the remaining daily budget is + enough to cover all boxes. + """ + if len(boxes) <= 1: + return 0 + budget_left = max_per_day - calls_today + if budget_left >= len(boxes): + return calls_today % len(boxes) + return 0 + + +# ── HTTP / poll ─────────────────────────────────────────────────────────── + +async def _resolve_key() -> str: + from keystore import get_api_key + return ( + os.getenv("VESSELAPI_API_KEY") + or VESSELAPI_API_KEY + or (await get_api_key("VESSELAPI_API_KEY")) + or "" + ).strip() + + +async def _get_client() -> httpx.AsyncClient: + global _client + if _client is None: + async with _client_lock: + if _client is None: + _client = httpx.AsyncClient( + timeout=httpx.Timeout(15.0, connect=5.0), + follow_redirects=True, + headers={"User-Agent": OSINT_USER_AGENT, "Accept": "application/json"}, + limits=httpx.Limits(max_connections=1, max_keepalive_connections=1), + ) + return _client + + +async def close_client() -> None: + global _client + if _client is not None: + await _client.aclose() + _client = None + + +def _int_header(value: str | None) -> int | None: + if value is None: + return None + try: + return int(value) + except (TypeError, ValueError): + return None + + +async def poll_once(store, boxes: list[tuple[float, float, float, float]], key: str) -> bool: + """One quota-checked poll. Returns True if a successful 2xx was made. + + Only successful 2xx responses count against the monthly quota; 4xx/5xx/429 + are skipped without retry-storming (Retry-After respected by simply + sleeping the interval). + """ + now = datetime.now(timezone.utc) + today = now.date() + calls = await store.calls_today(today) + remaining = await store.remaining_today(today) + days_left = days_left_in_month(now) + if not budget_allows(calls, remaining, days_left, VESSELAPI_MAX_CALLS_PER_DAY): + logger.info( + "VesselAPI quota reached (calls_today=%d, remaining=%s, days_left=%d) — skip poll", + calls, remaining, days_left, + ) + return False + + idx = choose_box(boxes, calls, VESSELAPI_MAX_CALLS_PER_DAY) + minlat, minlon, maxlat, maxlon = boxes[idx] + client = await _get_client() + params = { + "filter.latBottom": str(minlat), + "filter.latTop": str(maxlat), + "filter.lonLeft": str(minlon), + "filter.lonRight": str(maxlon), + "pagination.limit": str(PAGE_LIMIT), + } + headers = {"Authorization": f"Bearer {key}"} + try: + resp = await client.get(ENDPOINT, params=params, headers=headers) + except httpx.HTTPError as exc: + logger.warning("VesselAPI request failed: %s", exc) + return False + + if resp.status_code == 429: + logger.warning( + "VesselAPI rate-limited (Retry-After=%s) — skip poll", + resp.headers.get("Retry-After"), + ) + return False + if resp.status_code >= 400: + logger.warning("VesselAPI HTTP %d — not counted against quota", resp.status_code) + return False + + # 2xx success — counts against the monthly quota. + remaining = _int_header(resp.headers.get("X-RateLimit-Remaining")) + calls = await store.bump(today, remaining) + try: + data = resp.json() + except ValueError: + logger.warning("VesselAPI 2xx with non-JSON body — counted but ignored") + return True + markers = transform_vesselapi_payload(data) + for m in markers: + await upsert_vessel(m) + logger.info( + "VesselAPI poll OK: %d vessels (remaining=%s, calls_today=%d)", + len(markers), remaining, calls, + ) + return True + + +# ── Worker loop ─────────────────────────────────────────────────────────── + +async def run_vesselapi_worker(store: PgQuotaStore | None = None) -> None: + """Long-lived poll loop. Idle when the key is unset; never crashes the app.""" + if store is None: + store = PgQuotaStore() + boxes = parse_boxes_validated(VESSELAPI_BBOX) + if not boxes: + logger.warning( + "VESSELAPI_BBOX has no valid boxes (span ≤ %.1f°) — poller idle", MAX_SPAN_DEG, + ) + while True: + try: + if not boxes: + await asyncio.sleep(VESSELAPI_INTERVAL) + continue + key = await _resolve_key() + if not key: + logger.warning( + "VESSELAPI_API_KEY not set — VesselAPI poller idle. " + "Create a free key at https://dashboard.vesselapi.com/" + ) + await asyncio.sleep(VESSELAPI_INTERVAL) + continue + await poll_once(store, boxes, key) + except asyncio.CancelledError: + raise + except Exception: # noqa: BLE001 — keep the loop alive across transient failures + logger.exception("VesselAPI poll error") + await asyncio.sleep(VESSELAPI_INTERVAL) diff --git a/docker-compose.yml b/docker-compose.yml index 00fd71c..f908975 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -97,6 +97,11 @@ services: AISSTREAM_API_KEY: ${AISSTREAM_API_KEY:-} AISSTREAM_BBOX: ${AISSTREAM_BBOX:-24,-125,50,-66} AISSTREAM_IN_INGEST: ${AISSTREAM_IN_INGEST:-0} + VESSELAPI_API_KEY: ${VESSELAPI_API_KEY:-} + VESSELAPI_BBOX: ${VESSELAPI_BBOX:-25.5,55.4,27.3,57.2} + VESSELAPI_INTERVAL: ${VESSELAPI_INTERVAL:-17280} + VESSELAPI_MAX_CALLS_PER_DAY: ${VESSELAPI_MAX_CALLS_PER_DAY:-5} + VESSELAPI_IN_INGEST: ${VESSELAPI_IN_INGEST:-0} command: ["python", "app/run_ingester.py"] entrypoint: ["python", "app/run_ingester.py"] @@ -131,6 +136,11 @@ services: AISSTREAM_API_KEY: ${AISSTREAM_API_KEY:-} AISSTREAM_BBOX: ${AISSTREAM_BBOX:-24,-125,50,-66} AISSTREAM_IN_APP: ${AISSTREAM_IN_APP:-1} + VESSELAPI_API_KEY: ${VESSELAPI_API_KEY:-} + VESSELAPI_BBOX: ${VESSELAPI_BBOX:-25.5,55.4,27.3,57.2} + VESSELAPI_INTERVAL: ${VESSELAPI_INTERVAL:-17280} + VESSELAPI_MAX_CALLS_PER_DAY: ${VESSELAPI_MAX_CALLS_PER_DAY:-5} + VESSELAPI_IN_APP: ${VESSELAPI_IN_APP:-1} ports: - "127.0.0.1:8000:8000" deploy: diff --git a/tests/test_vesselapi.py b/tests/test_vesselapi.py new file mode 100644 index 0000000..5891ca3 --- /dev/null +++ b/tests/test_vesselapi.py @@ -0,0 +1,298 @@ +"""Unit tests for the VesselAPI poller (no network, no DB). + +Covers box span validation, position → marker mapping, glitch skipping, +and the daily-quota gate (6th 2xx attempt skipped). ``poll_once`` is driven +with an in-memory fake quota store + fake HTTP client; ``upsert_vessel``'s +DB/WS side effects are monkeypatched to no-ops so markers can be asserted in +``vessel_last_known``. +""" + +from __future__ import annotations + +import asyncio +from datetime import datetime, timezone + +import pytest + +import vesselapi +from vesselapi import ( + BboxError, + budget_allows, + choose_box, + days_left_in_month, + parse_boxes, + parse_boxes_validated, + poll_once, + transform_vesselapi_payload, + transform_vesselapi_position, + validate_bbox_span, +) +from live_layers import vessel_last_known + + +# ── Fake quota store (in-memory, injected) ──────────────────────────────── + +class FakeStore: + def __init__(self, calls: int = 0, remaining: int | None = None): + self.calls = calls + self.remaining = remaining + self.bumps = 0 + + async def calls_today(self, day): + return self.calls + + async def remaining_today(self, day): + return self.remaining + + async def bump(self, day, remaining): + self.calls += 1 + self.remaining = remaining + self.bumps += 1 + return self.calls + + +# ── Fake HTTP client ─────────────────────────────────────────────────────── + +class FakeResp: + def __init__(self, status: int = 200, headers: dict | None = None, data: dict | None = None): + self.status_code = status + self.headers = headers or {} + self._data = data or {} + + def json(self): + return self._data + + +class FakeClient: + def __init__(self, *responses: FakeResp): + self.responses = list(responses) + self.calls: list[tuple] = [] + + async def get(self, url, params=None, headers=None): + self.calls.append((url, params, headers)) + return self.responses.pop(0) + + async def aclose(self): + pass + + +def _sample_payload() -> dict: + return { + "vessels": [ + { + "mmsi": 422050100, + "imo": 9321483, + "vessel_name": "HORMUZ STAR", + "latitude": 26.5, + "longitude": 56.3, + "cog": 88.0, + "sog": 12.4, + "heading": 90, + "nav_status": 0, + "timestamp": "2026-08-29T12:00:00Z", + "suspected_glitch": False, + }, + { + "mmsi": 422050101, + "vessel_name": "GLITCHY", + "latitude": 26.6, + "longitude": 56.4, + "cog": 45.0, + "sog": 5.0, + "heading": 45, + "nav_status": 5, + "suspected_glitch": True, + }, + {"mmsi": 422050102, "vessel_name": "NOFIX"}, # no coords → drop + ], + "nextToken": "deadbeef", + } + + +# ── Box span / parsing ───────────────────────────────────────────────────── + +def test_validate_bbox_span_accepts_hormuz(): + validate_bbox_span(25.5, 55.4, 27.3, 57.2) # span 3.6 — no raise + + +def test_validate_bbox_span_rejects_conus(): + with pytest.raises(BboxError): + validate_bbox_span(24.0, -125.0, 50.0, -66.0) # span 85 + + +def test_validate_bbox_span_rejects_marine_regions_gazetteer_box(): + # 25.2732–27.3713 N, 55.1647–57.3419 E → span 4.28 > 4.0. + with pytest.raises(BboxError): + validate_bbox_span(25.2732, 55.1647, 27.3713, 57.3419) + + +def test_validate_bbox_span_rejects_inverted_axes(): + with pytest.raises(BboxError): + validate_bbox_span(27.0, 55.0, 25.0, 57.0) + + +def test_parse_boxes_semicolon_and_skip_malformed(): + boxes = parse_boxes("25.5,55.4,27.3,57.2; 10,20,11,21; garbage") + assert boxes == [(25.5, 55.4, 27.3, 57.2), (10.0, 20.0, 11.0, 21.0)] + + +def test_parse_boxes_validated_skips_over_span(): + # Second box is CONUS-sized → dropped, first kept. + valid = parse_boxes_validated("25.5,55.4,27.3,57.2;24,-125,50,-66") + assert valid == [(25.5, 55.4, 27.3, 57.2)] + + +# ── Position → marker mapping ───────────────────────────────────────────── + +def test_transform_position_maps_shared_marker_contract(): + m = transform_vesselapi_position({ + "mmsi": 422050100, "imo": 9321483, "vessel_name": "HORMUZ STAR", + "latitude": 26.5, "longitude": 56.3, "heading": 90, "cog": 88.0, + "sog": 12.4, "nav_status": 0, "timestamp": "2026-08-29T12:00:00Z", + "suspected_glitch": False, + }) + assert m is not None + assert m["id"] == "422050100" + assert m["lat"] == 26.5 + assert m["lon"] == 56.3 + assert m["label"] == "HORMUZ STAR" + assert m["heading"] == 90 + assert m["speed"] == 12.4 + assert m["extra"]["src"] == "vesselapi" + assert m["extra"]["mmsi"] == "422050100" + assert m["extra"]["imo"] == 9321483 + assert m["extra"]["navstat"] == 0 + assert m["extra"]["cog"] == 88.0 + assert m["extra"]["sog"] == 12.4 + assert m["extra"]["timestamp"] == "2026-08-29T12:00:00Z" + + +def test_transform_position_heading_falls_back_to_cog(): + m = transform_vesselapi_position({ + "mmsi": 123456789, "vessel_name": "X", "latitude": 1.0, "longitude": 2.0, + "heading": None, "cog": 123.4, "sog": 5.0, + }) + assert m["heading"] == 123.4 + + +def test_transform_position_skips_glitch(): + assert transform_vesselapi_position({ + "mmsi": 123456789, "latitude": 1.0, "longitude": 2.0, + "suspected_glitch": True, + }) is None + + +def test_transform_position_skips_missing_coords(): + assert transform_vesselapi_position({"mmsi": 123456789, "vessel_name": "NOFIX"}) is None + + +def test_transform_payload_skips_glitch_and_nofix_rows(): + rows = transform_vesselapi_payload(_sample_payload()) + assert [r["id"] for r in rows] == ["422050100"] + + +# ── Quota budget / scheduling ───────────────────────────────────────────── + +def test_days_left_in_month(): + assert days_left_in_month(datetime(2026, 8, 29, tzinfo=timezone.utc)) == 3 + + +def test_budget_allows_local_daily_cap(): + # 5 calls already made → 6th is blocked regardless of remaining. + assert budget_allows(5, remaining=1000, days_left=3, max_per_day=5) is False + + +def test_budget_allows_monthly_floor(): + # remaining 14 ≤ 5*3=15 → skip; 16 > 15 → allow. + assert budget_allows(2, remaining=14, days_left=3, max_per_day=5) is False + assert budget_allows(2, remaining=16, days_left=3, max_per_day=5) is True + + +def test_budget_allows_unknown_remaining(): + assert budget_allows(2, remaining=None, days_left=3, max_per_day=5) is True + + +def test_choose_box_prefers_primary_when_budget_tight(): + boxes = [(1, 1, 2, 2), (3, 3, 4, 4), (5, 5, 6, 6)] + # 4 calls made, 1 left → always box 0. + assert choose_box(boxes, 4, max_per_day=5) == 0 + + +def test_choose_box_round_robins_when_budget_covers_all(): + boxes = [(1, 1, 2, 2), (3, 3, 4, 4), (5, 5, 6, 6)] + # 0 calls made, 5 left ≥ 3 boxes → round-robin. + assert choose_box(boxes, 0, max_per_day=5) == 0 + assert choose_box(boxes, 1, max_per_day=5) == 1 + assert choose_box(boxes, 2, max_per_day=5) == 2 + + +# ── poll_once integration (fake store + fake client) ───────────────────── + +def _patch_side_effects(monkeypatch): + async def _noop(*a, **k): + return None + + monkeypatch.setattr("tracks.record_position", _noop) + monkeypatch.setattr("geofence.record_and_notify", _noop) + + +def test_poll_once_lands_markers_in_vessel_last_known(monkeypatch): + _patch_side_effects(monkeypatch) + vessel_last_known.clear() + client = FakeClient( + FakeResp(200, {"X-RateLimit-Remaining": "140"}, _sample_payload()), + ) + monkeypatch.setattr(vesselapi, "_get_client", _make_get_client(client)) + store = FakeStore() + + ok = asyncio.run(poll_once(store, [(25.5, 55.4, 27.3, 57.2)], "test-key")) + + assert ok is True + assert store.calls == 1 + assert "422050100" in vessel_last_known + assert vessel_last_known["422050100"]["extra"]["src"] == "vesselapi" + assert "422050101" not in vessel_last_known # glitch skipped + # One HTTP call, bounding-box params, no sat / no nextToken follow. + assert len(client.calls) == 1 + _url, params, headers = client.calls[0] + assert params["filter.latBottom"] == "25.5" + assert params["filter.latTop"] == "27.3" + assert params["filter.lonLeft"] == "55.4" + assert params["filter.lonRight"] == "57.2" + assert params["pagination.limit"] == "50" + assert "sat" not in params + assert headers["Authorization"] == "Bearer test-key" + + +def test_poll_once_sixth_2xx_is_skipped_with_zero_http(monkeypatch): + client = FakeClient() + monkeypatch.setattr(vesselapi, "_get_client", _make_get_client(client)) + # 5 successful calls already today → 6th poll makes no HTTP request. + store = FakeStore(calls=5, remaining=1000) + + ok = asyncio.run(poll_once(store, [(25.5, 55.4, 27.3, 57.2)], "test-key")) + + assert ok is False + assert store.bumps == 0 + assert client.calls == [] + + +def test_poll_once_4xx_not_counted_and_no_upsert(monkeypatch): + _patch_side_effects(monkeypatch) + vessel_last_known.clear() + client = FakeClient(FakeResp(400, {}, {"error": {}})) + monkeypatch.setattr(vesselapi, "_get_client", _make_get_client(client)) + store = FakeStore() + + ok = asyncio.run(poll_once(store, [(25.5, 55.4, 27.3, 57.2)], "test-key")) + + assert ok is False + assert store.bumps == 0 # 4xx does not count against quota + assert vessel_last_known == {} + + +def _make_get_client(client): + async def _get_client(): + return client + + return _get_client From e7429a4161893afe9532be42d2964f61c0afc442 Mon Sep 17 00:00:00 2001 From: Sirius DevOps Date: Sat, 29 Aug 2026 00:40:41 -0400 Subject: [PATCH 26/79] feat(vessels): present AISStream + VesselAPI as two independent providers - keystore KEY_REGISTRY copy splits the two keys (open/shared US-coast WS vs commercial Hormuz 5x/day REST); VesselAPI no longer reads as an AIS backup. - vesselapi.py docstring drops 'fallback'; states both are first-class. - /api/vessels docstring: last-known is the union (extra.src aisstream vs vesselapi). - tests: VesselAPI idles/polls independently of the AISStream key. --- app/keystore.py | 4 ++-- app/main.py | 7 +++--- app/vesselapi.py | 10 ++++---- tests/test_vesselapi.py | 53 +++++++++++++++++++++++++++++++++++++++++ 4 files changed, 65 insertions(+), 9 deletions(-) diff --git a/app/keystore.py b/app/keystore.py index c196e8e..ebae58a 100644 --- a/app/keystore.py +++ b/app/keystore.py @@ -68,12 +68,12 @@ KEY_REGISTRY: dict[str, dict] = { "example": "123456789:AA… (bot token from @BotFather)", }, "AISSTREAM_API_KEY": { - "description": "AISStream WebSocket key — live vessel positions (server-side only).", + "description": "AISStream (open/shared) — live US-coast AIS. Server-side WebSocket only.", "pattern": r"^.{8,}$", "example": "key from https://aisstream.io/account (GitHub login)", }, "VESSELAPI_API_KEY": { - "description": "VesselAPI REST AIS (150 calls/mo free; server-side poller).", + "description": "VesselAPI (commercial) — Strait of Hormuz AIS, 5×/day cache. Paste the Bearer token from dashboard.vesselapi.com. Not a US-coast feed.", "pattern": r"^.{8,}$", "example": "Bearer token from https://dashboard.vesselapi.com/", }, diff --git a/app/main.py b/app/main.py index 7131fc4..0b9e47b 100644 --- a/app/main.py +++ b/app/main.py @@ -1472,10 +1472,11 @@ async def list_vessels( limit: int = Query(2000, ge=1, le=5000), timestamp: str | None = Query(None, description="ISO time — DVR 1-min tracks instead of live"), ): - """AIS last-known from the AISStream worker and/or the VesselAPI poller. + """AIS last-known — union of two independent providers. - Empty without either key / until the first successful poll. VesselAPI - positions upsert into the same store (extra.src = "vesselapi"). + AISStream (extra.src="aisstream", live US-coast WebSocket) and VesselAPI + (extra.src="vesselapi", Strait of Hormuz 5×/day poll) both upsert into the + same store. Empty without either key / until the first successful poll. """ if bbox: _parse_bbox_query(bbox) diff --git a/app/vesselapi.py b/app/vesselapi.py index 266e3e9..2c41612 100644 --- a/app/vesselapi.py +++ b/app/vesselapi.py @@ -1,8 +1,10 @@ -"""VesselAPI REST poller — quota-capped AIS fallback (free tier 150 calls/mo). +"""VesselAPI REST poller — quota-capped AIS for the Middle East (free tier 150 calls/mo). -AISStream (WebSocket) keeps US coasts live; VesselAPI fills the Middle East -blind spot (Strait of Hormuz default box). This worker polls the REST -``GET /v1/location/vessels/bounding-box`` endpoint at most +VesselAPI and AISStream are two independent, first-class vessel providers — +not a primary/fallback pair. AISStream (WebSocket) owns live US-coast AIS; +VesselAPI (REST) covers the Strait of Hormuz (default box) where AISStream +has no coverage. Missing one key never disables the other. This worker polls +the REST ``GET /v1/location/vessels/bounding-box`` endpoint at most ``VESSELAPI_MAX_CALLS_PER_DAY`` (default 5) *successful 2xx* calls per UTC day and upserts the results into the shared ``vessel_last_known`` store. diff --git a/tests/test_vesselapi.py b/tests/test_vesselapi.py index 5891ca3..292bed4 100644 --- a/tests/test_vesselapi.py +++ b/tests/test_vesselapi.py @@ -296,3 +296,56 @@ def _make_get_client(client): return client return _get_client + + +# ── Independent-provider idle behaviour ─────────────────────────────────── +# VesselAPI must never be gated on AISStream (or vice versa): a missing key on +# one provider leaves the other running. ``_StopLoop`` is a BaseException so +# the worker's ``except Exception`` handler can't swallow it — the first +# ``asyncio.sleep`` aborts the loop after exactly one decision. + +class _StopLoop(BaseException): + pass + + +async def _stop_sleep(*_a, **_k): + raise _StopLoop() + + +async def _resolve(value: str): + return value + + +def test_worker_idles_without_vesselapi_key_even_if_aisstream_set(monkeypatch): + # AISStream key present, VesselAPI key absent -> no poll, still idles. + monkeypatch.setenv("AISSTREAM_API_KEY", "unused-aisstream-key") + monkeypatch.setenv("VESSELAPI_API_KEY", "") + monkeypatch.setattr(vesselapi, "_resolve_key", lambda: _resolve("")) + monkeypatch.setattr(vesselapi.asyncio, "sleep", _stop_sleep) + poll_calls: list = [] + async def _spy_poll(store, boxes, key): + poll_calls.append(key) + return True + monkeypatch.setattr(vesselapi, "poll_once", _spy_poll) + + with pytest.raises(_StopLoop): + asyncio.run(vesselapi.run_vesselapi_worker(FakeStore())) + + assert poll_calls == [] + + +def test_worker_polls_with_vesselapi_key_even_if_aisstream_unset(monkeypatch): + # AISStream key absent, VesselAPI key present -> still polls exactly once. + monkeypatch.setenv("AISSTREAM_API_KEY", "") + monkeypatch.setattr(vesselapi, "_resolve_key", lambda: _resolve("vesselapi-key")) + monkeypatch.setattr(vesselapi.asyncio, "sleep", _stop_sleep) + poll_calls: list = [] + async def _spy_poll(store, boxes, key): + poll_calls.append(key) + return True + monkeypatch.setattr(vesselapi, "poll_once", _spy_poll) + + with pytest.raises(_StopLoop): + asyncio.run(vesselapi.run_vesselapi_worker(FakeStore())) + + assert poll_calls == ["vesselapi-key"] From a8ad9ba1ff58fb16bf9f8130326e029cd16c7356 Mon Sep 17 00:00:00 2001 From: Sirius DevOps Date: Sat, 29 Aug 2026 00:58:57 -0400 Subject: [PATCH 27/79] fix(vessels): both AIS providers are first-class, not fallback Layer-panel note and .env.example now match the two-key model: AISStream (US live) and VesselAPI (Hormuz) run independently. --- .env.example | 10 ++++++---- app/static/index.html | 2 +- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/.env.example b/.env.example index 50cf113..d64b31b 100644 --- a/.env.example +++ b/.env.example @@ -59,10 +59,12 @@ FIRMS_INTERVAL=900 # Set to 0 to disable the fire loop entirely. INGEST_FIRES=1 -# ── VesselAPI (quota-capped REST AIS poller — free tier 150 calls/mo) ───── -# AISStream keeps US coasts live; VesselAPI fills the Middle East blind spot. -# The poller idles when VESSELAPI_API_KEY is unset. Never called from the map -# pans (GET /api/vessels serves the shared last-known cache only). +# ── VesselAPI (commercial REST AIS — Hormuz, 5×/day, 150 calls/mo cap) ───── +# Independent of AISStream (open/shared live US-coast WebSocket). Both stay +# on when their keys are set; missing one never disables the other. +# Prefer pasting VESSELAPI_API_KEY on the dashboard Keys page. +# The poller idles when the key is unset. Never called from map pans +# (GET /api/vessels serves the shared last-known cache only). VESSELAPI_API_KEY= # Bounding box(es) as minlat,minlon,maxlat,maxlon (lat/lon order). Semicolon- # separated for multiple boxes. Default = Strait of Hormuz (span 3.6 ≤ 4° cap). diff --git a/app/static/index.html b/app/static/index.html index 07cfd7f..c5737c3 100644 --- a/app/static/index.html +++ b/app/static/index.html @@ -805,7 +805,7 @@ 0
-
Needs AISSTREAM_API_KEY. Magenta = military · gold = law/gov · teal = underway. Click for type / dest / IMO.
+
Two feeds: AISStream (US live) and VesselAPI (Hormuz, 5×/day). Paste both keys on the Keys page. Magenta = military · gold = law/gov · teal = underway. Click for type / dest / IMO.
From 5212aaa5cdcd1ea28460c85482cf5db9bf017269 Mon Sep 17 00:00:00 2001 From: Sirius DevOps Date: Sat, 29 Aug 2026 01:01:09 -0400 Subject: [PATCH 28/79] feat(sentinel1): Sentinel-1 SAR STAC -> self-hosted TiTiler tile template Add GET /api/map/sentinel1?bbox=... which queries Planetary Computer STAC (sentinel-1-grd, last 7d, most recent), signs the vv/hh COG with a SAS token, and returns a same-origin /titiler/... XYZ tile template. Cache keyed on quantized bbox + UTC day (20 min TTL). 429 -> 429 (Retry-After), no imagery -> 404, other upstream errors -> 502. Self-host TiTiler on the Pi (ghcr.io/developmentseed/titiler, arm64, 1G cap, host loopback 8001 -> container 8000) instead of titiler.xyz. nginx /titiler/ proxy snippet routes browser tiles to it; TITILER_PUBLIC_BASE and TITILER_INTERNAL_URL are env-driven (no hardcoded hostnames). --- app/config.py | 7 ++ app/live_layers.py | 137 +++++++++++++++++++++++++++++++- app/main.py | 32 +++++++- deploy/osint-titiler.nginx.conf | 21 +++++ docker-compose.yml | 24 ++++++ tests/test_live_layers.py | 130 ++++++++++++++++++++++++++++++ 6 files changed, 346 insertions(+), 5 deletions(-) create mode 100644 deploy/osint-titiler.nginx.conf diff --git a/app/config.py b/app/config.py index be6ffec..a90f98f 100644 --- a/app/config.py +++ b/app/config.py @@ -72,6 +72,13 @@ OSINT_USER_AGENT = os.getenv( "OSINT_USER_AGENT", "osint-dashboard/1.0 (self-hosted; lancewalters94@gmail.com)" ) +# Self-hosted TiTiler (warps Sentinel-1 signed COGs into XYZ tiles on the Pi). +# TITILER_PUBLIC_BASE is the same-origin path prefix the browser hits through +# the osint.rpi.local nginx vhost (`location /titiler/` → 127.0.0.1:8001). +# TITILER_INTERNAL_URL is the compose-DNS address, used only for health checks. +TITILER_PUBLIC_BASE = os.getenv("TITILER_PUBLIC_BASE", "/titiler").rstrip("/") +TITILER_INTERNAL_URL = os.getenv("TITILER_INTERNAL_URL", "http://titiler:8000") + # AISStream (server-side WebSocket only). Idle when unset. AISSTREAM_API_KEY = os.getenv("AISSTREAM_API_KEY", "") # Bounding box(es) as minlat,minlon,maxlat,maxlon — note lat/lon order (AISStream). diff --git a/app/live_layers.py b/app/live_layers.py index 4e3b1fd..b6e80d1 100644 --- a/app/live_layers.py +++ b/app/live_layers.py @@ -15,13 +15,13 @@ import asyncio import logging import math import time -from datetime import datetime, timezone +from datetime import datetime, timedelta, timezone from typing import Any, Awaitable, Callable import httpx -from urllib.parse import quote +from urllib.parse import quote, urlencode -from config import OSINT_USER_AGENT +from config import OSINT_USER_AGENT, TITILER_PUBLIC_BASE logger = logging.getLogger("osint.live_layers") @@ -45,6 +45,15 @@ WFIGS_PERIMETERS = ( ) NHC_STORMS = "https://www.nhc.noaa.gov/CurrentStorms.json" +PC_STAC_SEARCH = "https://planetarycomputer.microsoft.com/api/stac/v1/search" +PC_SAS_TOKEN = "https://planetarycomputer.microsoft.com/api/sas/v1/token/sentinel-1-grd" +# Self-hosted TiTiler on the Pi, exposed same-origin through the osint.rpi.local +# nginx vhost. Relative template — Leaflet resolves it against the page origin, +# so the browser never touches a raw loopback port or titiler.xyz. +TITILER_COG_TILES = f"{TITILER_PUBLIC_BASE}/cog/tiles/WebMercatorQuad/{{z}}/{{x}}/{{y}}@1x" +SENTINEL1_TTL = 20 * 60 # 15–30 min quota-friendly window +SENTINEL1_ATTRIBUTION = "Copernicus Sentinel-1 / Microsoft Planetary Computer" + IEM_NEXRAD = "https://mesonet.agron.iastate.edu/cache/tile.py/1.0.0/nexrad-n0q/{z}/{x}/{y}.png" GIBS_THERMAL = ( "https://gibs.earthdata.nasa.gov/wmts/epsg3857/best/" @@ -110,6 +119,15 @@ def overlay_catalog() -> dict: "maxZoom": 9, "attribution": "NASA GIBS / EOSDIS", }, + "sentinel1_sar": { + "id": "sentinel1_sar", + "title": "Sentinel-1 SAR (Cloud-Penetrating)", + "kind": "raster", + "tileUrl": None, # filled from /api/map/sentinel1 (signed COG) + "endpoint": "/api/map/sentinel1", + "maxZoom": 14, + "attribution": SENTINEL1_ATTRIBUTION, + }, "nws_alerts": {"id": "nws_alerts", "kind": "geojson", "endpoint": "/api/weather-alerts"}, "wfigs_incidents": {"id": "wfigs_incidents", "kind": "points", "endpoint": "/api/fire-incidents"}, "wfigs_perimeters": {"id": "wfigs_perimeters", "kind": "geojson", "endpoint": "/api/fire-perimeters"}, @@ -1136,3 +1154,116 @@ async def fetch_storms() -> list[dict]: return transform_nhc_storms(await _get_json(NHC_STORMS)) return await _ttl_get("nhc:storms", 300.0, _load) + + +# ── Sentinel-1 SAR (Planetary Computer STAC → signed COG tile template) ──── + +class UpstreamRateLimited(Exception): + """Planetary Computer returned 429. Carries Retry-After for the client.""" + + def __init__(self, retry_after: str | None = None): + self.retry_after = retry_after + super().__init__("planetary computer rate limited") + + +async def _post_json( + url: str, json: dict | None = None, headers: dict | None = None, +) -> Any: + if _http is None: + async with httpx.AsyncClient( + timeout=_HTTP_TIMEOUT, follow_redirects=True, headers=_headers(), + ) as client: + resp = await client.post(url, json=json, headers=headers) + resp.raise_for_status() + return resp.json() + resp = await _http.post(url, json=json, headers=headers) + resp.raise_for_status() + return resp.json() + + +async def _pc_call(coro: Awaitable[Any]) -> Any: + """Run a Planetary Computer call, mapping 429 → UpstreamRateLimited.""" + try: + return await coro + except httpx.HTTPStatusError as exc: + if exc.response.status_code == 429: + raise UpstreamRateLimited( + exc.response.headers.get("Retry-After") + ) from exc + raise + + +def sign_cog_url(href: str, token: str) -> str: + """Append a SAS token to a PC blob URL (respect existing query string).""" + sep = "&" if "?" in href else "?" + return f"{href}{sep}token={quote(token, safe='')}" + + +def sentinel1_tile_url(signed_cog: str) -> str: + """TiTiler XYZ template for a signed COG (Leaflet substitutes {z}/{x}/{y}).""" + params = urlencode({ + "url": signed_cog, + "rescale": "0,500", + "colormap_name": "cfastie", + }) + return f"{TITILER_COG_TILES}?{params}" + + +async def fetch_sentinel1(bbox: str) -> dict | None: + """Most recent Sentinel-1 GRD COG for a viewport, signed and TiTiler-ready. + + Returns the overlay tile-template dict, or ``None`` when no GRD imagery + covers the bbox in the last 7 days (caller maps to 404). Queries Planetary + Computer only when called; cached per quantized bbox + UTC day. + """ + minlon, minlat, maxlon, maxlat = parse_bbox(bbox) + day = datetime.now(timezone.utc).date().isoformat() + key = f"sentinel1:{day}:{bbox_cell_key(bbox)}" + + async def _load() -> dict | None: + now = datetime.now(timezone.utc) + week_ago = now - timedelta(days=7) + payload = { + "collections": ["sentinel-1-grd"], + "bbox": [minlon, minlat, maxlon, maxlat], + "datetime": f"{week_ago.isoformat()}/{now.isoformat()}", + "limit": 1, + "sortby": [{"field": "datetime", "direction": "desc"}], + } + data = await _pc_call(_post_json(PC_STAC_SEARCH, json=payload)) + features = data.get("features") or [] + if not features: + return None + + feat = features[0] + assets = feat.get("assets") or {} + chosen_href: str | None = None + polarization: str | None = None + for pol in ("vv", "hh"): + href = (assets.get(pol) or {}).get("href") + if href: + chosen_href = href + polarization = pol + break + if not chosen_href: + return None + + sas = await _pc_call(_get_json(PC_SAS_TOKEN)) + token = (sas or {}).get("token") + if not token: + raise RuntimeError("planetarycomputer SAS token missing") + signed = sign_cog_url(chosen_href, token) + + props = feat.get("properties") or {} + return { + "id": "sentinel-1-sar", + "kind": "raster", + "tileUrl": sentinel1_tile_url(signed), + "opacity": 0.8, + "itemId": feat.get("id"), + "datetime": props.get("datetime") or feat.get("datetime"), + "polarization": polarization, + "attribution": SENTINEL1_ATTRIBUTION, + } + + return await _ttl_get(key, float(SENTINEL1_TTL), _load) diff --git a/app/main.py b/app/main.py index 80c5133..8be30d7 100644 --- a/app/main.py +++ b/app/main.py @@ -53,8 +53,9 @@ from keystore import KeyFormatError, delete_key, list_keys, set_key from settings_store import SettingsError, get_app_settings, list_models, set_summary_model from live_layers import ( fetch_aircraft, fetch_fire_incidents, fetch_fire_perimeters, - fetch_planespotters_photo, fetch_radar_meta, fetch_storms, fetch_trains, - fetch_vessels, fetch_weather_alerts, overlay_catalog, parse_bbox, + fetch_planespotters_photo, fetch_radar_meta, fetch_sentinel1, fetch_storms, + fetch_trains, fetch_vessels, fetch_weather_alerts, overlay_catalog, + parse_bbox, UpstreamRateLimited, ) logging.basicConfig(level=logging.INFO) @@ -1405,6 +1406,33 @@ async def map_radar(): _upstream_or_502(exc, "radar") +@app.get("/api/map/sentinel1") +async def map_sentinel1(bbox: str = Query(..., description="minlon,minlat,maxlon,maxlat")): + """Most recent Sentinel-1 GRD as a signed COG tile template (TiTiler). + + Queries Planetary Computer only on demand; no tiles proxied through the Pi. + """ + _parse_bbox_query(bbox) + try: + result = await fetch_sentinel1(bbox) + except UpstreamRateLimited as exc: + headers = {"Retry-After": exc.retry_after} if exc.retry_after else None + raise HTTPException( + 429, "Planetary Computer rate limit", headers=headers, + ) from exc + except Exception as exc: + _upstream_or_502(exc, "sentinel1") + if result is None: + return JSONResponse( + status_code=404, + content={ + "error": "no_imagery", + "message": "No Sentinel-1 GRD in the last 7 days for this bbox", + }, + ) + return overlay_json(result, 300) + + @app.get("/api/aircraft") async def list_aircraft( bbox: str = Query(..., description="minlon,minlat,maxlon,maxlat"), diff --git a/deploy/osint-titiler.nginx.conf b/deploy/osint-titiler.nginx.conf new file mode 100644 index 0000000..829ab66 --- /dev/null +++ b/deploy/osint-titiler.nginx.conf @@ -0,0 +1,21 @@ +# osint.rpi.local — Sentinel-1 SAR tile proxy (/titiler/) +# +# GitOps: this file is the source of truth. On the Pi: +# sudo cp deploy/osint-titiler.nginx.conf /etc/nginx/snippets/osint-titiler.conf +# then `include snippets/osint-titiler.conf;` inside the osint.rpi.local server +# block (before `location /`), `nginx -t && systemctl reload nginx`. +# +# The browser hits /titiler/cog/tiles/... (same-origin). We strip the /titiler +# prefix so self-hosted TiTiler (127.0.0.1:8001) sees /cog/tiles/... and proxy +# its response straight back. Tiles are heavy PNGs — disable buffering so a +# slow client doesn't hold a worker open. + +location /titiler/ { + proxy_pass http://127.0.0.1:8001/; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_buffering off; + proxy_read_timeout 300s; +} diff --git a/docker-compose.yml b/docker-compose.yml index 00fd71c..5785fdf 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -131,6 +131,9 @@ services: AISSTREAM_API_KEY: ${AISSTREAM_API_KEY:-} AISSTREAM_BBOX: ${AISSTREAM_BBOX:-24,-125,50,-66} AISSTREAM_IN_APP: ${AISSTREAM_IN_APP:-1} + # ── Self-hosted TiTiler (Sentinel-1 SAR tiles) ── + TITILER_PUBLIC_BASE: ${TITILER_PUBLIC_BASE:-/titiler} + TITILER_INTERNAL_URL: ${TITILER_INTERNAL_URL:-http://titiler:8000} ports: - "127.0.0.1:8000:8000" deploy: @@ -143,6 +146,27 @@ services: timeout: 5s retries: 5 + # ── Self-hosted TiTiler (Sentinel-1 SAR COG → XYZ tiles) ──────────────── + # Warps the signed Planetary Computer COG into WebMercator XYZ tiles so the + # browser never loads a multi-GB GeoTIFF. The FastAPI app signs the COG URL + # and returns a /titiler/... template; nginx routes /titiler/ here. + # Listens on 8000 INSIDE the container (the app already owns host 8000); + # published on host loopback 127.0.0.1:8001 only. + titiler: + image: ghcr.io/developmentseed/titiler:latest + container_name: osint-titiler + platform: linux/arm64 + restart: unless-stopped + environment: + - PORT=8000 + - WORKERS_PER_CORE=1 + ports: + - "127.0.0.1:8001:8000" + deploy: + resources: + limits: + memory: 1G + camera-service: build: context: . diff --git a/tests/test_live_layers.py b/tests/test_live_layers.py index ff70c8a..ebd4340 100644 --- a/tests/test_live_layers.py +++ b/tests/test_live_layers.py @@ -8,6 +8,8 @@ from live_layers import ( parse_bbox, quantize_bbox, rainviewer_tile_url, + sign_cog_url, + sentinel1_tile_url, slim_alert_properties, to_marker, transform_adsb_lol, @@ -15,6 +17,8 @@ from live_layers import ( transform_amtraker, transform_nhc_storms, transform_wfigs_incidents, + SENTINEL1_ATTRIBUTION, + TITILER_COG_TILES, _cache, _ttl_get, _wfigs_params, @@ -652,3 +656,129 @@ def test_planespotters_headers_add_contact_when_ua_is_generic(monkeypatch): ua = live_layers._planespotters_headers()["User-Agent"] assert "osint-dashboard" in ua assert "@" in ua + + +# ── Sentinel-1 SAR (Planetary Computer STAC → signed COG template) ──────── + +def test_sign_cog_url_appends_token(): + assert sign_cog_url("https://blob.example/x.tif", "tok=abc") == \ + "https://blob.example/x.tif?token=tok%3Dabc" + # Existing query string → append with & + assert sign_cog_url("https://blob.example/x.tif?st=1", "tok") == \ + "https://blob.example/x.tif?st=1&token=tok" + + +def test_sentinel1_tile_url_contains_titiler_rescale_and_cfastie(): + signed = "https://blob.example/x.tif?token=secret" + url = sentinel1_tile_url(signed) + assert url.startswith(TITILER_COG_TILES + "?") + assert "WebMercatorQuad/{z}/{x}/{y}@1x" in url + assert "url=https%3A%2F%2Fblob.example%2Fx.tif%3Ftoken%3Dsecret" in url + assert "rescale=0%2C500" in url + assert "colormap_name=cfastie" in url + + +def test_sentinel1_tile_url_is_same_origin_relative(): + # Self-hosted TiTiler: the browser must hit the Pi's nginx vhost, not + # titiler.xyz or a raw host:port. The template is a root-relative path. + url = sentinel1_tile_url("https://blob.example/x.tif") + assert url.startswith("/titiler/cog/tiles/WebMercatorQuad/") + assert "://" not in url + assert "titiler.xyz" not in url + + +def _stac_feature(assets: dict) -> dict: + return { + "type": "Feature", + "id": "S1A_IW_GRDH_1SDV_20240820T000000", + "properties": {"datetime": "2024-08-20T00:00:00Z"}, + "assets": assets, + } + + +def test_fetch_sentinel1_vv_signed_tile_url(monkeypatch): + import asyncio + from live_layers import fetch_sentinel1, _cache + + calls = [] + + async def fake_post(url, json=None, headers=None): + calls.append(("post", url, json)) + return {"features": [_stac_feature({ + "vv": {"href": "https://blob.example/grd-vv.tif"}, + })]} + + async def fake_get(url, params=None, headers=None): + calls.append(("get", url)) + return {"token": "sig=abc123"} + + monkeypatch.setattr("live_layers._post_json", fake_post) + monkeypatch.setattr("live_layers._get_json", fake_get) + _cache.clear() + + out = asyncio.run(fetch_sentinel1("-80,35,-79,36")) + assert out["id"] == "sentinel-1-sar" + assert out["kind"] == "raster" + assert out["polarization"] == "vv" + assert out["opacity"] == 0.8 + assert out["itemId"].startswith("S1A") + assert out["attribution"] == SENTINEL1_ATTRIBUTION + assert "WebMercatorQuad/{z}/{x}/{y}@1x" in out["tileUrl"] + assert "rescale=0%2C500" in out["tileUrl"] + assert "colormap_name=cfastie" in out["tileUrl"] + # SAS token "sig=abc123" is signed as ?token=sig%3Dabc123, then the whole + # COG URL is percent-encoded again as a query param (=> sig%253Dabc123). + assert "sig%253Dabc123" in out["tileUrl"] + # STAC search payload shape + post_url, post_json = calls[0][1], calls[0][2] + assert post_url.endswith("/api/stac/v1/search") + assert post_json["collections"] == ["sentinel-1-grd"] + assert post_json["limit"] == 1 + assert post_json["sortby"][0]["direction"] == "desc" + + +def test_fetch_sentinel1_uses_hh_when_vv_missing(monkeypatch): + import asyncio + from live_layers import fetch_sentinel1, _cache + + async def fake_post(url, json=None, headers=None): + return {"features": [_stac_feature({ + "hh": {"href": "https://blob.example/grd-hh.tif"}, + })]} + + async def fake_get(url, params=None, headers=None): + return {"token": "tok"} + + monkeypatch.setattr("live_layers._post_json", fake_post) + monkeypatch.setattr("live_layers._get_json", fake_get) + _cache.clear() + + out = asyncio.run(fetch_sentinel1("-80,35,-79,36")) + assert out["polarization"] == "hh" + assert "url=https%3A%2F%2Fblob.example%2Fgrd-hh.tif" in out["tileUrl"] + + +def test_fetch_sentinel1_none_on_empty_features(monkeypatch): + import asyncio + from live_layers import fetch_sentinel1, _cache + + async def fake_post(url, json=None, headers=None): + return {"features": []} + + monkeypatch.setattr("live_layers._post_json", fake_post) + _cache.clear() + + assert asyncio.run(fetch_sentinel1("-80,35,-79,36")) is None + + +def test_fetch_sentinel1_none_when_no_vv_or_hh(monkeypatch): + import asyncio + from live_layers import fetch_sentinel1, _cache + + async def fake_post(url, json=None, headers=None): + return {"features": [_stac_feature({"thumbnail": {"href": "https://x"}})]} + + monkeypatch.setattr("live_layers._post_json", fake_post) + _cache.clear() + + assert asyncio.run(fetch_sentinel1("-80,35,-79,36")) is None From 773d204f689c22b06ea5c19d06e484095937f06c Mon Sep 17 00:00:00 2001 From: Sirius DevOps Date: Sat, 29 Aug 2026 09:47:25 -0400 Subject: [PATCH 29/79] fix(ui): keep last Keys card above ticker on mobile Stage uses 100dvh (100vh fallback) plus safe-area so the scrollport ends above the dock. Subviews get extra bottom padding; phone key forms wrap with 44px tap targets. --- app/static/index.html | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/app/static/index.html b/app/static/index.html index c5737c3..65f004d 100644 --- a/app/static/index.html +++ b/app/static/index.html @@ -2,7 +2,7 @@ - + OSINT//DASHBOARD — Global Situational Awareness Terminal @@ -155,7 +155,9 @@ /* ═══════════════ STAGE / VIEWS ═══════════════ */ .stage { + /* 100vh first for old browsers; 100dvh shrinks with mobile URL chrome */ height: calc(100vh - var(--topbar-h) - var(--dock-h)); + height: calc(100dvh - var(--topbar-h) - var(--dock-h) - env(safe-area-inset-bottom, 0px)); position: relative; } .stage.scroll { overflow-y: auto; } @@ -382,7 +384,7 @@ /* ── Sub-views (News / Events / Alerts / ... ) ── */ .subview { - padding: 1.2rem clamp(1rem, 3vw, 2rem) 2.2rem; + padding: 1.2rem clamp(1rem, 3vw, 2rem) calc(var(--dock-h) + 1.5rem); max-width: 1280px; margin: 0 auto; } .subview > h2 { @@ -488,7 +490,7 @@ .key-status { font-size: 0.68rem; font-family: 'Share Tech Mono', monospace; padding: 0.18rem 0.55rem; border-radius: 3px; white-space: nowrap; } .key-status.set { background: rgba(83,240,165,0.1); color: var(--green); box-shadow: 0 0 10px rgba(83,240,165,0.3); } .key-status.missing { background: rgba(255,93,93,0.1); color: var(--red); box-shadow: 0 0 10px rgba(255,93,93,0.2); } - .key-desc { font-size: 0.8rem; color: var(--muted); margin-bottom: 0.7rem; } + .key-desc { font-size: 0.8rem; color: var(--muted); margin-bottom: 0.7rem; overflow-wrap: anywhere; } .key-hint { font-size: 0.7rem; color: var(--muted); opacity: 0.8; margin-top: 0.15rem; font-family: 'Share Tech Mono', monospace; } .key-form { display: flex; gap: 0.5rem; } .key-form input { flex: 1; background: var(--bg-0); border: 1px solid var(--line); border-radius: 4px; padding: 0.5rem 0.6rem; color: var(--text); font-size: 0.82rem; font-family: 'Share Tech Mono', monospace; } @@ -523,6 +525,8 @@ .dock { position: fixed; left: 0; right: 0; bottom: 0; z-index: 900; height: var(--dock-h); display: flex; flex-direction: column; + padding-bottom: env(safe-area-inset-bottom, 0px); + box-sizing: content-box; border-top: 1px solid var(--line); background: linear-gradient(180deg, var(--bg-1), #050a13); box-shadow: 0 -6px 30px rgba(0,0,0,0.5); @@ -605,6 +609,16 @@ .tick-tag { display: none; } .hud-chips { display: none; } .map-hint { max-width: 80%; } + .key-grid { grid-template-columns: minmax(0, 1fr); } + .key-card { min-width: 0; overflow: hidden; } + .key-form { flex-wrap: wrap; } + .key-form input { + flex: 1 1 100%; + width: 100%; + min-width: 0; + min-height: 44px; + } + .key-form .btn { min-height: 44px; min-width: 44px; } } @media (prefers-reduced-motion: reduce) { .tick-track { animation: none; } From 82ef815e2038481c049fb36734c418b660c965fb Mon Sep 17 00:00:00 2001 From: Sirius DevOps Date: Sat, 29 Aug 2026 10:30:46 -0400 Subject: [PATCH 30/79] fix(ui): stop map chrome overlapping on phone Retune the 820px layout so GIBS sits as a full-width bar under the header, LAYERS starts collapsed top-left, zoom stays top-right, and the DVR row clears the ticker. Hide attribution and map-hint on phone so NASA/RainViewer text no longer paints through MKT/NEWS. --- app/static/index.html | 71 +++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 69 insertions(+), 2 deletions(-) diff --git a/app/static/index.html b/app/static/index.html index 65f004d..38d1849 100644 --- a/app/static/index.html +++ b/app/static/index.html @@ -608,7 +608,6 @@ .tick-label { min-width: 56px; padding: 0 0.5rem; } .tick-tag { display: none; } .hud-chips { display: none; } - .map-hint { max-width: 80%; } .key-grid { grid-template-columns: minmax(0, 1fr); } .key-card { min-width: 0; overflow: hidden; } .key-form { flex-wrap: wrap; } @@ -619,6 +618,63 @@ min-height: 44px; } .key-form .btn { min-height: 44px; min-width: 44px; } + + /* Phone map chrome: one column, no shared pixels */ + #view-map.view.active { + display: flex; + flex-direction: column; + } + .map-toolbar { + position: relative; + left: auto; + top: auto; + transform: none; + margin: 6px 8px 4px; + width: auto; + max-width: none; + flex: 0 0 auto; + align-self: stretch; + flex-wrap: wrap; + } + .map-toolbar select { + flex: 1 1 8rem; + min-width: 0; + } + .map-stage { + flex: 1 1 auto; + height: auto; + min-height: 0; + } + #layer-panel { + top: 8px; + left: 8px; + width: min(268px, calc(100% - 68px)); + max-height: calc(100% - 16px - 52px); + } + /* Collapsed by default so Africa isn't buried under the stack */ + #layer-panel .lp-body { display: none; } + #layer-panel.is-open .lp-body { display: flex; } + #layer-panel:not(.is-open) .lp-caret { transform: rotate(-90deg); } + .map-hint { display: none; } + #dvr-bar { + left: 8px; + right: 8px; + bottom: 8px; + transform: none; + min-width: 0; + max-width: calc(100% - 16px); + width: calc(100% - 16px); + flex-wrap: wrap; + } + #dvr-bar input[type=range] { + min-width: 0; + min-height: 32px; + } + .leaflet-control-attribution { display: none !important; } + .leaflet-top.leaflet-right .leaflet-control-zoom { + margin-top: 8px; + margin-right: 8px; + } } @media (prefers-reduced-motion: reduce) { .tick-track { animation: none; } @@ -2228,8 +2284,15 @@ function quantizeBBox(bbox, decimals = 1) { } function toggleLayerPanel() { const panel = document.getElementById('layer-panel'); + const head = panel.querySelector('.lp-head'); + if (window.matchMedia('(max-width: 820px)').matches) { + panel.classList.toggle('is-open'); + const open = panel.classList.contains('is-open'); + head.setAttribute('aria-expanded', String(open)); + return; + } panel.classList.toggle('collapsed'); - panel.querySelector('.lp-head').setAttribute('aria-expanded', !panel.classList.contains('collapsed')); + head.setAttribute('aria-expanded', String(!panel.classList.contains('collapsed'))); } /* ── Basemap visibility / opacity ── */ @@ -3130,6 +3193,10 @@ initNav(); initSettings(); initMarketTicker(); checkHealth(); +if (window.matchMedia('(max-width: 820px)').matches) { + const lpHead = document.querySelector('#layer-panel .lp-head'); + if (lpHead) lpHead.setAttribute('aria-expanded', 'false'); +} initMap(); // Ticker lives on the map HUD — load after overlays start so it does not // contend with the first bbox burst. Payload is slim (no article bodies). From fa06c1dc42e9f5352870384ab4284939dde99fcb Mon Sep 17 00:00:00 2001 From: Sirius DevOps Date: Sat, 29 Aug 2026 11:15:34 -0400 Subject: [PATCH 31/79] feat(map): Sentinel-1 SAR layer toggle (Leaflet) Add a default-off Layers row that fetches GET /api/map/sentinel1?bbox= only when enabled, then L.tileLayer(tileUrl) at opacity 0.8. HUD hints for 404/429/502; moveend refetch while on. Same-origin tileUrl as-is. --- app/static/index.html | 77 +++++++++++++++++++++++++++++++- tests/test_sentinel1_frontend.py | 41 +++++++++++++++++ 2 files changed, 117 insertions(+), 1 deletion(-) create mode 100644 tests/test_sentinel1_frontend.py diff --git a/app/static/index.html b/app/static/index.html index 38d1849..937e03f 100644 --- a/app/static/index.html +++ b/app/static/index.html @@ -328,6 +328,7 @@ .lp-dot.vessels { background: #2dd4bf; box-shadow: 0 0 7px #2dd4bf; } .lp-dot.radar { background: #38bdf8; box-shadow: 0 0 7px #38bdf8; } .lp-dot.thermal { background: #f97316; box-shadow: 0 0 7px #f97316; } + .lp-dot.sar { background: #86efac; box-shadow: 0 0 7px #86efac; } .lp-dot.wfigs { background: #ef4444; box-shadow: 0 0 7px #ef4444; } .lp-dot.trains { background: #c084fc; box-shadow: 0 0 7px #c084fc; } .lp-dot.storms { background: #f472b6; box-shadow: 0 0 7px #f472b6; } @@ -844,6 +845,14 @@ VIIRS
+
+
+ + 7d +
+
Opacity 80%
+
Cloud-penetrating C-band. Last 7 days, viewport bbox. Tiles from same-origin TiTiler — not fetched on load.
+
@@ -1880,6 +1889,7 @@ let mapAttributionAdded = null; let extraAttribs = new Set(); let radarLayer = null, radarOn = true, radarOpacity = 0.7, radarMeta = null, radarTimer = null; let thermalLayer = null, thermalOn = false; +let sentinelLayer = null, sentinelOn = false, sentinelOpacity = 0.8; let wxAlertsGroup = null, wxAlertsOn = true; let perimGroup = null, perimOn = true; let incidentsGroup = null, incidentsOn = false; @@ -1887,7 +1897,7 @@ let acGroup = null, acOn = true; let trainsGroup = null, trainsOn = true; let vesselsGroup = null, vesselsOn = false; let stormsGroup = null, stormsOn = true; -let overlayReq = {ac:0, trains:0, vessels:0, alerts:0, perim:0, incidents:0, storms:0}; +let overlayReq = {ac:0, trains:0, vessels:0, alerts:0, perim:0, incidents:0, storms:0, sar:0}; let moveDebounce = null; let overlayAbort = null; let lastCell = ''; @@ -2113,6 +2123,7 @@ async function initMap() { radarOn = document.getElementById('lp-radar-on').checked; wxAlertsOn = document.getElementById('lp-alerts-on').checked; thermalOn = document.getElementById('lp-thermal-on').checked; + sentinelOn = document.getElementById('lp-sentinel-on').checked; perimOn = document.getElementById('lp-perim-on').checked; incidentsOn = document.getElementById('lp-incidents-on').checked; acOn = document.getElementById('lp-ac-on').checked; @@ -2634,6 +2645,7 @@ function refreshLiveOverlays() { if (!map) return; if (radarOn) loadRadar(); if (thermalOn) loadThermal(); + if (sentinelOn) loadSentinel1(); if (wxAlertsOn) loadWxAlerts(); if (perimOn) loadPerimeters(); if (incidentsOn) loadIncidents(); @@ -2948,6 +2960,69 @@ async function toggleThermal() { if (thermalOn) loadThermal(); else thermalLayer = dropLayer(thermalLayer); } +async function toggleSentinel1() { + sentinelOn = document.getElementById('lp-sentinel-on').checked; + if (sentinelOn) await loadSentinel1(); + else { + sentinelLayer = dropLayer(sentinelLayer); + const n = document.getElementById('lp-sentinel-count'); + if (n) n.textContent = '7d'; + } +} +function setSentinelOpacity(v) { + sentinelOpacity = v / 100; + document.getElementById('lp-sentinel-val').textContent = `${Math.round(v)}%`; + if (sentinelLayer) sentinelLayer.setOpacity(sentinelOpacity); +} +async function loadSentinel1() { + if (!map || !sentinelOn) return; + const req = ++overlayReq.sar; + const countEl = document.getElementById('lp-sentinel-count'); + const hint = document.getElementById('map-hint'); + try { + if (countEl) countEl.textContent = '…'; + const r = await overlayFetch(`${API}/api/map/sentinel1?bbox=${currentBBox()}`); + let body = null; + try { body = await r.json(); } catch (_) { body = null; } + if (req !== overlayReq.sar) return; + if (r.status === 404 && body && body.error === 'no_imagery') { + sentinelLayer = dropLayer(sentinelLayer); + if (hint) hint.textContent = 'No Sentinel-1 imagery for this view in the last 7 days.'; + if (countEl) countEl.textContent = 'none'; + return; + } + if (r.status === 429) { + sentinelLayer = dropLayer(sentinelLayer); + if (hint) hint.textContent = 'Sentinel-1 rate limited — retry later.'; + if (countEl) countEl.textContent = '429'; + return; + } + if (!r.ok || !body || !body.tileUrl) { + sentinelLayer = dropLayer(sentinelLayer); + if (hint) hint.textContent = 'Sentinel-1 unavailable — retry later.'; + if (countEl) countEl.textContent = 'err'; + return; + } + const attrib = body.attribution || ''; + sentinelLayer = dropLayer(sentinelLayer); + sentinelLayer = L.tileLayer(body.tileUrl, { + opacity: sentinelOpacity, + maxZoom: 18, + attribution: attrib, + }).addTo(map); + if (countEl) countEl.textContent = String(body.polarization || 'SAR').toUpperCase(); + if (hint) { + const when = body.datetime ? ` · ${body.datetime}` : ''; + hint.textContent = `Sentinel-1 SAR${when} · cloud-penetrating C-band`; + } + } catch (e) { + if (isAbort(e)) return; + if (req !== overlayReq.sar) return; + sentinelLayer = dropLayer(sentinelLayer); + if (hint) hint.textContent = 'Sentinel-1 unavailable — retry later.'; + if (countEl) countEl.textContent = 'err'; + } +} function loadThermal() { if (!map) return; const time = (document.getElementById('map-date') && document.getElementById('map-date').value) diff --git a/tests/test_sentinel1_frontend.py b/tests/test_sentinel1_frontend.py new file mode 100644 index 0000000..94a30a8 --- /dev/null +++ b/tests/test_sentinel1_frontend.py @@ -0,0 +1,41 @@ +"""Sentinel-1 SAR layer: Leaflet toggle contract (no browser STAC/TiTiler).""" + +from __future__ import annotations + +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +HTML = (ROOT / "app/static/index.html").read_text() + + +def test_sentinel1_toggle_default_off(): + assert 'id="lp-sentinel-on"' in HTML + assert 'id="sentinel-1-sar"' in HTML + assert "Sentinel-1 SAR (Cloud-Penetrating)" in HTML + on = HTML.split('id="lp-sentinel-on"', 1)[1].split(">", 1)[0] + assert "checked" not in on + + +def test_sentinel1_fetches_backend_not_planetary_computer(): + assert "/api/map/sentinel1?bbox=" in HTML + assert "titiler.xyz" not in HTML + js = HTML.split("async function loadSentinel1", 1)[1].split("function loadThermal", 1)[0] + assert "planetarycomputer" not in js.lower() + assert "stac" not in js.lower() + + +def test_sentinel1_hud_errors_not_alert(): + js = HTML.split("async function loadSentinel1", 1)[1].split("function loadThermal", 1)[0] + assert "alert(" not in js + assert "No Sentinel-1 imagery for this view in the last 7 days." in js + assert "retry later" in js + assert "opacity: sentinelOpacity" in js + assert "maxZoom: 18" in js + assert "L.tileLayer(body.tileUrl" in js + + +def test_sentinel1_not_fetched_on_init_unless_on(): + init = HTML.split("function initMap", 1)[1].split("function readMapPrefs", 1)[0] + assert "loadSentinel1()" not in init + refresh = HTML.split("function refreshLiveOverlays", 1)[1].split("function addExtraAttrib", 1)[0] + assert "if (sentinelOn) loadSentinel1();" in refresh From 68e1b634218c54c81faf52f6a8b9e5155540a530 Mon Sep 17 00:00:00 2001 From: Sirius DevOps Date: Sat, 29 Aug 2026 11:42:03 -0400 Subject: [PATCH 32/79] fix(titiler): drop @1x suffix + append SAS token top-level MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit TiTiler /tiles/{z}/{x}/{y} takes a strict int for y; the @1x scale-suffix template 422s on every SAR tile request (int_parsing on '21@1x'). sign_cog_url wrapped the Planetary Computer SAS token under a single token= param, which Azure rejects (403→409); the token is a pre-encoded query string and must be appended top-level (st=…&se=…&sig=…). Proven live: correct-form URL renders a 200 image/png 256px tile. --- app/live_layers.py | 12 +++++++++--- tests/test_live_layers.py | 19 ++++++++++--------- 2 files changed, 19 insertions(+), 12 deletions(-) diff --git a/app/live_layers.py b/app/live_layers.py index b6e80d1..eebf6c1 100644 --- a/app/live_layers.py +++ b/app/live_layers.py @@ -50,7 +50,7 @@ PC_SAS_TOKEN = "https://planetarycomputer.microsoft.com/api/sas/v1/token/sentine # Self-hosted TiTiler on the Pi, exposed same-origin through the osint.rpi.local # nginx vhost. Relative template — Leaflet resolves it against the page origin, # so the browser never touches a raw loopback port or titiler.xyz. -TITILER_COG_TILES = f"{TITILER_PUBLIC_BASE}/cog/tiles/WebMercatorQuad/{{z}}/{{x}}/{{y}}@1x" +TITILER_COG_TILES = f"{TITILER_PUBLIC_BASE}/cog/tiles/WebMercatorQuad/{{z}}/{{x}}/{{y}}" SENTINEL1_TTL = 20 * 60 # 15–30 min quota-friendly window SENTINEL1_ATTRIBUTION = "Copernicus Sentinel-1 / Microsoft Planetary Computer" @@ -1194,9 +1194,15 @@ async def _pc_call(coro: Awaitable[Any]) -> Any: def sign_cog_url(href: str, token: str) -> str: - """Append a SAS token to a PC blob URL (respect existing query string).""" + """Append a SAS token to a PC blob URL (respect existing query string). + + PC's SAS endpoint returns the token as an already-percent-encoded query + string (``st=…&se=…&sp=rl&…&sig=…``). Azure only honours those parameters + when they sit top-level on the blob URL — wrapping them under a single + ``token=`` param yields 403/409, so we append the token verbatim. + """ sep = "&" if "?" in href else "?" - return f"{href}{sep}token={quote(token, safe='')}" + return f"{href}{sep}{token}" def sentinel1_tile_url(signed_cog: str) -> str: diff --git a/tests/test_live_layers.py b/tests/test_live_layers.py index ebd4340..69f8164 100644 --- a/tests/test_live_layers.py +++ b/tests/test_live_layers.py @@ -661,18 +661,19 @@ def test_planespotters_headers_add_contact_when_ua_is_generic(monkeypatch): # ── Sentinel-1 SAR (Planetary Computer STAC → signed COG template) ──────── def test_sign_cog_url_appends_token(): - assert sign_cog_url("https://blob.example/x.tif", "tok=abc") == \ - "https://blob.example/x.tif?token=tok%3Dabc" + # PC returns the token pre-encoded as a query string; append verbatim. + assert sign_cog_url("https://blob.example/x.tif", "st=s&se=e&sig=x%3D") == \ + "https://blob.example/x.tif?st=s&se=e&sig=x%3D" # Existing query string → append with & - assert sign_cog_url("https://blob.example/x.tif?st=1", "tok") == \ - "https://blob.example/x.tif?st=1&token=tok" + assert sign_cog_url("https://blob.example/x.tif?foo=1", "st=s&sig=x") == \ + "https://blob.example/x.tif?foo=1&st=s&sig=x" def test_sentinel1_tile_url_contains_titiler_rescale_and_cfastie(): signed = "https://blob.example/x.tif?token=secret" url = sentinel1_tile_url(signed) assert url.startswith(TITILER_COG_TILES + "?") - assert "WebMercatorQuad/{z}/{x}/{y}@1x" in url + assert "WebMercatorQuad/{z}/{x}/{y}?" in url assert "url=https%3A%2F%2Fblob.example%2Fx.tif%3Ftoken%3Dsecret" in url assert "rescale=0%2C500" in url assert "colormap_name=cfastie" in url @@ -723,12 +724,12 @@ def test_fetch_sentinel1_vv_signed_tile_url(monkeypatch): assert out["opacity"] == 0.8 assert out["itemId"].startswith("S1A") assert out["attribution"] == SENTINEL1_ATTRIBUTION - assert "WebMercatorQuad/{z}/{x}/{y}@1x" in out["tileUrl"] + assert "WebMercatorQuad/{z}/{x}/{y}?" in out["tileUrl"] assert "rescale=0%2C500" in out["tileUrl"] assert "colormap_name=cfastie" in out["tileUrl"] - # SAS token "sig=abc123" is signed as ?token=sig%3Dabc123, then the whole - # COG URL is percent-encoded again as a query param (=> sig%253Dabc123). - assert "sig%253Dabc123" in out["tileUrl"] + # SAS token "sig=abc123" is appended top-level, then the whole COG URL is + # percent-encoded again as a query param (=> sig%3Dabc123). + assert "sig%3Dabc123" in out["tileUrl"] # STAC search payload shape post_url, post_json = calls[0][1], calls[0][2] assert post_url.endswith("/api/stac/v1/search") From 86b412dd37450f27980f6f9a0348c52f55fb007e Mon Sep 17 00:00:00 2001 From: Sirius DevOps Date: Sat, 29 Aug 2026 13:05:57 -0400 Subject: [PATCH 33/79] fix(vessels): protect Hormuz VesselAPI rows from AISStream eviction AISStream's live US-coast feed crowds vessel_last_known past _MAX_VESSELS (6000) and the 'evict oldest seen_at' pass reaps the Hormuz VesselAPI rows, which are only refreshed every VESSELAPI_INTERVAL (~4.8h). Result: the poller was fetching 50 Hormuz vessels per 2xx but /api/vessels?bbox=Hormuz stayed empty. Eviction now skips src=vesselapi rows (falls back to evictable-only, clamped) so the blind-spot box stays resident between polls. --- app/live_layers.py | 12 +++++++++++- tests/test_vesselapi.py | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+), 1 deletion(-) diff --git a/app/live_layers.py b/app/live_layers.py index eebf6c1..7022387 100644 --- a/app/live_layers.py +++ b/app/live_layers.py @@ -993,8 +993,18 @@ async def upsert_vessel(marker: dict) -> None: vessel_last_known[vid] = stored if len(vessel_last_known) > _MAX_VESSELS: excess = len(vessel_last_known) - int(_MAX_VESSELS * 0.9) + # AISStream's live US-coast feed can crowd the shared store past + # _MAX_VESSELS and evict the Hormuz VesselAPI rows (refreshed only + # every VESSELAPI_INTERVAL) as "oldest". Keep src=vesselapi rows + # resident so the blind-spot box stays visible between polls. + evictable = [ + k for k, v in vessel_last_known.items() + if (v.get("extra") or {}).get("src") != "vesselapi" + ] + if len(evictable) < excess: + excess = len(evictable) oldest = sorted( - vessel_last_known, + evictable, key=lambda k: vessel_last_known[k].get("seen_at", ""), )[:excess] for k in oldest: diff --git a/tests/test_vesselapi.py b/tests/test_vesselapi.py index 292bed4..f7ec9c1 100644 --- a/tests/test_vesselapi.py +++ b/tests/test_vesselapi.py @@ -298,6 +298,40 @@ def _make_get_client(client): return _get_client +def test_eviction_keeps_vesselapi_rows(monkeypatch): + """AISStream crowding past _MAX_VESSELS must not reap Hormuz VesselAPI rows.""" + from ws_manager import manager + from live_layers import _MAX_VESSELS, upsert_vessel + + _patch_side_effects(monkeypatch) + monkeypatch.setattr("live_layers._MAX_VESSELS", 10) + vessel_last_known.clear() + manager._queues.clear() + manager._viewports.clear() + + # One Hormuz VesselAPI row with the oldest seen_at — the first thing the + # old "evict oldest" logic would reap — plus enough AISStream rows to + # exceed the cap. + vessel_last_known["422050100"] = { + "id": "422050100", "lat": 26.5, "lon": 56.3, "label": "HORMUZ STAR", + "extra": {"src": "vesselapi"}, "seen_at": "2026-08-29T00:00:00+00:00", + } + for i in range(10): + vid = f"3{i:08d}" + vessel_last_known[vid] = { + "id": vid, "lat": 35.0 + i * 0.01, "lon": -79.0, "label": vid, + "extra": {"src": "aisstream"}, + "seen_at": f"2026-08-29T0{i}:00:00+00:00", + } + + # One more AISStream marker pushes past the cap and triggers eviction. + asyncio.run(upsert_vessel({"id": "399999999", "lat": 36.0, "lon": -78.0, "label": "NEW"})) + + assert "422050100" in vessel_last_known # VesselAPI row survives + assert vessel_last_known["422050100"]["extra"]["src"] == "vesselapi" + assert len(vessel_last_known) <= 10 + + # ── Independent-provider idle behaviour ─────────────────────────────────── # VesselAPI must never be gated on AISStream (or vice versa): a missing key on # one provider leaves the other running. ``_StopLoop`` is a BaseException so From 09fe615d8977008a228583d7ca56dc27d8fb1b2f Mon Sep 17 00:00:00 2001 From: Sirius DevOps Date: Sat, 29 Aug 2026 13:12:26 -0400 Subject: [PATCH 34/79] docs: add free satellite-feeds catalog from research card Live-probed 2026-08-29 inventory (GIBS extra layers, GOES/Himawari, HLS, OPERA, STAC/COG paths). Ranked drop-ins for the OSINT map; skip paid/NICFI. Does not change runtime code. --- docs/satellite-feeds.md | 347 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 347 insertions(+) create mode 100644 docs/satellite-feeds.md diff --git a/docs/satellite-feeds.md b/docs/satellite-feeds.md new file mode 100644 index 0000000..5d0d1c6 --- /dev/null +++ b/docs/satellite-feeds.md @@ -0,0 +1,347 @@ +# Free satellite feeds for the OSINT map + +Builder inventory (research profile). Probed **2026-08-29** from this machine. Do **not** treat search snippets as live — every row below had a `curl`/GET (tile, GetCapabilities, STAC, or GetMap). 404 tile rows are omitted unless Capabilities/DescribeDomains still prove the layer exists (sparse fire overlays 404 on empty tiles). + +**Pi rules:** browser `L.tileLayer` when CORS `*`; do not proxy multi-GB COGs through the Pi; STAC+SAS like existing Sentinel-1 is “backend same as S-1”; no Redis; home uplink is small. + +GIBS Web Mercator REST template (no key):[2] + +``` +https://gibs.earthdata.nasa.gov/wmts/epsg3857/best/{layer}/default/{time}/{TileMatrixSet}/{z}/{y}/{x}.{jpg|png} +``` + +Omit `{time}` for static layers. Sub-daily GOES/Himawari accept `YYYY-MM-DD` **or** `YYYY-MM-DDTHH:MI:SSZ` (GIBS snaps to nearest).[2] Attribution: NASA asks clients to acknowledge GIBS/ESDIS.[1] + +Live GetCapabilities `epsg3857/best` on 2026-08-29: **1315** `Layer` entries, **all** with a `GoogleMapsCompatible_LevelN` matrix, `access-control-allow-origin: *`.[4] GIBS documents **1000+** visualizations; many LANCE layers appear within **3.5 hours** of observation.[3] + +Worldview is the interactive catalog of the same tiles.[5] GIBS developer portal: Earthdata GIBS API page (HTTP 403 from this host at probe time; docs site above is the working copy).[27] + +--- + +## Already in the product (do not rediscover) + +| id | status | +|---|---| +| `BlueMarble_ShadedRelief_Bathymetry` | GIBS basemap (`app/gibs_map.py`) | +| `VIIRS_SNPP_CorrectedReflectance_TrueColor` | GIBS basemap | +| `MODIS_Terra_CorrectedReflectance_TrueColor` | GIBS basemap | +| `MODIS_Aqua_CorrectedReflectance_TrueColor` | GIBS basemap | +| `VIIRS_SNPP_DayNightBand_ENCC` | GIBS night lights | +| FIRMS VIIRS hotspot CSV | ingest + `FIRMS_MAP_KEY` | +| `VIIRS_SNPP_Thermal_Anomalies_375m_All` | overlay in `app/live_layers.py` (`gibs_thermal`). **Caps now say TMS `GoogleMapsCompatible_Level8`**, not Level9 — the wired URL uses Level9 (will 400). | +| Sentinel-1 GRD | Planetary Computer STAC + SAS + TiTiler `GET /api/map/sentinel1` | +| IEM NEXRAD / RainViewer | weather radar, not satellite | + +Repo docs already flag **Suomi NPP product stop 2026-11-01** — swap SNPP true color / DNB / thermal / FIRMS `VIIRS_SNPP_NRT` to NOAA-20/21 before then. + +--- + +## Ranked “add tomorrow” (sections 1–2) + +Most new OSINT signal per **zero dollars**, browser tiles only: + +1. **VIIRS NOAA-20 + NOAA-21 true color** — SNPP replacement, same dropdown pattern. +2. **VIIRS false-color SWIR** (`BandsM11-I2-I1`, `BandsM3-I3-M11`, MODIS 7-2-1) — burn scars, flood, bare soil. +3. **GIBS GOES-East/West GeoColor + Band13 IR** — 10-minute weather-sat, Hormuz + CONUS. +4. **GIBS Himawari AHI vis + IR** — same for IO/WestPac. +5. **HLS S30/L30** — 30 m Landsat/Sentinel-2 look without TiTiler. +6. **OPERA RTC Sentinel-1 + DIST-ALERT + DSWx** — SAR / disturbance / flood as GIBS tiles (not COGs). +7. **NOAA-20/21 DNB** — night lights after SNPP. +8. **IEM GOES XYZ** — “latest” tiles, no time in the URL, already CORS `*` like NEXRAD.[6] +9. **EUMETView WMS** — Meteosat/MTG for Europe–Africa–IO, CORS `*`.[18] +10. **GFW GLAD-S2 / integrated deforestation alerts** — raster tiles, CORS `*` when `Origin` is sent.[15] +11. **MUR SST + VIIRS/PACE/OLCI chlorophyll** — ocean. +12. **MODIS NDVI 8-day + IMERG rain** — veg / flood context. +13. **SRTM / ASTER GDEM color index** — satellite-derived DEM, static. +14. **NOAA-20/21 thermal anomalies** — FIRMS-shaped overlay after SNPP; empty tiles 404. + +--- + +## 1. Drop-in GIBS WMTS + +All rows: **key? no**. **CORS `*`**. **Pi fit: browser `L.tileLayer`**. Same time-domain helper as `gibs_map.py` (`…/1.0.0/{id}/default/{tms}/all/all.xml`). + +Format of URL column: layer id + TMS + ext. Date used in probes: `2026-08-27` unless noted. + +### 1.1 Optical (true / false / SWIR) + +| id | what you see | tile pattern | cadence | max zoom | license | already have? | probe | +|---|---|---|---|---|---|---|---| +| `VIIRS_NOAA20_CorrectedReflectance_TrueColor` | Daily true color, JPSS-1 | `…/{id}/default/{time}/GoogleMapsCompatible_Level9/{z}/{y}/{x}.jpg` | daily | 9 (~250 m) | NASA GIBS ack[1] | **no** (SNPP only) | 200 `*` jpeg | +| `VIIRS_NOAA21_CorrectedReflectance_TrueColor` | Daily true color, JPSS-2 | same Level9 jpg | daily | 9 | NASA GIBS[1] | no | 200 | +| `VIIRS_SNPP_CorrectedReflectance_BandsM11-I2-I1` | False color SWIR (burns, flood) | Level9 jpg | daily | 9 | NASA GIBS[1] | no | 200 | +| `VIIRS_SNPP_CorrectedReflectance_BandsM3-I3-M11` | False color (snow/ice/desert) | Level9 jpg | daily | 9 | NASA GIBS[1] | no | 200 | +| `VIIRS_NOAA20_CorrectedReflectance_BandsM11-I2-I1` | NOAA-20 SWIR false color | Level9 jpg | daily | 9 | NASA GIBS[1] | no | 200 | +| `VIIRS_NOAA21_CorrectedReflectance_BandsM11-I2-I1` | NOAA-21 SWIR false color | Level9 jpg | daily | 9 | NASA GIBS[1] | no | 200 | +| `MODIS_Terra_CorrectedReflectance_Bands721` | Classic 7-2-1 burn/SWIR | Level9 jpg | daily | 9 | NASA GIBS[1] | no | 200 | +| `MODIS_Terra_CorrectedReflectance_Bands367` | 3-6-7 false color | Level9 jpg | daily | 9 | NASA GIBS[1] | no | 200 | +| `MODIS_Aqua_CorrectedReflectance_Bands721` | Aqua 7-2-1 | Level9 jpg | daily | 9 | NASA GIBS[1] | no | 200 | +| `HLS_S30_Nadir_BRDF_Adjusted_Reflectance` | Harmonized Sentinel-2 30 m RGB | Level12 png | ~2–3 d when a granule exists | 12 (~30 m) | NASA GIBS[1] | no | 200 at z=5 NC; 404 on empty granules is normal. Domain from 2015–present | +| `HLS_L30_Nadir_BRDF_Adjusted_Reflectance` | Harmonized Landsat 30 m | Level12 png | 8–16 d | 12 | NASA GIBS[1] | no | in caps; tile 404 on empty scene | +| `Landsat_WELD_CorrectedReflectance_TrueColor_Global_Monthly` | Landsat WELD monthly mosaic | Level12 jpg | monthly, **not NRT** | 12 | NASA GIBS[1] | no | 200 | +| `Landsat_WELD_CorrectedReflectance_TrueColor_Global_Annual` | WELD annual | Level12 jpg | yearly | 12 | NASA GIBS[1] | no | 200 | + +### 1.2 Weather satellites (imagery, not NEXRAD) + +Sub-daily. Probe with `2026-08-27` **and** `2026-08-27T18:00:00Z` both 200 (nearestValue).[2] + +| id | what you see | TMS / ext | cadence | max zoom | already have? | probe | +|---|---|---|---|---|---|---| +| `GOES-East_ABI_GeoColor` | GeoColor full disk (Americas, Atlantic, Hormuz west edge) | Level7 png | ~10 min | 7 | no | 200 | +| `GOES-West_ABI_GeoColor` | GeoColor Pacific / CONUS west | Level7 png | ~10 min | 7 | no | 200 (also 200 over CA with ISO time) | +| `GOES-East_ABI_Band2_Red_Visible_1km` | ABI vis | Level7 png | ~10 min | 7 | no | 200 | +| `GOES-West_ABI_Band2_Red_Visible_1km` | ABI vis | Level7 png | ~10 min | 7 | no | 200 | +| `GOES-East_ABI_Band13_Clean_Infrared` | Clean IR window | Level6 png | ~10 min | 6 | no | 200 | +| `GOES-West_ABI_Band13_Clean_Infrared` | Clean IR | Level6 png | ~10 min | 6 | no | 200 | +| `GOES-East_ABI_FireTemp` | Fire temperature RGB | Level7 png | ~10 min | 7 | no | 200 | +| `GOES-West_ABI_FireTemp` | Fire temperature RGB | Level7 png | ~10 min | 7 | no | 404 on NC tile (wrong disk); use west longitudes | +| `GOES-East_ABI_Dust` | Dust RGB | Level7 png | ~10 min | 7 | no | 200 | +| `GOES-East_ABI_Air_Mass` | Air mass RGB | Level6 png | ~10 min | 6 | no | 200 | +| `GOES-West_ABI_Air_Mass` | Air mass RGB | Level6 png | ~10 min | 6 | no | 200 | +| `Himawari_AHI_Band3_Red_Visible_1km` | Himawari vis (IO / WestPac / Aus) | Level7 png | ~10 min | 7 | no | 200 (ISO time over Japan) | +| `Himawari_AHI_Band13_Clean_Infrared` | Himawari IR | Level6 png | ~10 min | 6 | no | 200 | +| `Himawari_AHI_Air_Mass` | Himawari air mass | Level6 png | ~10 min | 6 | no | 200 | + +**Meteosat is not in GIBS.** Use section 2 EUMETView. + +### 1.3 SAR / flood / disturbance (GIBS tiles — skip TiTiler) + +| id | what you see | TMS | cadence | max zoom | already have? | probe | +|---|---|---|---|---|---|---| +| `OPERA_L2_Radiometric_Terrain_Corrected_SAR_Sentinel-1` | S-1 RTC browse (better than GRD for terrain) | Level12 png | scene-based from 2025-01 | 12 | **no** (you have GRD COGs, not RTC tiles) | 200 at z=5; domain 2025-01-10/… | +| `OPERA_L3_DIST-ALERT-HLS_Color_Index` | Vegetation disturbance / clearing alert | Level12 png | ~2–3 d | 12 | no | 200 | +| `OPERA_L3_DIST-ANN-HLS_Color_Index` | Annual DIST | Level12 png | yearly | 12 | no | in caps | +| `OPERA_L3_Dynamic_Surface_Water_Extent-HLS` | Surface water / flood (HLS, 30 m) | Level12 png | ~2–3 d | 12 | no | 200 at z=5 | +| `OPERA_L3_Dynamic_Surface_Water_Extent-Sentinel-1` | Surface water from S-1 (clouds irrelevant) | Level12 png | S-1 revisit | 12 | no | 200 at z=5 | +| `NISAR_L2_Geocoded_Polarimetric_Covariance` | NISAR early browse | Level13 png | when downlinked | 13 | no | 200 (layer exists; coverage still sparse) | +| `SMAP_L4_Analyzed_Surface_Soil_Moisture` | Soil moisture | Level6 png | daily | 6 | no | 200 | +| `SMAP_L3_Active_Sigma0_VV` | SMAP radar σ0 | Level6 png | 2–3 d | 6 | no | in caps (SMAP radar died 2015 — historical) | + +No ICEYE / Capella / Umbra / ALOS PALSAR **daily** layers in this GIBS 3857 dump.[4] ALOS shows up as mosaics on Planetary Computer (section 3). + +### 1.4 Thermal / fire / volcano + +Sparse PNG overlays: **empty tiles 404**. Capabilities + DescribeDomains still 200. Frontend must tolerate 404 (Leaflet does). + +| id | what you see | TMS | cadence | max zoom | already have? | probe | +|---|---|---|---|---|---|---| +| `VIIRS_SNPP_Thermal_Anomalies_375m_All` | 375 m hotspots | **Level8** png (not 9) | daily | 8 | **yes**, but wired as Level9 | Domain 200; many tiles 404 | +| `VIIRS_NOAA20_Thermal_Anomalies_375m_All` | NOAA-20 hotspots | Level8 png | daily | 8 | no | Domain 200 (`2020-01-01/…` through at least 2025-09); tiles 404 if no fire in tile | +| `VIIRS_NOAA21_Thermal_Anomalies_375m_All` | NOAA-21 hotspots | Level8 png | daily | 8 | no | same | +| `VIIRS_*_Thermal_Anomalies_375m_{Day,Night}` | day/night split | Level8 png | daily | 8 | no | in caps | +| `MODIS_{Terra,Aqua,Combined}_Thermal_Anomalies_All` | 1 km MODIS fire | Level7 png | daily | 7 | no | in caps | +| `GOES-East_ABI_FireTemp` | geostationary fire RGB | Level7 png | ~10 min | 7 | no | 200 | + +Also keep FIRMS CSV — points beat raster for click/query. + +### 1.5 Night lights (beyond current DNB ENCC) + +| id | what you see | TMS / ext | cadence | max zoom | already have? | probe | +|---|---|---|---|---|---|---| +| `VIIRS_NOAA20_DayNightBand` | NOAA-20 DNB | Level7 png | daily | 7 | no | 200 | +| `VIIRS_NOAA21_DayNightBand` | NOAA-21 DNB | Level7 png | daily | 7 | no | 200 | +| `VIIRS_NOAA20_DayNightBand_At_Sensor_Radiance` | radiance, not ENCC | Level8 png | daily | 8 | no | 200 | +| `VIIRS_SNPP_DayNightBand_At_Sensor_Radiance` | SNPP radiance | Level8 png | daily | 8 | no | 200 | +| `VIIRS_NOAA20_DayNightBand_AtSensor_M15` | DNB+M15 composite jpg | Level8 jpg | daily | 8 | no | 200 | +| `VIIRS_Night_Lights` | Black-marble-style annual-ish | Level8 png | time-dim | 8 | no | 200 on 2026-08-27 mosaic date | +| `VIIRS_CityLights_2012` | Static 2012 city lights | Level8 jpg | **static** (`has_time=false`) | 8 | no | 200 | + +`VIIRS_Black_Marble` and `VIIRS_NOAA20_DayNightBand_ENCC` are in caps; ENCC-NOAA20 returned HTTP 400 on the Level8 template we tried — do not ship until DescribeDomains + a known-good date are wired. SNPP ENCC stays as the current layer. + +### 1.6 Ocean + +| id | what you see | TMS | cadence | max zoom | probe | +|---|---|---|---|---|---| +| `GHRSST_L4_MUR_Sea_Surface_Temperature` | 1 km MUR SST | Level7 png | daily | 7 | 200 | +| `GHRSST_L4_MUR_Sea_Surface_Temperature_Anomalies` | SST anomaly | Level7 png | daily | 7 | in caps | +| `MODIS_Aqua_L3_SST_MidIR_4km_Night_Daily` | MODIS SST | Level6 png | daily | 6 | 200 | +| `MODIS_Aqua_L2_Chlorophyll_A` | Aqua chl-a | Level7 png | daily | 7 | 200 | +| `VIIRS_SNPP_L2_Chlorophyll_A` | VIIRS chl-a | Level7 png | daily | 7 | 200 | +| `VIIRS_NOAA20_Chlorophyll_a` | NOAA-20 chl-a | Level7 png | daily | 7 | 200 | +| `OCI_PACE_Chlorophyll_a` | PACE OCI chl-a | Level7 png | daily | 7 | 200 | +| `S3A_OLCI_Chlorophyll_a` | Sentinel-3A OLCI chl-a | Level7 png | daily | 7 | 200 | +| `S3B_OLCI_Chlorophyll_a` | Sentinel-3B OLCI | Level7 png | daily | 7 | in caps | +| `MODIS_Terra_Sea_Ice` | sea ice | Level7 png | daily | 7 | 200 | +| `GHRSST_L4_MUR_Sea_Ice_Concentration` | MUR ice | Level7 png | daily | 7 | in caps | + +No dedicated “SAR oil slick” GIBS layer in the 3857 dump. Closest: OPERA RTC / DSWx-S1 + existing S-1 GRD TiTiler. + +### 1.7 Vegetation / burn / flood / precip / atm + +| id | what you see | TMS | cadence | max zoom | probe | +|---|---|---|---|---|---| +| `MODIS_Terra_NDVI_8Day` | NDVI | Level9 png | 8-day | 9 | 200 | +| `MODIS_Terra_L3_NDVI_16Day` | NDVI 16-day | Level9 png | 16-day | 9 | 200 | +| `IMERG_Precipitation_Rate` | GPM IMERG rain | Level6 png | sub-daily | 6 | 200 | +| `MODIS_Terra_Aerosol` | AOD | Level6 png | daily | 6 | 200 | +| `MODIS_Terra_Land_Surface_Temp_Day` | LST | Level7 png | daily | 7 | 200 | +| `VIIRS_SNPP_Land_Surface_Temp_Day` | VIIRS LST | Level7 png | daily | 7 | 200 | +| `AIRS_L3_Carbon_Monoxide_500hPa_Volume_Mixing_Ratio_Daily_Night` | CO (fires, industry) | Level6 png | daily | 6 | 200 | +| `OMI_NO2` / `OMI_Aerosol_Index` | NO2 / smoke index | Level6 png | daily | 6 | OMI AI 200; several OMPS 200 | +| `MODIS_Water_Mask` | static water mask | Level9 png | static | 9 | 200 | + +MODIS burned-area monthly (`MCD64` / `MODIS_Combined_L3_Burned_Area_Monthly`) is in caps; our dated tile 400’d — wire only after a DescribeDomains date hits 200. + +### 1.8 DEM (satellite-derived, tileable) + +| id | what you see | TMS / ext | cadence | max zoom | probe | +|---|---|---|---|---|---| +| `SRTM_Color_Index` | SRTM elevation color | Level12 png | static | 12 | 200 | +| `ASTER_GDEM_Color_Index` | ASTER GDEM color | Level12 png | static | 12 | 200 | +| `ASTER_GDEM_Color_Shaded_Relief` | ASTER hillshade | Level12 jpg | static | 12 | 200 | +| `ASTER_GDEM_Greyscale_Shaded_Relief` | grey hillshade | Level12 jpg | static | 12 | in caps | +| `GEDI_ISS_L3_Canopy_Height_Mean_RH100_201904-202303` | GEDI canopy height | Level7 png | static epoch | 7 | related GEDI biomass 200 | + +Blue Marble shaded relief is **already** the basemap — these are extra. + +--- + +## 2. Other XYZ / WMTS / WMS (no key) + +Ranked after GIBS for signal/$; still free. + +| id | what you see | provider | URL pattern | key? | CORS | cadence | max zoom / res | license / attribution | Pi fit | already have? | probe 2026-08-29 | +|---|---|---|---|---|---|---|---|---|---|---|---| +| `iem_goes_east_conus_ch02` | GOES-East CONUS ABI ch02 vis, **latest** | Iowa State IEM | `https://mesonet.agron.iastate.edu/cache/tile.py/1.0.0/goes_east_conus_ch02/{z}/{x}/{y}.png` | no | `*` | ~5 min cache header | TMS; vis ~1 km | Cite IEM / NOAA GOES[6][7] | **browser** (same stack as NEXRAD) | no | 200 image/png `*` | +| `iem_goes_east_conus_ch13` | GOES-East CONUS IR ch13 | IEM | `…/goes_east_conus_ch13/{z}/{x}/{y}.png` | no | `*` | ~5 min | IR ~2 km | IEM[6] | browser | no | 200 | +| `iem_goes_east_fulldisk_ch02` | GOES-East full disk vis | IEM | `…/goes_east_fulldisk_ch02/{z}/{x}/{y}.png` | no | `*` | ~5 min | full disk | IEM[6] | browser | no | 200 | +| `iem_goes_west_conus_ch02` | GOES-West CONUS vis | IEM | `…/goes_west_conus_ch02/{z}/{x}/{y}.png` | no | `*` | ~5 min | | IEM[6] | browser | no | 200 | +| `iem_goes_vis_1km` | Legacy name → GOES-East vis | IEM | `…/goes-vis-1km/{z}/{x}/{y}.png` | no | `*` | ~5 min | | IEM[6] | browser | no | 200 | +| IEM GOES template | Any bird/sector/channel | IEM | `goes_{east\|west}_{fulldisk\|conus\|mesoscale-1\|mesoscale-2\|alaska\|puertorico}_ch{01–16}`[6] | no | `*` | NRT | 16 ABI bands | IEM[6] | browser | no | template documented; ch02/ch13 probed | +| `eumet_msg_natural` | Meteosat natural color | EUMETSAT EUMETView GeoServer | WMS `https://view.eumetsat.int/geoserver/ows` layer `msg_fes:rgb_natural` EPSG:3857 GetMap | no | `*` | NRT | SEVIRI ~3 km | EUMETSAT viz; cite EUMETSAT[18] | **browser `L.tileLayer.wms`** (not XYZ). Caps 200, 165 layer names | no | GetMap 200 image/png `*` | +| `eumet_msg_ir108` | Meteosat IR 10.8 | EUMETView | WMS `msg_fes:ir108` | no | `*` | NRT | | EUMETSAT | browser WMS | no | name in caps | +| `eumet_msg_fire` | Meteosat fire | EUMETView | WMS `msg_fes:fire` | no | `*` | NRT | | EUMETSAT | browser WMS | no | name in caps | +| `eumet_mtg_ir105` | MTG-I IR | EUMETView | WMS `mtg_fd:ir105_hrfi` | no | `*` | NRT | FCI | EUMETSAT | browser WMS | no | name in caps | +| `eumet_s3_olci_rgb` | S3 OLCI RGB mosaic | EUMETView | WMS `copernicus:daily_sentinel3ab_olci_l1_rgb_fulres` | no | `*` | daily | OLCI | Copernicus/EUMETSAT | browser WMS | no | name in caps | +| `eumet_s3_chl` | S3 chl-a | EUMETView | WMS `copernicus:daily_sentinel3ab_olci_l2_chl_fullres` | no | `*` | daily | | Copernicus | browser WMS | no | name in caps | +| `gfw_glad_s2` | GLAD Sentinel-2 deforestation alerts | GFW tile cache | `https://tiles.globalforestwatch.org/umd_glad_sentinel2_alerts/latest/default/{z}/{x}/{y}.png` | no | `*` **if `Origin` header** (null without it) | ~daily | raster z 0–22 documented[15] | WRI/UMD; cite GFW | **browser** (Leaflet sends Origin) | no | 200 image/png; with Origin → CORS `*` | +| `gfw_integrated` | Integrated deforestation alerts | GFW | `https://tiles.globalforestwatch.org/gfw_integrated_alerts/latest/default/{z}/{x}/{y}.png` | no | `*` + Origin | ~daily | | GFW | browser | no | 200 | +| `gfw_tcl` | UMD tree-cover loss | GFW | `https://tiles.globalforestwatch.org/umd_tree_cover_loss/latest/tcd_30/{z}/{x}/{y}.png` | no | (same host) | annual | | GFW/UMD | browser | no | 200 | +| `star_goes19_fd_geocolor` | GOES-19 full-disk GeoColor **JPEG** (not XYZ) | NOAA NESDIS STAR CDN | `https://cdn.star.nesdis.noaa.gov/GOES19/ABI/FD/GEOCOLOR/latest.jpg` also `…/CONUS/GEOCOLOR/latest.jpg` | no | `*` | minutes | full-disk / CONUS image | NOAA | **not a map layer** — optional lightbox. Do not tile-proxy | no | 200 jpeg `*`[21] | +| `star_goes18_fd_geocolor` | GOES-18 FD GeoColor JPEG | STAR | `https://cdn.star.nesdis.noaa.gov/GOES18/ABI/FD/GEOCOLOR/latest.jpg` | no | `*` | minutes | | NOAA | lightbox only | no | 200 | + +IEM JSON `…/GOES/conus/channel02/GOES-16_C02.json` is **stale** (`generated_at` 2025-04-07) but the **tile names still 200**. Prefer GIBS GeoColor when you need a time slider; prefer IEM when you want “whatever is latest” with zero time plumbing.[6][7] + +### 2.x Works but **not** browser-direct (no CORS) + +| id | what you see | URL | CORS | Pi fit | probe | +|---|---|---|---|---|---| +| RAMMB/CIRA SLIDER GeoColor tiles | GOES-19 / Himawari / JPSS loops, ~10 min | Times: `https://rammb-slider.cira.colostate.edu/data/json/goes-19/full_disk/geocolor/latest_times.json` (`timestamps_int`). Tile: `https://rammb-slider.cira.colostate.edu/data/imagery/{YYYY}/{MM}/{DD}/goes-19---full_disk/geocolor/{ts}/{zz}/{yyy}_{xxx}.png` e.g. `…/2026/08/28/goes-19---full_disk/geocolor/20260828225021/00/000_000.png`. Himawari times JSON also 200. | **none** | **Do not proxy tiles through the Pi.** Bookmark / deep-link SLIDER instead.[19][26] | times 200; tile 200 png; CORS null | +| NICT Himawari-8 Real-time Web | 10-min full disk PNG grid | `https://himawari8.nict.go.jp/img/D531106/latest.json` then `https://himawari8.nict.go.jp/img/D531106/2d/550/{YYYY}/{MM}/{DD}/{HHMMSS}_{x}_{y}.png` | **none** | same — no Pi proxy | latest.json 200; tile 200 png; CORS null[22] | +| OpenAerialMap | Per-scene TMS of open UAV/sat | `https://api.openaerialmap.org/meta` → `properties.tms` | CORS **only** `https://map.openaerialmap.org` | not usable from the dashboard origin without a proxy; opportunistic, not a global basemap[23][25] | meta 200 | +| USGS LandsatLook STAC | Landsat C2 STAC | `https://landsatlook.usgs.gov/stac-server` | CORS locked to `https://landsatlook.usgs.gov/stac-server` | backend-only if ever; prefer Earth Search / PC / GIBS HLS[24] | collections + search 200 | +| NOAA CoastWatch ERDDAP WMS (`jplMURSST41`) | MUR SST WMS | `https://coastwatch.pfeg.noaa.gov/erddap/wms/jplMURSST41/request` | mixed | **flaky**: GetCapabilities 200 earlier, **503** on later GetMap/GetCapabilities. Prefer GIBS MUR | 503 on 2nd pass | +| RainViewer `satellite.infrared` | would be IR sat frames | `https://api.rainviewer.com/public/weather-maps.json` | `*` | **empty list** (`"infrared": []`) at probe time — do not ship. Radar path already in product[20] | JSON 200, satellite IR empty | + +--- + +## 3. STAC / COG (TiTiler, same pattern as Sentinel-1) + +Do **not** stream COGs through the Pi for a basemap. Viewport bbox + short datetime window + SAS/public HTTPS + existing TiTiler. Prefer GIBS HLS / OPERA tiles (section 1) when a browse PNG is enough. + +| id | what you see | provider | STAC | key? | CORS | cadence | res | license | Pi fit | already have? | probe | +|---|---|---|---|---|---|---|---|---|---|---|---| +| `sentinel-2-l2a` (Earth Search) | S2 L2A COGs, public HTTPS | Element 84 / AWS Open Data | `https://earth-search.aws.element84.com/v1` collections: `sentinel-2-l2a`, `sentinel-2-c1-l2a`, `sentinel-2-l1c`, `sentinel-2-pre-c1-l2a`, `sentinel-1-grd`, `landsat-c2-l2`, `naip`, `cop-dem-glo-30`, `cop-dem-glo-90`[8][9] | no | STAC `*` | S2 ~5 d | 10 m | Copernicus open; AWS public bucket HTTPS (not requester-pays for these COGs)[9] | **backend same as S-1**: search → TCI/visual COG → TiTiler. Live item `S2A_40RCP_20260827_0_L2A` href `https://sentinel-cogs.s3.us-west-2.amazonaws.com/…/TCI.tif` | no | collections + search 200 `*` | +| `sentinel-2-l2a` (Planetary Computer) | same S2 on Azure | Microsoft PC | `https://planetarycomputer.microsoft.com/api/stac/v1/collections/sentinel-2-l2a` | SAS token (unsigned search works) | STAC `*` | ~5 d | 10 m | Copernicus; Azure blob needs SAS like current S-1 | backend same as S-1 | no | collection + search 200 `*` (136 collections listed)[10][11] | +| `sentinel-1-rtc` | S-1 IW RTC γ0 COGs | PC / Catalyst | `/collections/sentinel-1-rtc` | **PC account required to retrieve SAS** for RTC blobs[12] | STAC `*` | IW land | ~10 m pixels | **CC BY 4.0**[12] | backend same as S-1 **plus** PC login for SAS. Prefer GIBS OPERA RTC tiles if browse is enough | no | collection 200; search item `S1D_IW_GRDH_…_rtc` assets `vv,vh,tilejson,rendered_preview` | +| `sentinel-1-grd` (PC) | GRD | PC | `/collections/sentinel-1-grd` | SAS | `*` | 6–12 d | | Copernicus | **already have** | yes | 200 | +| `sentinel-1-grd` (Earth Search) | GRD on AWS | E84 | `/collections/sentinel-1-grd` | requester-pays **s3://** URLs per E84 README[9] | `*` | | | Copernicus | worse than PC for the Pi (AWS creds) | no | collection 200 | +| `landsat-c2-l2` | Landsat 8/9 SR | E84 + PC | both catalogs | no / SAS | `*` | 8–16 d | 30 m | USGS public | backend TiTiler; or just use GIBS HLS | no | both 200 | +| `hls2-s30` / `hls2-l30` | HLS v2 COGs | PC | `/collections/hls2-s30`, `hls2-l30` | SAS | `*` | 2–3 d | 30 m | NASA | prefer GIBS HLS tiles | no | collections 200 | +| `goes-cmi` | GOES Cloud & Moisture Imagery COGs | PC | `/collections/goes-cmi` | SAS | `*` | 5–10 min | ABI | NOAA | **overkill vs GIBS/IEM tiles** | no | collection 200 | +| `modis-14A1-061` / `modis-64A1-061` | MODIS fire / burned area | PC | `/collections/modis-14A1-061`, `modis-64A1-061` | SAS | `*` | daily / monthly | 1 km / 500 m | NASA | prefer GIBS fire tiles + FIRMS | no | 200 | +| `alos-palsar-mosaic` / `alos-fnf-mosaic` | ALOS PALSAR yearly mosaic / forest-nonforest | PC | those collection ids | SAS | `*` | **annual** | 25 m | JAXA (check collection) | backend mosaic, not live SAR | no | 200 | +| `nasadem` / `cop-dem-glo-30` | DEM COGs | PC + E84 | `nasadem`, `cop-dem-glo-30` | public / SAS | `*` | static | 30 m | NASA / Copernicus | prefer GIBS SRTM/ASTER tiles | no | 200 | +| `naip` | USDA NAIP aerial (CONUS) | E84 + PC | `naip` | no | `*` | leaf-on, not NRT | ~0.6 m | USDA | CONUS only; huge. Optional TiTiler | no | 200 | +| `io-lulc-annual-v02` | 10 m land cover | PC | `io-lulc-annual-v02` | SAS | `*` | annual | 10 m | various | overlay, not sat photo | no | 200 | +| CDSE `sentinel-2-l2a` / `sentinel-1-grd` | Copernicus Dataspace STAC | ESA CDSE | `https://stac.dataspace.copernicus.eu/v1/collections/sentinel-2-l2a` (lowercase ids work; `SENTINEL-2` 404) | **free account** for many assets | **CORS none** | same as ESA | | Copernicus | backend only; Earth Search/PC easier on a Pi | no | collection 200, CORS null. List endpoint is paginated (first page was CLMS burned-area COGs)[14] | + +PC catalog also has Sentinel-3 OLCI/SLSTR NetCDF, Sentinel-5P, GOES-GLM — NetCDF is a bad TiTiler citizen; use GIBS/EUMETView for those. + +--- + +## 4. Free-account / license-gated (no card this week) + +| id | note | why not a dropdown tomorrow | +|---|---|---| +| Microsoft PC SAS for RTC (and some blobs) | “A Planetary Computer account is required to retrieve SAS tokens to read the RTC data.”[12] | Search is open; **read** needs an account. GRD path you already have may not need this. | +| Copernicus Data Space (`stac.dataspace.copernicus.eu`) | STAC search 200 without cookie; **no CORS**; downloads often need a free CDSE login | Use Earth Search/PC unless you want official ESA provenance | +| JAXA P-Tree / Himawari Monitor | Himawari standard data, account | NICT/GIBS already cover browse | +| EUMETSAT Data Store | full MTG/MSG granules | EUMETView WMS is the browse path | +| FIRMS map key | already in product | add `VIIRS_NOAA20_NRT` / `VIIRS_NOAA21_NRT` before SNPP sunset | +| USGS ERS / EarthExplorer | Landsat/ASTER download login | GIBS HLS + Earth Search cover browse | +| Planet Tropical Forest Observatory | paid successor after NICFI | see skip | + +--- + +## 5. Skip / costs money / dead + +| id | why | +|---|---| +| **NICFI / Planet tropical mosaics (free)** | Free NICFI phase **ended 1 Apr 2025**. Removed from GFW and Collect Earth Online. Successor is Planet **Tropical Forest Observatory (subscription)** or a future NICFI re-compete.[16][17] PC collections `planet-nicfi-analytic` / `planet-nicfi-visual` still exist but assets are **RFP winners only** + proprietary PLA.[13] | +| Sentinel Hub (paid tiers) | billed processing units | +| Google Earth Engine | billing project | +| Maxar / Planet commercial | $ | +| ICEYE commercial | no free global tile/STAC found this pass | +| Umbra / Capella / Maxar **open data** STAC | catalogs 200 (`maxar-opendata`, `umbra-open-data-catalog`) but **disaster events only**, not a standing layer | +| Esri World Imagery / Clarity | tiles 200 CORS `*` — **ToS not a free basemap we should wrap** | +| Mapbox / Google satellite | key + ToS | +| GEE Dynamic World / NICFI in EE | EE billing | +| `nowcoast.noaa.gov` | HTTP **403** | +| FIRMS WMS (`firms.modaps.eosdis.nasa.gov/wms/…`) | HTTP **404** — use CSV + GIBS | +| RainViewer satellite IR | payload empty[20] | +| CoastWatch ERDDAP | 503 at probe; GIBS MUR replaces SST | +| Proxying RAMMB or NICT tiles | no CORS; would soak the home uplink | + +--- + +## Implementation notes for builders + +1. **GIBS dropdown:** reuse `MAP_LAYERS` in `app/gibs_map.py`. New rows are `{id, title, tms, format, has_time, max_zoom}`. Time-domain fetch already exists. +2. **SNPP sunset:** NOAA-20/21 true color, DNB, thermal, FIRMS datasets first. SNPP true color can stay as fallback until 2026-11-01. +3. **Fix thermal TMS:** caps say `GoogleMapsCompatible_Level8` for `VIIRS_*_Thermal_Anomalies_375m_*`. Level9 GetTile is HTTP 400 XML. +4. **GOES time:** either GIBS `{time}` ISO + existing date slider, or IEM “latest” XYZ with no time (simpler, CONUS/FD only). +5. **HLS / OPERA:** empty granules 404 — same as “today’s MODIS isn’t ingested yet”. Clamp latest date via DescribeDomains like current daily mosaics. +6. **Do not add TiTiler S2 as a global basemap.** 10 m COGs will thrash the Pi. GIBS HLS Level12 is the browse path; Earth Search TCI is a “inspect this viewport” action like S-1. +7. **EUMETView:** `L.tileLayer.wms` against `https://view.eumetsat.int/geoserver/ows`, layers `msg_fes:rgb_natural` / `msg_fes:ir108`. Caps CORS `*`. +8. **GFW:** send browser Origin (Leaflet does). No key. +9. **Attribution strings:** NASA GIBS acknowledgment[1]; IEM; EUMETSAT; GFW/UMD; NOAA STAR. + +### Probe stats (this run) + +- GIBS WMTS caps: 5 796 177 bytes, CORS `*`, 1315 layers.[4] +- Curated GIBS GetTile: **78/90 HTTP 200** first batch; extra GOES/DNB/HLS/OPERA/ocean 200 as tabulated. +- Earth Search collections (complete list): `sentinel-2-pre-c1-l2a`, `cop-dem-glo-30`, `naip`, `cop-dem-glo-90`, `landsat-c2-l2`, `sentinel-2-l2a`, `sentinel-2-l1c`, `sentinel-2-c1-l2a`, `sentinel-1-grd`.[8] +- Planetary Computer: 136 collections; S-1 RTC CC-BY-4.0.[11][12] + +Raw probe JSON lives next to this file in the kanban workspace (`gibs_probes.json`, `wave2_probes.json`, `wave3_probes.json`, `gibs_all_layers.json`). + +## Sources + +[1] https://nasa-gibs.github.io/gibs-api-docs +[2] https://nasa-gibs.github.io/gibs-api-docs/access-basics +[3] https://nasa-gibs.github.io/gibs-api-docs/available-visualizations +[4] https://gibs.earthdata.nasa.gov/wmts/epsg3857/best/1.0.0/WMTSCapabilities.xml +[5] https://worldview.earthdata.nasa.gov +[6] https://mesonet.agron.iastate.edu/ogc +[7] https://mesonet.agron.iastate.edu/GIS/goes.phtml +[8] https://earth-search.aws.element84.com/v1/collections +[9] https://github.com/Element84/earth-search +[10] https://planetarycomputer.microsoft.com/catalog +[11] https://planetarycomputer.microsoft.com/api/stac/v1/collections +[12] https://planetarycomputer.microsoft.com/dataset/sentinel-1-rtc +[13] https://planetarycomputer.microsoft.com/dataset/planet-nicfi-analytic +[14] https://stac.dataspace.copernicus.eu/v1/collections +[15] https://tiles.globalforestwatch.org +[16] https://www.collect.earth/planet-imagery-via-nicfi-is-no-longer-available-on-ceo +[17] https://www.globalforestwatch.org/blog/data-and-tools/planet-imagery-changes-gfw +[18] https://view.eumetsat.int/geoserver/ows?service=WMS&request=GetCapabilities +[19] https://rammb-slider.cira.colostate.edu +[20] https://api.rainviewer.com/public/weather-maps.json +[21] https://cdn.star.nesdis.noaa.gov/GOES19/ABI/FD/GEOCOLOR/latest.jpg +[22] https://himawari8.nict.go.jp +[23] https://api.openaerialmap.org/meta?limit=1 +[24] https://landsatlook.usgs.gov/stac-server/collections +[25] https://openaerialmap.org +[26] https://bellingcat.gitbook.io/toolkit/more/all-tools/rammb-slider +[27] https://www.earthdata.nasa.gov/engage/open-data-services-software/earthdata-developer-portal/gibs-api From ef8b877d2118a3ec53606029f9b4749cd9a9a5d5 Mon Sep 17 00:00:00 2001 From: Sirius DevOps Date: Sat, 29 Aug 2026 14:03:15 -0400 Subject: [PATCH 35/79] feat(map): chokepoint preset catalog + vessels ?src= filter - GET /api/map/chokepoints: static five-strait fly-to catalog (Hormuz, Bab el-Mandeb, Suez, Malacca, Taiwan) with bbox/center/zoom/vesselapi. No VesselAPI calls; only Hormuz flags vesselapi=true. - GET /api/vessels?src=aisstream|vesselapi|all (default all) filters the union store by provider so a Hormuz view skips ~5k CONUS AISStream rows. - Tests: span validation of all five boxes, catalog 200 shape, src filter. --- app/chokepoints.py | 62 +++++++++++++++++++ app/live_layers.py | 8 ++- app/main.py | 18 +++++- tests/test_chokepoints.py | 122 ++++++++++++++++++++++++++++++++++++++ 4 files changed, 208 insertions(+), 2 deletions(-) create mode 100644 app/chokepoints.py create mode 100644 tests/test_chokepoints.py diff --git a/app/chokepoints.py b/app/chokepoints.py new file mode 100644 index 0000000..fdd98db --- /dev/null +++ b/app/chokepoints.py @@ -0,0 +1,62 @@ +"""Static chokepoint preset catalog — one-tap fly-to targets for the map. + +Pure data, no upstream calls and no VesselAPI quota spend. ``vesselapi`` is +``True`` only for Hormuz (the single box the VesselAPI poller already covers); +every other strait is AISStream-only until a human later spends quota. Never +call VesselAPI from here. + +Bounding boxes are ``minlat,minlon,maxlat,maxlon`` (VesselAPI order) and each +stays within the ``|dLat|+|dLon| <= 4`` span rule enforced by +``vesselapi.validate_bbox_span``. +""" + +from __future__ import annotations + +# id → preset. ``center`` is ``[lat, lon]`` for Leaflet ``setView``. +_CHOKEPOINTS: tuple[dict, ...] = ( + { + "id": "hormuz", + "title": "Strait of Hormuz", + "bbox": "25.5,55.4,27.3,57.2", + "center": [26.4, 56.5], + "zoom": 9, + "vesselapi": True, + }, + { + "id": "bab_el_mandeb", + "title": "Bab el-Mandeb", + "bbox": "12.0,42.8,13.5,44.3", + "center": [12.7, 43.4], + "zoom": 9, + "vesselapi": False, + }, + { + "id": "suez", + "title": "Suez / N. Red Sea", + "bbox": "29.5,32.0,31.0,33.5", + "center": [30.0,32.5], + "zoom": 9, + "vesselapi": False, + }, + { + "id": "malacca", + "title": "Malacca / Singapore", + "bbox": "1.0,103.0,2.5,104.5", + "center": [1.3, 103.8], + "zoom": 9, + "vesselapi": False, + }, + { + "id": "taiwan", + "title": "Taiwan Strait", + "bbox": "23.5,119.0,25.0,120.5", + "center": [24.2, 119.8], + "zoom": 9, + "vesselapi": False, + }, +) + + +def chokepoints() -> list[dict]: + """Return a fresh copy of the catalog (callers must not mutate the source).""" + return [dict(p) for p in _CHOKEPOINTS] diff --git a/app/live_layers.py b/app/live_layers.py index 7022387..6608bf5 100644 --- a/app/live_layers.py +++ b/app/live_layers.py @@ -957,10 +957,16 @@ async def fetch_trains(bbox: str | None, limit: int = DEFAULT_LIMIT) -> list[dic return rows[:limit] -async def fetch_vessels(bbox: str | None, limit: int = DEFAULT_LIMIT) -> list[dict]: +async def fetch_vessels( + bbox: str | None, + limit: int = DEFAULT_LIMIT, + src: str | None = None, +) -> list[dict]: async with vessel_lock: rows = [dict(v) for v in vessel_last_known.values() if v.get("lat") is not None and v.get("lon") is not None] + if src and src != "all": + rows = [r for r in rows if (r.get("extra") or {}).get("src") == src] if bbox: minlon, minlat, maxlon, maxlat = parse_bbox(bbox) return filter_points_bbox(rows, minlon, minlat, maxlon, maxlat, limit) diff --git a/app/main.py b/app/main.py index 6b39d71..d5ac7b4 100644 --- a/app/main.py +++ b/app/main.py @@ -1400,6 +1400,17 @@ async def map_layers(): return {"layers": MAP_LAYERS, "overlays": overlay_catalog()} +@app.get("/api/map/chokepoints") +async def map_chokepoints(): + """Static one-tap fly-to presets (Strait of Hormuz, Bab el-Mandeb, …). + + Pure catalog — no upstream calls and no VesselAPI quota spend. ``vesselapi`` + is True only for Hormuz (the box the VesselAPI poller already covers). + """ + from chokepoints import chokepoints + return {"chokepoints": chokepoints()} + + def _upstream_or_502(exc: Exception, name: str) -> NoReturn: logger.warning("live_layer_upstream_failed", layer=name, error=str(exc)) raise HTTPException(502, f"{name} upstream unavailable: {exc}") from exc @@ -1499,13 +1510,18 @@ async def list_vessels( bbox: str | None = Query(None, description="minlon,minlat,maxlon,maxlat"), limit: int = Query(2000, ge=1, le=5000), timestamp: str | None = Query(None, description="ISO time — DVR 1-min tracks instead of live"), + src: str | None = Query(None, description="aisstream|vesselapi|all (default all)"), ): """AIS last-known — union of two independent providers. AISStream (extra.src="aisstream", live US-coast WebSocket) and VesselAPI (extra.src="vesselapi", Strait of Hormuz 5×/day poll) both upsert into the same store. Empty without either key / until the first successful poll. + ``src`` filters the union to one provider (default ``all``) so a Hormuz + view can skip the ~5k CONUS AISStream rows. """ + if src is not None and src not in ("aisstream", "vesselapi", "all"): + raise HTTPException(422, "src must be one of: aisstream, vesselapi, all") if bbox: _parse_bbox_query(bbox) try: @@ -1513,7 +1529,7 @@ async def list_vessels( ts = parse_timestamp(timestamp) if ts is not None: return overlay_json(await fetch_positions_at("vessel", ts, bbox, limit), 5) - return overlay_json(await fetch_vessels(bbox, limit), 5) + return overlay_json(await fetch_vessels(bbox, limit, src=src), 5) except ValueError as exc: raise HTTPException(422, str(exc)) from exc diff --git a/tests/test_chokepoints.py b/tests/test_chokepoints.py new file mode 100644 index 0000000..62a687b --- /dev/null +++ b/tests/test_chokepoints.py @@ -0,0 +1,122 @@ +"""Tests for the chokepoint preset catalog + vessels ``src=`` filter. + +- Span: every catalog box passes VesselAPI's ``|dLat|+|dLon| <= 4`` validator. +- Catalog: ``GET /api/map/chokepoints`` returns 200 with the documented shape. +- Vessels filter: ``GET /api/vessels?src=`` narrows the union store by provider. +""" + +from __future__ import annotations + +import asyncio + +import httpx + +from chokepoints import chokepoints +from live_layers import fetch_vessels, vessel_last_known +from main import app +from vesselapi import validate_bbox_span + +BASE = "http://test" + + +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) + + +# ── Span validation (VesselAPI rule) ────────────────────────────────────── + +def test_all_catalog_boxes_within_span() -> None: + for preset in chokepoints(): + minlat, minlon, maxlat, maxlon = (float(p) for p in preset["bbox"].split(",")) + dlat = abs(maxlat - minlat) + dlon = abs(maxlon - minlon) + assert dlat + dlon <= 4.0, preset["id"] + validate_bbox_span(minlat, minlon, maxlat, maxlon) # no raise + + +# ── Catalog API contract ────────────────────────────────────────────────── + +def test_chokepoints_catalog_shape() -> None: + resp = asyncio.run(_get("/api/map/chokepoints")) + assert resp.status_code == 200 + body = resp.json() + assert set(body) == {"chokepoints"} + rows = body["chokepoints"] + assert [r["id"] for r in rows] == [ + "hormuz", "bab_el_mandeb", "suez", "malacca", "taiwan", + ] + for r in rows: + assert set(r) == {"id", "title", "bbox", "center", "zoom", "vesselapi"} + assert isinstance(r["center"], list) and len(r["center"]) == 2 + assert r["zoom"] == 9 + assert isinstance(r["vesselapi"], bool) + # bbox is minlat,minlon,maxlat,maxlon + minlat, minlon, maxlat, maxlon = (float(p) for p in r["bbox"].split(",")) + assert minlat < maxlat and minlon < maxlon + + +def test_only_hormuz_is_vesselapi() -> None: + rows = chokepoints() + by_id = {r["id"]: r for r in rows} + assert by_id["hormuz"]["vesselapi"] is True + for cid in ("bab_el_mandeb", "suez", "malacca", "taiwan"): + assert by_id[cid]["vesselapi"] is False + + +# ── Vessels src= filter (mocked store) ──────────────────────────────────── + +def _seed_store() -> None: + vessel_last_known.clear() + vessel_last_known["422050100"] = { + "id": "422050100", "lat": 26.5, "lon": 56.3, "label": "HORMUZ STAR", + "extra": {"src": "vesselapi", "mmsi": "422050100"}, + } + vessel_last_known["366001230"] = { + "id": "366001230", "lat": 35.0, "lon": -79.0, "label": "CONUS SHIP", + "extra": {"src": "aisstream", "mmsi": "366001230"}, + } + vessel_last_known["366001231"] = { + "id": "366001231", "lat": 36.0, "lon": -78.0, "label": "CONUS SHIP 2", + "extra": {"src": "aisstream", "mmsi": "366001231"}, + } + + +def test_fetch_vessels_src_filters() -> None: + _seed_store() + assert {v["id"] for v in asyncio.run(fetch_vessels(None, src="vesselapi"))} == {"422050100"} + assert {v["id"] for v in asyncio.run(fetch_vessels(None, src="aisstream"))} == { + "366001230", "366001231", + } + assert len(asyncio.run(fetch_vessels(None, src="all"))) == 3 + assert len(asyncio.run(fetch_vessels(None))) == 3 # default all + + +def test_vessels_src_query_param(monkeypatch) -> None: + _seed_store() + + async def _fake_fetch(bbox, limit, src=None): + rows = [ + {"id": k, **{kk: v[kk] for kk in ("lat", "lon", "label", "extra")}} + for k, v in vessel_last_known.items() + ] + if src and src != "all": + rows = [r for r in rows if (r.get("extra") or {}).get("src") == src] + return rows + + monkeypatch.setattr("main.fetch_vessels", _fake_fetch) + + body = asyncio.run(_get("/api/vessels?src=vesselapi")).json() + assert [r["id"] for r in body] == ["422050100"] + + body = asyncio.run(_get("/api/vessels?src=aisstream")).json() + assert {r["id"] for r in body} == {"366001230", "366001231"} + + body = asyncio.run(_get("/api/vessels?src=all")).json() + assert len(body) == 3 + + +def test_vessels_src_rejects_bad_value() -> None: + resp = asyncio.run(_get("/api/vessels?src=marine-traffic")) + assert resp.status_code == 422 From ac03442998c55777164b2cbd9df2660da2ca7544 Mon Sep 17 00:00:00 2001 From: Sirius DevOps Date: Sat, 29 Aug 2026 14:12:02 -0400 Subject: [PATCH 36/79] feat(map): chokepoint preset buttons on the Leaflet toolbar Fetch GET /api/map/chokepoints once. Desktop buttons / phone + +
@@ -1902,6 +1918,8 @@ let moveDebounce = null; let overlayAbort = null; let lastCell = ''; let lastVesselSubBox = ''; // last viewport box sent to the AIS stream +let chokepointCatalog = []; // GET /api/map/chokepoints, fetched once +let vesselSrcPref = ''; // 'vesselapi' only on Hormuz preset — no extra polls let vesselRefollowTimer = null; // one follow-up fetch after a retune function bboxCell() { if (!map) return ''; @@ -2023,6 +2041,7 @@ async function initMap() { maxZoom: 12, attributionControl: true, }); + window.map = map; L.control.zoom({ position: 'topright' }).addTo(map); map.attributionControl.setPrefix(''); let activeHls = null; @@ -2131,6 +2150,7 @@ async function initMap() { vesselsOn = document.getElementById('lp-vessels-on').checked; stormsOn = document.getElementById('lp-storms-on').checked; connectLiveWs(); + loadChokepoints(); requestAnimationFrame(() => { if (firesOn) loadFires(); setTimeout(() => { @@ -2258,7 +2278,93 @@ function mapGoDays(n) { document.getElementById('map-date').value = iso; mapDateChanged(); } -function mapResetView() { if (map) map.setView([25, 10], 2); } +function mapResetView() { + vesselSrcPref = ''; + document.querySelectorAll('#chokepoint-btns .btn').forEach(b => { + b.classList.remove('is-on'); + b.setAttribute('aria-pressed', 'false'); + }); + const sel = document.getElementById('chokepoint-select'); + if (sel) sel.value = ''; + if (map) map.setView([25, 10], 2); +} + +const CHOKEPOINT_SHORT = { + hormuz: 'Hormuz', + bab_el_mandeb: 'Bab el-Mandeb', + suez: 'Suez', + malacca: 'Malacca', + taiwan: 'Taiwan', +}; +async function loadChokepoints() { + try { + const r = await fetch(`${API}/api/map/chokepoints`); + const d = await r.json(); + if (r.ok && Array.isArray(d.chokepoints)) chokepointCatalog = d.chokepoints; + } catch (_) { /* catalog is optional until the backend PR lands */ } + renderChokepointControls(); +} +function renderChokepointControls() { + const btns = document.getElementById('chokepoint-btns'); + const sel = document.getElementById('chokepoint-select'); + if (!btns || !sel) return; + btns.replaceChildren(); + sel.querySelectorAll('option:not([value=""])').forEach(o => o.remove()); + for (const p of chokepointCatalog) { + const label = CHOKEPOINT_SHORT[p.id] || p.title || p.id; + const b = document.createElement('button'); + b.type = 'button'; + b.className = 'btn'; + b.dataset.id = p.id; + b.textContent = label; + b.setAttribute('aria-pressed', 'false'); + b.addEventListener('click', () => applyChokepoint(p.id)); + btns.appendChild(b); + const opt = document.createElement('option'); + opt.value = p.id; + opt.textContent = label; + sel.appendChild(opt); + } +} +function chokepointLeafletBounds(bbox) { + // Catalog bbox is minlat,minlon,maxlat,maxlon — Leaflet wants [[lat,lon],[lat,lon]]. + const [minlat, minlon, maxlat, maxlon] = String(bbox || '').split(',').map(Number); + if (![minlat, minlon, maxlat, maxlon].every(Number.isFinite)) return null; + return [[minlat, minlon], [maxlat, maxlon]]; +} +function applyChokepoint(id) { + if (!id || !map) return; + const p = chokepointCatalog.find(x => x.id === id); + if (!p) return; + document.querySelectorAll('#chokepoint-btns .btn').forEach(b => { + const on = b.dataset.id === id; + b.classList.toggle('is-on', on); + b.setAttribute('aria-pressed', on ? 'true' : 'false'); + }); + const sel = document.getElementById('chokepoint-select'); + if (sel && sel.value !== id) sel.value = id; + vesselSrcPref = p.vesselapi ? 'vesselapi' : ''; + if (Array.isArray(p.center) && p.center.length === 2 && p.zoom) { + map.setView(p.center, p.zoom); + } else { + const bounds = chokepointLeafletBounds(p.bbox); + if (bounds) map.fitBounds(bounds, { padding: [24, 24] }); + } + const vChk = document.getElementById('lp-vessels-on'); + if (vChk) vChk.checked = true; + vesselsOn = true; + // Hormuz especially: turn SAR on so AIS dots sit on the radar raster. User can untick. + if (p.id === 'hormuz' || p.vesselapi) { + const sChk = document.getElementById('lp-sentinel-on'); + if (sChk && !sChk.checked) { + sChk.checked = true; + sentinelOn = true; + } + } + lastCell = ''; + if (vesselsOn) loadVessels(); + if (sentinelOn) loadSentinel1(); +} function currentBBox() { const b = map.getBounds(); @@ -3208,7 +3314,9 @@ async function loadVessels() { const isWorld = (be - bw) >= 300 || bb.startsWith('-180.0000,-85.0000,180.0000,85.0000'); const subKey = isWorld ? '' : quantizeBBox(bb); let retuned = false; - if (subKey && subKey !== lastVesselSubBox) { + // AISStream subscribe retunes the US feed. Never fire it for Gulf/strait + // boxes or the free stream leaves CONUS. VesselAPI is a cached poll. + if (subKey && subKey !== lastVesselSubBox && intersectsConus()) { lastVesselSubBox = subKey; retuned = true; fetch(`${API}/api/vessels/subscribe`, { @@ -3218,7 +3326,8 @@ async function loadVessels() { }).catch(() => {}); } try { - const r = await overlayFetch(`${API}/api/vessels?bbox=${bb}${dvrQs()}`); + const srcQs = vesselSrcPref ? `&src=${encodeURIComponent(vesselSrcPref)}` : ''; + const r = await overlayFetch(`${API}/api/vessels?bbox=${bb}${srcQs}${dvrQs()}`); const pts = await r.json(); if (req !== overlayReq.vessels) return; vesselsGroup = renderPoints(vesselsGroup, Array.isArray(pts) ? pts : [], p => { diff --git a/tests/test_frontend_reliability.py b/tests/test_frontend_reliability.py index 908f779..d734f49 100644 --- a/tests/test_frontend_reliability.py +++ b/tests/test_frontend_reliability.py @@ -47,3 +47,32 @@ def test_ws_reconnect_uses_backoff(): def test_check_health_treats_degraded_status(): fn = HTML.split("async function checkHealth")[1].split("/* ═══════════════ NAV")[0] assert "degraded" in fn.lower() or "d.status" in fn + + +def test_chokepoint_presets_in_toolbar(): + assert 'id="chokepoint-btns"' in HTML + assert 'id="chokepoint-select"' in HTML + assert "loadChokepoints()" in HTML + assert "/api/map/chokepoints" in HTML + assert "function applyChokepoint" in HTML + for name in ("Hormuz", "Bab el-Mandeb", "Suez", "Malacca", "Taiwan"): + assert name in HTML + + +def test_chokepoint_skips_aisstream_subscribe_outside_conus(): + load = HTML.split("async function loadVessels")[1].split("async function toggleStorms")[0] + assert "intersectsConus()" in load + assert "api/vessels/subscribe" in load + assert "src=${encodeURIComponent(vesselSrcPref)}" in load or "&src=" in load + apply = HTML.split("function applyChokepoint")[1].split("function currentBBox")[0] + assert "vesselapi" in apply + assert "lp-vessels-on" in apply + assert "lp-sentinel-on" in apply + assert "map.setView" in apply + assert "minlat,minlon,maxlat,maxlon" in HTML.split("function chokepointLeafletBounds")[1][:400] + + +def test_phone_chokepoints_use_select_not_buttons(): + mobile = HTML.split("@media (max-width: 820px)")[1].split("@media (prefers-reduced-motion")[0] + assert "#chokepoint-select { display: block; }" in mobile + assert ".chokepoint-btns { display: none; }" in mobile or "#chokepoint-label, .chokepoint-btns { display: none; }" in mobile From 42ca6295f045ff298cfdf3edb6600023b0b069ad Mon Sep 17 00:00:00 2001 From: Sirius DevOps Date: Sat, 29 Aug 2026 14:14:08 -0400 Subject: [PATCH 37/79] feat(gpsjam): GPS interference hex overlay API (GPSJAM/ADS-B Exchange) GET /api/map/gpsjam?date=YYYY-MM-DD (default yesterday UTC) fetches the daily gpsjam.org H3 resolution-4 CSV, converts hexes to GeoJSON polygons, and tags each with level low|medium|high (0-2% / 2-10% / >10%) via GPSJAM's denoise formula. Whole world once, 1h TTL, graceful unavailable fallback. - overlay_catalog: add kind=geojson gpsjam stub - tests: mocked-HTTP unit + API contract (9 new) --- app/live_layers.py | 89 +++++++++++++++++++++++++ app/main.py | 43 ++++++++++++- app/requirements.txt | 1 + tests/test_gpsjam.py | 150 +++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 280 insertions(+), 3 deletions(-) create mode 100644 tests/test_gpsjam.py diff --git a/app/live_layers.py b/app/live_layers.py index 7022387..e243fd6 100644 --- a/app/live_layers.py +++ b/app/live_layers.py @@ -54,6 +54,13 @@ TITILER_COG_TILES = f"{TITILER_PUBLIC_BASE}/cog/tiles/WebMercatorQuad/{{z}}/{{x} SENTINEL1_TTL = 20 * 60 # 15–30 min quota-friendly window SENTINEL1_ATTRIBUTION = "Copernicus Sentinel-1 / Microsoft Planetary Computer" +# GPSJAM (John Wiseman / ADS-B Exchange): daily H3 hexes of aircraft nav +# accuracy. Hexes are published as a gzip CSV at a stable per-date URL, soon +# after midnight UTC. Red/yellow != proven jamming. +GPSJAM_BASE = "https://gpsjam.org" +GPSJAM_RES = 4 +GPSJAM_TTL = 3600.0 # 1h — whole-world layer, fetched once per day effectively + IEM_NEXRAD = "https://mesonet.agron.iastate.edu/cache/tile.py/1.0.0/nexrad-n0q/{z}/{x}/{y}.png" GIBS_THERMAL = ( "https://gibs.earthdata.nasa.gov/wmts/epsg3857/best/" @@ -135,6 +142,12 @@ def overlay_catalog() -> dict: "vessels": {"id": "vessels", "kind": "points", "endpoint": "/api/vessels"}, "trains": {"id": "trains", "kind": "points", "endpoint": "/api/trains"}, "storms": {"id": "storms", "kind": "points", "endpoint": "/api/storms"}, + "gpsjam": { + "id": "gpsjam", + "kind": "geojson", + "endpoint": "/api/map/gpsjam", + "attribution": "GPSJAM / John Wiseman / ADS-B Exchange", + }, } @@ -1283,3 +1296,79 @@ async def fetch_sentinel1(bbox: str) -> dict | None: } return await _ttl_get(key, float(SENTINEL1_TTL), _load) +# ── GPSJAM ────────────────────────────────────────────────────────────────── + + +def gpsjam_level(percent_bad: float) -> str: + """Map a denoised bad-aircraft percentage to GPSJAM's three tiers.""" + if percent_bad > 10.0: + return "high" + if percent_bad > 2.0: + return "medium" + return "low" + + +def gpsjam_csv_to_geojson(text: str) -> dict: + """Convert a GPSJAM daily CSV to a world FeatureCollection of hex polygons. + + Rows are ``hex,count_good_aircraft,count_bad_aircraft``. The interference + percentage uses GPSJAM's published denoise formula + ``100 * (bad - 1) / (good + bad)``; hexes with zero bad aircraft are the + "normal" background and are dropped (the base map already shows nothing). + """ + import csv + import io + + import h3 + + features = [] + for row in csv.DictReader(io.StringIO(text)): + hex_id = (row.get("hex") or "").strip() + if not hex_id: + continue + try: + good = int(row.get("count_good_aircraft") or 0) + bad = int(row.get("count_bad_aircraft") or 0) + except (TypeError, ValueError): + continue + if bad < 1: + continue + denom = good + bad + percent = 100.0 * (bad - 1) / denom if denom > 0 else 0.0 + try: + # h3 returns (lat, lng); GeoJSON needs (lng, lat) closed rings. + ring = [[lng, lat] for lat, lng in h3.cell_to_boundary(hex_id)] + except Exception: # malformed/unknown cell id — skip + continue + ring.append(ring[0]) + features.append({ + "type": "Feature", + "geometry": {"type": "Polygon", "coordinates": [ring]}, + "properties": { + "level": gpsjam_level(percent), + "percent_bad": round(percent, 2), + "good": good, + "bad": bad, + "hex": hex_id, + }, + }) + return {"type": "FeatureCollection", "features": features} + + +async def fetch_gpsjam(date: str) -> dict: + """Fetch + convert one GPSJAM daily hex layer (whole world, 1h TTL).""" + url = f"{GPSJAM_BASE}/data/{date}-h3_{GPSJAM_RES}.csv" + + async def _load(): + if _http is None: + async with httpx.AsyncClient( + timeout=_HTTP_TIMEOUT, follow_redirects=True, headers=_headers(), + ) as client: + resp = await client.get(url) + resp.raise_for_status() + return gpsjam_csv_to_geojson(resp.text) + resp = await _http.get(url) + resp.raise_for_status() + return gpsjam_csv_to_geojson(resp.text) + + return await _ttl_get(f"gpsjam:{date}", GPSJAM_TTL, _load) diff --git a/app/main.py b/app/main.py index 6b39d71..e2ce82b 100644 --- a/app/main.py +++ b/app/main.py @@ -14,6 +14,7 @@ from __future__ import annotations import asyncio import json import logging +import re from contextlib import asynccontextmanager from datetime import datetime, timedelta, timezone from decimal import Decimal @@ -21,6 +22,7 @@ from pathlib import Path from typing import NoReturn from uuid import UUID +import httpx import structlog from fastapi import BackgroundTasks, FastAPI, HTTPException, Query, WebSocket, WebSocketDisconnect from fastapi.middleware.gzip import GZipMiddleware @@ -53,9 +55,9 @@ from keystore import KeyFormatError, delete_key, list_keys, set_key from settings_store import SettingsError, get_app_settings, list_models, set_summary_model from live_layers import ( fetch_aircraft, fetch_fire_incidents, fetch_fire_perimeters, - fetch_planespotters_photo, fetch_radar_meta, fetch_sentinel1, fetch_storms, - fetch_trains, fetch_vessels, fetch_weather_alerts, overlay_catalog, - parse_bbox, UpstreamRateLimited, + fetch_gpsjam, fetch_planespotters_photo, fetch_radar_meta, fetch_sentinel1, + fetch_storms, fetch_trains, fetch_vessels, fetch_weather_alerts, + overlay_catalog, parse_bbox, UpstreamRateLimited, ) logging.basicConfig(level=logging.INFO) @@ -1682,6 +1684,41 @@ async def list_storms(): _upstream_or_502(exc, "storms") +_GPSJAM_DATE = re.compile(r"^\d{4}-\d{2}-\d{2}$") + + +@app.get("/api/map/gpsjam") +async def map_gpsjam( + date: str | None = Query(None, description="YYYY-MM-DD (default: yesterday UTC)"), +): + """GPSJAM daily GPS-interference hex layer (whole world, GeoJSON). + + Red/yellow hexes correlate with suspected jamming but are NOT proof of it. + Fetched once per day from gpsjam.org (ADS-B Exchange data) and cached 1h. + """ + target = date + if target is None: + target = (datetime.now(timezone.utc) - timedelta(days=1)).strftime("%Y-%m-%d") + if not _GPSJAM_DATE.match(target): + raise HTTPException(422, "date must be YYYY-MM-DD") + try: + fc = await fetch_gpsjam(target) + except httpx.HTTPStatusError as exc: + if exc.response.status_code == 404: + return JSONResponse( + {"error": "unavailable", "href": "https://gpsjam.org/", + "date": target}, + ) + _upstream_or_502(exc, "gpsjam") + except Exception as exc: + _upstream_or_502(exc, "gpsjam") + if not fc.get("features"): + return JSONResponse( + {"error": "unavailable", "href": "https://gpsjam.org/", "date": target}, + ) + return overlay_json(fc, 3600) + + @app.get("/api/map/times") async def map_layer_times( layer: str = Query(..., description="GIBS layer identifier, e.g. VIIRS_SNPP_CorrectedReflectance_TrueColor"), diff --git a/app/requirements.txt b/app/requirements.txt index 691ab71..2389199 100644 --- a/app/requirements.txt +++ b/app/requirements.txt @@ -12,3 +12,4 @@ python-dateutil>=2.9 structlog>=24.4 websockets>=14 cachetools>=5.5 +h3>=4.0 diff --git a/tests/test_gpsjam.py b/tests/test_gpsjam.py new file mode 100644 index 0000000..4976523 --- /dev/null +++ b/tests/test_gpsjam.py @@ -0,0 +1,150 @@ +"""GPSJAM GPS-interference overlay: level mapping, CSV→GeoJSON, API contract.""" + +import asyncio + +import httpx + +from live_layers import gpsjam_csv_to_geojson, gpsjam_level, overlay_catalog, _cache +from main import app + +BASE = "http://test" + +# A valid H3 resolution-4 cell id (the payload hex column carries these). +HEX_A = "8400c57ffffffff" + +CSV = ( + "hex,count_good_aircraft,count_bad_aircraft\n" + f"{HEX_A},0,20\n" # 100*(20-1)/20 = 95 -> high + f"{HEX_A},8,2\n" # 100*(2-1)/10 = 10 -> medium + f"{HEX_A},98,2\n" # 100*(2-1)/100 = 1 -> low + f"{HEX_A},100,0\n" # bad == 0 -> dropped +) + + +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 test_gpsjam_level_thresholds(): + assert gpsjam_level(0.0) == "low" + assert gpsjam_level(2.0) == "low" + assert gpsjam_level(2.1) == "medium" + assert gpsjam_level(10.0) == "medium" + assert gpsjam_level(10.1) == "high" + assert gpsjam_level(95.0) == "high" + + +def test_gpsjam_csv_to_geojson_levels_and_drop_zero_bad(): + fc = gpsjam_csv_to_geojson(CSV) + assert fc["type"] == "FeatureCollection" + assert len(fc["features"]) == 3 # bad==0 row dropped + levels = [f["properties"]["level"] for f in fc["features"]] + assert levels == ["high", "medium", "low"] + for f in fc["features"]: + geom = f["geometry"] + assert geom["type"] == "Polygon" + ring = geom["coordinates"][0] + assert len(ring) == 7 # 6 verts + closing point + assert ring[0] == ring[-1] + assert f["properties"]["hex"] == HEX_A + assert set(f["properties"]).issuperset({"level", "percent_bad", "good", "bad", "hex"}) + + +def test_gpsjam_csv_skips_malformed_rows(): + bad_csv = "hex,count_good_aircraft,count_bad_aircraft\n" \ + ",1,5\n" \ + f"{HEX_A},x,5\n" \ + f"{HEX_A},1,notanint\n" \ + "not_a_cell,1,5\n" + fc = gpsjam_csv_to_geojson(bad_csv) + assert fc["features"] == [] + + +def test_overlay_catalog_has_gpsjam_stub(): + entry = overlay_catalog()["gpsjam"] + assert entry["kind"] == "geojson" + assert entry["endpoint"] == "/api/map/gpsjam" + assert "GPSJAM" in entry["attribution"] + + +def test_map_gpsjam_returns_featurecollection(monkeypatch): + async def fake_fetch(date): + return {"type": "FeatureCollection", "features": [{"type": "Feature"}]} + + monkeypatch.setattr("main.fetch_gpsjam", fake_fetch) + resp = asyncio.run(_get("/api/map/gpsjam?date=2026-08-28")) + assert resp.status_code == 200 + assert resp.json()["type"] == "FeatureCollection" + assert "max-age" in (resp.headers.get("cache-control") or "").lower() + + +def test_map_gpsjam_rejects_bad_date(): + resp = asyncio.run(_get("/api/map/gpsjam?date=08-28-2026")) + assert resp.status_code == 422 + + +def test_map_gpsjam_unavailable_on_404(monkeypatch): + import httpx as _httpx + + async def fake_fetch(date): + exc = _httpx.HTTPStatusError( + "404", request=_httpx.Request("GET", "http://x"), response=_httpx.Response(404) + ) + raise exc + + monkeypatch.setattr("main.fetch_gpsjam", fake_fetch) + resp = asyncio.run(_get("/api/map/gpsjam?date=2026-08-28")) + assert resp.status_code == 200 + body = resp.json() + assert body["error"] == "unavailable" + assert body["href"] == "https://gpsjam.org/" + + +def test_map_gpsjam_unavailable_on_empty_features(monkeypatch): + async def fake_fetch(date): + return {"type": "FeatureCollection", "features": []} + + monkeypatch.setattr("main.fetch_gpsjam", fake_fetch) + resp = asyncio.run(_get("/api/map/gpsjam?date=2026-08-28")) + assert resp.status_code == 200 + assert resp.json()["error"] == "unavailable" + + +def test_fetch_gpsjam_hits_http_once_within_ttl(monkeypatch): + _cache.clear() + hits = {"n": 0} + + class FakeResp: + text = CSV + + def raise_for_status(self): + pass + + class FakeClient: + def __init__(self, **kw): + pass + + async def __aenter__(self): + return self + + async def __aexit__(self, *exc): + return False + + async def get(self, url): + hits["n"] += 1 + assert url == "https://gpsjam.org/data/2026-08-28-h3_4.csv" + return FakeResp() + + monkeypatch.setattr("live_layers.httpx.AsyncClient", FakeClient) + monkeypatch.setattr("live_layers._http", None) + + from live_layers import fetch_gpsjam + + fc1 = asyncio.run(fetch_gpsjam("2026-08-28")) + fc2 = asyncio.run(fetch_gpsjam("2026-08-28")) + assert len(fc1["features"]) == 3 + assert fc2 == fc1 + assert hits["n"] == 1 + _cache.clear() From 5651d251d0b29ad2f8f7ee909e8964aeb0411928 Mon Sep 17 00:00:00 2001 From: Sirius DevOps Date: Sat, 29 Aug 2026 19:32:00 -0400 Subject: [PATCH 38/79] fix(ingest): skip known KEV/FIRMS rows; CI skips unchanged images CISA KEV republished 1685 NIST URLs every 5 min; FIRMS re-inserted ~325k global hotspots every 15 min. Producer now skips URLs already in event_dedup and FIRMS CSVs that are unchanged (delta-only persist). CI rebuilds only images whose paths changed and never pulls/rebuilds Timescale or bounces osint-db unless Dockerfile.pg changes. --- .forgejo/workflows/build.yml | 157 +++++++++++++++++++++++++++-------- app/fire_sources.py | 83 ++++++++++++------ app/ingestor.py | 2 +- app/sources.py | 43 ++++++++-- docker-compose.yml | 11 ++- scripts/compose-reup.sh | 74 ++++++++++++----- tests/test_fire_sources.py | 94 +++++++++++++++++++++ tests/test_new_sources.py | 62 ++++++++++++++ tests/test_upstream_cache.py | 6 +- 9 files changed, 438 insertions(+), 94 deletions(-) diff --git a/.forgejo/workflows/build.yml b/.forgejo/workflows/build.yml index 6116fdf..b2c2a0d 100644 --- a/.forgejo/workflows/build.yml +++ b/.forgejo/workflows/build.yml @@ -1,6 +1,10 @@ -# Build all OSINT images, publish to the Forgejo container registry, then +# Build changed OSINT images, publish to the Forgejo container registry, then # redeploy on the Pi runner (docker.sock mounted). # +# Unchanged images are skipped. Dockerfile.pg / osint-dashboard-pg is NOT +# rebuilt or pulled on a normal merge — Postgres stays up. Rebuild it only +# when Dockerfile.pg changes, or via workflow_dispatch rebuild_pg. +# # Public pull host: forgejo.siriusdevops.com (NOT ghcr.io) # CI push host: 127.0.0.1:3000 — Cloudflare 413s layers ≳100MB on the public # hostname, even from the Pi (hairpins out through the tunnel). @@ -19,6 +23,15 @@ on: push: branches: [main, master] workflow_dispatch: + inputs: + rebuild_pg: + description: Rebuild Timescale+PostGIS (Dockerfile.pg) + type: boolean + default: false + rebuild_all: + description: Rebuild every app image (ignore path filter) + type: boolean + default: false env: PUBLIC_REGISTRY: ${{ vars.FORGEJO_REGISTRY || 'forgejo.siriusdevops.com' }} @@ -36,6 +49,68 @@ jobs: steps: - name: Checkout uses: https://code.forgejo.org/actions/checkout@v4 + with: + fetch-depth: 50 + + - name: Plan image builds + id: plan + run: | + set -euo pipefail + APP=0 + SCRAPER=0 + SUM=0 + PG=0 + COMPOSE=0 + + mark() { + case "$1" in + Dockerfile.pg) + PG=1 ;; + Dockerfile|app/*|alembic/*|alembic.ini) + APP=1 ;; + news/scraper/*) + SCRAPER=1 ;; + news/summerizer/*) + SUM=1 ;; + docker-compose.yml|scripts/compose-reup.sh) + COMPOSE=1 ;; + esac + } + + if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then + APP=1; SCRAPER=1; SUM=1 + if [ "${{ github.event.inputs.rebuild_all }}" = "true" ]; then + APP=1; SCRAPER=1; SUM=1; PG=1 + fi + if [ "${{ github.event.inputs.rebuild_pg }}" = "true" ]; then + PG=1 + fi + else + BEFORE="${{ github.event.before }}" + SHA="${GITHUB_SHA}" + ZEROS="0000000000000000000000000000000000000000" + if [ -z "$BEFORE" ] || [ "$BEFORE" = "$ZEROS" ]; then + echo "No previous SHA — build app images, skip pg" + APP=1; SCRAPER=1; SUM=1 + elif ! git cat-file -e "${BEFORE}^{commit}" 2>/dev/null; then + echo "Previous SHA $BEFORE not in history — build app images, skip pg" + APP=1; SCRAPER=1; SUM=1 + else + while IFS= read -r f; do + [ -z "$f" ] && continue + mark "$f" + done < <(git diff --name-only "$BEFORE" "$SHA") + fi + fi + + { + echo "app=$APP" + echo "scraper=$SCRAPER" + echo "summarizer=$SUM" + echo "pg=$PG" + echo "compose=$COMPOSE" + } >> "$GITHUB_OUTPUT" + echo "plan app=$APP scraper=$SCRAPER summarizer=$SUM pg=$PG compose=$COMPOSE" - name: Image refs id: img @@ -59,6 +134,7 @@ jobs: echo "SHA tag: $SHA" - name: Login to Forgejo registry + if: steps.plan.outputs.app == '1' || steps.plan.outputs.scraper == '1' || steps.plan.outputs.summarizer == '1' || steps.plan.outputs.pg == '1' run: | set -euo pipefail # GITHUB_TOKEN login "succeeds" but blob uploads 401 (Forgejo packages @@ -71,6 +147,7 @@ jobs: -u sirius --password-stdin - name: Build application image (api / ingester / cameras) + if: steps.plan.outputs.app == '1' run: | set -ex APP="${{ steps.img.outputs.app }}" @@ -81,6 +158,7 @@ jobs: docker push "${APP}:${SHA}" - name: Build news-scraper image + if: steps.plan.outputs.scraper == '1' run: | set -ex IMG="${{ steps.img.outputs.scraper }}" @@ -91,6 +169,7 @@ jobs: docker push "${IMG}:${SHA}" - name: Build news-summarizer image + if: steps.plan.outputs.summarizer == '1' run: | set -ex IMG="${{ steps.img.outputs.summarizer }}" @@ -101,22 +180,17 @@ jobs: docker push "${IMG}:${SHA}" - name: Build / refresh Timescale+PostGIS image + if: steps.plan.outputs.pg == '1' run: | set -ex PG="${{ steps.img.outputs.pg }}" SHA="${{ steps.img.outputs.sha }}" - # Prefer rebuild so registry always has a current pg image. If packagecloud - # is unreachable, fall back to whatever local image already exists. if docker build -f Dockerfile.pg -t "${PG}:latest" -t "${PG}:${SHA}" \ -t "localhost/osint-dashboard-pg:latest" .; then docker push "${PG}:latest" docker push "${PG}:${SHA}" elif docker image inspect "localhost/osint-dashboard-pg:latest" >/dev/null 2>&1; then - echo "WARN: Dockerfile.pg build failed; retagging existing local pg image into registry" - docker tag "localhost/osint-dashboard-pg:latest" "${PG}:latest" - docker tag "localhost/osint-dashboard-pg:latest" "${PG}:${SHA}" - docker push "${PG}:latest" - docker push "${PG}:${SHA}" + echo "WARN: Dockerfile.pg build failed; keeping existing local pg image" else echo "ERROR: cannot build or find osint-dashboard-pg image" exit 1 @@ -126,39 +200,50 @@ jobs: run: | set -ex cd "${GITHUB_WORKSPACE}" - # Pull from Forgejo registry into local tags compose expects, then up. - # Compose file still uses localhost/* for stable local names; we mirror - # registry tags so a cold host can recover via docker pull. - REG="${{ steps.img.outputs.reg }}" - PUB="${{ steps.img.outputs.pub }}" - OWN="${{ env.OWNER }}" - for name in osint-dashboard osint-dashboard-pg osint-news-scraper osint-news-summarizer; do - docker pull "${REG}/${OWN}/${name}:latest" || true - docker tag "${REG}/${OWN}/${name}:latest" "localhost/${name}:latest" || true - docker tag "${REG}/${OWN}/${name}:latest" "${PUB}/${OWN}/${name}:latest" || true - done - # Do NOT set COMPOSE_PROJECT_NAME differently — volumes must stay - # osint-dashboard_osint-pgdata (pinned by `name:` in compose). - docker compose build --no-cache app ingester camera-service news-scraper news-summarizer || \ - docker compose build app ingester camera-service news-scraper news-summarizer - # Name-pinned containers (container_name: osint-dashboard, …) collide - # when compose tries to create instead of recreate — e.g. leftover from - # a different working_dir or a half-failed previous up. down + rm -f - # the known names, then up the full ingest profile. + APP="${{ steps.plan.outputs.app }}" + SCRAPER="${{ steps.plan.outputs.scraper }}" + SUM="${{ steps.plan.outputs.summarizer }}" + PG="${{ steps.plan.outputs.pg }}" + COMPOSE="${{ steps.plan.outputs.compose }}" + + SVCS=() + [ "$APP" = "1" ] && SVCS+=(app ingester camera-service) + [ "$SCRAPER" = "1" ] && SVCS+=(news-scraper) + [ "$SUM" = "1" ] && SVCS+=(news-summarizer) + if [ "$COMPOSE" = "1" ]; then + # compose/script change: bounce workers so env/command updates apply. + # Still do not bounce Postgres. + for s in app ingester camera-service news-scraper news-summarizer; do + case " ${SVCS[*]} " in + *" $s "*) ;; + *) SVCS+=("$s") ;; + esac + done + fi + chmod +x scripts/compose-reup.sh - COMPOSE_PROJECT_NAME=osint-dashboard COMPOSE_PROFILES=ingest \ - scripts/compose-reup.sh + if [ "$PG" = "1" ]; then + FORCE_RECREATE_DB=1 COMPOSE_PROJECT_NAME=osint-dashboard COMPOSE_PROFILES=ingest \ + scripts/compose-reup.sh "${SVCS[@]}" db + elif [ "${#SVCS[@]}" -gt 0 ]; then + COMPOSE_PROJECT_NAME=osint-dashboard COMPOSE_PROFILES=ingest \ + scripts/compose-reup.sh "${SVCS[@]}" + else + echo "No image or compose changes — leave running containers alone" + docker compose --profile ingest ps + fi docker image prune -f - echo "osint-dashboard deployed; images also on ${PUB}/${OWN}/" + echo "osint-dashboard deploy done; db image left in place unless pg=1" - name: Summary if: always() run: | { - echo "## Forgejo registry images" - echo "Pushed via ${{ steps.img.outputs.reg }} (loopback). Pull publicly:" - echo "- \`${{ steps.img.outputs.pub }}/sirius/osint-dashboard:latest\`" - echo "- \`${{ steps.img.outputs.pub }}/sirius/osint-dashboard-pg:latest\`" - echo "- \`${{ steps.img.outputs.pub }}/sirius/osint-news-scraper:latest\`" - echo "- \`${{ steps.img.outputs.pub }}/sirius/osint-news-summarizer:latest\`" + echo "## Image plan" + echo "- app: \`${{ steps.plan.outputs.app }}\`" + echo "- news-scraper: \`${{ steps.plan.outputs.scraper }}\`" + echo "- news-summarizer: \`${{ steps.plan.outputs.summarizer }}\`" + echo "- pg (Timescale): \`${{ steps.plan.outputs.pg }}\`" + echo + echo "Postgres is rebuilt/pulled only when \`Dockerfile.pg\` changes (or workflow_dispatch rebuild_pg)." } >> "$GITHUB_STEP_SUMMARY" diff --git a/app/fire_sources.py b/app/fire_sources.py index c27b0f7..46f9fe9 100644 --- a/app/fire_sources.py +++ b/app/fire_sources.py @@ -22,6 +22,7 @@ UTC date (YYYY-MM-DD). from __future__ import annotations import csv +import hashlib import io import json import logging @@ -44,6 +45,11 @@ from upstream_cache import firms_cache logger = logging.getLogger("osint.firms") +# In-process poll state: skip byte-identical CSVs, persist only new hotspots. +# Survives the 15-minute loop; one full ON CONFLICT after process start. +_csv_digest: dict[tuple, bytes] = {} +_seen_ids: dict[tuple, set[int]] = {} + # ── FIRMS API ───────────────────────────────────────────────────────────── FIRMS_AREA_CSV = ( @@ -86,33 +92,34 @@ def normalize_acq_time(acq_date: object, acq_time: object) -> datetime | None: return None -def parse_firms_csv(text: str) -> list[dict]: - """Parse a FIRMS area CSV payload into normalized fire messages. +def _hotspot_id(lat: float, lon: float, acq_iso: str, satellite: str) -> int: + return hash((round(lat, 5), round(lon, 5), acq_iso, satellite)) - Returns one dict per hotspot with the fields stored in the ``fires`` table - (acq_time already combined into a UTC ISO timestamp). Rows that don't look - like valid VIIRS detections are skipped rather than failing the whole poll. + +def parse_firms_csv_delta( + text: str, skip_ids: set[int] | None = None, +) -> tuple[list[dict], set[int]]: + """Parse FIRMS CSV; optionally drop hotspots already seen this process. + + Returns (new_or_all_points, ids_for_every_valid_row). Streaming — does not + materialize the raw CSV as a list of lists. """ - rows = list(csv.reader(io.StringIO(text))) - if not rows: - return [] - - # Locate the real header row. FIRMS normally returns the CSV header first, - # but occasionally prepends a legend/info line, so scan until we see the - # canonical header. - header_idx = 0 - for i, row in enumerate(rows): + reader = csv.reader(io.StringIO(text)) + header = None + for row in reader: if row and row[0].strip().lower() == "latitude" and len(row) >= 4: - header_idx = i + header = [c.strip().lower() for c in row] break - header = [c.strip().lower() for c in rows[header_idx]] - # Guard against a header that isn't actually the FIRMS one. - if "latitude" not in header or "longitude" not in header: - logger.warning("FIRMS payload does not look like a hotspot CSV (first row: %r)", header[:6]) - return [] + if not header or "latitude" not in header or "longitude" not in header: + logger.warning( + "FIRMS payload does not look like a hotspot CSV (first row: %r)", + (header or [])[:6], + ) + return [], set() points: list[dict] = [] - for row in rows[header_idx + 1:]: + ids: set[int] = set() + for row in reader: if len(row) < len(header): continue rec = dict(zip(header, row)) @@ -123,13 +130,19 @@ def parse_firms_csv(text: str) -> list[dict]: acq_time = normalize_acq_time(rec.get("acq_date"), rec.get("acq_time")) if acq_time is None: continue + sat = str(rec.get("satellite") or "").strip() + acq_iso = acq_time.isoformat() + hid = _hotspot_id(lat, lon, acq_iso, sat) + ids.add(hid) + if skip_ids is not None and hid in skip_ids: + continue points.append({ "latitude": lat, "longitude": lon, "brightness": _to_float(rec.get("bright_ti4")), "confidence": str(rec.get("confidence") or "").strip(), - "acq_time": acq_time.isoformat(), - "satellite": str(rec.get("satellite") or "").strip(), + "acq_time": acq_iso, + "satellite": sat, "instrument": str(rec.get("instrument") or "").strip(), "bright_ti5": _to_float(rec.get("bright_ti5")), "frp": _to_float(rec.get("frp")), @@ -138,6 +151,17 @@ def parse_firms_csv(text: str) -> list[dict]: "track": _to_float(rec.get("track")), "version": str(rec.get("version") or "").strip(), }) + return points, ids + + +def parse_firms_csv(text: str) -> list[dict]: + """Parse a FIRMS area CSV payload into normalized fire messages. + + Returns one dict per hotspot with the fields stored in the ``fires`` table + (acq_time already combined into a UTC ISO timestamp). Rows that don't look + like valid VIIRS detections are skipped rather than failing the whole poll. + """ + points, _ids = parse_firms_csv_delta(text) return points @@ -215,11 +239,18 @@ async def ingest_fires(bbox: str | None = None) -> int: dataset, first_line, ) continue - points = parse_firms_csv(text) - published = await persist_hotspots(points) + poll_key = (dataset, area, FIRMS_DAYS) + digest = hashlib.sha256(text.encode("utf-8", "surrogatepass")).digest() + if _csv_digest.get(poll_key) == digest: + logger.info("FIRMS %s CSV unchanged, skip parse/insert", dataset) + continue + points, ids = parse_firms_csv_delta(text, skip_ids=_seen_ids.get(poll_key)) + published = await persist_hotspots(points) if points else 0 + _csv_digest[poll_key] = digest + _seen_ids[poll_key] = ids total_published += published logger.info( "FIRMS: fetched %d hotspot(s) for bbox=%s (%s), published %d", - len(points), area, dataset, published, + len(ids), area, dataset, published, ) return total_published diff --git a/app/ingestor.py b/app/ingestor.py index ac0bcbd..ccf1471 100644 --- a/app/ingestor.py +++ b/app/ingestor.py @@ -213,7 +213,7 @@ async def ingest_event(msg: dict): claimed = await session.execute(dedup) if not claimed.rowcount: await session.commit() - logger.info("skip duplicate event url=%s", key) + logger.debug("skip duplicate event url=%s", key) return None result = await session.execute(events_table.insert().values(**event_row)) await session.commit() diff --git a/app/sources.py b/app/sources.py index c12c303..7d587a5 100644 --- a/app/sources.py +++ b/app/sources.py @@ -55,6 +55,35 @@ def event_dedup_key(msg: dict) -> str | None: return url or None +async def existing_event_urls(urls: list[str]) -> set[str]: + """URLs already claimed in event_dedup. Empty input -> empty set.""" + if not urls: + return set() + from sqlalchemy import select + + from database import async_session + from models import event_dedup as event_dedup_table + + async with async_session() as session: + result = await session.execute( + select(event_dedup_table.c.url).where(event_dedup_table.c.url.in_(urls)) + ) + return {row[0] for row in result} + + +async def _publish_unknown(subject: str, events: list[dict]) -> int: + """Publish only events whose URL is not already in event_dedup.""" + keys = [event_dedup_key(e) for e in events] + known = await existing_event_urls([k for k in keys if k]) + published = 0 + for event, key in zip(events, keys): + if key and key in known: + continue + await publish_event(subject, event) + published += 1 + return published + + def _ua_headers() -> dict[str, str]: return {"User-Agent": OSINT_USER_AGENT} @@ -283,10 +312,9 @@ async def ingest_eonet(): resp.raise_for_status() data = resp.json() events = parse_eonet_events(data if isinstance(data, dict) else {}) - for event in events: - await publish_event("events.disaster", event) - logger.info("Ingested %d EONET events", len(events)) - return len(events) + published = await _publish_unknown("events.disaster", events) + logger.info("Ingested %d EONET events (%d already known)", published, len(events) - published) + return published # ─── CISA KEV ─────────────────────────────────────────────────────────── @@ -330,10 +358,9 @@ async def ingest_cisa_kev(): resp.raise_for_status() data = resp.json() events = parse_cisa_kev(data if isinstance(data, dict) else {}) - for event in events: - await publish_event("events.disaster", event) - logger.info("Ingested %d CISA KEV rows", len(events)) - return len(events) + published = await _publish_unknown("events.disaster", events) + logger.info("Ingested %d CISA KEV rows (%d already known)", published, len(events) - published) + return published # ─── Social Signals (Twitter/X-like placeholder) ──────────────────────── diff --git a/docker-compose.yml b/docker-compose.yml index 6e38729..76d0431 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -20,8 +20,10 @@ services: # networks (and ISP abuse-mitigation blackholes) block, so rebuilding it # on every CI deploy made the pipeline flaky. Rebuild manually when the # base image or extensions need bumping: - # docker compose build db && docker compose up -d db + # docker build -f Dockerfile.pg -t localhost/osint-dashboard-pg:latest . + # FORCE_RECREATE_DB=1 scripts/compose-reup.sh db image: localhost/osint-dashboard-pg:latest + pull_policy: never container_name: osint-db restart: unless-stopped environment: @@ -52,6 +54,7 @@ services: nats: image: nats:2.10 + pull_policy: missing platform: linux/arm64 container_name: osint-nats restart: unless-stopped @@ -67,6 +70,7 @@ services: dockerfile: Dockerfile platforms: ["linux/arm64"] image: localhost/osint-dashboard:latest + pull_policy: never container_name: osint-ingester restart: unless-stopped profiles: ["ingest"] @@ -111,6 +115,7 @@ services: dockerfile: Dockerfile platforms: ["linux/arm64"] image: localhost/osint-dashboard:latest + pull_policy: never container_name: osint-dashboard restart: unless-stopped depends_on: @@ -164,6 +169,7 @@ services: # published on host loopback 127.0.0.1:8001 only. titiler: image: ghcr.io/developmentseed/titiler:latest + pull_policy: missing container_name: osint-titiler platform: linux/arm64 restart: unless-stopped @@ -183,6 +189,7 @@ services: dockerfile: Dockerfile platforms: ["linux/arm64"] image: localhost/osint-dashboard:latest + pull_policy: never container_name: osint-camera-scraper restart: unless-stopped profiles: ["ingest"] @@ -221,6 +228,7 @@ services: dockerfile: Dockerfile platforms: ["linux/arm64"] image: localhost/osint-news-scraper:latest + pull_policy: never container_name: osint-news-scraper restart: unless-stopped profiles: ["ingest"] @@ -246,6 +254,7 @@ services: dockerfile: Dockerfile platforms: ["linux/arm64"] image: localhost/osint-news-summarizer:latest + pull_policy: never container_name: osint-news-summarizer restart: unless-stopped profiles: ["ingest"] diff --git a/scripts/compose-reup.sh b/scripts/compose-reup.sh index f279981..68023a2 100755 --- a/scripts/compose-reup.sh +++ b/scripts/compose-reup.sh @@ -1,11 +1,15 @@ #!/usr/bin/env bash -# Recreate the OSINT compose stack without container_name collisions. -# Named volumes (osint-dashboard_osint-pgdata, camera-snapshots) are kept — -# never pass -v to `compose down`. +# Recreate selected OSINT compose services WITHOUT bouncing Postgres. # -# Usage: scripts/compose-reup.sh +# The old path was `compose down` + up, which stopped osint-db on every merge +# even when Dockerfile.pg did not change. Name-pinned leftovers are still +# removed, but only for the services we are actually replacing. +# +# Usage: scripts/compose-reup.sh [compose-service ...] +# (default: app ingester camera-service news-scraper news-summarizer) # Env: COMPOSE_PROJECT_NAME (default osint-dashboard) -# COMPOSE_PROFILES (default ingest — nats/ingester/news/cameras) +# COMPOSE_PROFILES (default ingest) +# FORCE_RECREATE_DB=1 also recreate db set -euo pipefail ROOT="$(cd "$(dirname "$0")/.." && pwd)" @@ -14,29 +18,57 @@ cd "$ROOT" export COMPOSE_PROJECT_NAME="${COMPOSE_PROJECT_NAME:-osint-dashboard}" PROFILE="${COMPOSE_PROFILES:-ingest}" -NAMES=( - osint-dashboard - osint-db - osint-nats - osint-ingester - osint-camera-scraper - osint-news-scraper - osint-news-summarizer +DEFAULT_SVCS=(app ingester camera-service news-scraper news-summarizer) +if [ "$#" -gt 0 ]; then + SVCS=("$@") +else + SVCS=("${DEFAULT_SVCS[@]}") +fi + +if [ "${FORCE_RECREATE_DB:-0}" = "1" ]; then + SVCS+=(db) +fi + +# Never recreate db unless it was requested. +FILTERED=() +for svc in "${SVCS[@]}"; do + if [ "$svc" = "db" ] && [ "${FORCE_RECREATE_DB:-0}" != "1" ]; then + echo "compose-reup: skipping db (set FORCE_RECREATE_DB=1 to bounce Postgres)" + continue + fi + FILTERED+=("$svc") +done +SVCS=("${FILTERED[@]}") + +declare -A CONTAINER_NAME=( + [app]=osint-dashboard + [ingester]=osint-ingester + [camera-service]=osint-camera-scraper + [news-scraper]=osint-news-scraper + [news-summarizer]=osint-news-summarizer + [db]=osint-db + [nats]=osint-nats + [titiler]=osint-titiler ) echo "compose-reup: project=${COMPOSE_PROJECT_NAME} profile=${PROFILE} dir=${ROOT}" +echo "compose-reup: recreate=${SVCS[*]:-none}" -# Stop compose-owned containers first. Foreign/name-pinned leftovers survive this. -docker compose --profile "${PROFILE}" down --remove-orphans || true +# Keep data-plane containers running (db / nats / titiler). +docker compose --profile "${PROFILE}" up -d --no-build --no-recreate db nats titiler || true -# Drop any leftover name-pinned containers compose does not own (the -# "Conflict. The container name is already in use" failure mode). -for c in "${NAMES[@]}"; do - if docker inspect "$c" >/dev/null 2>&1; then - echo "compose-reup: removing leftover ${c}" +if [ "${#SVCS[@]}" -eq 0 ]; then + docker compose --profile "${PROFILE}" ps + exit 0 +fi + +for svc in "${SVCS[@]}"; do + c="${CONTAINER_NAME[$svc]:-}" + if [ -n "$c" ] && docker inspect "$c" >/dev/null 2>&1; then + echo "compose-reup: replacing ${c}" docker rm -f "$c" >/dev/null fi done -docker compose --profile "${PROFILE}" up -d --no-build "$@" +docker compose --profile "${PROFILE}" up -d --no-build --no-deps "${SVCS[@]}" docker compose --profile "${PROFILE}" ps diff --git a/tests/test_fire_sources.py b/tests/test_fire_sources.py index 24fcf94..dbff5fc 100644 --- a/tests/test_fire_sources.py +++ b/tests/test_fire_sources.py @@ -131,6 +131,100 @@ def test_ingest_fires_uses_keystore_key(monkeypatch): assert any("VIIRS_NOAA21_NRT" in u for u in captured["urls"]) +def _reset_firms_poll_state(): + from upstream_cache import firms_cache + import fire_sources + + firms_cache.clear() + if hasattr(fire_sources, "_csv_digest"): + fire_sources._csv_digest.clear() + if hasattr(fire_sources, "_seen_ids"): + fire_sources._seen_ids.clear() + + +def _fake_firms_http(monkeypatch, bodies_by_call: list[str] | None = None, body: str = SAMPLE_CSV): + hits = {"n": 0} + + class FakeResp: + def __init__(self, text): + self.text = text + + def raise_for_status(self): + pass + + class FakeClient: + def __init__(self, **kw): + pass + + async def __aenter__(self): + return self + + async def __aexit__(self, *exc): + return False + + async def get(self, url): + idx = hits["n"] + hits["n"] += 1 + if bodies_by_call is not None: + text = bodies_by_call[min(idx, len(bodies_by_call) - 1)] + else: + text = body + return FakeResp(text) + + monkeypatch.setenv("FIRMS_MAP_KEY", "k" * 32) + monkeypatch.setattr("fire_sources.FIRMS_DATASETS", ["VIIRS_NOAA20_NRT"]) + monkeypatch.setattr("fire_sources.httpx.AsyncClient", FakeClient) + return hits + + +def test_ingest_fires_skips_unchanged_csv(monkeypatch): + """Same FIRMS CSV must not be re-parsed into a 100k-row ON CONFLICT insert.""" + _reset_firms_poll_state() + hits = _fake_firms_http(monkeypatch) + persisted = [] + + async def fake_persist(points): + persisted.append(len(points)) + return len(points) + + monkeypatch.setattr("fire_sources.persist_hotspots", fake_persist) + + assert asyncio.run(ingest_fires()) == 5 + assert persisted == [5] + firms_cache_hits = hits["n"] + persisted.clear() + assert asyncio.run(ingest_fires()) == 0 + assert persisted == [] + # TTL cache may skip HTTP; either way we must not persist again. + assert hits["n"] >= firms_cache_hits + + +def test_ingest_fires_persists_only_new_hotspots(monkeypatch): + """When the CSV grows, persist the delta — not the whole 2-day dump.""" + _reset_firms_poll_state() + extra = ( + SAMPLE_CSV + + "16.00000,-12.00000,340.00,0.40,0.40,2025-06-06,1500,N20,VIIRS,h,2.0NRT,310.00,8.00,D\n" + ) + hits = _fake_firms_http(monkeypatch, bodies_by_call=[SAMPLE_CSV, extra]) + persisted = [] + + async def fake_persist(points): + persisted.append([p["latitude"] for p in points]) + return len(points) + + monkeypatch.setattr("fire_sources.persist_hotspots", fake_persist) + + from upstream_cache import firms_cache + + assert asyncio.run(ingest_fires()) == 5 + firms_cache.clear() # force the next poll to see the grown CSV + persisted.clear() + assert asyncio.run(ingest_fires()) == 1 + assert persisted == [[16.0]] + assert hits["n"] == 2 + + def _async_return(value): async def inner(): return value diff --git a/tests/test_new_sources.py b/tests/test_new_sources.py index 9cd0b85..fcad6ce 100644 --- a/tests/test_new_sources.py +++ b/tests/test_new_sources.py @@ -64,3 +64,65 @@ def test_parse_cisa_kev_emits_cve_url_no_coords(): assert "cisa-kev" in ev["tags"] assert "CVE-2024-1234" in ev["tags"] assert ev["raw"]["cveID"] == "CVE-2024-1234" + + +def test_ingest_cisa_kev_does_not_republish_known_nist_urls(monkeypatch): + """Producer must not push the whole KEV catalog to NATS every cycle.""" + import asyncio + + from sources import ingest_cisa_kev + + payload = { + "vulnerabilities": [ + { + "cveID": "CVE-2024-1111", + "vulnerabilityName": "old", + "dateAdded": "2024-01-01", + "shortDescription": "already in db", + }, + { + "cveID": "CVE-2024-2222", + "vulnerabilityName": "new", + "dateAdded": "2024-06-01", + "shortDescription": "not in db yet", + }, + ] + } + + class FakeResp: + def raise_for_status(self): + pass + + def json(self): + return payload + + class FakeClient: + def __init__(self, **kw): + pass + + async def __aenter__(self): + return self + + async def __aexit__(self, *exc): + return False + + async def get(self, url): + return FakeResp() + + published: list[str] = [] + + async def fake_publish(subject, event): + published.append(event["url"]) + + known = {"https://nvd.nist.gov/vuln/detail/CVE-2024-1111"} + + async def fake_existing(urls): + return {u for u in urls if u in known} + + monkeypatch.setattr("sources.httpx.AsyncClient", FakeClient) + monkeypatch.setattr("sources.publish_event", fake_publish) + monkeypatch.setattr("sources.existing_event_urls", fake_existing, raising=False) + + n = asyncio.run(ingest_cisa_kev()) + assert n == 1 + assert published == ["https://nvd.nist.gov/vuln/detail/CVE-2024-2222"] diff --git a/tests/test_upstream_cache.py b/tests/test_upstream_cache.py index 249d2f4..8ce8783 100644 --- a/tests/test_upstream_cache.py +++ b/tests/test_upstream_cache.py @@ -22,7 +22,11 @@ def test_firms_and_rss_caches_are_ttlcache(): def test_ingest_fires_hits_http_once_within_ttl(monkeypatch): + from fire_sources import _csv_digest, _seen_ids + firms_cache.clear() + _csv_digest.clear() + _seen_ids.clear() monkeypatch.setenv("FIRMS_MAP_KEY", "k" * 32) monkeypatch.setenv("FIRMS_DATASETS", "VIIRS_NOAA20_NRT") # fire_sources already imported FIRMS_DATASETS — patch the module attr @@ -58,7 +62,7 @@ def test_ingest_fires_hits_http_once_within_ttl(monkeypatch): monkeypatch.setattr("fire_sources.persist_hotspots", fake_publish) assert asyncio.run(ingest_fires()) == 5 - assert asyncio.run(ingest_fires()) == 5 + assert asyncio.run(ingest_fires()) == 0 assert hits["n"] == 1 From c48788d4b6140ed2479254305bf3ef8ccb012d94 Mon Sep 17 00:00:00 2001 From: Sirius DevOps Date: Sat, 29 Aug 2026 20:40:27 -0400 Subject: [PATCH 39/79] fix(map): geofence delete, vessel snapshots, sentinel cache, news briefs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Geofences could be drawn but not removed. VesselAPI Hormuz dots vanished on restart and DVR skipped between the 5 daily polls. Sentinel-1 re-hit STAC on every pan and often painted a neighbouring swath. Executive briefs truncated; ticker stayed empty unless something was critical. - Layer-panel list + polygon popup DELETE /api/geofences/{id} - Persist VesselAPI polls to vessels (UTC-day purge, DVR as-of, boot hydrate) - Cache Sentinel-1 by 2° cell; pick covering scene; clip Leaflet tiles - Retry truncated LLM JSON; ticker falls back to medium/low; 3-min HUD poll --- alembic/versions/009_vessels.py | 41 ++++ app/live_layers.py | 63 +++++- app/main.py | 33 +++- app/static/index.html | 82 +++++++- app/tracks.py | 17 +- app/vesselapi.py | 228 +++++++++++++++++++++- docs/news.md | 17 +- news/summerizer/intel.py | 21 +- news/summerizer/nous_client.py | 37 +++- news/summerizer/summarizer.py | 24 ++- news/summerizer/tests/test_intel.py | 10 + news/summerizer/tests/test_nous_client.py | 27 +++ news/summerizer/tests/test_prompts.py | 8 + tests/test_api_news.py | 15 ++ tests/test_frontend_reliability.py | 8 + tests/test_geofence_frontend.py | 26 +++ tests/test_live_layers.py | 23 ++- tests/test_sentinel1_frontend.py | 8 + tests/test_vesselapi.py | 2 + tests/test_vessels_snapshot.py | 36 ++++ 20 files changed, 669 insertions(+), 57 deletions(-) create mode 100644 alembic/versions/009_vessels.py create mode 100644 tests/test_geofence_frontend.py create mode 100644 tests/test_vessels_snapshot.py diff --git a/alembic/versions/009_vessels.py b/alembic/versions/009_vessels.py new file mode 100644 index 0000000..8f0dd01 --- /dev/null +++ b/alembic/versions/009_vessels.py @@ -0,0 +1,41 @@ +"""vessels — daily VesselAPI snapshots for DVR as-of + +Revision ID: 009_vessels +Revises: 008_summary_kind +Create Date: 2026-08-29 +""" + +from alembic import op + +revision = "009_vessels" +down_revision = "008_summary_kind" +branch_labels = None +depends_on = None + + +def upgrade() -> None: + op.execute( + """ + CREATE TABLE IF NOT EXISTS vessels ( + mmsi TEXT NOT NULL, + poll_at TIMESTAMPTZ NOT NULL, + lat DOUBLE PRECISION NOT NULL, + lon DOUBLE PRECISION NOT NULL, + heading DOUBLE PRECISION, + speed DOUBLE PRECISION, + label TEXT, + extra JSONB, + PRIMARY KEY (mmsi, poll_at) + ) + """ + ) + op.execute( + "CREATE INDEX IF NOT EXISTS ix_vessels_poll_at ON vessels (poll_at DESC)" + ) + op.execute( + "CREATE INDEX IF NOT EXISTS ix_vessels_bbox ON vessels (lon, lat)" + ) + + +def downgrade() -> None: + op.execute("DROP TABLE IF EXISTS vessels") diff --git a/app/live_layers.py b/app/live_layers.py index 2731047..fa632b1 100644 --- a/app/live_layers.py +++ b/app/live_layers.py @@ -51,7 +51,9 @@ PC_SAS_TOKEN = "https://planetarycomputer.microsoft.com/api/sas/v1/token/sentine # nginx vhost. Relative template — Leaflet resolves it against the page origin, # so the browser never touches a raw loopback port or titiler.xyz. TITILER_COG_TILES = f"{TITILER_PUBLIC_BASE}/cog/tiles/WebMercatorQuad/{{z}}/{{x}}/{{y}}" -SENTINEL1_TTL = 20 * 60 # 15–30 min quota-friendly window +SENTINEL1_TTL = 6 * 3600 # S-1 revisit is 6–12 days; cache the COG all afternoon +SENTINEL1_CELL = 2.0 # degrees — pan/zoom inside a cell reuses the same scene +SENTINEL1_STAC_LIMIT = 8 SENTINEL1_ATTRIBUTION = "Copernicus Sentinel-1 / Microsoft Planetary Computer" # GPSJAM (John Wiseman / ADS-B Exchange): daily H3 hexes of aircraft nav @@ -1244,25 +1246,71 @@ def sentinel1_tile_url(signed_cog: str) -> str: return f"{TITILER_COG_TILES}?{params}" +def feature_bbox(feat: dict) -> list[float] | None: + """STAC Feature bbox as [minlon, minlat, maxlon, maxlat], or None.""" + raw = feat.get("bbox") if isinstance(feat, dict) else None + if isinstance(raw, (list, tuple)) and len(raw) >= 4: + try: + return [float(raw[0]), float(raw[1]), float(raw[2]), float(raw[3])] + except (TypeError, ValueError): + pass + geom = (feat or {}).get("geometry") or {} + coords = geom.get("coordinates") if isinstance(geom, dict) else None + if not coords: + return None + lons: list[float] = [] + lats: list[float] = [] + + def _walk(node: Any) -> None: + if isinstance(node, (list, tuple)) and node and isinstance(node[0], (int, float)): + lons.append(float(node[0])) + lats.append(float(node[1])) + elif isinstance(node, (list, tuple)): + for child in node: + _walk(child) + + _walk(coords) + if not lons: + return None + return [min(lons), min(lats), max(lons), max(lats)] + + +def pick_sentinel_feature(features: list, lon: float, lat: float) -> dict | None: + """Prefer the scene whose bbox covers the viewport center; else first.""" + if not features: + return None + for feat in features: + bb = feature_bbox(feat) + if bb and bb[0] <= lon <= bb[2] and bb[1] <= lat <= bb[3]: + return feat + return features[0] + + async def fetch_sentinel1(bbox: str) -> dict | None: """Most recent Sentinel-1 GRD COG for a viewport, signed and TiTiler-ready. Returns the overlay tile-template dict, or ``None`` when no GRD imagery covers the bbox in the last 7 days (caller maps to 404). Queries Planetary - Computer only when called; cached per quantized bbox + UTC day. + Computer only when called; cached per 2° cell + UTC day so pan/zoom inside + the same region reuses the COG instead of picking a neighbouring swath. """ minlon, minlat, maxlon, maxlat = parse_bbox(bbox) + qminlon, qminlat, qmaxlon, qmaxlat = quantize_bbox( + minlon, minlat, maxlon, maxlat, step=SENTINEL1_CELL, + ) day = datetime.now(timezone.utc).date().isoformat() - key = f"sentinel1:{day}:{bbox_cell_key(bbox)}" + key = f"sentinel1:{day}:{qminlon:.4f},{qminlat:.4f},{qmaxlon:.4f},{qmaxlat:.4f}" + clon = (qminlon + qmaxlon) / 2.0 + clat = (qminlat + qmaxlat) / 2.0 async def _load() -> dict | None: now = datetime.now(timezone.utc) week_ago = now - timedelta(days=7) payload = { "collections": ["sentinel-1-grd"], - "bbox": [minlon, minlat, maxlon, maxlat], + "bbox": [qminlon, qminlat, qmaxlon, qmaxlat], "datetime": f"{week_ago.isoformat()}/{now.isoformat()}", - "limit": 1, + "limit": SENTINEL1_STAC_LIMIT, "sortby": [{"field": "datetime", "direction": "desc"}], } data = await _pc_call(_post_json(PC_STAC_SEARCH, json=payload)) @@ -1270,7 +1318,9 @@ async def fetch_sentinel1(bbox: str) -> dict | None: if not features: return None - feat = features[0] + feat = pick_sentinel_feature(features, clon, clat) + if not feat: + return None assets = feat.get("assets") or {} chosen_href: str | None = None polarization: str | None = None @@ -1299,6 +1349,7 @@ async def fetch_sentinel1(bbox: str) -> dict | None: "datetime": props.get("datetime") or feat.get("datetime"), "polarization": polarization, "attribution": SENTINEL1_ATTRIBUTION, + "bbox": feature_bbox(feat), } return await _ttl_get(key, float(SENTINEL1_TTL), _load) diff --git a/app/main.py b/app/main.py index dd799d7..2d12e25 100644 --- a/app/main.py +++ b/app/main.py @@ -74,6 +74,11 @@ async def _lifespan(app: FastAPI): await refresh_cache() except Exception: pass + try: + from vesselapi import hydrate_last_known + await hydrate_last_known() + except Exception: + pass from config import AISSTREAM_IN_APP, VESSELAPI_IN_APP ais_task = None vesselapi_task = None @@ -1263,6 +1268,7 @@ async def list_news_summaries( _FLAGGED = ("critical", "high") +_LESSER = ("medium", "low") @app.get("/api/news/ticker", response_model=list[NewsTickerItemOut]) @@ -1273,7 +1279,7 @@ async def list_news_ticker( ), limit: int = Query(20, ge=1, le=50), ): - """Flagged ticker rows (critical/high), newest first. No LLM required.""" + """Ticker rows: critical/high first; medium/low if nothing is flagged.""" async with async_session() as session: stmt = ( select(news_items) @@ -1287,6 +1293,19 @@ async def list_news_ticker( stmt = stmt.where(news_items.c.created_at >= since) stmt = stmt.limit(limit) rows = (await session.execute(stmt)).mappings().all() + if not rows: + stmt = ( + select(news_items) + .where( + news_items.c.kind == "ticker", + news_items.c.importance.in_(_LESSER), + ) + .order_by(news_items.c.created_at.desc()) + ) + if since: + stmt = stmt.where(news_items.c.created_at >= since) + stmt = stmt.limit(limit) + rows = (await session.execute(stmt)).mappings().all() return [ NewsTickerItemOut( id=r["id"], headline=r["headline"], importance=r["importance"], @@ -1530,7 +1549,17 @@ async def list_vessels( from tracks import fetch_positions_at, parse_timestamp ts = parse_timestamp(timestamp) if ts is not None: - return overlay_json(await fetch_positions_at("vessel", ts, bbox, limit), 5) + from vesselapi import fetch_vessels_as_of + if src == "vesselapi": + return overlay_json(await fetch_vessels_as_of(ts, bbox, limit), 5) + ais = await fetch_positions_at("vessel", ts, bbox, limit) + if src == "aisstream": + return overlay_json(ais, 5) + va = await fetch_vessels_as_of(ts, bbox, limit) + by_id = {m["id"]: m for m in ais} + for m in va: + by_id[m["id"]] = m + return overlay_json(list(by_id.values())[:limit], 5) return overlay_json(await fetch_vessels(bbox, limit, src=src), 5) except ValueError as exc: raise HTTPException(422, str(exc)) from exc diff --git a/app/static/index.html b/app/static/index.html index 4100be3..02122d1 100644 --- a/app/static/index.html +++ b/app/static/index.html @@ -358,6 +358,11 @@ .lp-future .lp-name { cursor: not-allowed; } .lp-error { color: var(--red); font-size: 0.66rem; } .lp-note { font-size: 0.6rem; color: var(--muted); opacity: 0.85; line-height: 1.35; } + .gf-list { display: flex; flex-direction: column; gap: 0.22rem; max-height: 8rem; overflow-y: auto; } + .gf-item { display: flex; justify-content: space-between; align-items: center; gap: 0.4rem; font-size: 0.64rem; } + .gf-item span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--text); } + .gf-del { background: transparent; border: 1px solid var(--magenta); color: var(--magenta); font-family: 'Share Tech Mono', monospace; font-size: 0.58rem; letter-spacing: 0.08em; text-transform: uppercase; padding: 0.12rem 0.35rem; border-radius: 3px; cursor: pointer; } + .gf-del:hover { background: rgba(255,46,151,0.16); } /* ── Camera / blip popup thumbnails ── */ .cam-pop { min-width: 210px; max-width: 260px; } @@ -583,6 +588,8 @@ .tick-item .b-tag { font-family: 'Share Tech Mono', monospace; font-size: 0.6rem; color: #1c0311; background: var(--magenta); border-radius: 2px; padding: 0.08rem 0.4rem; letter-spacing: 0.1em; } .tick-item .b-tag.critical { background: var(--red); } .tick-item .b-tag.high { background: var(--amber); } + .tick-item .b-tag.medium { background: var(--cyan); color: #041018; } + .tick-item .b-tag.low { background: var(--muted); color: #041018; } .tick-item.brief:hover { color: var(--magenta); } .tick-item.standby { color: var(--muted); opacity: 0.75; } .tick-item.standby .price { color: var(--muted); } @@ -906,7 +913,8 @@
-
No Leaflet.Draw — click vertices, double-click to close. Saved to POST /api/geofences.
+
+
Click vertices, double-click to close. Delete a saved fence from the list or its popup.
@@ -1420,7 +1428,7 @@ function initMarketTicker() { /* ═══════════════ NEWS FEED + TICKER ═══════════════ */ let newsInterval = null; -const NEWS_REFRESH_MS = 900000; // 15-min cycle +const NEWS_REFRESH_MS = 180000; // 3-min ticker/brief poll let newsTickerBuilt = false; function newsEsc(s) { @@ -1527,10 +1535,11 @@ function renderNewsTicker(articles, summaries, tickerItems) { if (ticks.length) { ticks.forEach(t => { const imp = String(t.importance || '').toLowerCase(); - const tag = imp === 'critical' ? 'CRITICAL' : 'HIGH'; + const tag = imp === 'critical' ? 'CRITICAL' : imp === 'high' ? 'HIGH' : imp === 'medium' ? 'MED' : 'LOW'; + const tagClass = (imp === 'critical' || imp === 'high' || imp === 'medium' || imp === 'low') ? imp : 'high'; const loc = (t.location_name || '').trim(); const inner = - `${tag}` + + `${tag}` + `${newsEsc((t.headline || '').trim())}` + (loc ? `${newsEsc(loc)}` : '') + `${newsTimeAgo(t.created_at)}▸`; @@ -1906,6 +1915,7 @@ let extraAttribs = new Set(); let radarLayer = null, radarOn = true, radarOpacity = 0.7, radarMeta = null, radarTimer = null; let thermalLayer = null, thermalOn = false; let sentinelLayer = null, sentinelOn = false, sentinelOpacity = 0.8; +let sentinelItemId = null, sentinelBounds = null; let wxAlertsGroup = null, wxAlertsOn = true; let perimGroup = null, perimOn = true; let incidentsGroup = null, incidentsOn = false; @@ -3071,6 +3081,8 @@ async function toggleSentinel1() { if (sentinelOn) await loadSentinel1(); else { sentinelLayer = dropLayer(sentinelLayer); + sentinelItemId = null; + sentinelBounds = null; const n = document.getElementById('lp-sentinel-count'); if (n) n.textContent = '7d'; } @@ -3080,8 +3092,15 @@ function setSentinelOpacity(v) { document.getElementById('lp-sentinel-val').textContent = `${Math.round(v)}%`; if (sentinelLayer) sentinelLayer.setOpacity(sentinelOpacity); } +function sentinelStillCovers() { + if (!map || !sentinelBounds || sentinelBounds.length < 4) return false; + const c = map.getCenter(); + return c.lng >= sentinelBounds[0] && c.lng <= sentinelBounds[2] + && c.lat >= sentinelBounds[1] && c.lat <= sentinelBounds[3]; +} async function loadSentinel1() { if (!map || !sentinelOn) return; + if (sentinelLayer && sentinelStillCovers()) return; const req = ++overlayReq.sar; const countEl = document.getElementById('lp-sentinel-count'); const hint = document.getElementById('map-hint'); @@ -3093,6 +3112,8 @@ async function loadSentinel1() { if (req !== overlayReq.sar) return; if (r.status === 404 && body && body.error === 'no_imagery') { sentinelLayer = dropLayer(sentinelLayer); + sentinelItemId = null; + sentinelBounds = null; if (hint) hint.textContent = 'No Sentinel-1 imagery for this view in the last 7 days.'; if (countEl) countEl.textContent = 'none'; return; @@ -3109,13 +3130,31 @@ async function loadSentinel1() { if (countEl) countEl.textContent = 'err'; return; } + if (body.itemId && body.itemId === sentinelItemId && sentinelLayer) { + if (Array.isArray(body.bbox) && body.bbox.length >= 4) sentinelBounds = body.bbox; + sentinelLayer.setOpacity(sentinelOpacity); + if (countEl) countEl.textContent = String(body.polarization || 'SAR').toUpperCase(); + return; + } const attrib = body.attribution || ''; - sentinelLayer = dropLayer(sentinelLayer); - sentinelLayer = L.tileLayer(body.tileUrl, { + const layerOpts = { opacity: sentinelOpacity, maxZoom: 18, attribution: attrib, - }).addTo(map); + noWrap: true, + }; + if (Array.isArray(body.bbox) && body.bbox.length >= 4) { + sentinelBounds = body.bbox; + layerOpts.bounds = L.latLngBounds( + [body.bbox[1], body.bbox[0]], + [body.bbox[3], body.bbox[2]], + ); + } else { + sentinelBounds = null; + } + sentinelLayer = dropLayer(sentinelLayer); + sentinelLayer = L.tileLayer(body.tileUrl, layerOpts).addTo(map); + sentinelItemId = body.itemId || null; if (countEl) countEl.textContent = String(body.polarization || 'SAR').toUpperCase(); if (hint) { const when = body.datetime ? ` · ${body.datetime}` : ''; @@ -3477,17 +3516,44 @@ async function onGfClose(e) { toggleGeofenceDraw(); loadGeofences(); } +async function deleteGeofence(id) { + if (!id) return; + try { + const r = await fetch(`${API}/api/geofences/${encodeURIComponent(id)}`, { method: 'DELETE' }); + if (!r.ok && r.status !== 204) throw new Error('delete failed'); + } catch (err) { console.error('geofence delete failed', err); } + loadGeofences(); +} async function loadGeofences() { if (!map) return; try { const r = await overlayFetch(`${API}/api/geofences`); const rows = await r.json(); + const list = Array.isArray(rows) ? rows : []; + const box = document.getElementById('gf-list'); + if (box) { + box.innerHTML = list.map(f => { + const id = newsEsc(f.id || ''); + const name = newsEsc(f.name || 'Fence'); + return `
${name}` + + `
`; + }).join(''); + } if (gfSaved && map.hasLayer(gfSaved)) map.removeLayer(gfSaved); - const feats = (Array.isArray(rows) ? rows : []).map(f => ({ + const feats = list.map(f => ({ type: 'Feature', properties: { name: f.name, id: f.id }, geometry: f.geojson, })); gfSaved = L.geoJSON({ type: 'FeatureCollection', features: feats }, { style: { color: '#ff2e97', weight: 2, fillOpacity: 0.08 }, + onEachFeature: (feat, layer) => { + const id = feat.properties && feat.properties.id; + const name = newsEsc((feat.properties && feat.properties.name) || 'Fence'); + if (!id) return; + layer.bindPopup( + `
${name}
` + + `
` + ); + }, }).addTo(map); } catch (e) { if (!isAbort(e)) console.error('geofences load failed', e); } } diff --git a/app/tracks.py b/app/tracks.py index b3a3d83..a31a7c5 100644 --- a/app/tracks.py +++ b/app/tracks.py @@ -186,15 +186,14 @@ async def track_range() -> dict: async with async_session() as session: row = (await session.execute(text( """ - SELECT - LEAST( - (SELECT min(bucket) FROM vessel_tracks_1min), - (SELECT min(bucket) FROM aircraft_tracks_1min) - ) AS tmin, - GREATEST( - (SELECT max(bucket) FROM vessel_tracks_1min), - (SELECT max(bucket) FROM aircraft_tracks_1min) - ) AS tmax + SELECT min(t) AS tmin, max(t) AS tmax FROM ( + SELECT min(bucket) AS t FROM vessel_tracks_1min + UNION ALL SELECT max(bucket) FROM vessel_tracks_1min + UNION ALL SELECT min(bucket) FROM aircraft_tracks_1min + UNION ALL SELECT max(bucket) FROM aircraft_tracks_1min + UNION ALL SELECT min(poll_at) FROM vessels + UNION ALL SELECT max(poll_at) FROM vessels + ) s """ ))).mappings().first() if not row or row["tmin"] is None: diff --git a/app/vesselapi.py b/app/vesselapi.py index 2c41612..0b2317b 100644 --- a/app/vesselapi.py +++ b/app/vesselapi.py @@ -17,6 +17,7 @@ from __future__ import annotations import asyncio import calendar +import json import logging import os from datetime import date, datetime, timezone @@ -32,7 +33,7 @@ from config import ( VESSELAPI_MAX_CALLS_PER_DAY, ) from database import async_session, engine, metadata -from live_layers import to_marker, upsert_vessel +from live_layers import parse_bbox, to_marker, upsert_vessel, vessel_last_known, vessel_lock logger = logging.getLogger("osint.vesselapi") @@ -176,6 +177,49 @@ def transform_vesselapi_payload(payload: dict | None) -> list[dict]: return out +def utc_day_start(now: datetime) -> datetime: + """Floor ``now`` to 00:00:00 UTC.""" + if now.tzinfo is None: + now = now.replace(tzinfo=timezone.utc) + now = now.astimezone(timezone.utc) + return now.replace(hour=0, minute=0, second=0, microsecond=0) + + +def pick_poll_at(poll_times: list[datetime], as_of: datetime) -> datetime | None: + """Latest poll timestamp at or before ``as_of`` (DVR as-of).""" + if as_of.tzinfo is None: + as_of = as_of.replace(tzinfo=timezone.utc) + else: + as_of = as_of.astimezone(timezone.utc) + eligible: list[datetime] = [] + for raw in poll_times: + ts = raw if raw.tzinfo else raw.replace(tzinfo=timezone.utc) + ts = ts.astimezone(timezone.utc) + if ts <= as_of: + eligible.append(ts) + return max(eligible) if eligible else None + + +def snapshot_as_of(rows: list[dict], as_of: datetime) -> list[dict]: + """Keep only rows from the latest poll_at ≤ ``as_of``.""" + chosen = pick_poll_at( + [r["poll_at"] for r in rows if r.get("poll_at") is not None], + as_of, + ) + if chosen is None: + return [] + out = [] + for row in rows: + ts = row.get("poll_at") + if ts is None: + continue + if ts.tzinfo is None: + ts = ts.replace(tzinfo=timezone.utc) + if ts.astimezone(timezone.utc) == chosen: + out.append(row) + return out + + # ── Durable daily quota (Postgres, survives restarts) ───────────────────── # Mirrors keystore.api_keys: lazy CREATE TABLE IF NOT EXISTS, no alembic fork. @@ -261,6 +305,183 @@ class PgQuotaStore: return (int(existing) if existing else 0) + 1 +# ── Daily VesselAPI snapshots (DVR as-of + survive restarts) ────────────── +# Cleared at the UTC day boundary so the table holds today's 5 polls only. + +_CREATE_VESSELS_SQL = text( + """ + CREATE TABLE IF NOT EXISTS vessels ( + mmsi TEXT NOT NULL, + poll_at TIMESTAMPTZ NOT NULL, + lat DOUBLE PRECISION NOT NULL, + lon DOUBLE PRECISION NOT NULL, + heading DOUBLE PRECISION, + speed DOUBLE PRECISION, + label TEXT, + extra JSONB, + PRIMARY KEY (mmsi, poll_at) + ) + """ +) +_CREATE_VESSELS_POLL_IDX = text( + "CREATE INDEX IF NOT EXISTS ix_vessels_poll_at ON vessels (poll_at DESC)" +) +_CREATE_VESSELS_BBOX_IDX = text( + "CREATE INDEX IF NOT EXISTS ix_vessels_bbox ON vessels (lon, lat)" +) + +_vessels_lock = asyncio.Lock() +_vessels_ensured = False + + +async def ensure_vessels_table() -> None: + global _vessels_ensured + if _vessels_ensured: + return + async with _vessels_lock: + if _vessels_ensured: + return + async with engine.begin() as conn: + await conn.execute(_CREATE_VESSELS_SQL) + await conn.execute(_CREATE_VESSELS_POLL_IDX) + await conn.execute(_CREATE_VESSELS_BBOX_IDX) + _vessels_ensured = True + + +def _marker_from_vessel_row(r) -> dict: + extra = r.get("extra") or {} + if isinstance(extra, str): + try: + extra = json.loads(extra) + except (TypeError, ValueError): + extra = {} + if not isinstance(extra, dict): + extra = {} + extra.setdefault("src", "vesselapi") + poll_at = r.get("poll_at") + if poll_at is not None and hasattr(poll_at, "isoformat"): + extra["poll_at"] = poll_at.isoformat() + marker = to_marker( + str(r["id"]), r["lat"], r["lon"], + heading=r.get("heading"), speed=r.get("speed"), + label=r.get("label") or str(r["id"]), + extra=extra, + ) + marker["seen_at"] = extra.get("poll_at") or datetime.now(timezone.utc).isoformat() + return marker + + +async def persist_vessel_snapshot(markers: list[dict], poll_at: datetime) -> None: + """Write one VesselAPI poll into ``vessels`` (today's snapshots).""" + await ensure_vessels_table() + if not markers: + return + async with async_session() as session: + for m in markers: + vid = str(m.get("id") or "") + lat, lon = m.get("lat"), m.get("lon") + if not vid or lat is None or lon is None: + continue + extra = dict(m.get("extra") or {}) + extra.setdefault("src", "vesselapi") + await session.execute( + text( + """ + INSERT INTO vessels + (mmsi, poll_at, lat, lon, heading, speed, label, extra) + VALUES + (:mmsi, :poll_at, :lat, :lon, :heading, :speed, :label, + CAST(:extra AS jsonb)) + ON CONFLICT (mmsi, poll_at) DO UPDATE SET + lat = EXCLUDED.lat, + lon = EXCLUDED.lon, + heading = EXCLUDED.heading, + speed = EXCLUDED.speed, + label = EXCLUDED.label, + extra = EXCLUDED.extra + """ + ), + { + "mmsi": vid, + "poll_at": poll_at, + "lat": float(lat), + "lon": float(lon), + "heading": m.get("heading"), + "speed": m.get("speed"), + "label": m.get("label") or vid, + "extra": json.dumps(extra), + }, + ) + await session.commit() + + +async def purge_old_vessels(before: datetime | None = None) -> None: + """Drop snapshots from before the current UTC day (or ``before``).""" + await ensure_vessels_table() + cutoff = before or utc_day_start(datetime.now(timezone.utc)) + async with async_session() as session: + await session.execute( + text("DELETE FROM vessels WHERE poll_at < :cutoff"), + {"cutoff": cutoff}, + ) + await session.commit() + + +async def fetch_vessels_as_of( + ts: datetime, + bbox: str | None = None, + limit: int = 2000, +) -> list[dict]: + """Latest VesselAPI poll at or before ``ts`` (DVR as-of, not exact minute).""" + try: + await ensure_vessels_table() + async with async_session() as session: + poll = (await session.execute( + text("SELECT max(poll_at) FROM vessels WHERE poll_at <= :ts"), + {"ts": ts}, + )).scalar() + if poll is None: + return [] + sql = """ + SELECT mmsi AS id, lat, lon, heading, speed, label, extra, poll_at + FROM vessels + WHERE poll_at = :poll + """ + params: dict = {"poll": poll, "limit": limit} + if bbox: + minlon, minlat, maxlon, maxlat = parse_bbox(bbox) + sql += ( + " AND lon BETWEEN :minlon AND :maxlon" + " AND lat BETWEEN :minlat AND :maxlat" + ) + params.update( + minlon=minlon, minlat=minlat, maxlon=maxlon, maxlat=maxlat, + ) + sql += " LIMIT :limit" + rows = (await session.execute(text(sql), params)).mappings().all() + return [_marker_from_vessel_row(r) for r in rows] + except Exception: + logger.exception("VesselAPI snapshot fetch failed") + return [] + + +async def hydrate_last_known() -> int: + """Seed in-memory last-known from today's latest poll (app boot).""" + try: + rows = await fetch_vessels_as_of(datetime.now(timezone.utc)) + except Exception: + logger.exception("VesselAPI hydrate failed") + return 0 + if not rows: + return 0 + async with vessel_lock: + for m in rows: + vid = str(m.get("id") or "") + if vid: + vessel_last_known[vid] = m + return len(rows) + + # ── Budget / scheduling (pure, unit-testable) ───────────────────────────── def days_left_in_month(now: datetime) -> int: @@ -406,6 +627,11 @@ async def poll_once(store, boxes: list[tuple[float, float, float, float]], key: markers = transform_vesselapi_payload(data) for m in markers: await upsert_vessel(m) + try: + await persist_vessel_snapshot(markers, now) + await purge_old_vessels(utc_day_start(now)) + except Exception: # noqa: BLE001 — live overlay must not die on persist + logger.exception("VesselAPI snapshot persist failed") logger.info( "VesselAPI poll OK: %d vessels (remaining=%s, calls_today=%d)", len(markers), remaining, calls, diff --git a/docs/news.md b/docs/news.md index d94d29f..d64b31d 100644 --- a/docs/news.md +++ b/docs/news.md @@ -128,11 +128,12 @@ Key set **unchanged** (no `lat`/`lon` on articles; geo lives on `/api/news/map`) `?kind=daily_recap` pins the nightly 24h recap. Empty DB → `[]` (no crash). Malformed `kind` → `422`. -### GET /api/news/ticker — flagged HUD headlines +### GET /api/news/ticker — HUD headlines -Critical/high `news_items` with `kind=ticker` only. Do **not** reuse -`GET /api/alerts`. Bottom HUD `#nt-track` scrolls these rows, not a dump of -the whole brief. +Critical/high `news_items` with `kind=ticker` first. If none are flagged, +medium/low ticker rows fill the tape so the dock is not blank. Do **not** +reuse `GET /api/alerts`. Bottom HUD `#nt-track` scrolls these rows, not a +dump of the whole brief. | Query param | Meaning | Default | |---|---|---| @@ -226,10 +227,10 @@ markdown json fences, then brace-slices: } ``` -Persist ticker/map only for `importance` in `critical`/`high`. Map rows also -need valid coords; Unknown / invented places are dropped. Caps: 12 ticker -(≤140 chars, no markdown), 20 map. Empty ticker is allowed. `summary_en` -lands in `article_summaries.summary_text`. +Persist ticker for critical/high first; if none, persist medium/low so the +tape is not empty. Map rows stay critical/high with valid coords; Unknown / +invented places are dropped. Caps: 12 ticker (≤140 chars, no markdown), 20 +map. `summary_en` lands in `article_summaries.summary_text`. ## Configuration (all via env / `.env`) diff --git a/news/summerizer/intel.py b/news/summerizer/intel.py index d404f44..1f9874c 100644 --- a/news/summerizer/intel.py +++ b/news/summerizer/intel.py @@ -7,6 +7,7 @@ import re _EMPTY = {"summary_en": "", "ticker": [], "map_items": []} _KEEP = frozenset({"critical", "high"}) +_RANK = {"critical": 0, "high": 1, "medium": 2, "low": 3} _THINK_RE = re.compile(r".*?", re.DOTALL) _FENCE_RE = re.compile(r"```(?:json)?", re.IGNORECASE) @@ -58,19 +59,29 @@ def _trimmed_headline(row: dict, limit: int) -> str: def select_ticker(rows: list) -> list: - out = [] + flagged = [] + medium = [] + low = [] for row in rows: - if row.get("importance") not in _KEEP: + imp = row.get("importance") + if imp not in _RANK: continue headline = _trimmed_headline(row, TICKER_HEADLINE_MAX) if not headline: continue item = dict(row) item["headline"] = headline - out.append(item) - if len(out) >= TICKER_CAP: + if imp in _KEEP: + flagged.append(item) + elif imp == "medium": + medium.append(item) + else: + low.append(item) + if len(flagged) >= TICKER_CAP: break - return out + if flagged: + return flagged[:TICKER_CAP] + return (medium + low)[:TICKER_CAP] def select_map(items: list) -> list: diff --git a/news/summerizer/nous_client.py b/news/summerizer/nous_client.py index da0b2c4..fc480f1 100644 --- a/news/summerizer/nous_client.py +++ b/news/summerizer/nous_client.py @@ -8,6 +8,10 @@ import httpx _DEFAULT_UA = "osint-dashboard-news-summarizer" _DEFAULT_BASE = "https://inference-api.nousresearch.com/v1" +_JSON_SYSTEM = ( + "You are an OSINT executive briefer. Reply with a single complete JSON object. " + "Never truncate mid-sentence. If you run out of room, drop the lowest-priority item." +) def chat(prompt, *, api_key, model, base_url, json_mode=False) -> str: @@ -17,20 +21,37 @@ def chat(prompt, *, api_key, model, base_url, json_mode=False) -> str: "Authorization": f"Bearer {api_key}", "User-Agent": os.environ.get("OSINT_USER_AGENT") or _DEFAULT_UA, } + max_tokens = 8192 if json_mode else 4096 + timeout = 120.0 if json_mode else 60.0 + messages = [{"role": "user", "content": prompt}] + if json_mode: + messages = [ + {"role": "system", "content": _JSON_SYSTEM}, + {"role": "user", "content": prompt}, + ] payload = { "model": model, - "messages": [{"role": "user", "content": prompt}], + "messages": messages, "temperature": 0.2, - "max_tokens": 4096, + "max_tokens": max_tokens, } if json_mode: payload["response_format"] = {"type": "json_object"} + last_content = "" try: - with httpx.Client(timeout=60.0) as client: - resp = client.post(url, headers=headers, json=payload) - if resp.status_code == 401 or resp.status_code >= 500: - return "" - data = resp.json() - return data["choices"][0]["message"]["content"] + for attempt in range(2): + with httpx.Client(timeout=timeout) as client: + resp = client.post(url, headers=headers, json=payload) + if resp.status_code == 401 or resp.status_code >= 500: + return "" + data = resp.json() + choice = (data.get("choices") or [{}])[0] + last_content = (choice.get("message") or {}).get("content") or "" + finish = choice.get("finish_reason") + if finish == "length" and attempt == 0: + payload["max_tokens"] = min(int(payload["max_tokens"]) * 2, 16384) + continue + return last_content + return last_content except Exception: return "" diff --git a/news/summerizer/summarizer.py b/news/summerizer/summarizer.py index 73f9cb6..acc1262 100644 --- a/news/summerizer/summarizer.py +++ b/news/summerizer/summarizer.py @@ -94,7 +94,7 @@ FUTURES_TICKERS = { MAP_PROMPT_DEFAULT = """\ You are a precise, factual OSINT news processor. Your ONLY source of information is the articles provided below. Do NOT add external knowledge, assumptions, training data, or invented facts. -Focus on breaking important news (geopolitical, military/conflict, security, disasters, major political developments). Ignore futures prices, commodity tape, ticker chatter, and routine market moves unless they themselves are the breaking event. +Focus on breaking important news (geopolitical, military/conflict, security, disasters, major political developments). Ignore futures prices, commodity tape, ticker chatter, and routine market moves unless they themselves are the breaking event. If the batch has no critical/high stories, still extract minor incidents and crime reports. Write every field in English. Translate if the article is not English. @@ -133,7 +133,11 @@ You are writing an English operator HUD brief from the article facts in DATA bel Always write a real summary_en that recaps the most important stories present in DATA. Rank geopolitics, military/conflict, security, disasters, and major political developments first. Ignore futures prices, commodity tape, ticker chatter, and routine market data — do not treat price ticks as news. -ticker and map_items may be empty if nothing is critical or high. Never replace summary_en with a canned empty-brief sentence when DATA contains article facts. +Lead with critical and high breaking events. If DATA has no critical/high stories, fill the brief with minor incidents and crime reports rather than writing an empty or unfinished brief. Never truncate mid-sentence; finish every sentence. If you run out of room, drop the lowest-priority item instead of cutting a line short. + +ticker: prefer critical and high. If nothing is critical or high, fill ticker with medium then low incidents and crime so the HUD is not blank. + +map_items may be empty if no located critical/high event is explicit in the data. Demand a single JSON object (no markdown fences) with this exact shape: @@ -143,9 +147,9 @@ Demand a single JSON object (no markdown fences) with this exact shape: "map_items": [{"headline": "", "importance": "critical", "location_name": "", "lat": 0, "lon": 0, "location_confidence": "city", "category": "military/conflict", "url": ""}] } -ticker: only critical and high, max 12, ≤140 chars, no markdown. -map_items: only critical and high where a real-world location is explicit in the data. Estimate lat/lon. If location is Unknown or not in the data, omit the item. Never invent a place. Max 20. -summary_en: English markdown brief of breaking important news for an operator HUD (bullets or short paragraphs). Cover the actual stories in DATA. +ticker: max 12, ≤140 chars, no markdown. Rank critical > high > medium > low. +map_items: only where a real-world location is explicit in the data. Estimate lat/lon. If location is Unknown or not in the data, omit the item. Never invent a place. Max 20. +summary_en: English markdown executive brief for an operator HUD (4–8 complete bullets or short paragraphs). Cover the actual stories in DATA. Complete — never an unfinished sentence. DATA: {final_input} @@ -156,7 +160,9 @@ You are writing a daily recap of the last 24 hours of news for an OSINT operator Always write a real summary_en daily recap of the most important stories in DATA. Rank geopolitics, military/conflict, security, disasters, and major political developments first. Ignore futures prices, commodity tape, ticker chatter, and routine market data — do not treat price ticks as news. -ticker and map_items may be empty if nothing is critical or high. Never replace summary_en with a canned empty-brief sentence when DATA contains article facts. +Lead with critical and high breaking events. If DATA has no critical/high stories, fill the recap with minor incidents and crime reports rather than writing an empty or unfinished recap. Never truncate mid-sentence; finish every sentence. + +ticker: prefer critical and high. If nothing is critical or high, fill ticker with medium then low incidents and crime so the HUD is not blank. Demand a single JSON object (no markdown fences) with this exact shape: @@ -166,9 +172,9 @@ Demand a single JSON object (no markdown fences) with this exact shape: "map_items": [{"headline": "", "importance": "critical", "location_name": "", "lat": 0, "lon": 0, "location_confidence": "city", "category": "military/conflict", "url": ""}] } -ticker: only critical and high, max 12, ≤140 chars, no markdown. -map_items: only critical and high where a real-world location is explicit in the data. Estimate lat/lon. If location is Unknown or not in the data, omit the item. Never invent a place. Max 20. -summary_en: English markdown daily recap of the last 24 hours of breaking important news. Cover the actual stories in DATA. +ticker: max 12, ≤140 chars, no markdown. Rank critical > high > medium > low. +map_items: only where a real-world location is explicit in the data. Estimate lat/lon. If location is Unknown or not in the data, omit the item. Never invent a place. Max 20. +summary_en: English markdown daily recap of the last 24 hours. Complete sentences. Cover the actual stories in DATA. DATA: {final_input} diff --git a/news/summerizer/tests/test_intel.py b/news/summerizer/tests/test_intel.py index dde2b5c..02446ea 100644 --- a/news/summerizer/tests/test_intel.py +++ b/news/summerizer/tests/test_intel.py @@ -32,6 +32,16 @@ def test_select_ticker_keeps_critical_high_caps_12(): assert len(out) == 12 assert all(r["importance"] in ("critical", "high") for r in out) + +def test_select_ticker_falls_back_to_medium_low_when_nothing_flagged(): + rows = [ + {"headline": "shop theft", "importance": "low"}, + {"headline": "highway crash", "importance": "medium"}, + {"headline": "none", "importance": "none"}, + ] + out = select_ticker(rows) + assert [r["headline"] for r in out] == ["highway crash", "shop theft"] + def test_select_map_requires_valid_coords_and_flag(): items = [ {"headline": "A", "importance": "critical", "lat": 50.45, "lon": 30.52, "location_name": "Kyiv"}, diff --git a/news/summerizer/tests/test_nous_client.py b/news/summerizer/tests/test_nous_client.py index 002faa4..848db14 100644 --- a/news/summerizer/tests/test_nous_client.py +++ b/news/summerizer/tests/test_nous_client.py @@ -67,6 +67,33 @@ def test_json_mode_sets_response_format(monkeypatch): captured = _install_fake(monkeypatch, lambda *a: _ok_response("{}")) chat("p", api_key="k", model="m", base_url=BASE, json_mode=True) assert captured["json"]["response_format"] == {"type": "json_object"} + assert captured["json"]["max_tokens"] >= 8192 + roles = [m["role"] for m in captured["json"]["messages"]] + assert "system" in roles + assert "user" in roles + + +def test_retries_once_when_finish_reason_is_length(monkeypatch): + calls = {"n": 0} + + def post_impl(*a): + calls["n"] += 1 + if calls["n"] == 1: + resp = MagicMock() + resp.status_code = 200 + resp.json.return_value = { + "choices": [{ + "message": {"content": "{\"summary_en\": \"cut off"}, + "finish_reason": "length", + }] + } + return resp + return _ok_response('{"summary_en": "complete brief."}') + + _install_fake(monkeypatch, post_impl) + out = chat("p", api_key="k", model="m", base_url=BASE, json_mode=True) + assert calls["n"] == 2 + assert "complete brief" in out def test_401_returns_empty_string(monkeypatch): diff --git a/news/summerizer/tests/test_prompts.py b/news/summerizer/tests/test_prompts.py index e5d4374..954e5b3 100644 --- a/news/summerizer/tests/test_prompts.py +++ b/news/summerizer/tests/test_prompts.py @@ -22,6 +22,14 @@ def test_summary_prompt_focuses_on_breaking_news_not_futures(): assert "commodity" in p or "market" in p +def test_summary_prompt_covers_critical_then_incidents(): + p = SUMMARY_PROMPT_DEFAULT.lower() + assert "critical" in p + assert "crime" in p + assert "incident" in p + assert "complete" in p or "truncat" in p or "unfinished" in p or "mid-sentence" in p + + def test_summary_prompt_does_not_bail_out_with_canned_empty_brief(): p = SUMMARY_PROMPT_DEFAULT assert "AND STOP" not in p diff --git a/tests/test_api_news.py b/tests/test_api_news.py index 0ba569d..e94b0e3 100644 --- a/tests/test_api_news.py +++ b/tests/test_api_news.py @@ -230,6 +230,21 @@ def test_api_news_ticker_returns_only_flagged(clean_news): assert item["url"] == "https://example.com/ticker" +@requires_db +def test_api_news_ticker_falls_back_to_lesser_when_nothing_flagged(clean_news): + sid = _seed_summary("quiet brief", "2026-08-27T18:05:00+00:00", "Hermes-4.3-36B") + _seed_news_item( + sid, "ticker", "Shop theft downtown", "low", + location_name="Raleigh", url="https://example.com/theft", + ) + resp = _get("/api/news/ticker") + assert resp.status_code == 200 + body = resp.json() + assert len(body) == 1 + assert body[0]["headline"] == "Shop theft downtown" + assert body[0]["importance"] == "low" + + @requires_db def test_api_news_map_returns_only_flagged_with_coords(clean_news): _seed_flagged_items() diff --git a/tests/test_frontend_reliability.py b/tests/test_frontend_reliability.py index d734f49..2f6dbde 100644 --- a/tests/test_frontend_reliability.py +++ b/tests/test_frontend_reliability.py @@ -72,6 +72,14 @@ def test_chokepoint_skips_aisstream_subscribe_outside_conus(): assert "minlat,minlon,maxlat,maxlon" in HTML.split("function chokepointLeafletBounds")[1][:400] +def test_news_ticker_polls_more_often_than_summarizer_cycle(): + assert "NEWS_REFRESH_MS" in HTML + # Summarizer is 15 min; ticker should refresh on a shorter cadence so + # lesser-news fills show up without waiting for the next brief. + line = [ln for ln in HTML.splitlines() if "NEWS_REFRESH_MS" in ln][0] + assert "900000" not in line + + def test_phone_chokepoints_use_select_not_buttons(): mobile = HTML.split("@media (max-width: 820px)")[1].split("@media (prefers-reduced-motion")[0] assert "#chokepoint-select { display: block; }" in mobile diff --git a/tests/test_geofence_frontend.py b/tests/test_geofence_frontend.py new file mode 100644 index 0000000..50ee03e --- /dev/null +++ b/tests/test_geofence_frontend.py @@ -0,0 +1,26 @@ +"""Geofence layer panel: draw + delete (DELETE /api/geofences/{id}).""" + +from __future__ import annotations + +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +HTML = (ROOT / "app/static/index.html").read_text() + + +def test_geofence_panel_has_list_and_delete_hook(): + assert 'id="gf-draw"' in HTML + assert 'id="gf-list"' in HTML + assert "function deleteGeofence" in HTML + assert "method: 'DELETE'" in HTML or 'method: "DELETE"' in HTML + assert "/api/geofences/" in HTML + + +def test_load_geofences_renders_delete_controls(): + js = HTML.split("async function loadGeofences", 1)[1].split( + "async function loadFireAircraftHits", 1 + )[0] + assert "gf-list" in js + assert "deleteGeofence" in js + assert "onEachFeature" in js + assert "bindPopup" in js diff --git a/tests/test_live_layers.py b/tests/test_live_layers.py index 69f8164..ae0f68e 100644 --- a/tests/test_live_layers.py +++ b/tests/test_live_layers.py @@ -7,6 +7,7 @@ from live_layers import ( filter_points_bbox, parse_bbox, quantize_bbox, + pick_sentinel_feature, rainviewer_tile_url, sign_cog_url, sentinel1_tile_url, @@ -734,8 +735,9 @@ def test_fetch_sentinel1_vv_signed_tile_url(monkeypatch): post_url, post_json = calls[0][1], calls[0][2] assert post_url.endswith("/api/stac/v1/search") assert post_json["collections"] == ["sentinel-1-grd"] - assert post_json["limit"] == 1 + assert post_json["limit"] >= 1 assert post_json["sortby"][0]["direction"] == "desc" + assert "bbox" in out def test_fetch_sentinel1_uses_hh_when_vv_missing(monkeypatch): @@ -783,3 +785,22 @@ def test_fetch_sentinel1_none_when_no_vv_or_hh(monkeypatch): _cache.clear() assert asyncio.run(fetch_sentinel1("-80,35,-79,36")) is None + + +def test_pick_sentinel_feature_prefers_scene_covering_center(): + features = [ + {"id": "far", "bbox": [10.0, 10.0, 12.0, 12.0]}, + {"id": "cover", "bbox": [-80.5, 34.5, -78.5, 36.5]}, + {"id": "also-far", "bbox": [-10.0, 0.0, -8.0, 2.0]}, + ] + picked = pick_sentinel_feature(features, -79.5, 35.5) + assert picked["id"] == "cover" + + +def test_pick_sentinel_feature_falls_back_to_first_when_none_cover(): + features = [ + {"id": "a", "bbox": [10.0, 10.0, 12.0, 12.0]}, + {"id": "b", "bbox": [20.0, 20.0, 22.0, 22.0]}, + ] + assert pick_sentinel_feature(features, -79.5, 35.5)["id"] == "a" + assert pick_sentinel_feature([], -79.5, 35.5) is None diff --git a/tests/test_sentinel1_frontend.py b/tests/test_sentinel1_frontend.py index 94a30a8..fdc1d6b 100644 --- a/tests/test_sentinel1_frontend.py +++ b/tests/test_sentinel1_frontend.py @@ -39,3 +39,11 @@ def test_sentinel1_not_fetched_on_init_unless_on(): assert "loadSentinel1()" not in init refresh = HTML.split("function refreshLiveOverlays", 1)[1].split("function addExtraAttrib", 1)[0] assert "if (sentinelOn) loadSentinel1();" in refresh + + +def test_sentinel1_reuses_covering_scene_and_clips_tiles(): + js = HTML.split("async function loadSentinel1", 1)[1].split("function loadThermal", 1)[0] + assert "sentinelStillCovers" in HTML + assert "itemId" in js + assert "L.latLngBounds" in js + assert "sentinelBounds" in HTML diff --git a/tests/test_vesselapi.py b/tests/test_vesselapi.py index f7ec9c1..de5b574 100644 --- a/tests/test_vesselapi.py +++ b/tests/test_vesselapi.py @@ -234,6 +234,8 @@ def _patch_side_effects(monkeypatch): monkeypatch.setattr("tracks.record_position", _noop) monkeypatch.setattr("geofence.record_and_notify", _noop) + monkeypatch.setattr(vesselapi, "persist_vessel_snapshot", _noop) + monkeypatch.setattr(vesselapi, "purge_old_vessels", _noop) def test_poll_once_lands_markers_in_vessel_last_known(monkeypatch): diff --git a/tests/test_vessels_snapshot.py b/tests/test_vessels_snapshot.py new file mode 100644 index 0000000..a9ea4ea --- /dev/null +++ b/tests/test_vessels_snapshot.py @@ -0,0 +1,36 @@ +"""VesselAPI daily snapshot store — as-of DVR + UTC-day purge (no DB).""" + +from __future__ import annotations + +from datetime import datetime, timezone + +from vesselapi import pick_poll_at, snapshot_as_of, utc_day_start + + +def test_utc_day_start_floors_to_midnight_utc(): + now = datetime(2026, 8, 29, 15, 30, 12, tzinfo=timezone.utc) + assert utc_day_start(now) == datetime(2026, 8, 29, 0, 0, tzinfo=timezone.utc) + + +def test_pick_poll_at_returns_latest_snapshot_at_or_before_as_of(): + t1 = datetime(2026, 8, 29, 0, 0, tzinfo=timezone.utc) + t2 = datetime(2026, 8, 29, 4, 48, tzinfo=timezone.utc) + t3 = datetime(2026, 8, 29, 9, 36, tzinfo=timezone.utc) + as_of = datetime(2026, 8, 29, 6, 0, tzinfo=timezone.utc) + assert pick_poll_at([t1, t2, t3], as_of) == t2 + assert pick_poll_at([t1, t2, t3], t1) == t1 + assert pick_poll_at([t1, t2, t3], datetime(2026, 8, 28, 23, tzinfo=timezone.utc)) is None + + +def test_snapshot_as_of_returns_the_matching_poll_only(): + t1 = datetime(2026, 8, 29, 0, 0, tzinfo=timezone.utc) + t2 = datetime(2026, 8, 29, 4, 48, tzinfo=timezone.utc) + rows = [ + {"id": "1", "poll_at": t1, "lat": 26.5, "lon": 56.0}, + {"id": "2", "poll_at": t1, "lat": 26.6, "lon": 56.1}, + {"id": "1", "poll_at": t2, "lat": 26.7, "lon": 56.2}, + ] + out = snapshot_as_of(rows, datetime(2026, 8, 29, 6, 0, tzinfo=timezone.utc)) + assert {r["id"] for r in out} == {"1"} + assert out[0]["lat"] == 26.7 + assert all(r["poll_at"] == t2 for r in out) From a82b62a011763214f8e8784d2c23d82fc11d5787 Mon Sep 17 00:00:00 2001 From: Sirius DevOps Date: Mon, 31 Aug 2026 21:30:23 -0400 Subject: [PATCH 40/79] feat(conflicts): GET /api/conflicts catalog + news/GDELT event counts Curated static catalogue of 13 conflict theatres (Ukraine, Gaza, Sudan, Myanmar, DRC, Yemen, Syria, Lebanon, Sahel, Somalia, Red Sea, Taiwan Strait, Korean DMZ) with war|high|elevated severity and short factual descriptions. GET /api/conflicts returns { zones: [{id,label,severity, lat,lon,description,eventCount,lastUpdated}], timestamp } where eventCount rolls up pre-existing geocoded news/GDELT//api/news/map rows inside each zone bbox (0 when the tables are empty). Adds the conflicts entry to overlay_catalog(). No upstream scraping, no jittered coords. --- app/conflicts.py | 168 ++++++++++++++++++++++++++++++++++++++++ app/live_layers.py | 6 ++ app/main.py | 53 +++++++++++++ app/schemas.py | 23 +++++- tests/test_conflicts.py | 132 +++++++++++++++++++++++++++++++ 5 files changed, 381 insertions(+), 1 deletion(-) create mode 100644 app/conflicts.py create mode 100644 tests/test_conflicts.py diff --git a/app/conflicts.py b/app/conflicts.py new file mode 100644 index 0000000..bfc48cd --- /dev/null +++ b/app/conflicts.py @@ -0,0 +1,168 @@ +"""Curated OSINT conflict-zone catalog + point-in-bbox event counting. + +A static, human-curated list of active conflict theatres (war / high / +elevated). Purely descriptive — this is a catalog, not a live feed and not a +scrape of LiveUAMap or any other source. Severity and descriptions are +editorial judgement kept short and factual. + +Each zone carries an internal ``bbox`` (``min_lat, min_lon, max_lat, max_lon``) +used only to count pre-existing geocoded news/GDELT/``/api/news/map`` rows that +fall inside it. The bbox is not part of the API response; callers get the +``eventCount`` roll-up instead. + +Never call an upstream API from here — event counts come from rows already in +the local database (``events`` with geocoords + ``news_items`` map pins). +""" + +from __future__ import annotations + +from datetime import datetime + +# id → zone. ``lat``/``lon`` is the fly-to anchor; ``bbox`` is the internal +# count window in ``min_lat, min_lon, max_lat, max_lon`` order. +_ZONES: tuple[dict, ...] = ( + { + "id": "ukraine", + "label": "Ukraine", + "severity": "war", + "lat": 48.5, + "lon": 31.0, + "description": "Full-scale Russian invasion since 2022; active front lines in the east and south.", + "bbox": (44.3, 22.1, 52.4, 40.2), + }, + { + "id": "gaza", + "label": "Gaza", + "severity": "war", + "lat": 31.4, + "lon": 34.4, + "description": "Israel–Hamas war; sustained fighting and a severe humanitarian crisis in the Gaza Strip.", + "bbox": (31.0, 34.1, 31.8, 34.7), + }, + { + "id": "sudan", + "label": "Sudan", + "severity": "war", + "lat": 15.5, + "lon": 30.0, + "description": "Civil war between the SAF and RSF since 2023, with mass displacement across the country.", + "bbox": (8.7, 21.8, 22.0, 38.6), + }, + { + "id": "myanmar", + "label": "Myanmar", + "severity": "war", + "lat": 21.5, + "lon": 96.0, + "description": "Post-2021 coup conflict pitting the junta against resistance and ethnic armed groups.", + "bbox": (9.5, 92.2, 28.5, 101.2), + }, + { + "id": "drc", + "label": "DR Congo", + "severity": "war", + "lat": -1.5, + "lon": 28.0, + "description": "Eastern DRC conflict involving M23 and other armed groups; heavy displacement around Goma.", + "bbox": (-5.0, 26.0, 3.0, 31.0), + }, + { + "id": "yemen", + "label": "Yemen", + "severity": "war", + "lat": 15.5, + "lon": 47.5, + "description": "Protracted Houthi–government/coalition war with one of the world's worst humanitarian emergencies.", + "bbox": (12.6, 42.5, 19.0, 54.0), + }, + { + "id": "syria", + "label": "Syria", + "severity": "war", + "lat": 34.5, + "lon": 38.5, + "description": "Multi-sided civil war; government, opposition, and external actors continue to engage.", + "bbox": (32.3, 35.7, 37.3, 42.4), + }, + { + "id": "lebanon", + "label": "Lebanon", + "severity": "high", + "lat": 33.9, + "lon": 35.9, + "description": "Israel–Hezbollah hostilities with periodic escalation along the southern border.", + "bbox": (33.0, 35.0, 34.7, 36.6), + }, + { + "id": "sahel", + "label": "Sahel", + "severity": "high", + "lat": 14.5, + "lon": 0.0, + "description": "Jihadist insurgencies across Mali, Burkina Faso, and Niger destabilising the central Sahel.", + "bbox": (10.0, -10.0, 20.0, 12.0), + }, + { + "id": "somalia", + "label": "Somalia", + "severity": "high", + "lat": 6.0, + "lon": 45.0, + "description": "Al-Shabaab insurgency against the federal government and security forces.", + "bbox": (-2.0, 41.0, 12.0, 51.5), + }, + { + "id": "red_sea", + "label": "Red Sea", + "severity": "high", + "lat": 18.0, + "lon": 40.0, + "description": "Houthi attacks on commercial shipping transiting the Red Sea corridor.", + "bbox": (12.0, 34.0, 22.0, 44.0), + }, + { + "id": "taiwan_strait", + "label": "Taiwan Strait", + "severity": "elevated", + "lat": 24.5, + "lon": 119.5, + "description": "Heightened military standoff between China and Taiwan, including deterrence patrols.", + "bbox": (21.9, 117.0, 26.5, 122.0), + }, + { + "id": "korean_dmz", + "label": "Korean DMZ", + "severity": "elevated", + "lat": 38.3, + "lon": 127.0, + "description": "Heavily fortified inter-Korean border with periodic tensions and military drills.", + "bbox": (37.5, 126.0, 39.0, 128.5), + }, +) + +SEVERITIES: frozenset[str] = frozenset({"war", "high", "elevated"}) + + +def conflict_zones() -> list[dict]: + """Return a fresh shallow copy of the catalog (callers must not mutate).""" + return [dict(z) for z in _ZONES] + + +def zone_event_stats( + points: list[tuple[float, float, datetime | None]], + bbox: tuple[float, float, float, float], +) -> tuple[int, datetime | None]: + """Count points inside ``bbox`` and return (count, latest timestamp). + + ``points`` is an iterable of ``(lat, lon, ts)``; ``ts`` may be ``None``. + ``bbox`` is ``(min_lat, min_lon, max_lat, max_lon)``. + """ + min_lat, min_lon, max_lat, max_lon = bbox + count = 0 + latest: datetime | None = None + for lat, lon, ts in points: + if min_lat <= lat <= max_lat and min_lon <= lon <= max_lon: + count += 1 + if ts is not None and (latest is None or ts > latest): + latest = ts + return count, latest diff --git a/app/live_layers.py b/app/live_layers.py index fa632b1..1d8a0f1 100644 --- a/app/live_layers.py +++ b/app/live_layers.py @@ -150,6 +150,12 @@ def overlay_catalog() -> dict: "endpoint": "/api/map/gpsjam", "attribution": "GPSJAM / John Wiseman / ADS-B Exchange", }, + "conflicts": { + "id": "conflicts", + "kind": "points", + "endpoint": "/api/conflicts", + "attribution": "Curated OSINT conflict catalog", + }, } diff --git a/app/main.py b/app/main.py index 2d12e25..f659811 100644 --- a/app/main.py +++ b/app/main.py @@ -38,6 +38,7 @@ from models import ( ) from schemas import ( AlertCreate, AlertOut, AlertSeverity, AlertType, AlertUpdate, + ConflictZoneOut, ConflictsOut, DashboardSummary, EntityCreate, EntityKind, EntityOut, EventCreate, EventOut, FireOut, NewsArticleOut, NewsMapItemOut, NewsSummaryOut, NewsTickerItemOut, @@ -1432,6 +1433,58 @@ async def map_chokepoints(): return {"chokepoints": chokepoints()} +async def _fetch_geocoded_points() -> list[tuple[float, float, datetime | None]]: + """Collect geocoded ``(lat, lon, ts)`` rows from the local DB. + + Sources are the flagged map pins (``news_items`` kind=map) and geocoded + news/GDELT events (``events`` with ``location_lat/lon``). This is the + pre-existing geocoded corpus the conflict-zone counters roll up — no + upstream scraping and no generated/jittered coordinates. + """ + async with async_session() as session: + map_rows = ( + await session.execute( + select(news_items.c.lat, news_items.c.lon, news_items.c.created_at) + .where( + news_items.c.kind == "map", + news_items.c.lat.isnot(None), + news_items.c.lon.isnot(None), + ) + ) + ).all() + event_rows = ( + await session.execute( + select(events.c.location_lat, events.c.location_lon, events.c.source_timestamp) + .where( + events.c.source_type.in_(["rss", "gdel-t2"]), + events.c.location_lat.isnot(None), + events.c.location_lon.isnot(None), + ) + ) + ).all() + return [tuple(r) for r in map_rows] + [tuple(r) for r in event_rows] + + +@app.get("/api/conflicts", response_model=ConflictsOut) +async def list_conflicts(): + """Curated conflict-zone catalog with per-zone event counts. + + Static catalogue (severity + short factual description) merged with a live + ``eventCount`` roll-up of pre-existing geocoded news/GDELT//api/news/map + rows inside each zone bbox. Empty DB → ``eventCount=0`` (never 502). + """ + from conflicts import conflict_zones, zone_event_stats + + points = await _fetch_geocoded_points() + timestamp = datetime.now(timezone.utc) + zones = [] + for z in conflict_zones(): + bbox = z.pop("bbox") + count, latest = zone_event_stats(points, bbox) + zones.append({**z, "eventCount": count, "lastUpdated": latest}) + return {"zones": zones, "timestamp": timestamp} + + def _upstream_or_502(exc: Exception, name: str) -> NoReturn: logger.warning("live_layer_upstream_failed", layer=name, error=str(exc)) raise HTTPException(502, f"{name} upstream unavailable: {exc}") from exc diff --git a/app/schemas.py b/app/schemas.py index 799aeb3..64b86c5 100644 --- a/app/schemas.py +++ b/app/schemas.py @@ -4,7 +4,7 @@ from __future__ import annotations from datetime import datetime from enum import Enum -from typing import Optional +from typing import Literal, Optional from uuid import UUID from pydantic import BaseModel, Field, field_validator @@ -386,3 +386,24 @@ class GeofenceUpdate(BaseModel): geojson: Optional[dict] = None active: Optional[bool] = None + +class ConflictZoneOut(BaseModel): + """One curated conflict theatre as exposed by GET /api/conflicts.""" + + id: str + label: str + severity: Literal["war", "high", "elevated"] + lat: float + lon: float + description: str + eventCount: int + lastUpdated: Optional[datetime] = None + + +class ConflictsOut(BaseModel): + """Response envelope for GET /api/conflicts.""" + + zones: list[ConflictZoneOut] + timestamp: datetime + + diff --git a/tests/test_conflicts.py b/tests/test_conflicts.py new file mode 100644 index 0000000..eb60d68 --- /dev/null +++ b/tests/test_conflicts.py @@ -0,0 +1,132 @@ +"""GET /api/conflicts — curated conflict-zone catalog + event-count roll-up. + +No outbound HTTP: event counts come from geocoded rows already (or not) in the +DB, and the API tests monkeypatch ``main._fetch_geocoded_points`` so no database +is required for the contract checks. +""" + +from datetime import datetime, timezone + +import httpx + +from conflicts import SEVERITIES, conflict_zones, zone_event_stats +from live_layers import overlay_catalog +from main import app + +BASE = "http://test" + + +def _get(path: str, monkeypatch=None, points=None) -> httpx.Response: + import asyncio + + async def run() -> httpx.Response: + if monkeypatch is not None: + async def fake(): + return points or [] + + monkeypatch.setattr("main._fetch_geocoded_points", fake) + transport = httpx.ASGITransport(app=app) + async with httpx.AsyncClient(transport=transport, base_url=BASE) as client: + return await client.get(path) + + return asyncio.run(run()) + + +# ── Catalog shape ────────────────────────────────────────────────────── + + +def test_catalog_length(): + zones = conflict_zones() + assert len(zones) == 13 + + +def test_catalog_severity_enum(): + zones = conflict_zones() + sevs = {z["severity"] for z in zones} + assert sevs.issubset(SEVERITIES) + # All three tiers are represented. + assert sevs == SEVERITIES + + +def test_catalog_fields_factual_and_complete(): + zones = conflict_zones() + ids = [z["id"] for z in zones] + assert len(set(ids)) == len(ids) # unique ids + for z in zones: + assert z["label"] + assert z["description"].strip() + assert -90.0 <= z["lat"] <= 90.0 + assert -180.0 <= z["lon"] <= 180.0 + # internal-only bbox is well-formed: (min_lat, min_lon, max_lat, max_lon) + min_lat, min_lon, max_lat, max_lon = z["bbox"] + assert min_lat <= max_lat and min_lon <= max_lon + assert min_lat <= z["lat"] <= max_lat and min_lon <= z["lon"] <= max_lon + + +def test_overlay_catalog_has_conflicts(): + entry = overlay_catalog()["conflicts"] + assert entry["kind"] == "points" + assert entry["endpoint"] == "/api/conflicts" + + +# ── Pure counting ────────────────────────────────────────────────────── + +TS1 = datetime(2026, 8, 30, 12, 0, tzinfo=timezone.utc) +TS2 = datetime(2026, 8, 30, 13, 0, tzinfo=timezone.utc) + + +def test_zone_event_stats_counts_and_picks_latest(): + bbox = (40.0, 20.0, 52.0, 40.0) # roughly Ukraine + points = [ + (50.45, 30.52, TS1), # inside + (48.0, 25.0, TS2), # inside, later + (0.0, -60.0, TS1), # outside + (15.0, 45.0, TS2), # outside (lat ok, lon out) + ] + count, latest = zone_event_stats(points, bbox) + assert count == 2 + assert latest == TS2 + + +def test_zone_event_stats_empty_bbox(): + count, latest = zone_event_stats([], (0.0, 0.0, 1.0, 1.0)) + assert count == 0 + assert latest is None + + +# ── API contract (mocked map items, no DB) ───────────────────────────── + + +def test_conflicts_returns_catalog_with_mocked_counts(monkeypatch): + points = [ + (50.45, 30.52, TS1), # Ukraine + (25.03, 121.56, TS2), # Taiwan Strait + (0.0, -60.0, TS1), # nowhere + ] + resp = _get("/api/conflicts", monkeypatch=monkeypatch, points=points) + assert resp.status_code == 200 + body = resp.json() + assert "zones" in body and "timestamp" in body + by_id = {z["id"]: z for z in body["zones"]} + assert len(body["zones"]) == 13 + + zone = by_id["ukraine"] + assert zone["eventCount"] == 1 + assert zone["lastUpdated"] == TS1.isoformat().replace("+00:00", "Z") + assert zone["severity"] == "war" + + assert by_id["taiwan_strait"]["eventCount"] == 1 + assert by_id["gaza"]["eventCount"] == 0 + # exact per-zone key contract the frontend consumes + assert set(zone.keys()) == { + "id", "label", "severity", "lat", "lon", + "description", "eventCount", "lastUpdated", + } + + +def test_conflicts_empty_db_yields_zero_counts(monkeypatch): + resp = _get("/api/conflicts", monkeypatch=monkeypatch, points=[]) + assert resp.status_code == 200 + body = resp.json() + assert all(z["eventCount"] == 0 for z in body["zones"]) + assert all(z["lastUpdated"] is None for z in body["zones"]) From fbff9e5415aa3d823df648b76b7136824128d8fb Mon Sep 17 00:00:00 2001 From: Sirius DevOps Date: Mon, 31 Aug 2026 21:30:47 -0400 Subject: [PATCH 41/79] feat(cameras): MDOT MiDrive parser -> cameras table Add parse_mdot_json for the MDOT MiDrive camera/list JSON where coordinates/id live in the county field's map link (lat=/lon=/id=) and the JPEG still lives in the image field's . Michigan bbox filter, missing-coords drop, RTSP reject. discovery_source=mdot, stable source_url keyed on camera id, url_hash dedupe. Wired into scrape_source dispatch + CAMERA_SOURCE_URLS defaults. Unit tests: HTML field extract, bbox drop, missing-coords/image drop, malformed payload. --- app/camera_config.py | 4 +++ app/camera_scraper.py | 75 +++++++++++++++++++++++++++++++++++++++ tests/test_live_layers.py | 63 +++++++++++++++++++++++++++++++- 3 files changed, 141 insertions(+), 1 deletion(-) diff --git a/app/camera_config.py b/app/camera_config.py index fd12ab6..d83fc06 100644 --- a/app/camera_config.py +++ b/app/camera_config.py @@ -16,6 +16,8 @@ CALTRANS_CCTV_URLS = tuple( f"https://cwwp2.dot.ca.gov/data/d{n}/cctv/cctvStatusD{n:02d}.json" for n in range(1, 13) ) +# MDOT MiDrive official DOT CCTV list (fields carry rendered HTML). +MDOT_CAMERA_URL = "https://mdotjboss.state.mi.us/MiDrive/camera/list" _DEFAULT_SOURCE_URL = ",".join(( # Publicly published open-camera list (markdown bullets of stream URLs). "https://raw.githubusercontent.com/fury999io/public-ip-cams/main/README.md", @@ -25,6 +27,8 @@ _DEFAULT_SOURCE_URL = ",".join(( "https://raw.githubusercontent.com/willytop8/Live-Environment-Streams/main/streams.geojson", # Official Caltrans CWWP2 JPEG + HLS CCTV (districts 1–12). *CALTRANS_CCTV_URLS, + # Official MDOT MiDrive CCTV (JPEG stills, Michigan). + MDOT_CAMERA_URL, )) CAMERA_SOURCE_URLS = [ u.strip() diff --git a/app/camera_scraper.py b/app/camera_scraper.py index ad5dc91..bed3aea 100644 --- a/app/camera_scraper.py +++ b/app/camera_scraper.py @@ -379,6 +379,79 @@ def parse_caltrans_json(text: str, source_name: str) -> list[dict]: return out +# MDOT MiDrive field extractors (fields carry rendered HTML). +_MDOT_LAT_RE = re.compile(r"lat=(-?\d+(?:\.\d+)?)", re.I) +_MDOT_LON_RE = re.compile(r"lon=(-?\d+(?:\.\d+)?)", re.I) +_MDOT_ID_RE = re.compile(r"[?&]id=(\d+)", re.I) +_MDOT_IMG_RE = re.compile(r']+src=["\']([^"\']+)["\']', re.I) + +# Michigan bbox (docs/osiris-ideas.md §3.2): lat 41.6–48.3, lon -90.5–-82.1. +MDOT_LAT_RANGE = (41.6, 48.3) +MDOT_LON_RANGE = (-90.5, -82.1) + + +def parse_mdot_json(text: str, source_name: str) -> list[dict]: + """Parse MDOT MiDrive `camera/list` JSON (fields carry rendered HTML). + + Coordinates and the stable id live in the `county` field's map link + (`/MiDrive/map?...lat=&lon=&id=`); the `image` field carries an `` + whose src is the JPEG still. Out-of-bbox and coord-less rows are dropped. + """ + try: + payload = json.loads(text) + except (json.JSONDecodeError, ValueError): + return [] + if not isinstance(payload, list): + return [] + out: list[dict] = [] + for row in payload: + if not isinstance(row, dict): + continue + county_html = row.get("county") or "" + m_lat = _MDOT_LAT_RE.search(county_html) + m_lon = _MDOT_LON_RE.search(county_html) + m_id = _MDOT_ID_RE.search(county_html) + if not (m_lat and m_lon and m_id): + continue # missing coordinates / stable id → drop + try: + lat = float(m_lat.group(1)) + lon = float(m_lon.group(1)) + except ValueError: + continue + if not (MDOT_LAT_RANGE[0] <= lat <= MDOT_LAT_RANGE[1] + and MDOT_LON_RANGE[0] <= lon <= MDOT_LON_RANGE[1]): + continue # out of Michigan bbox → drop + img_m = _MDOT_IMG_RE.search(row.get("image") or "") + if not img_m: + continue + snap = img_m.group(1).strip() + low = snap.lower() + if not (low.startswith("http://") or low.startswith("https://")): + continue + if low.startswith("rtsp"): + continue + cam_id = m_id.group(1) + route = (row.get("route") or "").strip() + loc = (row.get("location") or "").strip().lstrip("@").strip() + county_name = county_html.split(" list[dict]: """Parse willytop8/Live-Environment-Streams GeoJSON. @@ -490,6 +563,8 @@ async def scrape_source(client: RateLimitedClient, geo: Geocoder, body = resp.text if "cwwp2.dot.ca.gov" in src_url or "cctvStatus" in src_url: cams = parse_caltrans_json(body, name) + elif "mdotjboss.state.mi.us" in src_url or "/MiDrive/camera/list" in src_url: + cams = parse_mdot_json(body, name) elif ("getCameraDataByLoc" in src_url or ("json" in ctype and '"locs"' in body[:4000] and '"cams"' in body[:8000])): cams = parse_alertwest_json(body, name) diff --git a/tests/test_live_layers.py b/tests/test_live_layers.py index ae0f68e..a646deb 100644 --- a/tests/test_live_layers.py +++ b/tests/test_live_layers.py @@ -1,5 +1,7 @@ """Unit tests for live map-layer mappers (aircraft, trains, AIS, WFIGS, Caltrans).""" +import json + from live_layers import ( MARKER_FIELDS, bbox_center_radius_nm, @@ -25,7 +27,7 @@ from live_layers import ( _wfigs_params, ) -from camera_scraper import parse_caltrans_json +from camera_scraper import parse_caltrans_json, parse_mdot_json def test_parse_bbox_and_radius_clamps_to_150_nm(): @@ -257,6 +259,65 @@ def test_parse_caltrans_skips_oos_and_maps_jpeg_hls(): assert "rtsp://" not in cam["snapshot_url"].lower() +def test_parse_mdot_extracts_html_fields_and_bbox_filters(): + rows = [ + # In-bbox, full fields. + { + "route": "11 Mile", + "county": 'Wayne County Go to', + "location": " @ Mound NB", + "direction": "Traffic closest to camera is traveling north.", + "image": 'x', + }, + # Out of bbox (lat 50) → drop. + { + "route": "Far", + "county": 'Nowhere Go to', + "location": "", + "image": '', + }, + # Missing coordinates → drop. + { + "route": "NoCoords", + "county": 'Somewhere Go to', + "location": "", + "image": '', + }, + # Missing image → drop. + { + "route": "NoImage", + "county": 'Kent Go to', + "location": " @ Division", + "image": "", + }, + # RTSP image src → drop. + { + "route": "Rtsp", + "county": 'Wayne Go to', + "location": "", + "image": '', + }, + ] + cams = parse_mdot_json(json.dumps(rows), "mdotjboss.state.mi.us") + assert len(cams) == 1 + cam = cams[0] + assert cam["discovery_source"] == "mdot" + assert cam["location_lat"] == 42.491304 + assert cam["location_lon"] == -83.04479 + assert cam["snapshot_url"] == "https://micamerasimages.net/thumbs/semtoc_cam_253.flv.jpg?item=1" + assert cam["source_url"] == "https://mdotjboss.state.mi.us/MiDrive/camera/1129" + assert cam["device_type"] == "http" + assert cam["vendor"] == "MDOT" + assert "11 Mile @ Mound NB" in cam["location_name"] + assert "Wayne County" in cam["location_name"] + + +def test_parse_mdot_handles_malformed_payload(): + assert parse_mdot_json("not json", "mdot") == [] + assert parse_mdot_json('{"not": "a list"}', "mdot") == [] + assert parse_mdot_json("[]", "mdot") == [] + + def test_quantize_bbox_stable_under_jitter(): a = quantize_bbox(*parse_bbox("-78.7912,35.7711,-78.6101,35.9102")) b = quantize_bbox(*parse_bbox("-78.7900,35.7700,-78.6110,35.9090")) From 6f5c11e8a72014ff6906fe570941dda69e70ee47 Mon Sep 17 00:00:00 2001 From: Sirius DevOps Date: Mon, 31 Aug 2026 21:31:20 -0400 Subject: [PATCH 42/79] feat(map): aircraft popup enrichment and emergency/MIL styling Show callsign/hex/registration/type/alt/gs/squawk in ADS-B popups, keep Planespotters photos, badge and color squawk 7700/7600/7500 plus emergency flags, and expose a MIL filter only after /api/aircraft sends extra.role. --- app/static/index.html | 111 +++++++++++++++++++++----- tests/test_aircraft_popup_frontend.py | 57 +++++++++++++ 2 files changed, 149 insertions(+), 19 deletions(-) create mode 100644 tests/test_aircraft_popup_frontend.py diff --git a/app/static/index.html b/app/static/index.html index 02122d1..3900d4f 100644 --- a/app/static/index.html +++ b/app/static/index.html @@ -236,6 +236,16 @@ filter: drop-shadow(0 0 4px currentColor) drop-shadow(0 1px 2px rgba(0,0,0,0.8)); } .hdg-glyph svg { width: 100%; height: 100%; display: block; } + .hdg-emerg { + animation: emerg-pulse 1.15s ease-in-out infinite; + } + @keyframes emerg-pulse { + 0%, 100% { filter: drop-shadow(0 0 4px #ff5d5d); } + 50% { filter: drop-shadow(0 0 12px #ff5d5d) drop-shadow(0 0 18px #ff5d5d); } + } + @media (prefers-reduced-motion: reduce) { + .hdg-emerg, .role-badge.emergency { animation: none; } + } /* ── Camera marker clusters (neon green, matches the dots) ──── */ .marker-cluster-small, .marker-cluster-medium, .marker-cluster-large { @@ -334,6 +344,7 @@ .lp-dot.news { background: var(--magenta); box-shadow: 0 0 7px var(--magenta); border-radius: 1px; transform: rotate(45deg); } .lp-dot.weather { background: var(--amber); box-shadow: 0 0 7px var(--amber); } .lp-dot.flights { background: #7dd3fc; box-shadow: 0 0 7px #7dd3fc; } + .lp-dot.mil { background: #f472b6; box-shadow: 0 0 7px #f472b6; } .lp-dot.vessels { background: #2dd4bf; box-shadow: 0 0 7px #2dd4bf; } .lp-dot.radar { background: #38bdf8; box-shadow: 0 0 7px #38bdf8; } .lp-dot.thermal { background: #f97316; box-shadow: 0 0 7px #f97316; } @@ -393,6 +404,10 @@ .role-badge.civilian { color: #7dd3fc; border: 1px solid #38bdf8; background: rgba(56,189,248,0.1); } .role-badge.government { color: #facc15; border: 1px solid #facc15; background: rgba(250,204,21,0.12); } .role-badge.firefighter { color: #fb923c; border: 1px solid #fb923c; background: rgba(251,146,60,0.12); } + .role-badge.emergency { + color: #ff5d5d; border: 1px solid #ff5d5d; background: rgba(255,93,93,0.16); + animation: emerg-pulse 1.4s ease-in-out infinite; + } .blip-pop { min-width: 200px; max-width: 260px; } .blip-pop .blip-src { font-family: 'Share Tech Mono', monospace; font-size: 0.62rem; color: var(--cyan); text-transform: uppercase; letter-spacing: 0.08em; } .blip-pop .blip-time { font-size: 0.7rem; color: var(--muted); font-family: 'Share Tech Mono', monospace; margin: 0.2rem 0 0.3rem; } @@ -893,7 +908,11 @@ 0
-
Magenta = military · orange = firefighting · else altitude. Click a plane for type / squawk / operator.
+ +
Magenta = military · orange = firefighting · red = emergency (7700/7600/7500) · else altitude. Click a plane for type / squawk / operator.
@@ -1919,7 +1938,7 @@ let sentinelItemId = null, sentinelBounds = null; let wxAlertsGroup = null, wxAlertsOn = true; let perimGroup = null, perimOn = true; let incidentsGroup = null, incidentsOn = false; -let acGroup = null, acOn = true; +let acGroup = null, acOn = true, acMilOn = false, acMilSupported = false; let trainsGroup = null, trainsOn = true; let vesselsGroup = null, vesselsOn = false; let stormsGroup = null, stormsOn = true; @@ -1950,6 +1969,14 @@ function sendLiveViewport() { if (!liveWs || liveWs.readyState !== 1 || !map) return; liveWs.send(JSON.stringify({ type: 'viewport', bbox: currentBBox() })); } +function dropLivePoint(group, id) { + if (!group || !group._osintById || id == null) return; + const key = String(id); + const m = group._osintById.get(key); + if (!m) return; + group.removeLayer(m); + group._osintById.delete(key); +} function upsertLivePoint(group, p, colorFn, feed) { if (!map || !p || p.id == null || p.lat == null || p.lon == null) return group; if (!group || !map.hasLayer(group) || !group._osintById) { @@ -1960,7 +1987,7 @@ function upsertLivePoint(group, p, colorFn, feed) { let m = group._osintById.get(id); if (m) { m.setLatLng([p.lat, p.lon]); - if (feed) m.setIcon(feedIcon(feed, col, p.heading)); + if (feed) m.setIcon(feedIcon(feed, col, p.heading, feedPulse(feed, p))); else if (m.setStyle) m.setStyle({ color: col, fillColor: col }); } else { m = makePointMarker(p, colorFn, feed, pointCanvas()); @@ -1976,24 +2003,48 @@ function applyLiveMarker(kind, p) { return sog > 0.5 ? '#2dd4bf' : '#64748b'; }, 'vessel'); } else if (kind === 'adsb' && acOn && map && map.getZoom() > 3 && !dvrTs) { + if (!acVisible(p)) { + dropLivePoint(acGroup, p.id); + return; + } acGroup = upsertLivePoint(acGroup, p, q => acColor(q), 'ac'); } else if (kind === 'geofence_alert') { showGeofenceToast(p); } else if (kind === 'fire_aircraft') { firefighterHex.add(String(p.aircraft_hex || '')); if (acOn && p.aircraft_lat != null) { - acGroup = upsertLivePoint(acGroup, { + const row = { id: p.aircraft_hex, lat: p.aircraft_lat, lon: p.aircraft_lon, label: p.label || p.aircraft_hex, extra: { type: p.aircraft_type, firefighter: true, hex: p.aircraft_hex, src: 'adsb.lol' }, - }, q => acColor(q), 'ac'); + }; + if (!acVisible(row)) dropLivePoint(acGroup, row.id); + else acGroup = upsertLivePoint(acGroup, row, q => acColor(q), 'ac'); } } } +const EMERG_SQUAWK = new Set(['7700', '7600', '7500']); +function acIsEmergency(p) { + const extra = (p && p.extra) || {}; + const em = String(extra.emergency || '').toLowerCase(); + if (em && em !== 'none') return true; + const sq = String(extra.squawk || '').replace(/\s/g, ''); + return EMERG_SQUAWK.has(sq); +} +function acVisible(p) { + if (!acMilOn) return true; + return ((p && p.extra) || {}).role === 'military'; +} +function noteMilSupport(pts) { + if (acMilSupported) return; + if (!Array.isArray(pts) || !pts.some(q => q && q.extra && q.extra.role)) return; + acMilSupported = true; + const row = document.getElementById('lp-ac-mil-row'); + if (row) row.hidden = false; +} function acColor(p) { const extra = p.extra || {}; const t = String(extra.type || '').toUpperCase(); - const em = String(extra.emergency || '').toLowerCase(); - if (em && em !== 'none') return '#ff5d5d'; + if (acIsEmergency(p)) return '#ff5d5d'; if (extra.firefighter || firefighterHex.has(String(p.id)) || FF_ICAO.has(t)) return '#fb923c'; if (extra.role === 'military') return '#f472b6'; return altColor(extra.alt_baro); @@ -2822,9 +2873,13 @@ function pointPopup(p) { const extra = p.extra || {}; const src = extra.src || ''; const role = extra.firefighter ? 'firefighter' : extra.role; - const badge = role - ? ` ${esc(String(role).toUpperCase())}` - : ''; + let badge = ''; + if (src === 'adsb.lol' && acIsEmergency(p)) { + badge += ' EMERGENCY'; + } + if (role) { + badge += ` ${esc(String(role).toUpperCase())}`; + } const rows = []; const add = (k, v) => { const val = _popVal(v); @@ -2832,10 +2887,12 @@ function pointPopup(p) { rows.push(`${esc(k)}${esc(val)}`); }; if (src === 'adsb.lol') { + add('callsign', p.label); + add('hex', extra.hex); + add('registration', extra.reg); add('type', extra.type); add('aircraft', extra.desc); add('operator', extra.ownOp); - add('reg', extra.reg); const alt = extra.alt_baro; add('alt', alt != null ? `${alt} ft` : null); add('vs', extra.vs != null ? `${extra.vs} fpm` : null); @@ -2844,7 +2901,6 @@ function pointPopup(p) { add('squawk', extra.squawk); add('emergency', extra.emergency); add('class', extra.emitter); - add('hex', extra.hex); } else if (src === 'aisstream') { add('kind', extra.kind); add('flag', extra.country); @@ -2943,20 +2999,24 @@ function sanitizeColor(c, fallback) { if (/^rgba?\(\s*[\d.]+\s*,\s*[\d.]+\s*,\s*[\d.]+\s*(,\s*[\d.]+\s*)?\)$/.test(s)) return s; return fallback; } -function feedIcon(feed, color, heading) { +function feedPulse(feed, p) { + return feed === 'ac' && acIsEmergency(p); +} +function feedIcon(feed, color, heading, pulse) { // Normalize heading to [0,360) integer so the cache stays bounded. // Missing/empty/NaN heading -> -1 sentinel -> glyph rendered upright. const hnum = Number(heading); const h = (heading === null || heading === '' || heading === undefined || !Number.isFinite(hnum)) ? -1 : (Math.round(hnum % 360) + 360) % 360; - const key = `${feed}|${color}|${h}`; + const key = `${feed}|${color}|${h}|${pulse ? 1 : 0}`; let ic = feedIconCache.get(key); if (!ic) { const rot = h >= 0 ? `transform:rotate(${h}deg);` : ''; + const pulseCls = pulse ? ' hdg-emerg' : ''; ic = L.divIcon({ className: '', - html: `${FEED_GLYPHS[feed]}`, + html: `${FEED_GLYPHS[feed]}`, iconSize: [26, 26], iconAnchor: [13, 13], }); feedIconCache.set(key, ic); @@ -2969,7 +3029,7 @@ function makePointMarker(p, colorFn, feed, renderer) { let m; if (feed) { const heading = Number(p.heading); - const icon = feedIcon(feed, col, Number.isNaN(heading) ? null : heading); + const icon = feedIcon(feed, col, Number.isNaN(heading) ? null : heading, feedPulse(feed, p)); m = L.marker([p.lat, p.lon], { icon }); } else { m = L.circleMarker([p.lat, p.lon], { @@ -3016,7 +3076,7 @@ function renderPoints(existing, points, colorFn, cluster, feed) { if (m) { m.setLatLng([p.lat, p.lon]); m._osintP = p; - if (feed) m.setIcon(feedIcon(feed, col, p.heading)); + if (feed) m.setIcon(feedIcon(feed, col, p.heading, feedPulse(feed, p))); else if (m.setStyle) m.setStyle({ color: col, fillColor: col }); } else { const nm = makePointMarker(p, colorFn, feed, renderer); @@ -3286,6 +3346,10 @@ async function toggleAircraft() { if (acOn) await loadAircraft(); else acGroup = dropLayer(acGroup); } +function toggleAircraftMil() { + acMilOn = document.getElementById('lp-ac-mil-on').checked; + if (acOn) loadAircraft(); +} async function loadAircraft() { if (!map) return; if (map.getZoom() <= 3) { @@ -3297,8 +3361,17 @@ async function loadAircraft() { const r = await overlayFetch(`${API}/api/aircraft?bbox=${currentBBox()}${dvrQs()}`); const pts = await r.json(); if (req !== overlayReq.ac) return; - acGroup = renderPoints(acGroup, Array.isArray(pts) ? pts : [], p => acColor(p), true, 'ac'); - document.getElementById('lp-ac-count').textContent = (pts.length || 0).toLocaleString(); + const all = Array.isArray(pts) ? pts : []; + noteMilSupport(all); + const shown = acMilOn ? all.filter(acVisible) : all; + acGroup = renderPoints(acGroup, shown, p => acColor(p), true, 'ac'); + document.getElementById('lp-ac-count').textContent = shown.length.toLocaleString(); + const milEl = document.getElementById('lp-ac-mil-count'); + if (milEl) { + milEl.textContent = acMilOn + ? shown.length.toLocaleString() + : String(all.filter(q => ((q.extra || {}).role === 'military')).length); + } addExtraAttrib('ADSB.lol ODbL'); addExtraAttrib('Photo © planespotters.net'); } catch (e) { diff --git a/tests/test_aircraft_popup_frontend.py b/tests/test_aircraft_popup_frontend.py new file mode 100644 index 0000000..98c1f09 --- /dev/null +++ b/tests/test_aircraft_popup_frontend.py @@ -0,0 +1,57 @@ +"""Aircraft popup enrichment + emergency/MIL layer contract (static HTML).""" + +from __future__ import annotations + +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +HTML = (ROOT / "app/static/index.html").read_text() + + +def _fn(name: str, nxt: str) -> str: + return HTML.split(f"function {name}", 1)[1].split(f"function {nxt}", 1)[0] + + +def test_popup_has_required_adsb_fields_and_photo(): + js = _fn("pointPopup", "loadPlanePhoto") + for field in ("callsign", "hex", "registration", "type", "alt", "gs", "squawk"): + assert f"add('{field}'" in js + assert "class=\"ps-photo\"" in js or "class='ps-photo'" in js + assert "wikipedia" not in js.lower() + assert "ceo" not in js.lower() + + +def test_emergency_badge_and_squawk_codes(): + assert "role-badge emergency" in HTML + assert "hdg-emerg" in HTML + assert "EMERG_SQUAWK" in HTML + assert "['7700', '7600', '7500']" in HTML + emerg = HTML.split("function acIsEmergency", 1)[1].split("function acVisible", 1)[0] + assert "EMERG_SQUAWK.has(sq)" in emerg + color = HTML.split("function acColor", 1)[1].split("function connectLiveWs", 1)[0] + assert "acIsEmergency(p)" in color + assert "#ff5d5d" in color + + +def test_mil_toggle_hidden_until_role_flag_and_never_hits_adsb_lol(): + assert 'id="lp-ac-mil-row"' in HTML + assert 'id="lp-ac-mil-on"' in HTML + row = HTML.split('id="lp-ac-mil-row"', 1)[1].split(">", 1)[0] + assert "hidden" in row + on = HTML.split('id="lp-ac-mil-on"', 1)[1].split(">", 1)[0] + assert "checked" not in on + load = HTML.split("async function loadAircraft", 1)[1].split("async function toggleTrains", 1)[0] + assert "/api/aircraft?bbox=" in load + assert "api.adsb.lol" not in load + assert "noteMilSupport" in load + assert "acMilOn" in load + note = HTML.split("function noteMilSupport", 1)[1].split("function acColor", 1)[0] + assert "extra.role" in note + assert "lp-ac-mil-row" in note + assert "hidden = false" in note + + +def test_planespotters_lazy_photo_still_wired(): + assert "function loadPlanePhoto" in HTML + assert "/api/aircraft/photo?" in HTML + assert "map.on('popupopen', (e) => { loadPlanePhoto(e.popup); });" in HTML From 150cc5fdc45dba10eb3b5ca1a82436b33071aebf Mon Sep 17 00:00:00 2001 From: Sirius DevOps Date: Mon, 31 Aug 2026 21:31:31 -0400 Subject: [PATCH 43/79] feat(infra): GET /api/infrastructure Overpass nuclear markers (bbox) Overpass nwr power=plant + plant:source=nuclear, bbox-required, one in-flight per quantized bbox, 25s server query with identifying UA, 24h TTL cache. Normalized to {id,name,lat,lon,type,extra}. overlay_catalog entry infra_nuclear. Missing bbox 400; unknown type 422. --- app/live_layers.py | 107 ++++++++++++++++++++++++++ app/main.py | 35 ++++++++- tests/test_infrastructure.py | 145 +++++++++++++++++++++++++++++++++++ 3 files changed, 286 insertions(+), 1 deletion(-) create mode 100644 tests/test_infrastructure.py diff --git a/app/live_layers.py b/app/live_layers.py index fa632b1..36b4bb5 100644 --- a/app/live_layers.py +++ b/app/live_layers.py @@ -150,6 +150,12 @@ def overlay_catalog() -> dict: "endpoint": "/api/map/gpsjam", "attribution": "GPSJAM / John Wiseman / ADS-B Exchange", }, + "infra_nuclear": { + "id": "infra_nuclear", + "kind": "points", + "endpoint": "/api/infrastructure?types=nuclear", + "attribution": "OpenStreetMap contributors / Overpass API", + }, } @@ -1429,3 +1435,104 @@ async def fetch_gpsjam(date: str) -> dict: return gpsjam_csv_to_geojson(resp.text) return await _ttl_get(f"gpsjam:{date}", GPSJAM_TTL, _load) +# ── Infrastructure (Overpass) ─────────────────────────────────────────────── + + +OVERPASS_INTERPRETER = "https://overpass-api.de/api/interpreter" +# One in-flight query per quantized bbox (the per-key lock in _ttl_get). Overpass +# asks for a 25s server timeout in-band; the client gives it 30s of headroom. +OVERPASS_TIMEOUT = httpx.Timeout(30.0, connect=5.0) +INFRA_TTL = 24 * 3600 # 24h per quantized bbox — static infrastructure + +# `types=` enum. Nuclear ships first; military/hospital slot in behind the same +# query template without touching the transport. Overpass bbox is +# (south, west, north, east), i.e. (minlat, minlon, maxlat, maxlon). +_INFRA_QUERIES: dict[str, str] = { + "nuclear": ( + '[out:json][timeout:25];\n' + 'nwr["power"="plant"]["plant:source"="nuclear"]({bbox});\n' + 'out center;' + ), +} + + +def infra_query(type_: str, minlon: float, minlat: float, maxlon: float, maxlat: float) -> str: + """Render one Overpass query with the bbox substituted in south,west,north,east.""" + bbox = f"{minlat},{minlon},{maxlat},{maxlon}" + return _INFRA_QUERIES[type_].replace("{bbox}", bbox) + + +def normalize_infra_element(elem: dict, type_: str) -> dict | None: + """Map one Overpass element to ``{id, name, lat, lon, type, extra}``. + + ``out center`` gives nodes their own ``lat``/``lon`` and ways/relations a + ``center``. Elements with no usable coordinate are dropped. + """ + etype = elem.get("type") + eid = elem.get("id") + if eid is None: + return None + if etype == "node": + lat, lon = elem.get("lat"), elem.get("lon") + else: + center = elem.get("center") or {} + lat, lon = center.get("lat"), center.get("lon") + if lat is None or lon is None: + return None + tags = elem.get("tags") or {} + name = tags.get("name") or tags.get("ref") or f"{etype}/{eid}" + extra = {k: v for k, v in tags.items() if k != "name"} + return { + "id": f"{etype}/{eid}", + "name": name, + "lat": lat, + "lon": lon, + "type": type_, + "extra": extra, + } + + +def overpass_nuclear_to_markers(data: dict) -> list[dict]: + """Convert an Overpass JSON response to normalized nuclear markers.""" + markers = [] + for elem in data.get("elements") or []: + marker = normalize_infra_element(elem, "nuclear") + if marker is not None: + markers.append(marker) + return markers + + +async def fetch_infrastructure(types: str, bbox: str) -> list[dict]: + """Fetch Overpass infrastructure markers, cached 24h per quantized bbox. + + ``types`` is a single supported enum value (``nuclear`` for now). ``bbox`` + is ``minlon,minlat,maxlon,maxlat``. + """ + requested = [t.strip() for t in types.split(",") if t.strip()] + minlon, minlat, maxlon, maxlat = parse_bbox(bbox) + key = f"infra:{','.join(requested)}:{bbox_cell_key(bbox)}" + + async def _load() -> list[dict]: + # One query per requested type, concatenated. Nuclear is the only type + # today; the loop keeps the shape ready for military/hospital. + out: list[dict] = [] + for type_ in requested: + query = infra_query(type_, minlon, minlat, maxlon, maxlat) + if _http is None: + async with httpx.AsyncClient( + timeout=OVERPASS_TIMEOUT, follow_redirects=True, + headers=_headers(), + ) as client: + resp = await client.post(OVERPASS_INTERPRETER, data={"data": query}) + resp.raise_for_status() + out.extend(overpass_nuclear_to_markers(resp.json())) + else: + resp = await _http.post( + OVERPASS_INTERPRETER, data={"data": query}, + timeout=OVERPASS_TIMEOUT, + ) + resp.raise_for_status() + out.extend(overpass_nuclear_to_markers(resp.json())) + return out + + return await _ttl_get(key, float(INFRA_TTL), _load) diff --git a/app/main.py b/app/main.py index 2d12e25..b4fe5bd 100644 --- a/app/main.py +++ b/app/main.py @@ -57,7 +57,7 @@ from live_layers import ( fetch_aircraft, fetch_fire_incidents, fetch_fire_perimeters, fetch_gpsjam, fetch_planespotters_photo, fetch_radar_meta, fetch_sentinel1, fetch_storms, fetch_trains, fetch_vessels, fetch_weather_alerts, - overlay_catalog, parse_bbox, UpstreamRateLimited, + fetch_infrastructure, overlay_catalog, parse_bbox, UpstreamRateLimited, ) logging.basicConfig(level=logging.INFO) @@ -1764,6 +1764,39 @@ async def map_gpsjam( return overlay_json(fc, 3600) +_INFRA_TYPES = frozenset({"nuclear"}) + + +@app.get("/api/infrastructure") +async def api_infrastructure( + types: str = Query(..., description="comma-separated enum (nuclear)"), + bbox: str | None = Query(None, description="minlon,minlat,maxlon,maxlat"), +): + """Overpass-derived static infrastructure markers (nuclear power plants). + + ``bbox`` is required; ``types`` is a comma-separated subset of ``nuclear``. + Fetched from Overpass (identifying UA, 25s query) and cached 24h per + quantized bbox. Markers are ``{id, name, lat, lon, type, extra}``. + """ + if not bbox: + raise HTTPException(400, "bbox required (minlon,minlat,maxlon,maxlat)") + requested = [t.strip() for t in (types or "").split(",") if t.strip()] + if not requested: + raise HTTPException(422, "types required (e.g. nuclear)") + unknown = [t for t in requested if t not in _INFRA_TYPES] + if unknown: + raise HTTPException( + 422, f"unsupported types: {', '.join(unknown)} (supported: nuclear)" + ) + try: + markers = await fetch_infrastructure(",".join(requested), bbox) + except ValueError as exc: + raise HTTPException(422, str(exc)) from exc + except Exception as exc: + _upstream_or_502(exc, "infrastructure") + return overlay_json(markers, 86400) + + @app.get("/api/map/times") async def map_layer_times( layer: str = Query(..., description="GIBS layer identifier, e.g. VIIRS_SNPP_CorrectedReflectance_TrueColor"), diff --git a/tests/test_infrastructure.py b/tests/test_infrastructure.py new file mode 100644 index 0000000..27dd80f --- /dev/null +++ b/tests/test_infrastructure.py @@ -0,0 +1,145 @@ +"""GET /api/infrastructure — Overpass nuclear markers.""" + +import asyncio + +import httpx + +from live_layers import ( + normalize_infra_element, + overlay_catalog, + overpass_nuclear_to_markers, + _cache, +) +from main import app + +BASE = "http://test" + +OVERPASS = { + "version": 0.6, + "generator": "Overpass API", + "elements": [ + { + "type": "node", + "id": 12345, + "lat": 44.0, + "lon": -1.5, + "tags": {"name": "Test NPP", "operator": "EDF", "plant:source": "nuclear"}, + }, + { + "type": "way", + "id": 67890, + "center": {"lat": 43.5, "lon": -1.25}, + "tags": {"name": "Test Plant Way", "plant:source": "nuclear"}, + }, + { + "type": "relation", + "id": 999, + "center": {"lat": 43.0, "lon": -1.0}, + "tags": {}, + }, + ], +} + + +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 test_normalize_node_to_marker(): + m = normalize_infra_element(OVERPASS["elements"][0], "nuclear") + assert m["id"] == "node/12345" + assert m["name"] == "Test NPP" + assert m["lat"] == 44.0 + assert m["lon"] == -1.5 + assert m["type"] == "nuclear" + assert m["extra"]["operator"] == "EDF" + assert "name" not in m["extra"] + + +def test_way_center_and_unnamed_fallback(): + way = normalize_infra_element(OVERPASS["elements"][1], "nuclear") + assert way["lat"] == 43.5 + assert way["lon"] == -1.25 + rel = normalize_infra_element(OVERPASS["elements"][2], "nuclear") + assert rel["name"] == "relation/999" + + +def test_overpass_json_to_markers(): + markers = overpass_nuclear_to_markers(OVERPASS) + assert len(markers) == 3 + assert markers[0]["id"] == "node/12345" + + +def test_missing_bbox_400(): + resp = asyncio.run(_get("/api/infrastructure?types=nuclear")) + assert resp.status_code == 400 + + +def test_unknown_type_422(): + resp = asyncio.run(_get("/api/infrastructure?types=military&bbox=-2,43,-1,44")) + assert resp.status_code == 422 + + +def test_map_infrastructure_returns_markers(monkeypatch): + async def fake_fetch(types, bbox): + return [ + {"id": "node/1", "name": "X", "lat": 1.0, "lon": 2.0, + "type": "nuclear", "extra": {}} + ] + + monkeypatch.setattr("main.fetch_infrastructure", fake_fetch) + resp = asyncio.run(_get("/api/infrastructure?types=nuclear&bbox=-2,43,-1,44")) + assert resp.status_code == 200 + body = resp.json() + assert body[0]["name"] == "X" + assert body[0]["type"] == "nuclear" + assert "max-age" in (resp.headers.get("cache-control") or "").lower() + + +def test_overlay_catalog_has_infra_nuclear(): + entry = overlay_catalog()["infra_nuclear"] + assert entry["kind"] == "points" + assert "nuclear" in entry["endpoint"] + + +def test_fetch_infrastructure_cache_hit_no_refetch(monkeypatch): + _cache.clear() + hits = {"n": 0} + + class FakeResp: + def raise_for_status(self): + pass + + def json(self): + return OVERPASS + + class FakeClient: + def __init__(self, **kw): + pass + + async def __aenter__(self): + return self + + async def __aexit__(self, *exc): + return False + + async def post(self, url, data=None, timeout=None): + hits["n"] += 1 + assert "overpass-api.de" in url + assert "plant:source" in data["data"] + assert "nuclear" in data["data"] + return FakeResp() + + monkeypatch.setattr("live_layers.httpx.AsyncClient", FakeClient) + monkeypatch.setattr("live_layers._http", None) + + from live_layers import fetch_infrastructure + + m1 = asyncio.run(fetch_infrastructure("nuclear", "-2,43,-1,44")) + m2 = asyncio.run(fetch_infrastructure("nuclear", "-2,43,-1,44")) + assert len(m1) == 3 + assert m2 == m1 + assert hits["n"] == 1 + _cache.clear() From 5cef596a3c6795f68858786190a539cd92e741da Mon Sep 17 00:00:00 2001 From: Sirius DevOps Date: Mon, 31 Aug 2026 21:35:00 -0400 Subject: [PATCH 44/79] feat(map): right-click place dossier (Nominatim + nearby overlays) Right-click (long-press on touch) opens a What's here? HUD panel: reverse geocode via GET /api/place (honest UA, 1 req/s, 60s/500-key cache) and lists already-loaded cameras, aircraft, vessels, fires, and alerts within 5 km. --- app/config.py | 3 + app/main.py | 20 ++ app/place.py | 99 ++++++++++ app/static/index.html | 262 ++++++++++++++++++++++++++- docker-compose.yml | 2 + tests/test_api_place.py | 127 +++++++++++++ tests/test_place_dossier_frontend.py | 59 ++++++ 7 files changed, 566 insertions(+), 6 deletions(-) create mode 100644 app/place.py create mode 100644 tests/test_api_place.py create mode 100644 tests/test_place_dossier_frontend.py diff --git a/app/config.py b/app/config.py index d93f492..b2bdab8 100644 --- a/app/config.py +++ b/app/config.py @@ -71,6 +71,9 @@ FIRMS_DATASETS = [d.strip() for d in _FIRMS_DATASETS_RAW.split(",") if d.strip() OSINT_USER_AGENT = os.getenv( "OSINT_USER_AGENT", "osint-dashboard/1.0 (self-hosted; lancewalters94@gmail.com)" ) +# Nominatim reverse (GET /api/place). Camera scraper has its own copy in camera_config. +NOMINATIM_URL = os.getenv("NOMINATIM_URL", "https://nominatim.openstreetmap.org") +NOMINATIM_MIN_INTERVAL = float(os.getenv("NOMINATIM_MIN_INTERVAL", "1.0")) # Self-hosted TiTiler (warps Sentinel-1 signed COGs into XYZ tiles on the Pi). # TITILER_PUBLIC_BASE is the same-origin path prefix the browser hits through diff --git a/app/main.py b/app/main.py index 2d12e25..e97308b 100644 --- a/app/main.py +++ b/app/main.py @@ -59,6 +59,7 @@ from live_layers import ( fetch_storms, fetch_trains, fetch_vessels, fetch_weather_alerts, overlay_catalog, parse_bbox, UpstreamRateLimited, ) +from place import reverse_geocode logging.basicConfig(level=logging.INFO) logger = structlog.get_logger("osint.dashboard") @@ -1729,6 +1730,25 @@ async def list_storms(): _upstream_or_502(exc, "storms") +@app.get("/api/place") +async def get_place( + lat: float = Query(..., ge=-90, le=90), + lon: float = Query(..., ge=-180, le=180), +): + """Nominatim reverse geocode for the map \"What's here?\" dossier. + + Identifying ``OSINT_USER_AGENT``, 1 req/s, 60s cache, 500 keys. The HUD + lists already-loaded overlay entities client-side — this route does not + refetch aircraft/vessels/cameras/fires. + """ + try: + return overlay_json(await reverse_geocode(lat, lon), 60) + except ValueError as exc: + raise HTTPException(422, str(exc)) from exc + except Exception as exc: + _upstream_or_502(exc, "nominatim") + + _GPSJAM_DATE = re.compile(r"^\d{4}-\d{2}-\d{2}$") diff --git a/app/place.py b/app/place.py new file mode 100644 index 0000000..e1729ee --- /dev/null +++ b/app/place.py @@ -0,0 +1,99 @@ +"""Nominatim reverse-geocode proxy for the map place dossier. + +Browser clients cannot set an identifying User-Agent, and Nominatim typically +blocks CORS — so the HUD calls GET /api/place instead of talking to OSM +directly. Cache 60s / 500 keys; never exceed 1 req/s upstream. +""" + +from __future__ import annotations + +import asyncio +import time + +import httpx +from cachetools import TTLCache + +from config import NOMINATIM_MIN_INTERVAL, NOMINATIM_URL, OSINT_USER_AGENT + +_NOMINATIM = NOMINATIM_URL.rstrip("/") + +place_cache: TTLCache = TTLCache(maxsize=500, ttl=60) + +_lock = asyncio.Lock() +_last_req = 0.0 + +_ADDR_KEEP = ( + "house_number", "road", "neighbourhood", "suburb", "city", "town", + "village", "hamlet", "county", "state", "postcode", "country", "country_code", +) + + +def cache_key(lat: float, lon: float) -> str: + return f"{lat:.4f},{lon:.4f}" + + +def slim_place(lat: float, lon: float, data: dict | None) -> dict: + data = data or {} + raw_addr = data.get("address") + addr_in: dict = raw_addr if isinstance(raw_addr, dict) else {} + address = {k: addr_in[k] for k in _ADDR_KEEP if addr_in.get(k)} + err = data.get("error") + display = None if err else (data.get("display_name") or None) + name = None if err else (data.get("name") or address.get("city") + or address.get("town") or address.get("village") or None) + return { + "lat": lat, + "lon": lon, + "display_name": display, + "name": name, + "address": address, + "osm_type": None if err else data.get("osm_type"), + "osm_id": None if err else data.get("osm_id"), + "attribution": "© OpenStreetMap contributors", + } + + +async def reverse_geocode(lat: float, lon: float) -> dict: + """Reverse-geocode a point. Cache hits skip Nominatim entirely.""" + if not (-90.0 <= lat <= 90.0 and -180.0 <= lon <= 180.0): + raise ValueError("lat/lon out of range") + key = cache_key(lat, lon) + qlat, qlon = (float(p) for p in key.split(",")) + async with _lock: + hit = place_cache.get(key) + if hit is not None: + return hit + global _last_req + wait = _last_req + NOMINATIM_MIN_INTERVAL - time.monotonic() + if wait > 0: + await asyncio.sleep(wait) + body = await _fetch_nominatim(qlat, qlon) + _last_req = time.monotonic() + place_cache[key] = body + return body + + +async def _fetch_nominatim(lat: float, lon: float) -> dict: + headers = { + "User-Agent": OSINT_USER_AGENT, + "Accept": "application/json", + } + url = f"{_NOMINATIM}/reverse" + params = { + "lat": f"{lat:.6f}", + "lon": f"{lon:.6f}", + "format": "jsonv2", + "addressdetails": "1", + "zoom": "18", + } + async with _http_client(timeout=10.0, follow_redirects=True) as client: + r = await client.get(url, params=params, headers=headers) + r.raise_for_status() + data = r.json() + if not isinstance(data, dict): + data = {} + return slim_place(lat, lon, data) + + +def _http_client(**kwargs): + return httpx.AsyncClient(**kwargs) diff --git a/app/static/index.html b/app/static/index.html index 02122d1..9d9fc0f 100644 --- a/app/static/index.html +++ b/app/static/index.html @@ -364,6 +364,55 @@ .gf-del { background: transparent; border: 1px solid var(--magenta); color: var(--magenta); font-family: 'Share Tech Mono', monospace; font-size: 0.58rem; letter-spacing: 0.08em; text-transform: uppercase; padding: 0.12rem 0.35rem; border-radius: 3px; cursor: pointer; } .gf-del:hover { background: rgba(255,46,151,0.16); } + /* ── Place dossier (“What’s here?”) ── */ + #place-dossier { + position: absolute; top: 58px; right: 54px; z-index: 650; + width: 280px; max-height: calc(100% - 90px); overflow: hidden; + background: rgba(6,11,20,0.90); backdrop-filter: blur(8px); + border: 1px solid var(--line-hi); border-radius: 6px; + box-shadow: 0 0 22px rgba(53,224,255,0.14), 0 0 2px rgba(53,224,255,0.4); + color: var(--text); font-size: 0.78rem; display: none; flex-direction: column; + clip-path: polygon(0 8px, 8px 0, calc(100% - 8px) 0, 100% 8px, 100% calc(100% - 8px), calc(100% - 8px) 100%, 8px 100%, 0 calc(100% - 8px)); + } + #place-dossier.open { display: flex; } + .pd-head { + display: flex; justify-content: space-between; align-items: center; + padding: 0.55rem 0.95rem 0.55rem 0.85rem; border-bottom: 1px solid var(--line); + font-family: 'Orbitron', sans-serif; font-size: 0.68rem; font-weight: 700; + letter-spacing: 0.14em; text-transform: uppercase; color: var(--cyan); + text-shadow: 0 0 10px rgba(53,224,255,0.55); + background: linear-gradient(180deg, rgba(53,224,255,0.07), transparent); + } + .pd-close { + background: transparent; border: 1px solid var(--line); color: var(--muted); + font-family: 'Share Tech Mono', monospace; font-size: 0.78rem; + width: 28px; height: 28px; border-radius: 4px; cursor: pointer; line-height: 1; + flex-shrink: 0; margin-right: 2px; + } + .pd-close:hover { border-color: var(--cyan); color: var(--cyan); } + .pd-body { padding: 0.55rem 0.75rem 0.7rem; overflow-y: auto; display: flex; flex-direction: column; gap: 0.55rem; min-height: 0; flex: 1; } + .pd-status { font-family: 'Share Tech Mono', monospace; font-size: 0.66rem; color: var(--muted); } + .pd-status.err { color: var(--red); } + .pd-coords { font-family: 'Share Tech Mono', monospace; font-size: 0.66rem; color: var(--cyan); letter-spacing: 0.04em; } + .pd-name { font-family: 'Rajdhani', sans-serif; font-weight: 700; font-size: 0.92rem; color: var(--text); line-height: 1.25; } + .pd-addr { font-size: 0.72rem; color: var(--muted); line-height: 1.4; } + .pd-sec { + font-family: 'Orbitron', sans-serif; font-size: 0.58rem; letter-spacing: 0.12em; + text-transform: uppercase; color: var(--muted); margin-top: 0.15rem; + } + .pd-list { display: flex; flex-direction: column; gap: 0.18rem; } + .pd-item { + display: flex; justify-content: space-between; align-items: baseline; gap: 0.5rem; + background: transparent; border: 0; border-left: 2px solid var(--line); + color: var(--text); text-align: left; cursor: pointer; padding: 0.22rem 0.35rem; + font-family: 'Rajdhani', sans-serif; font-size: 0.78rem; font-weight: 600; + } + .pd-item:hover, .pd-item:focus-visible { border-left-color: var(--cyan); color: var(--cyan); background: rgba(53,224,255,0.06); } + .pd-item .k { text-transform: uppercase; letter-spacing: 0.06em; font-size: 0.58rem; color: var(--muted); font-family: 'Share Tech Mono', monospace; flex-shrink: 0; } + .pd-item .d { font-family: 'Share Tech Mono', monospace; font-size: 0.62rem; color: var(--cyan); white-space: nowrap; } + .pd-empty { font-size: 0.72rem; color: var(--muted); font-style: italic; } + .pd-note { font-size: 0.6rem; color: var(--muted); opacity: 0.85; line-height: 1.35; } + /* ── Camera / blip popup thumbnails ── */ .cam-pop { min-width: 210px; max-width: 260px; } .cam-pop .thumb { width: 100%; height: 160px; object-fit: cover; border-radius: 4px; border: 1px solid var(--line); margin: 0.3rem 0; box-shadow: 0 0 10px rgba(53,224,255,0.2); background: var(--bg-0); } @@ -694,6 +743,14 @@ margin-top: 8px; margin-right: 8px; } + #place-dossier { + top: auto; + right: 8px; + left: 8px; + bottom: 56px; + width: auto; + max-height: 36vh; + } } @media (prefers-reduced-motion: reduce) { .tick-track { animation: none; } @@ -932,6 +989,21 @@
+
Initializing…
FIRMS —
@@ -1931,6 +2003,8 @@ let lastVesselSubBox = ''; // last viewport box sent to the AIS stream let chokepointCatalog = []; // GET /api/map/chokepoints, fetched once let vesselSrcPref = ''; // 'vesselapi' only on Hormuz preset — no extra polls let vesselRefollowTimer = null; // one follow-up fetch after a retune +let lastCams = [], lastFires = [], lastAircraft = [], lastVessels = [], lastAlerts = []; +let placeMarker = null, placeReq = 0, placeLongPress = null; function bboxCell() { if (!map) return ''; return currentBBox().split(',').map(n => Number(n).toFixed(2)).join(',') + '@' + map.getZoom(); @@ -2122,6 +2196,17 @@ async function initMap() { map.on('popupclose', () => { camPopupOpen = false; }); map.on('zoomstart', () => { if (camPopupOpen) map.closePopup(); }); map.on('dragstart', () => { if (camPopupOpen) map.closePopup(); }); + map.on('contextmenu', (e) => { + if (e.originalEvent) e.originalEvent.preventDefault(); + if (typeof gfDrawOn !== 'undefined' && gfDrawOn) return; + openPlaceDossier(e.latlng); + }); + bindPlaceLongPress(map); + const pdClose = document.getElementById('pd-close'); + if (pdClose) pdClose.addEventListener('click', closePlaceDossier); + document.addEventListener('keydown', (ev) => { + if (ev.key === 'Escape') closePlaceDossier(); + }); map.on('moveend', () => { if (camPopupOpen) return; // only the popup's own autopan now if (moveDebounce) clearTimeout(moveDebounce); @@ -2466,7 +2551,7 @@ function sinceToISO(sel) { async function toggleFires() { firesOn = document.getElementById('lp-fires-on').checked; if (firesOn) await loadFires(); - else if (firesHeat) { map.removeLayer(firesHeat); firesHeat = null; } + else if (firesHeat) { map.removeLayer(firesHeat); firesHeat = null; lastFires = []; } hudFiresCount = null; syncHud(); } @@ -2496,6 +2581,7 @@ async function loadFires() { if (req !== fireReq) return; // superseded by a newer pan/zoom if (firesHeat) map.removeLayer(firesHeat); const pts = fires.map(f => [f.lat ?? f.latitude, f.lon ?? f.longitude, firesIntensity(f)]); + lastFires = Array.isArray(fires) ? fires : []; firesHeat = L.heatLayer(pts, { radius: 22, blur: 20, maxZoom: 9, max: 1.0, minOpacity: 0.2, gradient: firesGradient(), @@ -2518,7 +2604,7 @@ async function loadFires() { async function toggleCams() { camsOn = document.getElementById('lp-cams-on').checked; if (camsOn) await loadCams(); - else if (camsGroup) { map.removeLayer(camsGroup); camsGroup = null; } + else if (camsGroup) { map.removeLayer(camsGroup); camsGroup = null; lastCams = []; } hudCamsCount = null; syncHud(); } @@ -2590,6 +2676,7 @@ async function loadCams() { if (!map) return; if (tooZoomedOut()) { camsGroup = dropLayer(camsGroup); + lastCams = []; markZoom('lp-cams-count'); hudCamsCount = null; syncHud(); @@ -2600,6 +2687,7 @@ async function loadCams() { const r = await overlayFetch(`${API}/api/cameras?bbox=${currentBBox()}&limit=2000`); const cams = await r.json(); if (req !== camReq) return; // superseded by a newer pan/zoom + lastCams = Array.isArray(cams) ? cams : []; if (camsGroup) map.removeLayer(camsGroup); // Clustered markers: camera coverage stays visible as numbered // clusters at every zoom instead of vanishing into a sparse/empty @@ -3180,12 +3268,13 @@ function loadThermal() { async function toggleWxAlerts() { wxAlertsOn = document.getElementById('lp-alerts-on').checked; if (wxAlertsOn) await loadWxAlerts(); - else wxAlertsGroup = dropLayer(wxAlertsGroup); + else { wxAlertsGroup = dropLayer(wxAlertsGroup); lastAlerts = []; } } async function loadWxAlerts() { if (!map) return; if (tooZoomedOut()) { wxAlertsGroup = dropLayer(wxAlertsGroup); + lastAlerts = []; markZoom('lp-alerts-count'); return; } @@ -3196,6 +3285,7 @@ async function loadWxAlerts() { if (req !== overlayReq.alerts) return; wxAlertsGroup = dropLayer(wxAlertsGroup); const feats = fc.features || []; + lastAlerts = feats; wxAlertsGroup = L.geoJSON(fc, { renderer: L.canvas({ padding: 0.5 }), style: (f) => ({ @@ -3284,7 +3374,7 @@ async function loadIncidents() { async function toggleAircraft() { acOn = document.getElementById('lp-ac-on').checked; if (acOn) await loadAircraft(); - else acGroup = dropLayer(acGroup); + else { acGroup = dropLayer(acGroup); lastAircraft = []; } } async function loadAircraft() { if (!map) return; @@ -3297,7 +3387,8 @@ async function loadAircraft() { const r = await overlayFetch(`${API}/api/aircraft?bbox=${currentBBox()}${dvrQs()}`); const pts = await r.json(); if (req !== overlayReq.ac) return; - acGroup = renderPoints(acGroup, Array.isArray(pts) ? pts : [], p => acColor(p), true, 'ac'); + lastAircraft = Array.isArray(pts) ? pts : []; + acGroup = renderPoints(acGroup, lastAircraft, p => acColor(p), true, 'ac'); document.getElementById('lp-ac-count').textContent = (pts.length || 0).toLocaleString(); addExtraAttrib('ADSB.lol ODbL'); addExtraAttrib('Photo © planespotters.net'); @@ -3335,6 +3426,7 @@ async function toggleVessels() { await loadVessels(); } else { vesselsGroup = dropLayer(vesselsGroup); + lastVessels = []; clearTimeout(vesselRefollowTimer); } } @@ -3369,7 +3461,8 @@ async function loadVessels() { const r = await overlayFetch(`${API}/api/vessels?bbox=${bb}${srcQs}${dvrQs()}`); const pts = await r.json(); if (req !== overlayReq.vessels) return; - vesselsGroup = renderPoints(vesselsGroup, Array.isArray(pts) ? pts : [], p => { + lastVessels = Array.isArray(pts) ? pts : []; + vesselsGroup = renderPoints(vesselsGroup, lastVessels, p => { const extra = p.extra || {}; if (extra.role === 'military') return '#f472b6'; if (extra.role === 'government') return '#facc15'; @@ -3411,6 +3504,163 @@ async function loadStorms() { } } +/* ── Place dossier (“What’s here?”) — Nominatim + already-loaded overlays ── */ +const PLACE_PAD_KM = 5; +function haversineKm(aLat, aLon, bLat, bLon) { + const toRad = (d) => d * Math.PI / 180; + const dLat = toRad(bLat - aLat), dLon = toRad(bLon - aLon); + const a = Math.sin(dLat / 2) ** 2 + + Math.cos(toRad(aLat)) * Math.cos(toRad(bLat)) * Math.sin(dLon / 2) ** 2; + return 2 * 6371 * Math.asin(Math.min(1, Math.sqrt(a))); +} +function placePt(p) { + const lat = p.lat ?? p.latitude; + const lon = p.lon ?? p.longitude; + if (lat == null || lon == null) return null; + return { lat: Number(lat), lon: Number(lon) }; +} +function nearbyFromPoints(rows, origin, kind, labelFn) { + const out = []; + (rows || []).forEach((p) => { + const pt = placePt(p); + if (!pt) return; + const km = haversineKm(origin.lat, origin.lng, pt.lat, pt.lon); + if (km <= PLACE_PAD_KM) out.push({ kind, km, label: labelFn(p), lat: pt.lat, lon: pt.lon }); + }); + return out; +} +function alertCentroid(f) { + const g = f && f.geometry; + if (!g) return null; + let c = g.coordinates; + if (g.type === 'Point' && Array.isArray(c)) return { lat: c[1], lon: c[0] }; + while (Array.isArray(c) && Array.isArray(c[0])) c = c[0]; + if (Array.isArray(c) && typeof c[0] === 'number') return { lat: c[1], lon: c[0] }; + return null; +} +function nearbyFromAlerts(feats, origin) { + const out = []; + (feats || []).forEach((f) => { + const p = f.properties || {}; + const label = p.event || p.headline || 'Alert'; + const pt = alertCentroid(f); + if (!pt) return; + const km = haversineKm(origin.lat, origin.lng, pt.lat, pt.lon); + if (km <= PLACE_PAD_KM) out.push({ kind: 'alert', km, label, lat: pt.lat, lon: pt.lon }); + }); + return out; +} +function collectNearby(origin) { + const items = [ + ...nearbyFromPoints(lastCams, origin, 'camera', (p) => p.location_name || 'Camera'), + ...nearbyFromPoints(lastAircraft, origin, 'aircraft', (p) => p.label || (p.extra || {}).hex || 'Aircraft'), + ...nearbyFromPoints(lastVessels, origin, 'vessel', (p) => p.label || 'Vessel'), + ...nearbyFromPoints(lastFires, origin, 'fire', () => 'FIRMS hotspot'), + ...nearbyFromAlerts(lastAlerts, origin), + ]; + items.sort((a, b) => a.km - b.km); + return items; +} +function renderNearby(origin) { + const box = document.getElementById('pd-nearby'); + if (!box) return; + const items = collectNearby(origin); + if (!items.length) { + box.innerHTML = '
No loaded cameras, aircraft, vessels, fires, or alerts within 5 km.
'; + return; + } + const shown = items.slice(0, 24); + const more = items.length - shown.length; + box.innerHTML = shown.map((it) => { + const km = it.km < 1 ? `${Math.round(it.km * 1000)} m` : `${it.km.toFixed(1)} km`; + return ``; + }).join('') + (more > 0 ? `
+ ${more} more
` : ''); + box.querySelectorAll('.pd-item').forEach((btn) => { + btn.addEventListener('click', () => { + const lat = Number(btn.dataset.lat), lon = Number(btn.dataset.lon); + if (!map || Number.isNaN(lat) || Number.isNaN(lon)) return; + map.setView([lat, lon], Math.max(map.getZoom(), 10)); + }); + }); +} +function closePlaceDossier() { + const panel = document.getElementById('place-dossier'); + if (panel) { + panel.classList.remove('open'); + panel.setAttribute('aria-hidden', 'true'); + } + if (placeMarker && map) { map.removeLayer(placeMarker); placeMarker = null; } +} +function bindPlaceLongPress(m) { + const el = m.getContainer(); + const clear = () => { + if (placeLongPress) { clearTimeout(placeLongPress.timer); placeLongPress = null; } + }; + el.addEventListener('touchstart', (ev) => { + if (ev.touches.length !== 1) { clear(); return; } + const t = ev.touches[0]; + placeLongPress = { + x: t.clientX, y: t.clientY, + timer: setTimeout(() => { + const start = placeLongPress; + placeLongPress = null; + if (!start || gfDrawOn) return; + const latlng = m.mouseEventToLatLng({ clientX: start.x, clientY: start.y }); + openPlaceDossier(latlng); + }, 550), + }; + }, { passive: true }); + el.addEventListener('touchmove', (ev) => { + if (!placeLongPress) return; + const t = ev.touches[0]; + if (Math.hypot(t.clientX - placeLongPress.x, t.clientY - placeLongPress.y) > 14) clear(); + }, { passive: true }); + el.addEventListener('touchend', clear); + el.addEventListener('touchcancel', clear); + el.addEventListener('contextmenu', (ev) => ev.preventDefault()); +} +async function openPlaceDossier(latlng) { + if (!latlng || !map) return; + const panel = document.getElementById('place-dossier'); + const status = document.getElementById('pd-status'); + const coords = document.getElementById('pd-coords'); + const nameEl = document.getElementById('pd-name'); + const addrEl = document.getElementById('pd-addr'); + if (!panel) return; + panel.classList.add('open'); + panel.setAttribute('aria-hidden', 'false'); + const lat = latlng.lat, lon = latlng.lng; + if (coords) coords.textContent = `${lat.toFixed(5)}, ${lon.toFixed(5)}`; + if (nameEl) nameEl.textContent = ''; + if (addrEl) addrEl.textContent = ''; + if (status) { status.classList.remove('err'); status.textContent = 'Looking up place…'; } + if (placeMarker) map.removeLayer(placeMarker); + placeMarker = L.circleMarker([lat, lon], { + radius: 7, color: '#35e0ff', weight: 2, fillColor: '#35e0ff', fillOpacity: 0.25, + pane: 'markerPane', + }).addTo(map); + renderNearby(latlng); + const req = ++placeReq; + try { + const r = await fetch(`${API}/api/place?lat=${encodeURIComponent(lat)}&lon=${encodeURIComponent(lon)}`); + if (req !== placeReq) return; + if (!r.ok) throw new Error(`place ${r.status}`); + const d = await r.json(); + if (req !== placeReq) return; + if (nameEl) nameEl.textContent = d.name || d.display_name || 'Unknown place'; + if (addrEl) addrEl.textContent = d.display_name && d.name && d.display_name !== d.name + ? d.display_name : ''; + if (status) status.textContent = d.display_name ? 'Nominatim · OSM' : 'No reverse geocode for this point'; + const closeBtn = document.getElementById('pd-close'); + if (closeBtn) closeBtn.focus(); + } catch (e) { + if (req !== placeReq) return; + if (status) { status.classList.add('err'); status.textContent = 'Place lookup failed — nearby list is still from loaded overlays.'; } + } +} + /* ═══════════════ INITIAL LOAD ═══════════════ */ initNav(); initSettings(); diff --git a/docker-compose.yml b/docker-compose.yml index 76d0431..01abd37 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -138,6 +138,8 @@ services: FIRMS_DATASETS: ${FIRMS_DATASETS:-VIIRS_NOAA20_NRT,VIIRS_NOAA21_NRT} FIRMS_BBOX: ${FIRMS_BBOX:--180,-60,180,75} OSINT_USER_AGENT: ${OSINT_USER_AGENT:-osint-dashboard/1.0 (self-hosted; lancewalters94@gmail.com)} + NOMINATIM_URL: ${NOMINATIM_URL:-https://nominatim.openstreetmap.org} + NOMINATIM_MIN_INTERVAL: ${NOMINATIM_MIN_INTERVAL:-1.0} AISSTREAM_API_KEY: ${AISSTREAM_API_KEY:-} AISSTREAM_BBOX: ${AISSTREAM_BBOX:-24,-125,50,-66} AISSTREAM_IN_APP: ${AISSTREAM_IN_APP:-1} diff --git a/tests/test_api_place.py b/tests/test_api_place.py new file mode 100644 index 0000000..52e15ad --- /dev/null +++ b/tests/test_api_place.py @@ -0,0 +1,127 @@ +"""GET /api/place — Nominatim reverse proxy (60s cache, 500 keys, 1 req/s).""" + +from __future__ import annotations + +import asyncio + +import httpx +import pytest + +from main import app +from place import cache_key, place_cache, slim_place + +BASE = "http://test" + +SAMPLE = { + "display_name": "Raleigh, Wake County, North Carolina, United States", + "name": "Raleigh", + "osm_type": "relation", + "osm_id": 123, + "address": { + "city": "Raleigh", + "state": "North Carolina", + "country": "United States", + "country_code": "us", + "tourism": "ignore-me", + }, +} + + +class _FakeResp: + def __init__(self, payload, status=200): + self._payload = payload + self.status_code = status + + def raise_for_status(self): + if self.status_code >= 400: + req = httpx.Request("GET", "https://nominatim.openstreetmap.org/reverse") + raise httpx.HTTPStatusError( + "upstream", request=req, + response=httpx.Response(self.status_code, request=req), + ) + + def json(self): + return self._payload + + +class _FakeNominatim: + calls: list[dict] = [] + + def __init__(self, *args, **kwargs): + pass + + async def __aenter__(self): + return self + + async def __aexit__(self, *args): + return False + + async def get(self, url, params=None, headers=None): + _FakeNominatim.calls.append({"url": url, "params": params, "headers": headers}) + return _FakeResp(SAMPLE) + + +def _nominatim_client(**kwargs): + return _FakeNominatim() + + +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) + + +@pytest.fixture(autouse=True) +def _reset_place(monkeypatch): + place_cache.clear() + _FakeNominatim.calls = [] + monkeypatch.setattr("place._http_client", _nominatim_client) + monkeypatch.setattr("place.NOMINATIM_MIN_INTERVAL", 0.0) + monkeypatch.setattr("place._last_req", 0.0) + yield + place_cache.clear() + + +def test_slim_place_keeps_address_subset(): + body = slim_place(35.78, -78.64, SAMPLE) + assert body["display_name"].startswith("Raleigh") + assert body["name"] == "Raleigh" + assert body["address"]["city"] == "Raleigh" + assert "tourism" not in body["address"] + assert body["attribution"].startswith("© OpenStreetMap") + + +def test_cache_key_quantizes_to_4_decimals(): + assert cache_key(35.77961, -78.63821) == cache_key(35.77964, -78.63819) + + +def test_place_requires_lat_lon(): + resp = asyncio.run(_get("/api/place")) + assert resp.status_code == 422 + + +def test_place_rejects_out_of_range(): + assert asyncio.run(_get("/api/place?lat=99&lon=0")).status_code == 422 + assert asyncio.run(_get("/api/place?lat=0&lon=200")).status_code == 422 + + +def test_place_reverse_and_cache(): + r1 = asyncio.run(_get("/api/place?lat=35.7796&lon=-78.6382")) + assert r1.status_code == 200 + body = r1.json() + assert body["display_name"].startswith("Raleigh") + assert body["lat"] == pytest.approx(35.7796, abs=0.001) + assert "max-age=60" in (r1.headers.get("cache-control") or "").lower() + assert len(_FakeNominatim.calls) == 1 + ua = _FakeNominatim.calls[0]["headers"]["User-Agent"] + assert "osint-dashboard" in ua.lower() or "@" in ua + r2 = asyncio.run(_get("/api/place?lat=35.77961&lon=-78.63821")) + assert r2.status_code == 200 + assert len(_FakeNominatim.calls) == 1 # cache hit, same 4-decimal key + + +def test_place_cache_cap_500(): + from cachetools import TTLCache + assert isinstance(place_cache, TTLCache) + assert place_cache.maxsize == 500 + assert place_cache.ttl == 60 diff --git a/tests/test_place_dossier_frontend.py b/tests/test_place_dossier_frontend.py new file mode 100644 index 0000000..6fc1fd8 --- /dev/null +++ b/tests/test_place_dossier_frontend.py @@ -0,0 +1,59 @@ +"""Right-click place dossier HUD contract.""" + +from __future__ import annotations + +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +HTML = (ROOT / "app/static/index.html").read_text() + + +def test_place_dossier_panel_markup(): + assert 'id="place-dossier"' in HTML + assert "What’s here?" in HTML or "What's here?" in HTML + assert 'id="pd-nearby"' in HTML + assert 'id="pd-close"' in HTML + assert 'role="dialog"' in HTML + + +def test_place_dossier_uses_backend_nominatim_proxy(): + js = HTML.split("async function openPlaceDossier", 1)[1].split( + "/* ═══════════════ INITIAL LOAD", 1 + )[0] + assert "/api/place?lat=" in js + assert "nominatim.openstreetmap.org" not in js + assert "/api/aircraft" not in js + assert "/api/vessels" not in js + assert "/api/cameras" not in js + assert "/api/fires" not in js + assert "/api/weather-alerts" not in js + assert "/api/infrastructure" not in js + + +def test_place_dossier_scans_loaded_overlays_5km(): + assert "const PLACE_PAD_KM = 5" in HTML + assert "function collectNearby" in HTML + assert "lastCams" in HTML + assert "lastAircraft" in HTML + assert "lastVessels" in HTML + assert "lastFires" in HTML + assert "lastAlerts" in HTML + assert "function haversineKm" in HTML + + +def test_place_dossier_right_click_and_long_press(): + assert "map.on('contextmenu'" in HTML + assert "function bindPlaceLongPress" in HTML + assert "function closePlaceDossier" in HTML + assert "Escape" in HTML.split("function initMap", 1)[1][:8000] or "Escape" in HTML.split( + "bindPlaceLongPress(map)", 1 + )[0][-500:] + + +def test_place_dossier_mobile_is_bottom_sheet(): + mobile = HTML.split("@media (max-width: 820px)")[1].split( + "@media (prefers-reduced-motion" + )[0] + assert "#place-dossier" in mobile + assert "bottom: 56px" in mobile + assert "max-height: 36vh" in mobile From a9ca98e79107511ef5d8ff6736f19b22a41e0915 Mon Sep 17 00:00:00 2001 From: Sirius DevOps Date: Mon, 31 Aug 2026 21:34:50 -0400 Subject: [PATCH 45/79] feat(cameras): UDOT IBI 511 parser -> cameras table Add parse_udot_ibi_page + scrape_udot_ibi for the UDOT IBI 511 traffic camera feed (prod-ut.ibi511.com, no key). DataTables endpoint is POST form-encoded and caps at 100 rows/page regardless of `length`; page walk uses recordsTotal with a UDOT_IBI_MAX_PAGES (default 40) runaway cap. Skip images[0].blocked/disabled, parse WKT POINT(lng lat) from latLng.geography.wellKnownText, drop outside the Utah bbox (lat 36.9-42.1, lon -114.2--108.9). discovery_source=udot, stable source_url == snapshot_url == /map/Cctv/{id} (never scrape frames), url_hash dedupe, OSINT_USER_AGENT + X-Requested-With header. Unit tests: WKT lng/lat order, blocked/disabled skip, bbox drop, malformed payload, missing WKT. --- app/camera_config.py | 12 ++++ app/camera_scraper.py | 136 ++++++++++++++++++++++++++++++++++++++ tests/test_live_layers.py | 79 +++++++++++++++++++++- 3 files changed, 226 insertions(+), 1 deletion(-) diff --git a/app/camera_config.py b/app/camera_config.py index fd12ab6..b5a95f1 100644 --- a/app/camera_config.py +++ b/app/camera_config.py @@ -55,3 +55,15 @@ SNAPSHOT_TIMEOUT = float(os.getenv("SNAPSHOT_TIMEOUT", "8.0")) # NATS subject cameras are published on (consumed by the shared ingester). CAMERA_NATS_SUBJECT = os.getenv("CAMERA_NATS_SUBJECT", "events.camera") + + +# ── UDOT IBI 511 traffic cameras ────────────────────────────────────────── +# DataTables endpoint (POST form-encoded; server caps at 100 rows/page no +# matter what `length` is sent). No API key. Snapshot stills live at a stable +# /map/Cctv/{id} URL — same URL always serves the latest frame, so we store +# the URL and never scrape every frame ourselves. +UDOT_IBI_URL = "https://prod-ut.ibi511.com/List/GetData/Cameras" +UDOT_IBI_BASE = "https://prod-ut.ibi511.com" +UDOT_IBI_PAGE_SIZE = 100 +# Safety cap on pages per cycle so a runaway recordsTotal cannot fan out. +UDOT_IBI_MAX_PAGES = int(os.getenv("UDOT_IBI_MAX_PAGES", "40")) diff --git a/app/camera_scraper.py b/app/camera_scraper.py index ad5dc91..6df326e 100644 --- a/app/camera_scraper.py +++ b/app/camera_scraper.py @@ -37,6 +37,7 @@ from camera_config import ( CAMERA_SOURCE_URLS, CAMERA_REQUEST_DELAY, CAMERA_MAX_PER_SOURCE, NOMINATIM_URL, NOMINATIM_MIN_INTERVAL, USER_AGENT, SNAPSHOT_CACHE_DIR, SNAPSHOT_TTL_SECONDS, SNAPSHOT_TIMEOUT, + UDOT_IBI_URL, UDOT_IBI_BASE, UDOT_IBI_PAGE_SIZE, UDOT_IBI_MAX_PAGES, ) from camera_models import cameras from database import async_session @@ -114,6 +115,15 @@ class RateLimitedClient: self._last[host] = time.monotonic() return await self.client.get(url, **kw) + async def post(self, url: str, **kw) -> httpx.Response: + host = urlparse(url).netloc + now = time.monotonic() + wait = self._last.get(host, 0.0) + self._delay - now + if wait > 0: + await asyncio.sleep(wait) + self._last[host] = time.monotonic() + return await self.client.post(url, **kw) + async def aclose(self): await self.client.aclose() @@ -379,6 +389,83 @@ def parse_caltrans_json(text: str, source_name: str) -> list[dict]: return out +# ── UDOT IBI 511 ────────────────────────────────────────────────────────── +# Utah bbox (lat 36.9–42.1, lon -114.2–-108.9). WKT is `POINT (lng lat)`. +_UDOT_IBI_MIN_LAT, _UDOT_IBI_MAX_LAT = 36.9, 42.1 +_UDOT_IBI_MIN_LON, _UDOT_IBI_MAX_LON = -114.2, -108.9 +_UDOT_WKT_POINT_RE = re.compile( + r"POINT\s*\(\s*(-?\d+(?:\.\d+)?)\s+(-?\d+(?:\.\d+)?)\s*\)", re.I, +) + + +def parse_udot_ibi_page(text: str, source_name: str = "udot") -> list[dict]: + """Parse one UDOT IBI 511 DataTables camera page (`{"data": [...]}`). + + Skips rows whose first image is `blocked` or `disabled`, and drops any + point outside the Utah bbox. The `/map/Cctv/{id}` URL is a stable identity + (always serves the latest frame), so it is stored as both source_url and + snapshot_url — we never scrape frames ourselves. + """ + try: + payload = json.loads(text) + except (json.JSONDecodeError, ValueError): + return [] + rows = payload.get("data") if isinstance(payload, dict) else None + if not isinstance(rows, list): + return [] + out: list[dict] = [] + for row in rows: + if not isinstance(row, dict): + continue + cam_id = row.get("id") + images = row.get("images") or [] + if cam_id is None or not images: + continue + img = images[0] or {} + if img.get("blocked") or img.get("disabled"): + continue + lon = lat = None + try: + wkt = (row.get("latLng") or {}).get("geography") or {} + wkt = wkt.get("wellKnownText") or "" + m = _UDOT_WKT_POINT_RE.match(str(wkt).strip()) + if m: + lon, lat = float(m.group(1)), float(m.group(2)) + except (AttributeError, TypeError, ValueError): + lon = lat = None + if lat is None or lon is None: + continue + if not (_UDOT_IBI_MIN_LAT <= lat <= _UDOT_IBI_MAX_LAT + and _UDOT_IBI_MIN_LON <= lon <= _UDOT_IBI_MAX_LON): + continue + snap = f"{UDOT_IBI_BASE}/map/Cctv/{cam_id}" + roadway, direction, location = ( + row.get("roadway"), row.get("direction"), row.get("location"), + ) + name = ", ".join( + str(b) for b in (roadway, direction, location) + if b and str(b).strip() and str(b).strip().lower() != "unknown" + ) or None + out.append({ + "source_url": snap, + "snapshot_url": snap, + "discovery_source": source_name, + "location_lat": lat, + "location_lon": lon, + "location_name": name, + "vendor": "UDOT", + "device_type": "http", + "raw": { + "udot_id": cam_id, + "agency": row.get("source"), + "source_id": row.get("sourceId"), + "roadway": roadway, + "direction": direction, + }, + }) + return out + + def parse_live_streams_geojson(text: str, source_name: str) -> list[dict]: """Parse willytop8/Live-Environment-Streams GeoJSON. @@ -549,6 +636,54 @@ async def scrape_source(client: RateLimitedClient, geo: Geocoder, return out +# ── UDOT IBI 511 paginated fetcher ──────────────────────────────────────── + +async def scrape_udot_ibi(client: RateLimitedClient) -> list[dict]: + """Page through the UDOT IBI 511 DataTables endpoint and normalize. + + POSTs `start`/`length` form fields (server caps at 100 rows/page), walking + pages until `recordsTotal` is exhausted or UDOT_IBI_MAX_PAGES is hit. + """ + out: list[dict] = [] + seen: set[str] = set() + start = 0 + for _ in range(UDOT_IBI_MAX_PAGES): + try: + resp = await client.post( + UDOT_IBI_URL, + data={ + "start": str(start), + "length": str(UDOT_IBI_PAGE_SIZE), + "lang": "en-US", + }, + headers={"X-Requested-With": "XMLHttpRequest"}, + ) + resp.raise_for_status() + body = resp.text + except Exception: # noqa: BLE001 + logger.exception("failed to fetch UDOT IBI page start=%d", start) + break + try: + payload = json.loads(body) + except ValueError: + logger.warning("UDOT IBI non-JSON response at start=%d", start) + break + total = int(payload.get("recordsTotal") or 0) + rows = payload.get("data") or [] + if not isinstance(rows, list) or not rows: + break + for cam in parse_udot_ibi_page(body, "udot"): + if cam["source_url"] in seen: + continue + seen.add(cam["source_url"]) + out.append(cam) + if start + len(rows) >= total: + break + start += len(rows) + logger.info("UDOT IBI yielded %d cameras", len(out)) + return out + + # ── Persistence ──────────────────────────────────────────────────────────── async def upsert_cameras(cams: list[dict]) -> int: @@ -600,6 +735,7 @@ async def run_cycle() -> int: try: results = await asyncio.gather( *(scrape_source(client, geo, s) for s in CAMERA_SOURCE_URLS), + scrape_udot_ibi(client), return_exceptions=True, ) all_cams: list[dict] = [] diff --git a/tests/test_live_layers.py b/tests/test_live_layers.py index ae0f68e..c32aa7d 100644 --- a/tests/test_live_layers.py +++ b/tests/test_live_layers.py @@ -25,7 +25,7 @@ from live_layers import ( _wfigs_params, ) -from camera_scraper import parse_caltrans_json +from camera_scraper import parse_caltrans_json, parse_udot_ibi_page def test_parse_bbox_and_radius_clamps_to_150_nm(): @@ -257,6 +257,83 @@ def test_parse_caltrans_skips_oos_and_maps_jpeg_hls(): assert "rtsp://" not in cam["snapshot_url"].lower() +# ── UDOT IBI 511 parser ────────────────────────────────────────────────── + +def _udot_row(cam_id, lng, lat, **img_overrides): + img = { + "id": cam_id, "cameraSiteId": cam_id, + "imageUrl": f"/map/Cctv/{cam_id}", "disabled": False, "blocked": False, + } + img.update(img_overrides) + return { + "id": cam_id, "sourceId": "102771", "source": "ADX", + "roadway": "Unknown", "direction": "Unknown", + "location": "Freedom Blvd / 200 W @ 1100 N, PVO", + "latLng": {"geography": { + "coordinateSystemId": 4326, + "wellKnownText": f"POINT ({lng} {lat})"}}, + "images": [img], + } + + +def _udot_page(rows): + import json + return json.dumps({"draw": 0, "recordsTotal": len(rows), + "recordsFiltered": len(rows), "data": rows}) + + +def test_parse_udot_wkt_maps_lng_lat(): + cams = parse_udot_ibi_page(_udot_page([_udot_row(112731, -111.66204, 40.24863)])) + assert len(cams) == 1 + cam = cams[0] + # WKT is `POINT (lng lat)` — order must not be swapped. + assert cam["location_lat"] == 40.24863 + assert cam["location_lon"] == -111.66204 + assert cam["discovery_source"] == "udot" + assert cam["vendor"] == "UDOT" + assert cam["source_url"] == "https://prod-ut.ibi511.com/map/Cctv/112731" + assert cam["snapshot_url"] == cam["source_url"] + assert "rtsp://" not in cam["source_url"].lower() + assert cam["raw"]["udot_id"] == 112731 + + +def test_parse_udot_skips_blocked_and_disabled(): + rows = [ + _udot_row(1, -111.0, 40.0), + _udot_row(2, -111.1, 40.1, blocked=True), + _udot_row(3, -111.2, 40.2, disabled=True), + ] + rows.append(_udot_row(4, -111.3, 40.3)) + rows[3]["images"] = [] # no images → drop + cams = parse_udot_ibi_page(_udot_page(rows)) + assert [c["raw"]["udot_id"] for c in cams] == [1] + + +def test_parse_udot_drops_out_of_bbox(): + rows = [ + _udot_row(1, -111.0, 40.0), # inside Utah + _udot_row(2, -100.0, 40.0), # east of -108.9 + _udot_row(3, -120.0, 40.0), # west of -114.2 + _udot_row(4, -111.0, 44.0), # north of 42.1 + _udot_row(5, -111.0, 30.0), # south of 36.9 + ] + cams = parse_udot_ibi_page(_udot_page(rows)) + assert [c["raw"]["udot_id"] for c in cams] == [1] + + +def test_parse_udot_bad_payload_returns_empty(): + import json + assert parse_udot_ibi_page("not json") == [] + assert parse_udot_ibi_page(json.dumps({"data": None})) == [] + assert parse_udot_ibi_page(json.dumps({"data": "nope"})) == [] + + +def test_parse_udot_missing_wkt_skipped(): + row = _udot_row(1, -111.0, 40.0) + row["latLng"] = {} + assert parse_udot_ibi_page(_udot_page([row])) == [] + + def test_quantize_bbox_stable_under_jitter(): a = quantize_bbox(*parse_bbox("-78.7912,35.7711,-78.6101,35.9102")) b = quantize_bbox(*parse_bbox("-78.7900,35.7700,-78.6110,35.9090")) From 2ec210aaa42972ab87684d80a17903a8d4e32867 Mon Sep 17 00:00:00 2001 From: Sirius DevOps Date: Mon, 31 Aug 2026 21:37:10 -0400 Subject: [PATCH 46/79] feat(map): Conflicts layer toggle from /api/conflicts Default-off LAYERS row paints L.circleMarker theatres colored by severity (war/high/elevated). Popup shows label, description, and eventCount. Catalog is fetched once (not on moveend). A 404 hides the toggle. Null lat/lon rows are skipped so they never pin at 0,0. --- app/static/index.html | 104 ++++++++++++++++++++++++++++++- tests/test_conflicts_frontend.py | 66 ++++++++++++++++++++ 2 files changed, 169 insertions(+), 1 deletion(-) create mode 100644 tests/test_conflicts_frontend.py diff --git a/app/static/index.html b/app/static/index.html index 02122d1..9298d03 100644 --- a/app/static/index.html +++ b/app/static/index.html @@ -341,6 +341,7 @@ .lp-dot.wfigs { background: #ef4444; box-shadow: 0 0 7px #ef4444; } .lp-dot.trains { background: #c084fc; box-shadow: 0 0 7px #c084fc; } .lp-dot.storms { background: #f472b6; box-shadow: 0 0 7px #f472b6; } + .lp-dot.conflicts { background: #ff2a6d; box-shadow: 0 0 7px #ff2a6d; } .lp-count { font-family: 'Share Tech Mono', monospace; font-size: 0.7rem; color: var(--cyan); } .lp-sub { display: flex; justify-content: space-between; align-items: center; gap: 0.5rem; } .lp-opacity { display: flex; align-items: center; gap: 0.4rem; font-size: 0.62rem; color: var(--muted); text-transform: uppercase; letter-spacing: 0.05em; } @@ -396,6 +397,7 @@ .blip-pop { min-width: 200px; max-width: 260px; } .blip-pop .blip-src { font-family: 'Share Tech Mono', monospace; font-size: 0.62rem; color: var(--cyan); text-transform: uppercase; letter-spacing: 0.08em; } .blip-pop .blip-time { font-size: 0.7rem; color: var(--muted); font-family: 'Share Tech Mono', monospace; margin: 0.2rem 0 0.3rem; } + .blip-pop .blip-desc { font-size: 0.72rem; color: var(--text); line-height: 1.35; margin-top: 0.15rem; } /* ── Sub-views (News / Events / Alerts / ... ) ── */ .subview { @@ -922,6 +924,13 @@ 0
+
+
+ + 0 +
+
Curated theatres · color by severity · news counts, not LiveUAMap.
+

Fire heat intensity

@@ -1923,7 +1932,8 @@ let acGroup = null, acOn = true; let trainsGroup = null, trainsOn = true; let vesselsGroup = null, vesselsOn = false; let stormsGroup = null, stormsOn = true; -let overlayReq = {ac:0, trains:0, vessels:0, alerts:0, perim:0, incidents:0, storms:0, sar:0}; +let conflictsGroup = null, conflictsOn = false, conflictsCache = null; +let overlayReq = {ac:0, trains:0, vessels:0, alerts:0, perim:0, incidents:0, storms:0, sar:0, conflicts:0}; let moveDebounce = null; let overlayAbort = null; let lastCell = ''; @@ -2159,8 +2169,10 @@ async function initMap() { trainsOn = document.getElementById('lp-trains-on').checked; vesselsOn = document.getElementById('lp-vessels-on').checked; stormsOn = document.getElementById('lp-storms-on').checked; + conflictsOn = document.getElementById('lp-conflicts-on').checked; connectLiveWs(); loadChokepoints(); + probeConflicts(); requestAnimationFrame(() => { if (firesOn) loadFires(); setTimeout(() => { @@ -3411,6 +3423,96 @@ async function loadStorms() { } } +function conflictSeverityColor(sev) { + const s = String(sev || '').toLowerCase(); + if (s === 'war') return '#ff2a6d'; + if (s === 'high') return '#fb923c'; + if (s === 'elevated') return '#facc15'; + return '#35e0ff'; +} +function hideConflictsToggle() { + const row = document.getElementById('conflicts-layer'); + if (row) row.hidden = true; + const cb = document.getElementById('lp-conflicts-on'); + if (cb) cb.checked = false; + conflictsOn = false; + conflictsCache = null; + conflictsGroup = dropLayer(conflictsGroup); +} +function paintConflicts() { + if (!map || !conflictsOn) return; + const zones = (conflictsCache && Array.isArray(conflictsCache.zones)) ? conflictsCache.zones : []; + conflictsGroup = dropLayer(conflictsGroup); + const markers = []; + for (const z of zones) { + if (z.lat == null || z.lon == null) continue; + const lat = Number(z.lat), lon = Number(z.lon); + if (!Number.isFinite(lat) || !Number.isFinite(lon)) continue; + const col = conflictSeverityColor(z.severity); + const sev = String(z.severity || '').toLowerCase(); + const radius = sev === 'war' ? 10 : sev === 'high' ? 8 : 7; + const m = L.circleMarker([lat, lon], { + radius, + color: col, + fillColor: col, + fillOpacity: 0.28, + weight: 2, + className: 'conflict-zone', + }); + const n = Number(z.eventCount); + const count = Number.isFinite(n) ? n : 0; + m.bindPopup( + `
` + + `
${esc(z.severity || '')} · ${esc(count)} events
` + + `${esc(z.label || '')}` + + `
${esc(z.description || '')}
` + + `
` + ); + markers.push(m); + } + conflictsGroup = L.layerGroup(markers).addTo(map); + const countEl = document.getElementById('lp-conflicts-count'); + if (countEl) countEl.textContent = markers.length.toLocaleString(); + addExtraAttrib('Curated OSINT conflict catalog'); +} +async function probeConflicts() { + await loadConflicts(false); +} +async function toggleConflicts() { + const cb = document.getElementById('lp-conflicts-on'); + conflictsOn = !!(cb && cb.checked); + if (conflictsOn) await loadConflicts(true); + else conflictsGroup = dropLayer(conflictsGroup); +} +async function loadConflicts(paint) { + const shouldPaint = paint === true || conflictsOn; + const req = ++overlayReq.conflicts; + const countEl = document.getElementById('lp-conflicts-count'); + try { + if (!conflictsCache) { + // Own fetch — catalog is viewport-independent; overlayAbort on + // moveend must not cancel this (and we never refetch on pan). + const r = await fetch(`${API}/api/conflicts`); + if (req !== overlayReq.conflicts) return; + if (r.status === 404) { + hideConflictsToggle(); + return; + } + if (!r.ok) throw new Error('conflicts ' + r.status); + const body = await r.json(); + if (req !== overlayReq.conflicts) return; + conflictsCache = body && typeof body === 'object' ? body : { zones: [] }; + } + const zones = Array.isArray(conflictsCache.zones) ? conflictsCache.zones : []; + if (countEl) countEl.textContent = zones.length.toLocaleString(); + if (shouldPaint) paintConflicts(); + } catch (e) { + if (req !== overlayReq.conflicts) return; + console.error('Conflicts load failed', e); + if (countEl) countEl.textContent = 'err'; + } +} + /* ═══════════════ INITIAL LOAD ═══════════════ */ initNav(); initSettings(); diff --git a/tests/test_conflicts_frontend.py b/tests/test_conflicts_frontend.py new file mode 100644 index 0000000..058fd3b --- /dev/null +++ b/tests/test_conflicts_frontend.py @@ -0,0 +1,66 @@ +"""Conflicts Leaflet overlay: default-off toggle, catalog fetch, no jitter.""" + +from __future__ import annotations + +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +HTML = (ROOT / "app/static/index.html").read_text() + + +def _fn(name: str, until: str | None = None) -> str: + chunk = HTML.split(f"function {name}", 1)[1] + if until: + chunk = chunk.split(until, 1)[0] + return chunk + + +def test_conflicts_toggle_default_off(): + assert 'id="lp-conflicts-on"' in HTML + assert 'id="conflicts-layer"' in HTML + assert "> Conflicts<" in HTML or "> Conflicts", 1)[0] + assert "checked" not in on + + +def test_conflicts_fetches_catalog_not_liveuamap(): + js = _fn("loadConflicts", "/* ═══════════════ INITIAL LOAD") + assert "/api/conflicts" in js + assert "liveuamap.com" not in HTML.lower() + assert "Math.random" not in js + assert "jitter" not in js.lower() + + +def test_conflicts_not_refetched_on_moveend(): + refresh = HTML.split("function refreshLiveOverlays", 1)[1].split( + "function addExtraAttrib", 1 + )[0] + assert "loadConflicts" not in refresh + assert "probeConflicts" not in refresh + init = HTML.split("function initMap", 1)[1].split("function readMapPrefs", 1)[0] + assert "probeConflicts()" in init + assert "loadConflicts(true)" not in init + assert "paintConflicts()" not in init + + +def test_conflicts_hides_toggle_on_404(): + js = _fn("loadConflicts", "/* ═══════════════ INITIAL LOAD") + assert "r.status === 404" in js + assert "hideConflictsToggle()" in js + hide = _fn("hideConflictsToggle", "function paintConflicts") + assert "row.hidden = true" in hide + assert "lp-conflicts-on" in hide + + +def test_conflicts_popup_and_severity_colors(): + paint = _fn("paintConflicts", "async function probeConflicts") + assert "z.label" in paint + assert "z.description" in paint + assert "eventCount" in paint + assert "L.circleMarker" in paint + assert "z.lat == null || z.lon == null" in paint + assert "Number.isFinite(lat)" in paint + color = _fn("conflictSeverityColor", "function hideConflictsToggle") + assert "war" in color and "#ff2a6d" in color + assert "high" in color and "#fb923c" in color + assert "elevated" in color and "#facc15" in color From 41433be5740f04dda0e2d5ecaca95a166885f5f3 Mon Sep 17 00:00:00 2001 From: Sirius DevOps Date: Mon, 31 Aug 2026 21:37:32 -0400 Subject: [PATCH 47/79] feat(cameras): ODOT TripCheck parser -> cameras table Add parse_odot_json (Esri-style cctvinventory.js) next to parse_caltrans_json: JPEG snapshot_url, discovery_source=odot, Oregon bbox + filename guard, no RTSP. Wire dispatch + default CAMERA_SOURCE_URLS entry. Unit tests. --- app/camera_config.py | 2 ++ app/camera_scraper.py | 48 +++++++++++++++++++++++++++++++++++++++ tests/test_live_layers.py | 46 ++++++++++++++++++++++++++++++++++++- 3 files changed, 95 insertions(+), 1 deletion(-) diff --git a/app/camera_config.py b/app/camera_config.py index fd12ab6..72b64f7 100644 --- a/app/camera_config.py +++ b/app/camera_config.py @@ -25,6 +25,8 @@ _DEFAULT_SOURCE_URL = ",".join(( "https://raw.githubusercontent.com/willytop8/Live-Environment-Streams/main/streams.geojson", # Official Caltrans CWWP2 JPEG + HLS CCTV (districts 1–12). *CALTRANS_CCTV_URLS, + # Oregon DOT TripCheck public CCTV JPEG inventory (Esri JSON). + "https://www.tripcheck.com/Scripts/map/data/cctvinventory.js", )) CAMERA_SOURCE_URLS = [ u.strip() diff --git a/app/camera_scraper.py b/app/camera_scraper.py index ad5dc91..3989d90 100644 --- a/app/camera_scraper.py +++ b/app/camera_scraper.py @@ -25,6 +25,7 @@ import hashlib import ipaddress import json import logging +import math import re import time from datetime import datetime, timezone @@ -379,6 +380,51 @@ def parse_caltrans_json(text: str, source_name: str) -> list[dict]: return out +# Oregon DOT TripCheck inventory bounding box (approx state extent). +ODOT_BBOX = (41.9, 46.3, -124.6, -116.4) # lat_min, lat_max, lon_min, lon_max + + +def parse_odot_json(text: str, source_name: str) -> list[dict]: + """Parse Oregon DOT TripCheck cctvinventory Esri-style JSON. + + Store the JPEG still as snapshot_url (map thumbs); never RTSP. Keep only + rows with finite coordinates inside Oregon and a usable filename. + """ + try: + payload = json.loads(text) + except (json.JSONDecodeError, ValueError): + return [] + lat_min, lat_max, lon_min, lon_max = ODOT_BBOX + out: list[dict] = [] + for feat in payload.get("features") or []: + attrs = (feat or {}).get("attributes") or {} + filename = (attrs.get("filename") or "").strip() + if not filename: + continue + try: + lat = float(attrs.get("latitude")) + lon = float(attrs.get("longitude")) + except (TypeError, ValueError): + continue + if not (math.isfinite(lat) and math.isfinite(lon)): + continue + if not (lat_min <= lat <= lat_max and lon_min <= lon <= lon_max): + continue + jpeg = f"https://tripcheck.com/RoadCams/cams/{filename}" + title = (attrs.get("title") or "").strip() + out.append({ + "source_url": jpeg, + "snapshot_url": jpeg, + "discovery_source": "odot", + "location_lat": lat, + "location_lon": lon, + "location_name": title or None, + "vendor": "ODOT", + "device_type": "http", + }) + return out + + def parse_live_streams_geojson(text: str, source_name: str) -> list[dict]: """Parse willytop8/Live-Environment-Streams GeoJSON. @@ -490,6 +536,8 @@ async def scrape_source(client: RateLimitedClient, geo: Geocoder, body = resp.text if "cwwp2.dot.ca.gov" in src_url or "cctvStatus" in src_url: cams = parse_caltrans_json(body, name) + elif "cctvinventory" in src_url or "tripcheck.com" in src_url: + cams = parse_odot_json(body, name) elif ("getCameraDataByLoc" in src_url or ("json" in ctype and '"locs"' in body[:4000] and '"cams"' in body[:8000])): cams = parse_alertwest_json(body, name) diff --git a/tests/test_live_layers.py b/tests/test_live_layers.py index ae0f68e..e79c2de 100644 --- a/tests/test_live_layers.py +++ b/tests/test_live_layers.py @@ -25,7 +25,7 @@ from live_layers import ( _wfigs_params, ) -from camera_scraper import parse_caltrans_json +from camera_scraper import parse_caltrans_json, parse_odot_json def test_parse_bbox_and_radius_clamps_to_150_nm(): @@ -257,6 +257,50 @@ def test_parse_caltrans_skips_oos_and_maps_jpeg_hls(): assert "rtsp://" not in cam["snapshot_url"].lower() +def test_parse_odot_tripcheck_keeps_valid_skips_missing_and_oob(): + payload = """ + {"features":[ + {"attributes":{ + "cameraId":277,"filename":"AstoriaUS101_pid392.jpg", + "latitude":46.18785,"longitude":-123.85347, + "route":"US101 ","title":"US101 at Astoria" + }}, + {"attributes":{ + "cameraId":200,"filename":"","latitude":45.0,"longitude":-122.0, + "route":"I-5","title":"missing filename" + }}, + {"attributes":{ + "cameraId":300,"filename":"nocal_pid1.jpg", + "latitude":40.0,"longitude":-122.0, + "route":"US97","title":"out of bbox" + }}, + {"attributes":{ + "cameraId":400,"filename":"badcoord_pid2.jpg", + "latitude":null,"longitude":-122.0, + "route":"OR22","title":"null coord" + }} + ]} + """ + cams = parse_odot_json(payload, "www.tripcheck.com") + assert len(cams) == 1 + cam = cams[0] + assert cam["discovery_source"] == "odot" + assert cam["snapshot_url"] == ( + "https://tripcheck.com/RoadCams/cams/AstoriaUS101_pid392.jpg") + assert cam["source_url"] == cam["snapshot_url"] + assert cam["location_lat"] == 46.18785 + assert cam["location_lon"] == -123.85347 + assert "US101 at Astoria" in cam["location_name"] + assert cam["vendor"] == "ODOT" + assert cam["device_type"] == "http" + assert "rtsp://" not in cam["snapshot_url"].lower() + + +def test_parse_odot_tripcheck_handles_malformed(): + assert parse_odot_json("not json", "www.tripcheck.com") == [] + assert parse_odot_json('{"features":null}', "www.tripcheck.com") == [] + + def test_quantize_bbox_stable_under_jitter(): a = quantize_bbox(*parse_bbox("-78.7912,35.7711,-78.6101,35.9102")) b = quantize_bbox(*parse_bbox("-78.7900,35.7700,-78.6110,35.9090")) From 92dd9c5803fcff30de780d258403426d4b4da7be Mon Sep 17 00:00:00 2001 From: Sirius DevOps Date: Mon, 31 Aug 2026 21:41:00 -0400 Subject: [PATCH 48/79] feat(api): GET /api/stats HUD counters (counts only, never 500) --- app/live_layers.py | 9 +++++ app/main.py | 62 +++++++++++++++++++++++++++++ tests/test_api_stats.py | 87 +++++++++++++++++++++++++++++++++++++++++ 3 files changed, 158 insertions(+) create mode 100644 tests/test_api_stats.py diff --git a/app/live_layers.py b/app/live_layers.py index fa632b1..c79714b 100644 --- a/app/live_layers.py +++ b/app/live_layers.py @@ -97,6 +97,11 @@ _MAX_VESSELS = 6000 # Last ADS-B snapshot + WFIGS points for fire↔tanker correlation. aircraft_last_known: dict[str, dict] = {} fire_last_known: list[dict] = [] +# Last-known counts for the cheap GET /api/stats HUD counter. Updated by the +# upstream fetchers so the stats endpoint never does its own network/SQL fan-out +# for these layers; reads are O(1) in-process. +train_count: int = 0 +nws_alert_count: int = 0 def overlay_catalog() -> dict: @@ -966,6 +971,8 @@ async def fetch_trains(bbox: str | None, limit: int = DEFAULT_LIMIT) -> list[dic return transform_amtraker(await _get_json(AMTRAKER_TRAINS)) rows = await _ttl_get("amtraker:trains", 20.0, _load) + global train_count + train_count = len(rows) if bbox: minlon, minlat, maxlon, maxlat = parse_bbox(bbox) return filter_points_bbox(rows, minlon, minlat, maxlon, maxlat, limit) @@ -1119,6 +1126,8 @@ async def fetch_weather_alerts(area: str | None, bbox: str | None) -> dict: logger.warning("NWS alerts fetch failed: %s", exc) nws_ok = False nws_fc = {"features": []} + global nws_alert_count + nws_alert_count = len(nws_fc.get("features") or []) sbw_fc = await _ttl_get("iem:sbw", 45.0, _load_iem) features = [] for feat in nws_fc.get("features") or []: diff --git a/app/main.py b/app/main.py index 2d12e25..177e1c7 100644 --- a/app/main.py +++ b/app/main.py @@ -15,6 +15,7 @@ import asyncio import json import logging import re +import time from contextlib import asynccontextmanager from datetime import datetime, timedelta, timezone from decimal import Decimal @@ -272,6 +273,67 @@ def overlay_json(data, max_age: int) -> JSONResponse: return resp +# ── HUD counters ───────────────────────────────────────────────────────── + +# Cheap ~100 B–2 KB counts for the layer rail. Cached in-process so the HUD +# can poll every second without re-hitting SQL or upstream feeds. +_STATS_TTL = 20.0 +_stats_cache: dict[str, tuple[float, dict]] = {} + + +async def _stats_counts() -> dict: + """Fan out to in-memory last-known / cheap SQL counts. Never raises.""" + from live_layers import ( + aircraft_last_known, vessel_last_known, train_count, nws_alert_count, + ) + + counts: dict[str, int | str] = { + "aircraft": len(aircraft_last_known), + "vessels": len(vessel_last_known), + "trains": train_count, + "cameras": 0, + "fires": 0, + "quakes": 0, + "alerts": nws_alert_count, + } + + # SQL counts are best-effort: a down DB or missing table must not 500 the + # rail — the frontend still renders with zeros. + try: + from camera_models import cameras as cam_table + async with async_session() as session: + counts["cameras"] = int( + (await session.execute(select(func.count()).select_from(cam_table))).scalar() or 0 + ) + counts["fires"] = int( + (await session.execute(select(func.count()).select_from(fires))).scalar() or 0 + ) + counts["quakes"] = int( + (await session.execute( + select(func.count()).select_from(events).where( + events.c.source_type == "earthquake" + ) + )).scalar() or 0 + ) + except Exception as exc: # noqa: BLE001 + logger.warning("stats_db_failed", error=str(exc)) + + counts["timestamp"] = datetime.now(timezone.utc).isoformat().replace("+00:00", "Z") + return counts + + +@app.get("/api/stats") +async def api_stats(): + """Cheap HUD counters (counts only — no GeoJSON). Cached ~20 s.""" + now = time.monotonic() + cached = _stats_cache.get("stats") + if cached and now - cached[0] < _STATS_TTL: + return cached[1] + payload = await _stats_counts() + _stats_cache["stats"] = (now, payload) + return overlay_json(payload, 15) + + # ── Feed Sources ────────────────────────────────────────────────────────── @app.get("/api/sources", response_model=list[FeedSourceOut]) diff --git a/tests/test_api_stats.py b/tests/test_api_stats.py new file mode 100644 index 0000000..870965d --- /dev/null +++ b/tests/test_api_stats.py @@ -0,0 +1,87 @@ +"""GET /api/stats HUD counter contract (counts only, small, never 500).""" + +from __future__ import annotations + +import asyncio +import re +from datetime import timezone + +import httpx + +from main import app, _stats_counts + +BASE = "http://test" + +EXPECTED_KEYS = ("aircraft", "vessels", "trains", "cameras", + "fires", "quakes", "alerts", "timestamp") + + +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 test_stats_200_all_keys_present(): + resp = asyncio.run(_get("/api/stats")) + assert resp.status_code == 200 + body = resp.json() + for key in EXPECTED_KEYS: + assert key in body, f"missing key {key}" + assert "max-age" in (resp.headers.get("cache-control") or "").lower() + + +def test_stats_counters_are_ints(): + body = asyncio.run(_get("/api/stats")).json() + for key in EXPECTED_KEYS: + if key == "timestamp": + continue + assert isinstance(body[key], int), f"{key} is not an int: {body[key]!r}" + + +def test_stats_timestamp_is_iso8601_z(): + body = asyncio.run(_get("/api/stats")).json() + ts = body["timestamp"] + # ISO8601 with a trailing Z (we normalize +00:00 -> Z). + assert isinstance(ts, str) and ts.endswith("Z") + assert re.match(r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}", ts) + + +def test_stats_payload_is_tiny(): + resp = asyncio.run(_get("/api/stats")) + assert len(resp.content) < 2048, "stats payload must be counts-only, not GeoJSON" + + +def test_stats_counts_reflect_last_known(monkeypatch): + """aircraft/vessels/trains/alerts come from in-memory last-known state.""" + import live_layers + + monkeypatch.setattr(live_layers, "aircraft_last_known", {str(i): {} for i in range(7)}) + monkeypatch.setattr(live_layers, "vessel_last_known", {str(i): {} for i in range(3)}) + monkeypatch.setattr(live_layers, "train_count", 11) + monkeypatch.setattr(live_layers, "nws_alert_count", 5) + + # _stats_counts imports the dicts/counters inside the function from live_layers, + # so monkeypatching the module attributes is what it observes. + from main import _stats_counts as fn + + body = asyncio.run(fn()) + assert body["aircraft"] == 7 + assert body["vessels"] == 3 + assert body["trains"] == 11 + assert body["alerts"] == 5 + + +def test_stats_db_failure_degrades_to_zero(monkeypatch): + """A down DB yields zeros for the SQL-backed counters, never a 500.""" + # Make the session factory raise synchronously so the try/except in + # _stats_counts degrades the SQL counters to zero (no dangling coroutine). + def _raise(*args, **kwargs): + raise RuntimeError("db down") + + monkeypatch.setattr("main.async_session", _raise) + body = asyncio.run(_stats_counts()) + assert body["cameras"] == 0 + assert body["fires"] == 0 + assert body["quakes"] == 0 + assert isinstance(body["timestamp"], str) \ No newline at end of file From f61d5875231e06ab30aab2a4a3a691b12dcc4cf1 Mon Sep 17 00:00:00 2001 From: Sirius DevOps Date: Mon, 31 Aug 2026 21:41:59 -0400 Subject: [PATCH 49/79] feat(hud): layer counts, shortcuts, terminator, zoom-gated cams, SWPC Poll GET /api/stats ~30s for rail integers (404 falls back to overlay array lengths). Keyboard: ? cheat sheet, L layers, R reset, Esc closes panels; F/S left unbound. Cheap sun-position day/night overlay default off. Camera/HLS thumbs only at zoom >= 12. NOAA SWPC Kp chip in the status strip (browser-direct; hide on failure). --- app/static/index.html | 290 ++++++++++++++++++++++++++++++++++++--- tests/test_hud_osiris.py | 90 ++++++++++++ 2 files changed, 364 insertions(+), 16 deletions(-) create mode 100644 tests/test_hud_osiris.py diff --git a/app/static/index.html b/app/static/index.html index 02122d1..4fe4812 100644 --- a/app/static/index.html +++ b/app/static/index.html @@ -341,6 +341,10 @@ .lp-dot.wfigs { background: #ef4444; box-shadow: 0 0 7px #ef4444; } .lp-dot.trains { background: #c084fc; box-shadow: 0 0 7px #c084fc; } .lp-dot.storms { background: #f472b6; box-shadow: 0 0 7px #f472b6; } + .lp-dot.night { + background: linear-gradient(90deg, #0b1c33 50%, #ffb454 50%); + box-shadow: 0 0 7px #64748b; + } .lp-count { font-family: 'Share Tech Mono', monospace; font-size: 0.7rem; color: var(--cyan); } .lp-sub { display: flex; justify-content: space-between; align-items: center; gap: 0.5rem; } .lp-opacity { display: flex; align-items: center; gap: 0.4rem; font-size: 0.62rem; color: var(--muted); text-transform: uppercase; letter-spacing: 0.05em; } @@ -364,6 +368,35 @@ .gf-del { background: transparent; border: 1px solid var(--magenta); color: var(--magenta); font-family: 'Share Tech Mono', monospace; font-size: 0.58rem; letter-spacing: 0.08em; text-transform: uppercase; padding: 0.12rem 0.35rem; border-radius: 3px; cursor: pointer; } .gf-del:hover { background: rgba(255,46,151,0.16); } + /* ── Keyboard cheat sheet (centered; keep off LAYERS / zoom / dock) ── */ + .cheat-sheet { + position: absolute; top: 50%; left: 50%; + transform: translate(-50%, -50%); + z-index: 640; + width: min(420px, calc(100% - 96px)); + max-height: calc(100% - 88px); + overflow: auto; + background: rgba(6,11,20,0.94); backdrop-filter: blur(10px); + border: 1px solid var(--line-hi); border-radius: 6px; + box-shadow: 0 0 28px rgba(53,224,255,0.18); + padding: 0.85rem 1rem 1rem; + clip-path: polygon(0 8px, 8px 0, calc(100% - 8px) 0, 100% 8px, 100% calc(100% - 8px), calc(100% - 8px) 100%, 8px 100%, 0 calc(100% - 8px)); + } + .cheat-sheet[hidden] { display: none !important; } + .cheat-sheet h3 { + font-family: 'Orbitron', sans-serif; font-size: 0.72rem; letter-spacing: 0.16em; + color: var(--cyan); margin: 0 0 0.65rem; text-transform: uppercase; + } + .cheat-sheet dl { display: grid; grid-template-columns: auto 1fr; gap: 0.35rem 0.85rem; margin: 0; } + .cheat-sheet dt kbd { + display: inline-block; min-width: 1.4em; text-align: center; + border: 1px solid var(--line-hi); border-radius: 3px; padding: 0.12rem 0.4rem; + color: var(--cyan); font-size: 0.72rem; background: var(--bg-1); + } + .cheat-sheet dd { margin: 0; font-size: 0.78rem; color: var(--muted); } + #swpc-chip { color: var(--text); letter-spacing: 0.08em; } + #swpc-chip.swpc-storm { color: var(--amber); text-shadow: 0 0 8px rgba(255,180,84,0.45); } + /* ── Camera / blip popup thumbnails ── */ .cam-pop { min-width: 210px; max-width: 260px; } .cam-pop .thumb { width: 100%; height: 160px; object-fit: cover; border-radius: 4px; border: 1px solid var(--line); margin: 0.3rem 0; box-shadow: 0 0 10px rgba(53,224,255,0.2); background: var(--bg-0); } @@ -732,6 +765,8 @@ --:--:-- UTC | — + +
Opacity 100%
+
+
+ + off +
+
Sun terminator overlay. Default off. No API.
+
@@ -939,6 +981,16 @@
BLIPS —
NEWS —
+
@@ -1280,6 +1332,152 @@ async function checkHealth() { } } +/* ═══════════════ HUD keys + SWPC + /api/stats rail ═══════════════ */ +const STATS_POLL_MS = 30000; +const SWPC_POLL_MS = 90000; +const CAM_THUMB_MIN_ZOOM = 12; +let statsRailActive = false; +let statsPollDisabled = false; +const STATS_COUNT_IDS = { + aircraft: 'lp-ac-count', + vessels: 'lp-vessels-count', + trains: 'lp-trains-count', + cameras: 'lp-cams-count', + fires: 'lp-fires-count', + alerts: 'lp-alerts-count', +}; + +function setLayerCount(id, value) { + if (statsRailActive && Object.values(STATS_COUNT_IDS).indexOf(id) !== -1) return; + const el = document.getElementById(id); + if (el) el.textContent = value; +} + +async function pollLayerStats() { + if (statsPollDisabled) return; + try { + const r = await fetch(`${API}/api/stats`); + if (r.status === 404) { statsPollDisabled = true; statsRailActive = false; return; } + if (!r.ok) return; + const s = await r.json(); + if (!s || typeof s !== 'object') return; + statsRailActive = true; + Object.keys(STATS_COUNT_IDS).forEach((k) => { + const n = s[k]; + if (typeof n !== 'number' || !isFinite(n)) return; + const el = document.getElementById(STATS_COUNT_IDS[k]); + if (el) el.textContent = n.toLocaleString(); + }); + } catch (e) { + // Never block the map on stats failure — keep last viewport lengths. + } +} + +function hideSwpcChip() { + const chip = document.getElementById('swpc-chip'); + const sep = document.getElementById('swpc-sep'); + if (chip) { chip.hidden = true; chip.classList.remove('swpc-storm'); } + if (sep) sep.hidden = true; +} +async function pollSwpc() { + const chip = document.getElementById('swpc-chip'); + const sep = document.getElementById('swpc-sep'); + if (!chip) return; + try { + const r = await fetch('https://services.swpc.noaa.gov/json/planetary_k_index_1m.json'); + if (!r.ok) { hideSwpcChip(); return; } + const rows = await r.json(); + const last = Array.isArray(rows) && rows.length ? rows[rows.length - 1] : null; + const kp = last && last.kp_index; + if (kp == null || !isFinite(Number(kp))) { hideSwpcChip(); return; } + let label = 'Kp ' + Number(kp); + try { + const fr = await fetch('https://services.swpc.noaa.gov/json/goes/primary/xray-flares-latest.json'); + if (fr.ok) { + const flares = await fr.json(); + const f = Array.isArray(flares) ? flares[0] : flares; + const cls = f && (f.max_class || f.current_class || f['class']); + if (cls && /^[MX]/i.test(String(cls))) label += ' · ' + cls; + } + } catch (e) { /* flares optional */ } + try { + const ar = await fetch('https://services.swpc.noaa.gov/products/alerts.json'); + if (ar.ok) { + const alerts = await ar.json(); + const n = Array.isArray(alerts) ? alerts.length : 0; + if (n) chip.title = 'NOAA SWPC · ' + n + ' alert(s)'; + } + } catch (e) { /* alerts optional */ } + chip.textContent = label; + chip.hidden = false; + if (sep) sep.hidden = false; + chip.classList.toggle('swpc-storm', Number(kp) >= 5); + } catch (e) { + hideSwpcChip(); + } +} + +function hudTypingTarget(el) { + if (!el) return false; + const tag = (el.tagName || '').toLowerCase(); + if (tag === 'input' || tag === 'textarea' || tag === 'select') return true; + return !!el.isContentEditable; +} +function toggleCheatSheet(force) { + const el = document.getElementById('cheat-sheet'); + if (!el) return; + const open = force === undefined ? el.hidden : !!force; + el.hidden = !open; +} +function closeLayerPanel() { + const panel = document.getElementById('layer-panel'); + if (!panel) return; + const head = panel.querySelector('.lp-head'); + if (window.matchMedia('(max-width: 820px)').matches) { + if (panel.classList.contains('is-open')) { + panel.classList.remove('is-open'); + if (head) head.setAttribute('aria-expanded', 'false'); + } + return; + } + if (!panel.classList.contains('collapsed')) { + panel.classList.add('collapsed'); + if (head) head.setAttribute('aria-expanded', 'false'); + } +} +function closeHudPanels() { + toggleCheatSheet(false); + closeNav(); + closeLayerPanel(); + if (map) map.closePopup(); +} +function initHudKeys() { + document.addEventListener('keydown', (e) => { + if (e.ctrlKey || e.metaKey || e.altKey) return; + if (e.key === 'Escape') { + closeHudPanels(); + return; + } + if (hudTypingTarget(e.target)) return; + if (e.key === '?' || (e.key === '/' && e.shiftKey)) { + e.preventDefault(); + const sheet = document.getElementById('cheat-sheet'); + toggleCheatSheet(sheet ? sheet.hidden : true); + return; + } + if (e.key === 'l' || e.key === 'L') { + e.preventDefault(); + toggleLayerPanel(); + return; + } + if (e.key === 'r' || e.key === 'R') { + e.preventDefault(); + mapResetView(); + } + // F / S intentionally unbound — Osiris conflicts (flights vs fullscreen / search). + }); +} + /* ═══════════════ NAV (dropdown) ═══════════════ */ const VIEWS = ['map', 'news', 'events', 'alerts', 'entities', 'ingest', 'keys', 'settings']; @@ -2093,7 +2291,7 @@ async function initMap() { .then(r => { if (!r.ok) throw new Error('camera detail'); return r.json(); }) .then(c => { box.outerHTML = camPopupHtml(c); - startHlsFrom(e.popup.getElement()); + if (camThumbsAllowed()) startHlsFrom(e.popup.getElement()); }) .catch(() => { const ph = box.querySelector('.thumb.placeholder'); @@ -2101,7 +2299,7 @@ async function initMap() { }); return; } - startHlsFrom(root); + if (camThumbsAllowed()) startHlsFrom(root); }); map.on('popupopen', (e) => { loadPlanePhoto(e.popup); }); map.on('popupclose', () => { @@ -2433,6 +2631,56 @@ function setBaseOpacity(v) { if (mapLayer && document.getElementById('lp-base-on').checked) mapLayer.setOpacity(baseOpacity); } +/* ── Day/night terminator (sun position, no API) ── */ +let terminatorGroup = null, terminatorOn = false, terminatorTimer = null; +function subsolarPoint(date) { + const rad = Math.PI / 180; + const jd = date.getTime() / 86400000 + 2440587.5; + const n = jd - 2451545.0; + const L = (280.460 + 0.9856474 * n) % 360; + const g = (357.528 + 0.9856003 * n) % 360; + const lambda = (L + 1.915 * Math.sin(g * rad) + 0.020 * Math.sin(2 * g * rad)) * rad; + const eps = (23.439 - 0.0000004 * n) * rad; + const delta = Math.asin(Math.sin(eps) * Math.sin(lambda)); + const alpha = Math.atan2(Math.cos(eps) * Math.sin(lambda), Math.cos(lambda)); + const gmst = (280.46061837 + 360.98564736629 * n) % 360; + let lon = (alpha * 180 / Math.PI) - gmst; + lon = ((lon + 180) % 360 + 360) % 360 - 180; + return [delta * 180 / Math.PI, lon]; +} +function paintTerminator() { + if (!map || !terminatorOn) return; + const [lat, lon] = subsolarPoint(new Date()); + const antiLat = -lat; + const antiLon = lon >= 0 ? lon - 180 : lon + 180; + const radius = 6378137 * Math.PI / 2; + const opts = { + radius, color: '#1e3a5f', weight: 1, fillColor: '#020814', + fillOpacity: 0.38, interactive: false, pane: 'overlayPane', + }; + if (terminatorGroup) { map.removeLayer(terminatorGroup); terminatorGroup = null; } + terminatorGroup = L.layerGroup([ + L.circle([antiLat, antiLon], opts), + L.circle([antiLat, antiLon + 360], opts), + L.circle([antiLat, antiLon - 360], opts), + ]).addTo(map); + const n = document.getElementById('lp-terminator-count'); + if (n) n.textContent = 'on'; +} +function toggleTerminator() { + terminatorOn = !!(document.getElementById('lp-terminator-on') && document.getElementById('lp-terminator-on').checked); + if (terminatorTimer) { clearInterval(terminatorTimer); terminatorTimer = null; } + if (!terminatorOn) { + if (terminatorGroup && map) map.removeLayer(terminatorGroup); + terminatorGroup = null; + const n = document.getElementById('lp-terminator-count'); + if (n) n.textContent = 'off'; + return; + } + paintTerminator(); + terminatorTimer = setInterval(paintTerminator, 60000); +} + /* ── FIRMS fire heatmap ── */ function firesIntensity(f) { const confidence = f.confidence || f.c; @@ -2501,7 +2749,7 @@ async function loadFires() { gradient: firesGradient(), }).addTo(map); firesHeat._canvas.style.opacity = firesOpacity; - document.getElementById('lp-fires-count').textContent = fires.length.toLocaleString(); + setLayerCount('lp-fires-count', fires.length.toLocaleString()); hudFiresCount = fires.length; syncHud(); document.getElementById('map-hint').textContent = @@ -2552,8 +2800,14 @@ function camKind(c) { if (c.device_type === 'rtsp' || u.startsWith('rtsp://')) return 'rtsp'; return 'http'; } +function camThumbsAllowed() { + return map && map.getZoom() >= CAM_THUMB_MIN_ZOOM; +} function camThumb(c) { if (!c.id) return '
no preview available
'; + if (!camThumbsAllowed()) { + return '
zoom in for preview
'; + } const kind = camKind(c); if (kind === 'youtube') { const vid = youtubeId(c.snapshot_url || c.source_url); @@ -2627,7 +2881,7 @@ async function loadCams() { }); camsGroup.addTo(map); camsGroup.eachLayer(l => l.setOpacity && l.setOpacity(camsOpacity)); - document.getElementById('lp-cams-count').textContent = cams.length.toLocaleString(); + setLayerCount('lp-cams-count', cams.length.toLocaleString()); hudCamsCount = cams.length; syncHud(); document.getElementById('map-hint').textContent = @@ -2786,8 +3040,7 @@ function dropLayer(ref) { const HEAVY_MIN_ZOOM = 4; function tooZoomedOut() { return !map || map.getZoom() <= HEAVY_MIN_ZOOM; } function markZoom(id) { - const el = document.getElementById(id); - if (el) el.textContent = 'zoom'; + setLayerCount(id, 'zoom'); } function intersectsConus() { if (!map) return false; @@ -3207,12 +3460,12 @@ async function loadWxAlerts() { layer.bindPopup(`
${esc(p.source || 'alert')}
${esc(p.event || p.headline || 'Alert')}
${esc(p.severity || '')} · ${esc(p.areaDesc || p.wfo || '')}
`); }, }).addTo(map); - document.getElementById('lp-alerts-count').textContent = feats.length.toLocaleString(); + setLayerCount('lp-alerts-count', feats.length.toLocaleString()); addExtraAttrib('NWS / IEM storm-based warnings'); } catch (e) { if (isAbort(e)) return; console.error('Alerts load failed', e); - document.getElementById('lp-alerts-count').textContent = 'err'; + setLayerCount('lp-alerts-count', 'err'); } } async function togglePerimeters() { @@ -3289,7 +3542,7 @@ async function toggleAircraft() { async function loadAircraft() { if (!map) return; if (map.getZoom() <= 3) { - document.getElementById('lp-ac-count').textContent = 'zoom'; + setLayerCount('lp-ac-count', 'zoom'); return; } const req = ++overlayReq.ac; @@ -3298,13 +3551,13 @@ async function loadAircraft() { const pts = await r.json(); if (req !== overlayReq.ac) return; acGroup = renderPoints(acGroup, Array.isArray(pts) ? pts : [], p => acColor(p), true, 'ac'); - document.getElementById('lp-ac-count').textContent = (pts.length || 0).toLocaleString(); + setLayerCount('lp-ac-count', (pts.length || 0).toLocaleString()); addExtraAttrib('ADSB.lol ODbL'); addExtraAttrib('Photo © planespotters.net'); } catch (e) { if (isAbort(e)) return; console.error('Aircraft load failed', e); - document.getElementById('lp-ac-count').textContent = 'err'; + setLayerCount('lp-ac-count', 'err'); } } async function toggleTrains() { @@ -3320,12 +3573,12 @@ async function loadTrains() { const pts = await r.json(); if (req !== overlayReq.trains) return; trainsGroup = renderPoints(trainsGroup, Array.isArray(pts) ? pts : [], p => (p.extra || {}).iconColor || '#c084fc', false, 'train'); - document.getElementById('lp-trains-count').textContent = (pts.length || 0).toLocaleString(); + setLayerCount('lp-trains-count', (pts.length || 0).toLocaleString()); addExtraAttrib('Amtraker'); } catch (e) { if (isAbort(e)) return; console.error('Trains load failed', e); - document.getElementById('lp-trains-count').textContent = 'err'; + setLayerCount('lp-trains-count', 'err'); } } async function toggleVessels() { @@ -3341,7 +3594,7 @@ async function toggleVessels() { async function loadVessels() { if (!map) return; if (map.getZoom() <= 3) { - document.getElementById('lp-vessels-count').textContent = 'zoom'; + setLayerCount('lp-vessels-count', 'zoom'); return; } const req = ++overlayReq.vessels; @@ -3376,7 +3629,7 @@ async function loadVessels() { const sog = Number((p.speed) || 0); return sog > 0.5 ? '#2dd4bf' : '#64748b'; }, true, 'vessel'); - document.getElementById('lp-vessels-count').textContent = (pts.length || 0).toLocaleString(); + setLayerCount('lp-vessels-count', (pts.length || 0).toLocaleString()); addExtraAttrib('AISStream'); // First positions for a new zone arrive ~1-3s after the retune. if (retuned) { @@ -3386,7 +3639,7 @@ async function loadVessels() { } catch (e) { if (isAbort(e)) return; console.error('Vessels load failed', e); - document.getElementById('lp-vessels-count').textContent = 'err'; + setLayerCount('lp-vessels-count', 'err'); } } async function toggleStorms() { @@ -3413,6 +3666,7 @@ async function loadStorms() { /* ═══════════════ INITIAL LOAD ═══════════════ */ initNav(); +initHudKeys(); initSettings(); initMarketTicker(); checkHealth(); @@ -3425,6 +3679,10 @@ initMap(); // contend with the first bbox burst. Payload is slim (no article bodies). setTimeout(() => loadNews(true), 400); setInterval(checkHealth, 30000); +setTimeout(pollLayerStats, 1800); +setInterval(() => { if (!statsPollDisabled) pollLayerStats(); }, STATS_POLL_MS); +setTimeout(pollSwpc, 2200); +setInterval(pollSwpc, SWPC_POLL_MS); /* Phase 2: DVR slider + geofence draw (no Leaflet.Draw) + fire/aircraft hits */ function dvrQs() { return dvrTs ? `×tamp=${encodeURIComponent(dvrTs)}` : ''; } diff --git a/tests/test_hud_osiris.py b/tests/test_hud_osiris.py new file mode 100644 index 0000000..a4035de --- /dev/null +++ b/tests/test_hud_osiris.py @@ -0,0 +1,90 @@ +"""HUD: layer-rail stats, shortcuts, terminator, zoom-gated cams, SWPC chip.""" + +from __future__ import annotations + +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +HTML = (ROOT / "app/static/index.html").read_text() + + +def _fn(name: str, nxt: str | None = None) -> str: + start = HTML.index(f"function {name}") + if nxt: + return HTML[start : HTML.index(f"function {nxt}", start + 1)] + return HTML[start : start + 4000] + + +def test_stats_poll_uses_api_then_falls_back(): + assert "/api/stats" in HTML + assert "30000" in HTML.split("pollLayerStats")[1][:2500] or "STATS_POLL_MS" in HTML + poll = HTML.split("async function pollLayerStats")[1].split("async function ")[0] + assert "404" in poll + assert "catch" in poll + ids = HTML.split("STATS_COUNT_IDS")[1].split("};")[0] + assert "aircraft" in ids and "cameras" in ids and "fires" in ids and "vessels" in ids + # Overlay loaders still write array lengths when stats is down. + assert "setLayerCount('lp-fires-count'" in HTML or 'setLayerCount("lp-fires-count"' in HTML + assert "setLayerCount('lp-cams-count'" in HTML or 'setLayerCount("lp-cams-count"' in HTML + assert "setLayerCount('lp-ac-count'" in HTML or 'setLayerCount("lp-ac-count"' in HTML + assert "setLayerCount('lp-vessels-count'" in HTML or 'setLayerCount("lp-vessels-count"' in HTML + + +def test_keyboard_shortcuts_do_not_steal_osiris_fs(): + keys = HTML.split("function initHudKeys")[1].split("function ")[0] + assert "Escape" in keys + assert "cheat-sheet" in keys or "toggleCheatSheet" in keys + assert "mapResetView" in keys + assert "toggleLayerPanel" in keys or "closeLayerPanel" in keys + # Do not bind Osiris's conflicting F/S (flights vs fullscreen / search). + assert "e.key === 'f'" not in keys.lower() + assert "e.key === 's'" not in keys.lower() + assert "case 'f'" not in keys.lower() + assert "case 's'" not in keys.lower() + assert 'id="cheat-sheet"' in HTML + assert "?" in keys or "Shift" in keys + + +def test_terminator_toggle_defaults_off(): + assert 'id="lp-terminator-on"' in HTML + row = HTML.split('id="lp-terminator-on"')[0][-120:] + HTML.split('id="lp-terminator-on"')[1][:80] + assert "checked" not in row.split(">")[0] + assert "function toggleTerminator" in HTML + assert "subsolarPoint" in HTML or "terminator" in HTML.lower() + + +def test_camera_thumbs_gated_at_zoom_12(): + assert "CAM_THUMB_MIN_ZOOM" in HTML + assert "CAM_THUMB_MIN_ZOOM = 12" in HTML + thumb = _fn("camThumb", "camPopupHtml") + assert "camThumbsAllowed" in thumb or "CAM_THUMB_MIN_ZOOM" in thumb + assert "zoom in for preview" in HTML or "zoom for preview" in HTML + assert "preview unavailable" in HTML + # Masscan / RTSP still proxy through snapshot; never emit rtsp hrefs. + src = _fn("camSourceLink", "youtubeId") + assert "rtsp://" in src + assert "href=" not in src.split("rtsp://")[1].split("return")[0] or "Never emit" in src + assert 'href="${esc(url)}"' in src or "href=\"${esc(url)}\"" in src + assert src.index("rtsp://") < src.index("href=") + + +def test_swpc_chip_browser_direct_correct_urls(): + assert 'id="swpc-chip"' in HTML + assert "services.swpc.noaa.gov/json/planetary_k_index_1m.json" in HTML + assert "services.swpc.noaa.gov/json/goes/primary/xray-flares-latest.json" in HTML + assert "services.swpc.noaa.gov/products/alerts.json" in HTML + assert "services.swpc.noaa.gov/json/alerts.json" not in HTML + sw = HTML.split("async function pollSwpc")[1].split("async function ")[0] + assert "hidden" in sw + assert "kp_index" in sw + assert "90000" in HTML or "SWPC_POLL_MS" in HTML + + +def test_new_chrome_does_not_cover_mobile_layers_zoom(): + mobile = HTML.split("@media (max-width: 820px)")[1].split("@media (prefers-reduced-motion")[0] + assert "#layer-panel" in mobile + assert ".leaflet-top.leaflet-right .leaflet-control-zoom" in mobile + assert 'id="cheat-sheet"' in HTML + cheat = HTML.split(".cheat-sheet")[1][:500] + assert "z-index" in cheat + assert "calc(100% - 96px)" in cheat or "96px" in cheat From 6b5eec3824cab7766e35bdf4a830549ab8bb39cf Mon Sep 17 00:00:00 2001 From: Sirius DevOps Date: Mon, 31 Aug 2026 21:42:50 -0400 Subject: [PATCH 50/79] feat(satellites): CelesTrak GP JSON satellites API with SGP4 propagation GET /api/satellites?groups=stations,weather returns last-known satellite positions propagated from CelesTrak GP JSON (OMM mean elements, not TLE) via the real sgp4 library (TEME->geodetic), not two-body Kepler. - Fetch gp.php?GROUP=...&FORMAT=JSON at most once per 2h per group, cached with a last-good blob fallback for 403 / stale responses. - SatNOGS TLE fallback only when the CelesTrak cache is empty. - bbox viewport culling; unknown group -> 400. - overlay_catalog() gains id=satellites (kind=points, /api/satellites). - OMM path handles NORAD cat numbers >= 100000 (no TLE round-trip). --- app/live_layers.py | 6 + app/main.py | 30 ++++ app/requirements.txt | 1 + app/satellites.py | 289 +++++++++++++++++++++++++++++++++++++++ tests/test_satellites.py | 200 +++++++++++++++++++++++++++ 5 files changed, 526 insertions(+) create mode 100644 app/satellites.py create mode 100644 tests/test_satellites.py diff --git a/app/live_layers.py b/app/live_layers.py index fa632b1..81865fb 100644 --- a/app/live_layers.py +++ b/app/live_layers.py @@ -150,6 +150,12 @@ def overlay_catalog() -> dict: "endpoint": "/api/map/gpsjam", "attribution": "GPSJAM / John Wiseman / ADS-B Exchange", }, + "satellites": { + "id": "satellites", + "kind": "points", + "endpoint": "/api/satellites", + "attribution": "CelesTrak (GP JSON / SGP4)", + }, } diff --git a/app/main.py b/app/main.py index 2d12e25..4c95224 100644 --- a/app/main.py +++ b/app/main.py @@ -59,6 +59,7 @@ from live_layers import ( fetch_storms, fetch_trains, fetch_vessels, fetch_weather_alerts, overlay_catalog, parse_bbox, UpstreamRateLimited, ) +from satellites import fetch_satellites, parse_groups, DEFAULT_GROUPS logging.basicConfig(level=logging.INFO) logger = structlog.get_logger("osint.dashboard") @@ -1764,6 +1765,35 @@ async def map_gpsjam( return overlay_json(fc, 3600) +@app.get("/api/satellites") +async def list_satellites( + groups: str | None = Query(None, description="Comma-separated CelesTrak groups"), + bbox: str | None = Query(None, description="minlon,minlat,maxlon,maxlat"), + limit: int = Query(2000, ge=1, le=5000), +): + """Last-known satellite positions from CelesTrak GP JSON, SGP4-propagated. + + Default groups are ``stations,weather`` (tens of objects). The GP element + blob is fetched at most once per 2 hours per group and cached; positions + are re-propagated on every request. Falls back to the last good blob on a + CelesTrak 403 / stale response, and to SatNOGS TLE only when the cache is + empty. Unknown groups 400. + """ + try: + group_list = parse_groups(groups if groups is not None else ",".join(DEFAULT_GROUPS)) + except ValueError as exc: + raise HTTPException(400, str(exc)) from exc + if bbox: + _parse_bbox_query(bbox) + try: + payload = await fetch_satellites(group_list, bbox=bbox, limit=limit) + except ValueError as exc: + raise HTTPException(422, str(exc)) from exc + except Exception as exc: + _upstream_or_502(exc, "satellites") + return overlay_json(payload, 30) + + @app.get("/api/map/times") async def map_layer_times( layer: str = Query(..., description="GIBS layer identifier, e.g. VIIRS_SNPP_CorrectedReflectance_TrueColor"), diff --git a/app/requirements.txt b/app/requirements.txt index 2389199..733d94d 100644 --- a/app/requirements.txt +++ b/app/requirements.txt @@ -13,3 +13,4 @@ structlog>=24.4 websockets>=14 cachetools>=5.5 h3>=4.0 +sgp4>=2.23 diff --git a/app/satellites.py b/app/satellites.py new file mode 100644 index 0000000..8bbd963 --- /dev/null +++ b/app/satellites.py @@ -0,0 +1,289 @@ +"""CelesTrak satellites last-known overlay. + +Fetches GP **JSON** (OMM mean elements — not TLE) per group at most once per +2 hours, caches the element blob, and propagates positions with a real SGP4 +library on every request. Positions move every second; the *element set* is +what we cache, not the derived lat/lon. + +Catalog numbers >= 100000 only fit OMM/JSON, never a 5-column TLE field, so +elements are initialized through :func:`sgp4.omm.initialize` (which consumes +the CelesTrak GP JSON fields verbatim) rather than round-tripping to TLE. + +CelesTrak usage policy is non-negotiable: fetch the GP JSON blob at most once +per 2 hours per group, never fan out every GROUP, never also fetch +``GROUP=active`` plus subsets, and identify with ``OSINT_USER_AGENT``. +""" + +from __future__ import annotations + +import logging +import math +from datetime import datetime, timezone +from urllib.parse import quote + +logger = logging.getLogger("osint.satellites") + +CELESTRAK_GP = "https://celestrak.org/NORAD/elements/gp.php" +SATNOGS_TLE = "https://db.satnogs.org/api/tle/" +DEFAULT_GROUPS = ("stations", "weather") +ALLOWED_GROUPS = ("stations", "weather", "gps-ops", "starlink") +# CelesTrak policy: do not hit gp.php more than once per 2 hours per group. +SATELLITE_TTL = 2 * 3600.0 +SOURCE_CELESTRAK = "celestrak" +SOURCE_SATNOGS = "satnogs" +DEFAULT_LIMIT = 2000 + +# WGS-84 ellipsoid for TEME -> geodetic. +_WGS84_A = 6378.137 +_WGS84_F = 1.0 / 298.257223563 + +# Last-good element blob per group, kept past TTL so a 403 / "has not updated +# since ..." still serves the previous set instead of failing the overlay. +_last_good: dict[str, list[dict]] = {} + + +def parse_groups(raw: str | None) -> list[str]: + """Validate + normalize a comma-separated group list. Raises ValueError. + + Starlink is allowed only when explicitly requested (never in the default); + it is a large supplemental feed, not part of the stations/weather default. + """ + groups = [g.strip().lower() for g in (raw or "").split(",") if g.strip()] + if not groups: + raise ValueError("groups must be a non-empty comma-separated list") + bad = [g for g in groups if g not in ALLOWED_GROUPS] + if bad: + raise ValueError(f"unknown group(s): {', '.join(bad)}") + # Dedup, preserve order. + seen: set[str] = set() + out: list[str] = [] + for g in groups: + if g not in seen: + seen.add(g) + out.append(g) + return out + + +def _teme_to_geodetic( + r: tuple[float, float, float], + jd: float, + fr: float, +) -> tuple[float, float, float]: + """SGP4 TEME position (km) -> geodetic (lat_deg, lon_deg, alt_km). + + Rotate TEME into an Earth-fixed frame via GMST, then iterate the WGS-84 + geodetic conversion. Good to well under a km for a ground-track overlay. + """ + # GMST (radians) from UT1 ~= UTC here (sub-second error is negligible). + d = (jd + fr) - 2451545.0 + t = d / 36525.0 + gmst_s = ( + 67310.54841 + + (876600.0 * 3600.0 + 8640184.812866) * t + + 0.093104 * t * t + - 6.2e-6 * t * t * t + ) + theta = math.radians((gmst_s % 86400.0) / 240.0) + + x, y, z = r + xe = x * math.cos(theta) + y * math.sin(theta) + ye = -x * math.sin(theta) + y * math.cos(theta) + ze = z + + e2 = _WGS84_F * (2.0 - _WGS84_F) + p = math.sqrt(xe * xe + ye * ye) + lon = math.atan2(ye, xe) + lat = math.atan2(ze, p * (1.0 - e2)) + alt = 0.0 + for _ in range(10): + n = _WGS84_A / math.sqrt(1.0 - e2 * math.sin(lat) ** 2) + alt = p / math.cos(lat) - n + lat = math.atan2(ze, p * (1.0 - e2 * n / (n + alt))) + n = _WGS84_A / math.sqrt(1.0 - e2 * math.sin(lat) ** 2) + alt = p / math.cos(lat) - n + return math.degrees(lat), math.degrees(lon), alt + + +def propagate_gp( + elements: list[dict], + group: str, + now: datetime, +) -> list[dict]: + """Propagate CelesTrak GP JSON elements to geodetic positions at ``now``. + + Pure and deterministic given ``now``. Returns ``[{id, name, lat, lon, + alt_km, group}]``; malformed elements and propagation errors are skipped. + """ + from sgp4.api import Satrec, jday + import sgp4.omm as omm + + jd, fr = jday( + now.year, now.month, now.day, + now.hour, now.minute, now.second + now.microsecond / 1e6, + ) + out: list[dict] = [] + for rec in elements: + if not isinstance(rec, dict): + continue + sat = Satrec() + try: + omm.initialize(sat, rec) + except (KeyError, ValueError, TypeError): + continue + err, r, _v = sat.sgp4(jd, fr) + if err != 0: + continue + lat, lon, alt = _teme_to_geodetic(r, jd, fr) + norad = rec.get("NORAD_CAT_ID") + out.append({ + "id": str(norad) if norad is not None else "", + "name": rec.get("OBJECT_NAME") or str(norad or ""), + "lat": round(lat, 5), + "lon": round(lon, 5), + "alt_km": round(alt, 2), + "group": group, + }) + return out + + +def _max_epoch(elements: list[dict]) -> str | None: + """Most recent EPOCH across an element set (ISO-8601 lexical max).""" + epochs = [ + str(e["EPOCH"]) for e in elements + if isinstance(e, dict) and e.get("EPOCH") + ] + return max(epochs) if epochs else None + + +def propagate_satnogs_tle( + payload: list[dict], + group: str, + now: datetime, +) -> tuple[list[dict], str | None]: + """Fallback parser for SatNOGS TLE JSON (``[{tle0,tle1,tle2,updated}]``). + + Returns ``(satellites, epoch)`` where epoch is the max ``updated`` time. + Only used when the CelesTrak cache is completely empty. + """ + from sgp4.api import Satrec, jday + + jd, fr = jday( + now.year, now.month, now.day, + now.hour, now.minute, now.second + now.microsecond / 1e6, + ) + out: list[dict] = [] + epochs: list[str] = [] + for rec in payload or []: + if not isinstance(rec, dict): + continue + line1 = rec.get("tle1") + line2 = rec.get("tle2") + if not line1 or not line2: + continue + try: + sat = Satrec.twoline2rv(line1, line2) + except (ValueError, TypeError): + continue + e, r, _v = sat.sgp4(jd, fr) + if e != 0: + continue + lat, lon, alt = _teme_to_geodetic(r, jd, fr) + satnum = getattr(sat, "satnum_str", None) or rec.get("norad_cat_id") + name = (rec.get("tle0") or "").strip().lstrip("0").strip() or str(satnum or "") + out.append({ + "id": str(satnum).strip() or "", + "name": name, + "lat": round(lat, 5), + "lon": round(lon, 5), + "alt_km": round(alt, 2), + "group": group, + }) + if rec.get("updated"): + epochs.append(str(rec["updated"])) + return out, (max(epochs) if epochs else None) + + +async def _group_elements(group: str) -> tuple[list[dict], str | None]: + """CelesTrak GP blob for one group, TTL-cached with a last-good fallback. + + Returns ``(elements, epoch)``. On a fetch failure (403 / "has not updated + since ...") falls back to the previous successful blob for that group. + """ + from live_layers import _get_json, _ttl_get + + url = f"{CELESTRAK_GP}?GROUP={quote(group)}&FORMAT=JSON" + + async def _load() -> list[dict]: + data = await _get_json(url) + if not isinstance(data, list): + raise ValueError(f"unexpected CelesTrak payload for {group}") + if data: + _last_good[group] = data + return data + + key = f"celestrak:gp:{group}" + try: + elements = await _ttl_get(key, SATELLITE_TTL, _load) + except Exception as exc: # noqa: BLE001 + logger.warning("celestrak_fetch_failed group=%s: %s", group, exc) + elements = _last_good.get(group, []) + if not elements: + return [], None + return elements, _max_epoch(elements) + + +async def fetch_satellites( + groups: list[str], + bbox: str | None = None, + limit: int = DEFAULT_LIMIT, +) -> dict: + """Assemble the ``/api/satellites`` payload for the requested groups.""" + from live_layers import _get_json, _ttl_get, filter_points_bbox, parse_bbox + + now = datetime.now(timezone.utc) + satellites: list[dict] = [] + epoch: str | None = None + source = SOURCE_CELESTRAK + + for group in groups: + elements, group_epoch = await _group_elements(group) + if not elements: + continue + if group_epoch and (epoch is None or group_epoch > epoch): + epoch = group_epoch + satellites.extend(propagate_gp(elements, group, now)) + + if not satellites: + # Fallback only when the CelesTrak cache is entirely empty — never + # poll both providers every cycle. + async def _load_satnogs() -> list[dict]: + data = await _get_json(SATNOGS_TLE, params={"format": "json"}) + return data if isinstance(data, list) else [] + + try: + satnogs = await _ttl_get("satnogs:tle", SATELLITE_TTL, _load_satnogs) + except Exception as exc: # noqa: BLE001 + logger.warning("satnogs_fetch_failed: %s", exc) + satnogs = [] + if satnogs: + source = SOURCE_SATNOGS + for group in groups: + rows, sn_epoch = propagate_satnogs_tle(satnogs, group, now) + if sn_epoch and (epoch is None or sn_epoch > epoch): + epoch = sn_epoch + satellites.extend(rows) + + if bbox: + minlon, minlat, maxlon, maxlat = parse_bbox(bbox) + satellites = filter_points_bbox( + satellites, minlon, minlat, maxlon, maxlat, limit, + ) + else: + satellites = satellites[:limit] + + return { + "satellites": satellites, + "source": source, + "tle_epoch": epoch, + "timestamp": now.isoformat(), + } diff --git a/tests/test_satellites.py b/tests/test_satellites.py new file mode 100644 index 0000000..d15f6fc --- /dev/null +++ b/tests/test_satellites.py @@ -0,0 +1,200 @@ +"""CelesTrak satellites overlay: GP JSON parser, 2h cache, groups, bbox.""" + +from __future__ import annotations + +import asyncio +from datetime import datetime, timezone + +import httpx + +import satellites +from live_layers import _cache, overlay_catalog +from main import app + +BASE = "http://test" + +# Two real CelesTrak GP JSON records (trimmed to the OMM fields sgp4 needs). +ISS = { + "OBJECT_NAME": "ISS (ZARYA)", "OBJECT_ID": "1998-067A", + "EPOCH": "2026-08-31T11:11:23.184384", "MEAN_MOTION": 15.4894954, + "ECCENTRICITY": 0.00050456, "INCLINATION": 51.6314, + "RA_OF_ASC_NODE": 287.5025, "ARG_OF_PERICENTER": 92.8598, + "MEAN_ANOMALY": 267.2968, "EPHEMERIS_TYPE": 0, + "CLASSIFICATION_TYPE": "U", "NORAD_CAT_ID": 25544, + "ELEMENT_SET_NO": 999, "REV_AT_EPOCH": 58342, + "BSTAR": 9.9862358e-5, "MEAN_MOTION_DOT": 5.046e-5, + "MEAN_MOTION_DDOT": 0, +} +HST = { + "OBJECT_NAME": "HST", "OBJECT_ID": "1990-037B", + "EPOCH": "2026-08-31T11:11:23.184384", "MEAN_MOTION": 15.0865888, + "ECCENTRICITY": 0.0002426, "INCLINATION": 28.4697, + "RA_OF_ASC_NODE": 102.1854, "ARG_OF_PERICENTER": 152.8462, + "MEAN_ANOMALY": 207.2795, "EPHEMERIS_TYPE": 0, + "CLASSIFICATION_TYPE": "U", "NORAD_CAT_ID": 20580, + "ELEMENT_SET_NO": 999, "REV_AT_EPOCH": 12345, + "BSTAR": 2.9e-5, "MEAN_MOTION_DOT": 0.0, + "MEAN_MOTION_DDOT": 0, +} +FIXTURE = [ISS, HST] + +NOW = datetime(2026, 8, 31, 12, 0, 0, tzinfo=timezone.utc) + + +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 test_propagate_gp_shape(): + rows = satellites.propagate_gp(FIXTURE, "stations", NOW) + assert len(rows) == 2 + by_id = {r["id"]: r for r in rows} + assert set(by_id) == {"25544", "20580"} + iss = by_id["25544"] + assert iss["name"] == "ISS (ZARYA)" + assert iss["group"] == "stations" + # ISS is in LEO: ~400 km, |lat| <= inclination 51.63, lon in range. + assert 300 < iss["alt_km"] < 500 + assert -51.7 <= iss["lat"] <= 51.7 + assert -180 <= iss["lon"] <= 180 + for key in ("id", "name", "lat", "lon", "alt_km", "group"): + assert key in iss + + +def test_propagate_gp_skips_malformed(): + bad = [{"OBJECT_NAME": "x"}, None, 42, {"NORAD_CAT_ID": 1}] + assert satellites.propagate_gp(bad, "stations", NOW) == [] + + +def test_parse_groups_defaults_and_validation(): + assert satellites.parse_groups("stations,weather") == ["stations", "weather"] + assert satellites.parse_groups("weather,gps-ops") == ["weather", "gps-ops"] + # starlink is allowed only when explicitly requested + assert satellites.parse_groups("starlink") == ["starlink"] + assert satellites.parse_groups("stations,stations") == ["stations"] + for bad in ("", None, "debris", "stations,active", "stations, weather, active"): + try: + satellites.parse_groups(bad) + except ValueError: + pass + else: + raise AssertionError(f"expected ValueError for {bad!r}") + + +def test_overlay_catalog_has_satellites_stub(): + entry = overlay_catalog()["satellites"] + assert entry["kind"] == "points" + assert entry["endpoint"] == "/api/satellites" + assert "CelesTrak" in entry["attribution"] + + +def test_unknown_group_400(): + resp = asyncio.run(_get("/api/satellites?groups=debris")) + assert resp.status_code == 400 + + +def test_default_groups_ok_with_fake_fetch(monkeypatch): + async def fake(groups, bbox=None, limit=2000): + return {"satellites": [], "source": "celestrak", + "tle_epoch": None, "timestamp": "t"} + + monkeypatch.setattr("main.fetch_satellites", fake) + resp = asyncio.run(_get("/api/satellites")) + assert resp.status_code == 200 + body = resp.json() + assert body["source"] == "celestrak" + assert "max-age" in (resp.headers.get("cache-control") or "").lower() + + +def test_2h_cache_does_not_refetch(monkeypatch): + satellites._last_good.clear() + _cache.clear() + hits = {"n": 0} + + class FakeResp: + def __init__(self, data): + self._data = data + + def raise_for_status(self): + pass + + def json(self): + return self._data + + class FakeClient: + def __init__(self): + pass + + async def get(self, url, params=None, headers=None): + hits["n"] += 1 + assert "celestrak.org/NORAD/elements/gp.php" in url + return FakeResp(FIXTURE) + + monkeypatch.setattr("live_layers._http", FakeClient()) + + async def run(): + p1 = await satellites.fetch_satellites(["stations"]) + p2 = await satellites.fetch_satellites(["stations"]) + return p1, p2 + + p1, p2 = asyncio.run(run()) + assert len(p1["satellites"]) == 2 + assert p1["tle_epoch"] == "2026-08-31T11:11:23.184384" + # Same element blob served from cache (no refetch), same ids/epochs. + assert [s["id"] for s in p2["satellites"]] == [s["id"] for s in p1["satellites"]] + assert p2["tle_epoch"] == p1["tle_epoch"] + assert hits["n"] == 1 + _cache.clear() + satellites._last_good.clear() + + +def test_bbox_culls_satellites(monkeypatch): + """bbox filtering in fetch_satellites, deterministic via fake propagation.""" + + async def fake_elements(group): + return [{"x": 1}], "2026-08-31T11:11:23.184384" + + monkeypatch.setattr("satellites._group_elements", fake_elements) + + def fake_propagate(elements, group, now): + return [ + {"id": "a", "name": "A", "lat": 10.0, "lon": 20.0, "alt_km": 400.0, "group": group}, + {"id": "b", "name": "B", "lat": 45.0, "lon": -70.0, "alt_km": 400.0, "group": group}, + {"id": "c", "name": "C", "lat": -10.0, "lon": 30.0, "alt_km": 400.0, "group": group}, + ] + + monkeypatch.setattr("satellites.propagate_gp", fake_propagate) + + payload = asyncio.run( + satellites.fetch_satellites(["stations"], bbox="-80,0,-60,50") + ) + ids = [s["id"] for s in payload["satellites"]] + assert ids == ["b"] # only (45, -70) falls inside the box + + +def test_bbox_culls_nothing_when_empty(): + from satellites import fetch_satellites + + # No bbox: all rows returned up to limit. + # (skip network; just sanity-check the arg is accepted by signature) + assert callable(fetch_satellites) + + +def test_satnogs_fallback_parser(): + payload = [{ + "tle0": "0 ISS (ZARYA)", + "tle1": "1 25544U 98067A 26243.85334329 .00004554 00000-0 90917-4 0 9992", + "tle2": "2 25544 51.6312 285.5873 0005057 94.2999 265.8567 15.48953200583481", + "norad_cat_id": 25544, + "updated": "2026-09-01T01:19:54.327653Z", + }] + rows, epoch = satellites.propagate_satnogs_tle(payload, "stations", NOW) + assert len(rows) == 1 + row = rows[0] + assert row["id"] == "25544" + assert row["name"] == "ISS (ZARYA)" + assert row["group"] == "stations" + assert epoch == "2026-09-01T01:19:54.327653Z" + assert 300 < row["alt_km"] < 500 From 74722f7628d097614676cc45527e39f9ad12114a Mon Sep 17 00:00:00 2001 From: Sirius DevOps Date: Tue, 1 Sep 2026 00:46:54 -0400 Subject: [PATCH 51/79] fix(ops): pin TiTiler digest, GIST bbox indexes, single uvicorn worker Pin titiler to the Pi-running digest, make workers=1 explicit for in-memory WS/layer caches, and add PostGIS GIST indexes for events/fires bbox pans without dropping the existing btree indexes. --- alembic/versions/010_bbox_gist.py | 29 ++++++++++++++++++++++++++++ app/main.py | 2 +- docker-compose.yml | 2 +- tests/test_phase1_guardrails.py | 32 +++++++++++++++++++++++++++++++ 4 files changed, 63 insertions(+), 2 deletions(-) create mode 100644 alembic/versions/010_bbox_gist.py diff --git a/alembic/versions/010_bbox_gist.py b/alembic/versions/010_bbox_gist.py new file mode 100644 index 0000000..a7feab3 --- /dev/null +++ b/alembic/versions/010_bbox_gist.py @@ -0,0 +1,29 @@ +"""GIST bbox indexes for events/fires map-pan queries. + +Revision ID: 010_bbox_gist +Revises: 009_vessels +Create Date: 2026-09-01 +""" + +from alembic import op + +revision = "010_bbox_gist" +down_revision = "009_vessels" +branch_labels = None +depends_on = None + + +def upgrade() -> None: + op.execute( + "CREATE INDEX IF NOT EXISTS ix_events_geom_gist ON events " + "USING gist (ST_SetSRID(ST_MakePoint(location_lon, location_lat), 4326))" + ) + op.execute( + "CREATE INDEX IF NOT EXISTS ix_fires_geom_gist ON fires " + "USING gist (ST_SetSRID(ST_MakePoint(longitude, latitude), 4326))" + ) + + +def downgrade() -> None: + op.execute("DROP INDEX IF EXISTS ix_fires_geom_gist") + op.execute("DROP INDEX IF EXISTS ix_events_geom_gist") diff --git a/app/main.py b/app/main.py index ecb2a64..b0052fc 100644 --- a/app/main.py +++ b/app/main.py @@ -1992,4 +1992,4 @@ app.mount("/static", CachedStaticFiles(directory=str(STATIC_DIR)), name="static" if __name__ == "__main__": import uvicorn - uvicorn.run(app, host="0.0.0.0", port=8000) + uvicorn.run(app, host="0.0.0.0", port=8000, workers=1) # single worker: in-memory WS/pubsub + layer caches diff --git a/docker-compose.yml b/docker-compose.yml index 01abd37..98e1cc3 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -170,7 +170,7 @@ services: # Listens on 8000 INSIDE the container (the app already owns host 8000); # published on host loopback 127.0.0.1:8001 only. titiler: - image: ghcr.io/developmentseed/titiler:latest + image: ghcr.io/developmentseed/titiler:latest@sha256:1809958d063543e3ec858259536002b2de78e9f8f09a22a8d9591bdc2b550b14 pull_policy: missing container_name: osint-titiler platform: linux/arm64 diff --git a/tests/test_phase1_guardrails.py b/tests/test_phase1_guardrails.py index de2a00c..bf3115d 100644 --- a/tests/test_phase1_guardrails.py +++ b/tests/test_phase1_guardrails.py @@ -31,3 +31,35 @@ def test_no_redis_kafka_celery(): assert "kafka" not in blob assert "celery" not in blob assert "cachetools" in req + + +def test_titiler_image_pinned_by_digest(): + text = (ROOT / "docker-compose.yml").read_text() + assert ( + "ghcr.io/developmentseed/titiler:latest@sha256:" + "1809958d063543e3ec858259536002b2de78e9f8f09a22a8d9591bdc2b550b14" + in text + ) + # Unpinned :latest would drift on every pull. + for line in text.splitlines(): + if "titiler" in line.lower() and "image:" in line: + assert "@sha256:" in line + + +def test_uvicorn_single_worker_guard(): + text = (ROOT / "app" / "main.py").read_text() + main_block = text.split('if __name__ == "__main__":', 1)[1] + assert "workers=1" in main_block + + +def test_bbox_gist_migration_keeps_btree_and_adds_gist(): + text = (ROOT / "alembic" / "versions" / "010_bbox_gist.py").read_text() + assert "down_revision" in text and "009_vessels" in text + assert "ix_events_geom_gist" in text + assert "ix_fires_geom_gist" in text + assert "ST_MakePoint(location_lon, location_lat)" in text + assert "ST_MakePoint(longitude, latitude)" in text + assert "USING gist" in text + models = (ROOT / "app" / "models.py").read_text() + assert 'Index("ix_events_location"' in models + assert 'Index("ix_fires_bbox"' in models From 59974be696111c2be22b1af1ddabbda60291ea62 Mon Sep 17 00:00:00 2001 From: Sirius DevOps Date: Tue, 1 Sep 2026 00:47:15 -0400 Subject: [PATCH 52/79] fix(api): SSRF guard on ingest; whitelist PATCH /api/sources Reject private/loopback/link-local hosts on POST /api/ingest/rss and URL-shaped GDELT queries via camera_scraper.is_public_url (HTTP 400). PATCH /api/sources/{id} only accepts name, url, config, enabled (422 else). --- app/main.py | 34 ++++++++++---- app/schemas.py | 13 +++++- tests/test_ingest_ssrf_and_sources.py | 67 +++++++++++++++++++++++++++ 3 files changed, 103 insertions(+), 11 deletions(-) create mode 100644 tests/test_ingest_ssrf_and_sources.py diff --git a/app/main.py b/app/main.py index ecb2a64..e184e1d 100644 --- a/app/main.py +++ b/app/main.py @@ -21,6 +21,7 @@ from datetime import datetime, timedelta, timezone from decimal import Decimal from pathlib import Path from typing import NoReturn +from urllib.parse import urlparse from uuid import UUID import httpx @@ -43,7 +44,7 @@ from schemas import ( DashboardSummary, EntityCreate, EntityKind, EntityOut, EventCreate, EventOut, FireOut, NewsArticleOut, NewsMapItemOut, NewsSummaryOut, NewsTickerItemOut, - FeedSourceCreate, FeedSourceOut, + FeedSourceCreate, FeedSourceOut, FeedSourceUpdate, KeyOut, KeyValueIn, NewsModelsOut, SettingsIn, SettingsOut, SearchResult, SentimentSummary, SourceType, @@ -51,7 +52,8 @@ from schemas import ( GeofenceCreate, GeofenceUpdate, ) from ingestor import ingest_event, fetch_and_process -from sources import ingest_rss_feed, ingest_gdelt, ingest_earthquakes, ingest_social_signals +from camera_scraper import is_public_url +from sources import GDELT_API, ingest_rss_feed, ingest_gdelt, ingest_earthquakes, ingest_social_signals from fire_sources import ingest_fires from keystore import KeyFormatError, delete_key, list_keys, set_key from settings_store import SettingsError, get_app_settings, list_models, set_summary_model @@ -366,20 +368,22 @@ async def create_source(payload: FeedSourceCreate): @app.patch("/api/sources/{source_id}") -async def update_source(source_id: UUID, payload: dict): - """Update a feed source (e.g., toggle enabled).""" +async def update_source(source_id: UUID, payload: FeedSourceUpdate): + """Update a feed source (name/url/config/enabled only).""" + values = payload.model_dump(exclude_unset=True) async with async_session() as session: row = (await session.execute( select(feed_sources).where(feed_sources.c.id == source_id) )).mappings().one_or_none() if not row: raise HTTPException(404, "Source not found") - await session.execute( - feed_sources.update() - .where(feed_sources.c.id == source_id) - .values(**payload) - ) - await session.commit() + if values: + await session.execute( + feed_sources.update() + .where(feed_sources.c.id == source_id) + .values(**values) + ) + await session.commit() return {"ok": True} @@ -822,9 +826,15 @@ async def put_settings(payload: SettingsIn): # ── Ingestion Triggers ─────────────────────────────────────────────────── +def _require_public_url(url: str, field: str) -> None: + if not is_public_url(url): + raise HTTPException(400, f"{field} is not a public URL") + + @app.post("/api/ingest/rss") async def trigger_rss_ingest(feed_url: str, source_id: str | None = None): """Trigger RSS feed ingestion.""" + _require_public_url(feed_url, "feed_url") count = await ingest_rss_feed(feed_url, source_id) return {"status": "ok", "items_ingested": count} @@ -832,6 +842,10 @@ async def trigger_rss_ingest(feed_url: str, source_id: str | None = None): @app.post("/api/ingest/gdelt") async def trigger_gdelt_ingest(query: str = "", max_articles: int = 50): """Trigger GDELT data ingestion.""" + _require_public_url(GDELT_API, "GDELT target") + parsed = urlparse(query) + if parsed.scheme in ("http", "https") and parsed.hostname: + _require_public_url(query, "query") count = await ingest_gdelt(query, max_articles) return {"status": "ok", "articles_ingested": count} diff --git a/app/schemas.py b/app/schemas.py index 64b86c5..64676fc 100644 --- a/app/schemas.py +++ b/app/schemas.py @@ -7,7 +7,7 @@ from enum import Enum from typing import Literal, Optional from uuid import UUID -from pydantic import BaseModel, Field, field_validator +from pydantic import BaseModel, ConfigDict, Field, field_validator # ─── Enums ─────────────────────────────────────────────────────────────── @@ -63,6 +63,17 @@ class FeedSourceCreate(BaseModel): config: Optional[dict] = None +class FeedSourceUpdate(BaseModel): + """PATCH /api/sources/{id} — only these keys may be set.""" + + model_config = ConfigDict(extra="forbid") + + name: Optional[str] = None + url: Optional[str] = None + config: Optional[dict] = None + enabled: Optional[bool] = None + + class FeedSourceOut(BaseModel): id: UUID name: str diff --git a/tests/test_ingest_ssrf_and_sources.py b/tests/test_ingest_ssrf_and_sources.py new file mode 100644 index 0000000..21c85b2 --- /dev/null +++ b/tests/test_ingest_ssrf_and_sources.py @@ -0,0 +1,67 @@ +"""SSRF guard on ingest triggers + PATCH /api/sources allowlist.""" + +from __future__ import annotations + +import asyncio + +import httpx +import pytest +from pydantic import ValidationError + +from main import app + +BASE = "http://test" +LINK_LOCAL_META = "http://169.254.169.254/latest/meta-data/" +LOOPBACK = "http://127.0.0.1/secret" + + +async def _req(method: str, path: str, **kw) -> httpx.Response: + transport = httpx.ASGITransport(app=app) + async with httpx.AsyncClient(transport=transport, base_url=BASE) as client: + return await client.request(method, path, **kw) + + +def test_rss_ingest_rejects_link_local_metadata_url(monkeypatch): + called = {"n": 0} + + async def _boom(*_a, **_k): + called["n"] += 1 + raise AssertionError("ingest_rss_feed must not run for a private URL") + + monkeypatch.setattr("main.ingest_rss_feed", _boom) + resp = asyncio.run(_req("POST", "/api/ingest/rss", params={"feed_url": LINK_LOCAL_META})) + assert resp.status_code == 400 + assert called["n"] == 0 + + +def test_gdelt_ingest_rejects_private_query_url(monkeypatch): + called = {"n": 0} + + async def _boom(*_a, **_k): + called["n"] += 1 + raise AssertionError("ingest_gdelt must not run for a private URL query") + + monkeypatch.setattr("main.ingest_gdelt", _boom) + resp = asyncio.run(_req("POST", "/api/ingest/gdelt", params={"query": LOOPBACK})) + assert resp.status_code == 400 + assert called["n"] == 0 + + +def test_update_source_rejects_unknown_fields(): + sid = "00000000-0000-0000-0000-000000000001" + resp = asyncio.run(_req("PATCH", f"/api/sources/{sid}", json={"enabled": True, "source_type": "rss"})) + assert resp.status_code == 422 + + +def test_feed_source_update_allowlist_only(): + from schemas import FeedSourceUpdate + + payload = FeedSourceUpdate(name="n", url="https://example.com/rss", config={"k": 1}, enabled=False) + assert payload.model_dump(exclude_unset=True) == { + "name": "n", + "url": "https://example.com/rss", + "config": {"k": 1}, + "enabled": False, + } + with pytest.raises(ValidationError): + FeedSourceUpdate.model_validate({"enabled": True, "id": "00000000-0000-0000-0000-000000000001"}) From 158ecc623505198dceb1df330222621f0aac1e5a Mon Sep 17 00:00:00 2001 From: Sirius DevOps Date: Tue, 1 Sep 2026 00:47:24 -0400 Subject: [PATCH 53/79] chore: remove unused masscan scanner Active discovery never produced cameras rows. Drop the scanner, systemd unit, ingest trigger, and docs/env knobs. Keep RTSP preview via ffmpeg. --- .env.example | 14 --- app/bg_jobs.py | 35 +----- app/camera_preview.py | 61 +--------- app/main.py | 21 +--- app/masscan_config.py | 65 ---------- app/masscan_scanner.py | 226 ----------------------------------- app/run_masscan_service.py | 149 ----------------------- deploy/README.md | 31 ----- deploy/masscan-excludes.txt | 33 ----- deploy/osint-masscan.service | 29 ----- docs/free-data-streams.md | 10 +- tests/test_bg_jobs.py | 49 ++++---- tests/test_hud_osiris.py | 2 +- 13 files changed, 32 insertions(+), 693 deletions(-) delete mode 100644 app/masscan_config.py delete mode 100644 app/masscan_scanner.py delete mode 100644 app/run_masscan_service.py delete mode 100644 deploy/README.md delete mode 100644 deploy/masscan-excludes.txt delete mode 100644 deploy/osint-masscan.service diff --git a/.env.example b/.env.example index d64b31b..7d194f6 100644 --- a/.env.example +++ b/.env.example @@ -31,20 +31,6 @@ NOMINATIM_URL=https://nominatim.openstreetmap.org NOMINATIM_MIN_INTERVAL=1.1 SNAPSHOT_TTL_SECONDS=300 -# ── masscan active camera discovery (host-level systemd service, NOT compose) ─ -# Continuous rolling sweep for open RTSP port 554 across a range. Runs on the -# Pi host via deploy/osint-masscan.service (needs root + raw sockets). Results -# land in the same `cameras` table as the scraper (discovery_source=masscan). -# NOTE: 200 pps is the residential-safe default. 1k/10k pps saturated a home -# uplink. A full 0.0.0.0/0 sweep at 200 pps takes ~8 months (rolling). -MASSCAN_RANGE=0.0.0.0/0 -MASSCAN_PORTS=554 -MASSCAN_RATE=200 -MASSCAN_RETRIES=1 -MASSCAN_WAIT=0 -MASSCAN_EXCLUDEFILE=/etc/osint-dashboard/masscan-excludes.txt -MASSCAN_FLUSH_EVERY=250 - # ── NASA FIRMS (active fire / hotspot ingest) ────────────────────────────── # MAP_KEY is FREE — get one at https://firms.modaps.eosdis.nasa.gov/api/map_key_info/ # (1-minute signup, no payment). Leave blank to keep fire ingest idle. diff --git a/app/bg_jobs.py b/app/bg_jobs.py index 8d14747..3a38173 100644 --- a/app/bg_jobs.py +++ b/app/bg_jobs.py @@ -1,50 +1,19 @@ -"""Background masscan / ffmpeg — never block a FastAPI request on a scan. +"""Background ffmpeg — never block a FastAPI request on a frame grab. -masscan is capped at 200 pps (home uplink saturates at 1k+). ffmpeg frame -grabs are scheduled with asyncio.create_task and shared per URL. +ffmpeg frame grabs are scheduled with asyncio.create_task and shared per URL. """ from __future__ import annotations import asyncio -import logging import shutil from cachetools import TTLCache -logger = logging.getLogger("osint.bg_jobs") - -MASSCAN_PPS_CAP = 200 - -_masscan_task: asyncio.Task | None = None _ffmpeg_cache: TTLCache = TTLCache(maxsize=100, ttl=300) _ffmpeg_tasks: dict[str, asyncio.Task] = {} _FFMPEG = shutil.which("ffmpeg") -def schedule_masscan_pass() -> bool: - """Kick one capped masscan pass. Returns False if a pass is already running.""" - global _masscan_task - if _masscan_task is not None and not _masscan_task.done(): - return False - _masscan_task = asyncio.create_task(_run_masscan_capped()) - return True - - -async def _run_masscan_capped() -> None: - import masscan_config as cfg - from run_masscan_service import _verify_excludefile, run_pass - - orig = cfg.MASSCAN_RATE - if orig > MASSCAN_PPS_CAP: - logger.warning("capping masscan rate %s pps -> %s", orig, MASSCAN_PPS_CAP) - cfg.MASSCAN_RATE = MASSCAN_PPS_CAP - try: - _verify_excludefile() - await run_pass() - finally: - cfg.MASSCAN_RATE = orig - - def cached_ffmpeg_jpeg(url: str) -> bytes | None: return _ffmpeg_cache.get(url) diff --git a/app/camera_preview.py b/app/camera_preview.py index 2c89e77..e6f924c 100644 --- a/app/camera_preview.py +++ b/app/camera_preview.py @@ -1,7 +1,7 @@ """Resolve a browser-renderable preview for a camera. HTTP/MJPEG cameras already expose a snapshot_url the existing proxy can -stream. masscan finds are stored as `rtsp://IP/` with no snapshot_url, so +stream. Some scraper sources store `rtsp://` URLs with no snapshot_url, so the map popup used to skip the entirely and the leftover source link handed the browser an rtsp:// URL (which opens VLC). @@ -42,16 +42,6 @@ _HTTP_PATHS = ( "/tmpfs/auto.jpg", ) -# Browser-playable MJPEG paths the /stream proxy can pass through. -_MJPEG_PATHS = ( - "/mjpg/video.mjpg", - "/video.mjpg", - "/cgi-bin/mjpg/video.cgi", - "/axis-cgi/mjpg/video.cgi", - "/nphMotionJpeg", - "/mjpeg.cgi", -) - _FFMPEG = shutil.which("ffmpeg") @@ -87,55 +77,6 @@ async def _http_get_image(url: str, timeout: float = 2.5) -> bytes | None: return None -async def _http_feed_url(url: str, timeout: float = 2.5) -> str | None: - """Return url if it looks like an unauthenticated image/MJPEG feed.""" - try: - async with httpx.AsyncClient( - timeout=timeout, follow_redirects=True, - headers={"User-Agent": USER_AGENT}, - ) as c: - async with c.stream("GET", url) as r: - if r.status_code != 200: - return None - ctype = (r.headers.get("content-type") or "").lower() - if "html" in ctype or ctype.startswith("text/"): - return None - if any(x in ctype for x in ("image/", "multipart", "mjpeg", "octet-stream")): - # Read a little to reject empty/error bodies. - chunk = b"" - async for b in r.aiter_bytes(): - chunk += b - if len(chunk) >= 64: - break - if len(chunk) < 64: - return None - if b"html" in chunk[:64].lower(): - return None - return url - except Exception: # noqa: BLE001 - return None - return None - - -async def probe_public_feed(host: str) -> str | None: - """Unauthenticated HTTP still or MJPEG URL for this host, or None. - - Used at masscan ingest time so dead RTSP-only hosts never hit the map. - No credentials, no RTSP path-walking (too slow / rarely public). - """ - urls = [f"http://{host}{p}" for p in _HTTP_PATHS] - urls.append(f"http://{host}:8080/shot.jpg") - urls.extend(f"http://{host}{p}" for p in _MJPEG_PATHS) - results = await asyncio.gather( - *(_http_feed_url(u) for u in urls), - return_exceptions=True, - ) - for url, hit in zip(urls, results): - if isinstance(hit, str) and hit: - return hit - return None - - async def ffmpeg_snapshot(url: str, timeout: float = 8.0) -> bytes | None: """Grab a single JPEG frame from an RTSP URL. None if ffmpeg missing/fails. diff --git a/app/main.py b/app/main.py index ecb2a64..0a276b5 100644 --- a/app/main.py +++ b/app/main.py @@ -25,7 +25,7 @@ from uuid import UUID import httpx import structlog -from fastapi import BackgroundTasks, FastAPI, HTTPException, Query, WebSocket, WebSocketDisconnect +from fastapi import FastAPI, HTTPException, Query, WebSocket, WebSocketDisconnect from fastapi.middleware.gzip import GZipMiddleware from fastapi.responses import FileResponse, HTMLResponse, JSONResponse from fastapi.staticfiles import StaticFiles @@ -857,21 +857,6 @@ async def trigger_social_ingest(query: str = "", max_items: int = 50): return {"status": "ok", "signals_ingested": count} -@app.post("/api/ingest/masscan") -async def trigger_masscan(background_tasks: BackgroundTasks): - """Queue one masscan pass at ≤200 pps. Does not block the request on the scan.""" - from bg_jobs import MASSCAN_PPS_CAP, schedule_masscan_pass - - async def _kick() -> None: - schedule_masscan_pass() - - background_tasks.add_task(_kick) - return JSONResponse( - {"status": "accepted", "rate_pps": MASSCAN_PPS_CAP}, - status_code=202, - ) - - @app.websocket("/ws/live") async def live_ws(ws: WebSocket): """Viewport-filtered AIS/ADS-B fan-out. Client sends {type:viewport,bbox}.""" @@ -1051,7 +1036,7 @@ async def list_cameras( True, description="Only cameras with a verified HTTP/MJPEG snapshot_url " "(the ones that actually preview). Set false to include " - "unverified masscan port-554 hits.", + "rows without a snapshot_url.", ), limit: int = Query(500, ge=1, le=5000), ): @@ -1128,7 +1113,7 @@ async def get_camera(camera_id: UUID): async def camera_snapshot(camera_id: UUID): """Still image for one camera. - HTTP cameras go through the TTL cache. masscan/RTSP finds have no HTTP + HTTP cameras go through the TTL cache. RTSP finds have no HTTP snapshot_url — we probe common still-image paths and, failing that, grab one JPEG frame from RTSP via ffmpeg. No credentials are tried. """ diff --git a/app/masscan_config.py b/app/masscan_config.py deleted file mode 100644 index 3606d3f..0000000 --- a/app/masscan_config.py +++ /dev/null @@ -1,65 +0,0 @@ -"""Active camera-discovery configuration (masscan-based, env-driven). - -All knobs read from the environment with safe defaults. The scanner targets -open TCP port 554 (RTSP — the typical IP-camera port) across a configured -range and feeds results into the same `cameras` table as the passive scraper -(discovery_source='masscan'), deduped by URL hash. - -ETHICS / SCOPE (mirrors camera_scraper.py): - * Detection only — a SYN port scan for OPEN hosts. No credential guessing, - no login attempts, no banner grabbing, and no access to camera feeds. - * Private / reserved ranges are excluded via MASSCAN_EXCLUDEFILE so the - scanner never probes RFC1918, loopback, link-local, multicast, or the - bogons. Fail closed if the excludefile is missing. - -TIMING REALITY: at the residential-safe default of 200 pps a full IPv4 -sweep (0.0.0.0/0, ~4.29B addresses) takes ~8 months. This is therefore a -CONTINUOUS ROLLING SWEEP, not a "finish in a day" job: masscan streams -open hosts to stdout and the runner ingests them incrementally, then -restarts the sweep when a pass completes. New cameras are detected as they -appear on each pass. 1k/10k pps saturated a home uplink — do not raise the -rate unless you are on a VPS / unmetered link. -""" - -from __future__ import annotations - -import os - -# Path to the masscan binary (installed on the Pi host). -MASSCAN_BIN = os.getenv("MASSCAN_BIN", "masscan") - -# CIDR(s) to sweep. Default = the whole public IPv4 space. -MASSCAN_RANGE = os.getenv("MASSCAN_RANGE", "0.0.0.0/0") - -# Port(s) to probe. Default 554 = RTSP, the typical IP-camera port. -MASSCAN_PORTS = os.getenv("MASSCAN_PORTS", "554") - -# Packets/sec. 200 is the residential-safe default — 1k/10k pps saturated -# a home uplink. Raise only on a VPS / unmetered link. -MASSCAN_RATE = int(os.getenv("MASSCAN_RATE", "200")) - -# Retransmission count. 1 maximizes unique-host coverage at low rate; the -# default (10) spends most of the budget re-probing the same hosts. -MASSCAN_RETRIES = int(os.getenv("MASSCAN_RETRIES", "1")) - -# Seconds to keep listening for straggler responses after the last probe. -# 0 avoids a 10s tail per pass; tiny loss of the very last hosts is fine -# since the sweep repeats. -MASSCAN_WAIT = int(os.getenv("MASSCAN_WAIT", "0")) - -# Excludefile path on the Pi host. Must contain RFC1918/loopback/link-local/ -# multicast/bogons so the scanner never probes private ranges. Fail closed if -# the file is absent (the runner refuses to start rather than scan wide). -MASSCAN_EXCLUDEFILE = os.getenv( - "MASSCAN_EXCLUDEFILE", "/etc/osint-dashboard/masscan-excludes.txt" -) - -# Ingest batch size — flush this many newly-seen hosts to the DB per round. -MASSCAN_FLUSH_EVERY = int(os.getenv("MASSCAN_FLUSH_EVERY", "250")) - -# NATS subject newly-found cameras are published on (same feed as the -# passive scraper so the shared ingester persists them). -MASSCAN_NATS_SUBJECT = os.getenv("MASSCAN_NATS_SUBJECT", "events.camera") - -# discovery_source tag written into the cameras table. -MASSCAN_DISCOVERY_SOURCE = os.getenv("MASSCAN_DISCOVERY_SOURCE", "masscan") diff --git a/app/masscan_scanner.py b/app/masscan_scanner.py deleted file mode 100644 index 3aa287a..0000000 --- a/app/masscan_scanner.py +++ /dev/null @@ -1,226 +0,0 @@ -"""masscan result parsing + ingestion for the OSINT dashboard. - -Turns a stream of masscan JSON-lines (open port 554 hosts) into rows in the -`cameras` table with discovery_source='masscan', deduped by URL hash against -whatever the passive scraper already found. Newly discovered hosts are also -published to NATS (`events.camera`) so the shared ingester pipeline persists -them exactly like scraper finds. - -Scope: detection of OPEN hosts only. No credentials, no banners, no feed -access. Private/reserved ranges never enter masscan (see excludefile). -""" - -from __future__ import annotations - -import asyncio -import json -import logging -from datetime import datetime, timezone - -from camera_models import cameras -from camera_scraper import url_hash, geolocate_ips -from database import async_session - -from masscan_config import ( - MASSCAN_NATS_SUBJECT, MASSCAN_DISCOVERY_SOURCE, -) - -logger = logging.getLogger("osint.masscan_scanner") - - -# ── URL building ────────────────────────────────────────────────────────── - -def build_rtsp_url(ip: str) -> str: - """Canonical URL for an open-RTSP host. Used as the dedupe key.""" - return f"rtsp://{ip}/" - - -# ── masscan JSON parsing ────────────────────────────────────────────────── -# masscan --output-format=json --output-file=- emits line-delimited JSON on a -# pipe (a bare object per open host), not the array form used for seekable -# files. We parse per-line and tolerate an accidental leading '['. - -def parse_masscan_line(line: str) -> list[dict]: - """Parse one masscan stdout line into a list of host records. - - A line may contain one JSON object or, defensively, be wrapped in an - array. Returns [] on anything unparseable (harmless — the sweep repeats). - """ - s = line.strip() - if not s: - return [] - s = s.lstrip("[").rstrip("]").strip() - if not s: - return [] - # Multiple records may share a line separated by '},{'. - if s.endswith(","): - s = s[:-1].rstrip() - out: list[dict] = [] - for cand in _split_records(s): - try: - obj = json.loads(cand) - except (json.JSONDecodeError, ValueError): - continue - if isinstance(obj, dict) and obj.get("ip"): - out.append(obj) - return out - - -def _split_records(s: str) -> list[str]: - """Split a buffer into individual JSON object strings, honoring nesting.""" - records, depth, start = [], 0, 0 - for i, ch in enumerate(s): - if ch == "{": - if depth == 0: - start = i - depth += 1 - elif ch == "}": - depth -= 1 - if depth == 0: - records.append(s[start:i + 1]) - return records - - -def extract_open_ips(records: list[dict], port: int) -> list[str]: - """Return the list of IPs from records that have `port` open.""" - ips: list[str] = [] - for rec in records: - for p in rec.get("ports", []): - if p.get("port") == port and p.get("status") == "open": - ips.append(rec["ip"]) - break - return ips - - -# ── Persistence ─────────────────────────────────────────────────────────── - -async def ingest_open_hosts(ips: list[str]) -> tuple[int, list[str]]: - """Insert-or-refresh camera rows for open RTSP hosts that have a public feed. - - A host only lands in the table (and therefore on the map) if an - unauthenticated HTTP still or MJPEG URL responds. Port-554-only hosts - are skipped. Returns (newly_inserted, hosts_with_working_feed). - """ - if not ips: - return 0, [] - from camera_preview import probe_public_feed - - unique = list(dict.fromkeys(ips)) - sem = asyncio.Semaphore(20) - - async def _probe(ip: str) -> tuple[str, str | None]: - async with sem: - return ip, await probe_public_feed(ip) - - probed = await asyncio.gather(*(_probe(ip) for ip in unique)) - live = [(ip, feed) for ip, feed in probed if feed] - if not live: - logger.info("masscan ingest: 0 working feeds of %d open-554 hosts", - len(unique)) - return 0, [] - - now = datetime.now(timezone.utc) - coords = await geolocate_ips([ip for ip, _ in live]) - new = 0 - async with async_session() as session: - for ip, feed in live: - url = build_rtsp_url(ip) - h = url_hash(url) - lat, lon = coords.get(ip, (None, None)) - existing = (await session.execute( - cameras.select().where(cameras.c.url_hash == h) - )).one_or_none() - if existing is None: - await session.execute(cameras.insert().values( - url_hash=h, - source_url=url, - snapshot_url=feed, - discovery_source=MASSCAN_DISCOVERY_SOURCE, - location_lat=lat, - location_lon=lon, - location_name=f"{ip} (IP-geo)" if lat is not None else None, - vendor=None, - device_type="rtsp", - first_seen=now, - last_seen=now, - raw={"discovered_via": "masscan", "port": 554, - "public_feed": feed}, - )) - new += 1 - else: - await session.execute(cameras.update().where( - cameras.c.url_hash == h - ).values( - last_seen=now, - snapshot_url=feed, - location_lat=lat, - location_lon=lon, - location_name=f"{ip} (IP-geo)" if lat is not None else None, - )) - await session.commit() - logger.info("masscan ingest: %d new working feeds (%d probed, %d open-554)", - new, len(live), len(unique)) - return new, [ip for ip, _ in live] - - -# ── NATS publish ────────────────────────────────────────────────────────── - -async def publish_new_hosts(ips: list[str]) -> int: - """Publish newly-found open hosts to NATS for the shared ingester. - - Returns the number of messages published (0 if NATS is down). - """ - import json as _json - import nats - from config import NATS_URL - - if not ips: - return 0 - try: - nc = await nats.connect(NATS_URL) - except Exception: # noqa: BLE001 - logger.warning("NATS unavailable — skipping publish pass") - return 0 - published = 0 - try: - js = nc.jetstream() - for ip in dict.fromkeys(ips): - url = build_rtsp_url(ip) - msg = { - "source_type": "camera", - "title": f"Open RTSP camera ({ip})", - "url": url, - "location_lat": None, - "location_lon": None, - "location_name": None, - "tags": ["osint", "camera", MASSCAN_DISCOVERY_SOURCE], - "raw": { - "url_hash": url_hash(url), - "source_url": url, - "snapshot_url": None, - "vendor": None, - "device_type": "rtsp", - "discovered_via": "masscan", - "port": 554, - }, - "source_timestamp": datetime.now(timezone.utc).isoformat(), - } - await js.publish(MASSCAN_NATS_SUBJECT, _json.dumps(msg).encode()) - published += 1 - finally: - await nc.close() - logger.info("published %d masscan finds to %s", published, MASSCAN_NATS_SUBJECT) - return published - - -# ── Batch drain helper used by the runner ───────────────────────────────── - -async def flush(seen: set[str], new_accum: int) -> tuple[int, int]: - """Ingest + publish the accumulated host set; return (new, published).""" - if not seen: - return 0, 0 - ips = list(seen) - new, live = await ingest_open_hosts(ips) - published = await publish_new_hosts(live) - seen.clear() - return new, published diff --git a/app/run_masscan_service.py b/app/run_masscan_service.py deleted file mode 100644 index 2628576..0000000 --- a/app/run_masscan_service.py +++ /dev/null @@ -1,149 +0,0 @@ -"""Continuous masscan rolling-sweep service for the OSINT dashboard. - -Runs masscan against the configured range for open port 554 (RTSP), streams -the JSON-lines output, and ingests open hosts into the `cameras` table (new -finds only) plus publishes them to NATS — exactly like the passive scraper. - -Because a full IPv4 sweep at a conservative rate takes days, this runs -masscan CONTINUOUSLY: each pass streams results in as they're found, and when -a pass completes the sweep restarts from the top. New cameras are picked up -on every pass. - -Ethics: detection-only (open-port SYN scan). Private/reserved ranges are -excluded and the service REFUSES to start if the excludefile is missing, so -we never probe private space by accident. - -Run once (for a manual/test pass): python app/run_masscan_service.py --once -Run forever (systemd): python app/run_masscan_service.py -""" - -from __future__ import annotations - -import asyncio -import logging -import os -import sys -from pathlib import Path - -sys_path = str(Path(__file__).parent) -sys.path.insert(0, sys_path) - -import masscan_config as cfg # noqa: E402 -from database import init_extensions # noqa: E402 -from masscan_scanner import ( # noqa: E402 - parse_masscan_line, extract_open_ips, flush, -) - -logging.basicConfig(level=logging.INFO, - format="%(asctime)s %(levelname)s %(name)s: %(message)s") -logger = logging.getLogger("osint.masscan_service") - -ONCE = "--once" in sys.argv[1:] - - -def _verify_excludefile() -> None: - """Fail closed: refuse to sweep the wide range without an excludefile.""" - if not cfg.MASSCAN_EXCLUDEFILE: - raise SystemExit("MASSCAN_EXCLUDEFILE is empty — refusing to run") - if not Path(cfg.MASSCAN_EXCLUDEFILE).is_file(): - raise SystemExit( - f"excludefile {cfg.MASSCAN_EXCLUDEFILE!r} missing — refusing to " - f"run (would risk probing private ranges). Install the excludefile " - f"first (see deploy/masscan-excludes.txt)." - ) - - -def build_command() -> list[str]: - cmd = [ - cfg.MASSCAN_BIN, - cfg.MASSCAN_RANGE, - f"-p{cfg.MASSCAN_PORTS}", - f"--rate={cfg.MASSCAN_RATE}", - f"--retries={cfg.MASSCAN_RETRIES}", - f"--wait={cfg.MASSCAN_WAIT}", - "--output-format=json", - "--output-file=-", - ] - if cfg.MASSCAN_EXCLUDEFILE: - cmd.append(f"--excludefile={cfg.MASSCAN_EXCLUDEFILE}") - return cmd - - -async def _drain_stderr(stream: asyncio.StreamReader) -> None: - """Consume masscan's progress chatter so its stderr pipe never fills.""" - while True: - line = await stream.readline() - if not line: - break - text = line.decode(errors="ignore").strip() - if text and not text.startswith("rate:"): - logger.debug("masscan: %s", text) - - -async def run_pass() -> tuple[int, int]: - """Run one full sweep pass, ingesting incrementally. - - Returns (new_hosts, total_hosts_seen) for the whole pass. - """ - cmd = build_command() - logger.info("starting masscan pass: %s", " ".join(cmd)) - proc = await asyncio.create_subprocess_exec( - *cmd, - stdout=asyncio.subprocess.PIPE, - stderr=asyncio.subprocess.PIPE, - ) - if proc.stderr is not None: - asyncio.ensure_future(_drain_stderr(proc.stderr)) - - seen: set[str] = set() - total_seen = 0 - total_new = 0 - try: - while True: - raw = await proc.stdout.readline() - if not raw: - break - records = parse_masscan_line(raw.decode(errors="ignore")) - for ip in extract_open_ips(records, 554): - if ip in seen: - continue - seen.add(ip) - if len(seen) >= cfg.MASSCAN_FLUSH_EVERY: - new, _published = await flush(seen, total_new) - total_new += new - total_seen += new - # Drain the final partial batch. - if seen: - new, _published = await flush(seen, total_new) - total_new += new - rc = await proc.wait() - except asyncio.CancelledError: - proc.kill() - raise - logger.info("masscan pass finished (rc=%s): %d new hosts ingested", - rc, total_new) - return total_new, total_seen - - -async def main() -> None: - _verify_excludefile() - await init_extensions() - logger.info( - "masscan service starting: range=%s ports=%s rate=%s pps (full sweep " - "~%.0fh at this rate)", - cfg.MASSCAN_RANGE, cfg.MASSCAN_PORTS, cfg.MASSCAN_RATE, - 4.29e9 / cfg.MASSCAN_RATE / 3600, - ) - while True: - try: - await run_pass() - except Exception: # noqa: BLE001 - logger.exception("masscan pass error") - if ONCE: - return - # Small gap between passes so the restart is visible in logs. - await asyncio.sleep(5) - - -if __name__ == "__main__": - asyncio.run(main()) diff --git a/deploy/README.md b/deploy/README.md deleted file mode 100644 index cbe25b8..0000000 --- a/deploy/README.md +++ /dev/null @@ -1,31 +0,0 @@ -# systemd unit template — copy to /etc/systemd/system/osint-masscan.service -# -# The masscan service is a CONTINUOUS rolling sweep (a full IPv4 pass at a -# conservative rate takes ~5 days), so it runs as a long-lived service, NOT a -# daily timer. The [Install] WantedBy means it starts at boot and Restart=always -# keeps it up. Install steps (run once on the Pi, as root): -# -# apt install -y masscan # or: apt-get install masscan -# mkdir -p /etc/osint-dashboard /opt/siriusdevops -# cp deploy/masscan-excludes.txt /etc/osint-dashboard/masscan-excludes.txt -# -# # Optional tuning (override env in this file; the DB_* values in the unit -# # already point at the host-published Postgres on 127.0.0.1:5432): -# cat > /etc/osint-dashboard/masscan.env <<'EOF' -# MASSCAN_RANGE=0.0.0.0/0 -# MASSCAN_PORTS=554 -# MASSCAN_RATE=1000 -# EOF -# -# # Venv for the scanner (host-level, not the compose image): -# cd /opt/siriusdevops/osint-dashboard -# python3 -m venv .venv-masscan -# .venv-masscan/bin/pip install -r app/requirements.txt -# -# install -m 644 deploy/osint-masscan.service /etc/systemd/system/ -# systemctl daemon-reload -# systemctl enable --now osint-masscan -# -# Watch: journalctl -u osint-masscan -f -# DB: writes into the same Postgres the compose stack uses (127.0.0.1:5432) -# so findings appear on the dashboard camera map automatically. diff --git a/deploy/masscan-excludes.txt b/deploy/masscan-excludes.txt deleted file mode 100644 index e93defb..0000000 --- a/deploy/masscan-excludes.txt +++ /dev/null @@ -1,33 +0,0 @@ -# masscan excludefile — never probe these ranges. -# RFC1918 private + loopback + link-local + multicast + documentation/bogons. -# The service refuses to start if this file is missing (fail closed). - -# Loopback -127.0.0.0/8 - -# RFC1918 private -10.0.0.0/8 -172.16.0.0/12 -192.168.0.0/16 - -# Link-local -169.254.0.0/16 - -# CGNAT (RFC 6598) -100.64.0.0/10 - -# Multicast + reserved -224.0.0.0/4 -240.0.0.0/4 - -# Documentation / benchmark / example ranges (never real hosts) -0.0.0.0/8 -192.0.2.0/24 -198.51.100.0/24 -203.0.113.0/24 -192.0.0.0/24 -198.18.0.0/15 -255.255.255.255/32 - -# Carrier NAT / TEST-NET leftovers -233.252.0.0/24 diff --git a/deploy/osint-masscan.service b/deploy/osint-masscan.service deleted file mode 100644 index ce6b34c..0000000 --- a/deploy/osint-masscan.service +++ /dev/null @@ -1,29 +0,0 @@ -[Unit] -Description=OSINT dashboard — masscan rolling sweep (open RTSP port 554) -Documentation=https://forgejo.siriusdevops.com/sirius/osint-dashboard -After=network-online.target -Wants=network-online.target - -[Service] -Type=simple -# masscan needs raw sockets (CAP_NET_RAW) — run as root on the Pi host. -User=root -WorkingDirectory=/opt/siriusdevops/osint-dashboard -EnvironmentFile=-/etc/osint-dashboard/masscan.env -# Point at the compose-published Postgres on the HOST (127.0.0.1:5432), not the -# docker service name 'postgres' which doesn't resolve outside the compose net. -Environment=DB_HOST=127.0.0.1 -Environment=DB_PORT=5432 -Environment=DB_USER=osint -Environment=DB_PASSWORD=osint -Environment=DB_NAME=osint_data -Environment=MASSCAN_EXCLUDEFILE=/etc/osint-dashboard/masscan-excludes.txt -ExecStart=/opt/siriusdevops/osint-dashboard/.venv-masscan/bin/python app/run_masscan_service.py -Restart=always -RestartSec=10 -# Log the sweep to journald (read with: journalctl -u osint-masscan -f) -StandardOutput=journal -StandardError=journal - -[Install] -WantedBy=multi-user.target diff --git a/docs/free-data-streams.md b/docs/free-data-streams.md index 3f14563..55e28ba 100644 --- a/docs/free-data-streams.md +++ b/docs/free-data-streams.md @@ -2,7 +2,7 @@ Builder brief for backend + frontend. Researched 2026-08-27. Every endpoint below was either live-probed from this machine or taken from the provider’s current docs. Prefer **free, no-key, CORS-open** sources first. Keys are called out explicitly. -This is **not** a camera-discovery / masscan change. Existing camera rules still apply: never emit `rtsp://` hrefs; masscan pins go through `/api/cameras/{id}/snapshot`; HTTP directory cams use `/stream` MJPEG. +This is **not** a camera-discovery change. Existing camera rules still apply: never emit `rtsp://` hrefs; camera pins go through `/api/cameras/{id}/snapshot`; HTTP directory cams use `/stream` MJPEG. --- @@ -13,7 +13,7 @@ This is **not** a camera-discovery / masscan change. Existing camera rules still | NASA FIRMS VIIRS hotspots | Ingested (`app/fire_sources.py` → NATS `events.fire` → `fires` hypertable → `GET /api/fires`) | Needs free `FIRMS_MAP_KEY`. See `docs/firms.md`. | | NASA GIBS basemaps | Frontend tiles via `app/gibs_map.py` | No key. CORS `*`. | | GIBS VIIRS thermal tiles | Documented, not wired as overlay | Same GIBS stack; no key. | -| Cameras | Scraper + masscan → `cameras` table | Defaults already include ALERTWest JPEGs + Live-Environment-Streams HLS/YouTube GeoJSON. | +| Cameras | Scraper → `cameras` table | Defaults already include ALERTWest JPEGs + Live-Environment-Streams HLS/YouTube GeoJSON. | | News / RSS / GDELT / USGS quakes | Ingest | Out of scope for this brief. | **Action for existing fire ingest:** NASA will stop Suomi NPP product delivery on **2026-11-01**. Switch `FIRMS_DATASET` from `VIIRS_SNPP_NRT` to `VIIRS_NOAA20_NRT` and/or `VIIRS_NOAA21_NRT` before then.[20] @@ -261,7 +261,7 @@ Use later if you want commuter rail / subway vehicle positions (LA Metro, MTA, e ## 6. Open video / camera feeds (official public only) -Do **not** add Insecam-style random IP cams as a new source. The scraper already has a public list + masscan; this section is **agency-published** JPEG/HLS. +Do **not** add Insecam-style random IP cams as a new source. The scraper already has a public list; this section is **agency-published** JPEG/HLS. ### 6.1 Already wired @@ -304,7 +304,7 @@ Do not call the YouTube Data API unless you want search. Embedding existing stre ### 6.5 Skip -- Insecam / random “public IP cam” aggregators — ToS / privacy / already covered by masscan ethics. +- Insecam / random “public IP cam” aggregators — ToS / privacy. - TrafficLand, EarthCam commercial APIs. - SkylineWebcams — scraping, not an API. @@ -523,7 +523,7 @@ Attribution bar (required): OpenSky / ADSB.lol ODbL / Amtraker / RainViewer / IE ## 12. Legal / ethics (non-negotiable) -- Masscan / RTSP policy unchanged. +- RTSP policy unchanged (never emit `rtsp://` hrefs). - AISStream: server-side only; do not put the key in JS.[5] - OpenSky: non-commercial unless licensed; cite if you publish.[2] - ADSB.lol: ODbL share-alike on derived databases.[4] diff --git a/tests/test_bg_jobs.py b/tests/test_bg_jobs.py index fed5541..8326aef 100644 --- a/tests/test_bg_jobs.py +++ b/tests/test_bg_jobs.py @@ -1,4 +1,4 @@ -"""masscan/ffmpeg stay off the request path (asyncio.create_task).""" +"""ffmpeg snapshots stay off the request path (asyncio.create_task).""" from __future__ import annotations @@ -7,36 +7,27 @@ import asyncio import bg_jobs -def test_schedule_masscan_pass_returns_without_awaiting_scan(monkeypatch): - started = {"n": 0} - - async def slow_pass(): - started["n"] += 1 - await asyncio.sleep(30) - - monkeypatch.setattr(bg_jobs, "_run_masscan_capped", slow_pass) - bg_jobs._masscan_task = None - - async def run(): - launched = bg_jobs.schedule_masscan_pass() - assert launched is True - # Must not have blocked for the 30s pass. - assert bg_jobs._masscan_task is not None - assert not bg_jobs._masscan_task.done() - launched2 = bg_jobs.schedule_masscan_pass() - assert launched2 is False # already running - bg_jobs._masscan_task.cancel() - try: - await bg_jobs._masscan_task - except (asyncio.CancelledError, Exception): - pass - bg_jobs._masscan_task = None - - asyncio.run(run()) +def test_bg_jobs_has_no_pps_cap(): + assert not any(name.endswith("_PPS_CAP") for name in dir(bg_jobs)) -def test_masscan_rate_cap_is_200(): - assert bg_jobs.MASSCAN_PPS_CAP == 200 +def test_camera_preview_has_no_public_feed_probe(): + import camera_preview + + assert not hasattr(camera_preview, "probe_public_feed") + assert not hasattr(camera_preview, "_http_feed_url") + + +def test_ingest_routes_exclude_active_discovery(): + from main import app + + ingest = [ + getattr(r, "path", "") + for r in app.routes + if getattr(r, "path", "").startswith("/api/ingest/") + ] + assert "/api/ingest/fires" in ingest + assert all("scan" not in path for path in ingest) def test_schedule_ffmpeg_snapshot_is_a_task_not_inline(monkeypatch): diff --git a/tests/test_hud_osiris.py b/tests/test_hud_osiris.py index a4035de..f2ad986 100644 --- a/tests/test_hud_osiris.py +++ b/tests/test_hud_osiris.py @@ -60,7 +60,7 @@ def test_camera_thumbs_gated_at_zoom_12(): assert "camThumbsAllowed" in thumb or "CAM_THUMB_MIN_ZOOM" in thumb assert "zoom in for preview" in HTML or "zoom for preview" in HTML assert "preview unavailable" in HTML - # Masscan / RTSP still proxy through snapshot; never emit rtsp hrefs. + # RTSP still proxy through snapshot; never emit rtsp hrefs. src = _fn("camSourceLink", "youtubeId") assert "rtsp://" in src assert "href=" not in src.split("rtsp://")[1].split("return")[0] or "Never emit" in src From f6c1cfc4546415f4a3b18031147821b29fac57e2 Mon Sep 17 00:00:00 2001 From: Sirius DevOps Date: Tue, 1 Sep 2026 01:24:36 -0400 Subject: [PATCH 54/79] feat(geofence): watch list, filtered hit log, fence snapshot Off-viewport clients that send {type:watch_geofences,ids} on /ws/live still receive geofence_alert; AIS/ADS-B stay viewport-only. GET /api/geofence-alerts accepts geofence_id/since/until/source_kind. GET /api/geofences/{id}/at returns CAGG+FIRMS inside the fence at T (404 if missing, empty lists if DB down). DELETE missing fences 404s. --- alembic/versions/011_geofence_alerts_fence.py | 24 ++ app/geofence.py | 151 +++++++++++ app/main.py | 92 +++++-- app/ws_manager.py | 38 ++- tests/test_geofence.py | 249 +++++++++++++++++- tests/test_phase2_api.py | 108 ++++++++ 6 files changed, 625 insertions(+), 37 deletions(-) create mode 100644 alembic/versions/011_geofence_alerts_fence.py diff --git a/alembic/versions/011_geofence_alerts_fence.py b/alembic/versions/011_geofence_alerts_fence.py new file mode 100644 index 0000000..4b29f74 --- /dev/null +++ b/alembic/versions/011_geofence_alerts_fence.py @@ -0,0 +1,24 @@ +"""geofence_alerts (geofence_id, created_at DESC) for fence-scoped hit log + +Revision ID: 011_geofence_alerts_fence +Revises: 010_bbox_gist +Create Date: 2026-09-01 +""" + +from alembic import op + +revision = "011_geofence_alerts_fence" +down_revision = "010_bbox_gist" +branch_labels = None +depends_on = None + + +def upgrade() -> None: + op.execute( + "CREATE INDEX IF NOT EXISTS ix_geofence_alerts_fence_created " + "ON geofence_alerts (geofence_id, created_at DESC)" + ) + + +def downgrade() -> None: + op.execute("DROP INDEX IF EXISTS ix_geofence_alerts_fence_created") diff --git a/app/geofence.py b/app/geofence.py index 398c73b..f010a3f 100644 --- a/app/geofence.py +++ b/app/geofence.py @@ -319,3 +319,154 @@ async def record_and_notify( except Exception: pass return sent + + +async def list_alerts( + *, + geofence_id: str | None = None, + since: datetime | None = None, + until: datetime | None = None, + source_kind: str | None = None, + limit: int = 100, +) -> list[dict]: + """Filterable hit log. Empty list if the DB is down — never raises.""" + where = ["TRUE"] + params: dict[str, Any] = {"limit": int(limit)} + if geofence_id: + where.append("geofence_id = CAST(:geofence_id AS uuid)") + params["geofence_id"] = geofence_id + if since is not None: + where.append("created_at >= :since") + params["since"] = since + if until is not None: + where.append("created_at <= :until") + params["until"] = until + if source_kind: + where.append("source_kind = :source_kind") + params["source_kind"] = source_kind + sql = f""" + SELECT id::text, geofence_id::text, source_kind, entity_id, + lat, lon, payload, created_at + FROM geofence_alerts + WHERE {' AND '.join(where)} + ORDER BY created_at DESC + LIMIT :limit + """ + try: + async with async_session() as session: + rows = (await session.execute(text(sql), params)).mappings().all() + out = [] + for r in rows: + item = dict(r) + if item.get("created_at") is not None: + item["created_at"] = item["created_at"].isoformat() + out.append(item) + return out + except Exception: + return [] + + +async def get_geofence(gid: str) -> dict | None: + current = next((f for f in _cache if f["id"] == gid), None) + if current is not None: + return current + try: + await refresh_cache() + except Exception: + return None + return next((f for f in _cache if f["id"] == gid), None) + + +def _marker_from_track(row) -> dict: + from live_layers import to_marker + + extra = {"bucket": row["bucket"].isoformat() if row.get("bucket") else None, "dvr": True} + return to_marker( + row["id"], row["lat"], row["lon"], + heading=row.get("heading"), speed=row.get("speed"), + label=row.get("label") or row["id"], + extra=extra, + ) + + +async def _cagg_inside(gid: str, kind: str, bucket: datetime, limit: int = 2000) -> list[dict]: + table = "aircraft_tracks_1min" if kind == "aircraft" else "vessel_tracks_1min" + id_col = "hex" if kind == "aircraft" else "mmsi" + sql = f""" + SELECT {id_col} AS id, lat, lon, heading, speed, label, bucket + FROM {table} + WHERE bucket = :bucket + AND ST_Intersects( + (SELECT geom FROM geofences WHERE id = CAST(:gid AS uuid)), + ST_SetSRID(ST_MakePoint(lon, lat), 4326) + ) + LIMIT :limit + """ + try: + async with async_session() as session: + rows = (await session.execute( + text(sql), {"bucket": bucket, "gid": gid, "limit": limit}, + )).mappings().all() + return [ + _marker_from_track(r) + for r in rows + if r["lat"] is not None and r["lon"] is not None + ] + except Exception: + return [] + + +async def _fires_inside(gid: str, ts: datetime, limit: int = 2000) -> list[dict]: + from tracks import minute_bucket + + bucket = minute_bucket(ts) + t1 = bucket + timedelta(minutes=1) + sql = """ + SELECT latitude, longitude, brightness, confidence, acq_time, satellite, + instrument, bright_ti5, frp, daynight + FROM fires + WHERE acq_time >= :t0 AND acq_time < :t1 + AND ST_Intersects( + (SELECT geom FROM geofences WHERE id = CAST(:gid AS uuid)), + ST_SetSRID(ST_MakePoint(longitude, latitude), 4326) + ) + LIMIT :limit + """ + try: + async with async_session() as session: + rows = (await session.execute( + text(sql), + {"t0": bucket, "t1": t1, "gid": gid, "limit": limit}, + )).mappings().all() + out = [] + for r in rows: + item = dict(r) + if item.get("acq_time") is not None: + item["acq_time"] = item["acq_time"].isoformat() + out.append(item) + return out + except Exception: + return [] + + +async def snapshot_at(gid: str, ts: datetime) -> dict | None: + """Positions inside the fence at time T. None if the fence is missing. + + Does not persist or notify. Empty lists if track/fire queries fail. + """ + fence = await get_geofence(gid) + if fence is None: + return None + from tracks import minute_bucket + + bucket = minute_bucket(ts) + aircraft = await _cagg_inside(gid, "aircraft", bucket) + vessels = await _cagg_inside(gid, "vessel", bucket) + fires = await _fires_inside(gid, ts) + return { + "geofence_id": gid, + "timestamp": ts.isoformat(), + "aircraft": aircraft, + "vessels": vessels, + "fires": fires, + } diff --git a/app/main.py b/app/main.py index 57c9d33..049d96c 100644 --- a/app/main.py +++ b/app/main.py @@ -873,7 +873,14 @@ async def trigger_social_ingest(query: str = "", max_items: int = 50): @app.websocket("/ws/live") async def live_ws(ws: WebSocket): - """Viewport-filtered AIS/ADS-B fan-out. Client sends {type:viewport,bbox}.""" + """Viewport-filtered AIS/ADS-B fan-out. + + Client JSON: + {"type":"viewport","bbox":"minlon,minlat,maxlon,maxlat"} + {"type":"watch_geofences","ids":["", ...]} — empty list = none + geofence_alert delivers if the point is in-viewport OR geofence_id is watched. + AIS/ADS-B/fire_aircraft stay viewport-only. + """ from ws_manager import manager client_id = str(id(ws)) @@ -899,6 +906,10 @@ async def live_ws(ws: WebSocket): manager.set_viewport(client_id, parse_bbox(str(data["bbox"]))) except ValueError: continue + elif data.get("type") == "watch_geofences": + ids = data.get("ids") or [] + if isinstance(ids, list): + manager.set_watched_geofences(client_id, [str(x) for x in ids]) except WebSocketDisconnect: pass finally: @@ -1757,33 +1768,68 @@ async def api_update_geofence(gid: str, payload: GeofenceUpdate): @app.delete("/api/geofences/{gid}", status_code=204) async def api_delete_geofence(gid: str): from geofence import delete_geofence - await delete_geofence(gid) + ok = await delete_geofence(gid) + if not ok: + raise HTTPException(404, "geofence not found") return None -@app.get("/api/geofence-alerts") -async def api_geofence_alerts(limit: int = Query(100, ge=1, le=500)): - from sqlalchemy import text as sql_text +@app.get("/api/geofences/{gid}/at") +async def api_geofence_at( + gid: str, + timestamp: str = Query(..., description="ISO-8601 instant for the 1-minute DVR bucket"), +): + """Aircraft/vessels/fires inside this fence at time T. Never writes.""" + from geofence import snapshot_at + from tracks import parse_timestamp + try: - async with async_session() as session: - rows = (await session.execute(sql_text( - """ - SELECT id::text, geofence_id::text, source_kind, entity_id, - lat, lon, payload, created_at - FROM geofence_alerts - ORDER BY created_at DESC - LIMIT :limit - """ - ), {"limit": limit})).mappings().all() - out = [] - for r in rows: - item = dict(r) - if item.get("created_at") is not None: - item["created_at"] = item["created_at"].isoformat() - out.append(item) - return out + ts = parse_timestamp(timestamp) + except ValueError as exc: + raise HTTPException(422, str(exc)) from exc + if ts is None: + raise HTTPException(422, "timestamp required") + try: + body = await snapshot_at(gid, ts) except Exception: - return [] + body = { + "geofence_id": gid, + "timestamp": ts.isoformat(), + "aircraft": [], + "vessels": [], + "fires": [], + } + if body is None: + raise HTTPException(404, "geofence not found") + return body + + +@app.get("/api/geofence-alerts") +async def api_geofence_alerts( + geofence_id: UUID | None = Query(None), + since: str | None = Query(None, description="ISO-8601 inclusive lower bound"), + until: str | None = Query(None, description="ISO-8601 inclusive upper bound"), + source_kind: str | None = Query(None, description="firms|ais|adsb"), + limit: int = Query(100, ge=1, le=500), +): + """Hit log for drawn fences. Not /api/alerts (entity/keyword).""" + from geofence import list_alerts + from tracks import parse_timestamp + + if source_kind is not None and source_kind not in ("firms", "ais", "adsb"): + raise HTTPException(422, "source_kind must be one of: firms, ais, adsb") + try: + since_ts = parse_timestamp(since) if since else None + until_ts = parse_timestamp(until) if until else None + except ValueError as exc: + raise HTTPException(422, str(exc)) from exc + return await list_alerts( + geofence_id=str(geofence_id) if geofence_id else None, + since=since_ts, + until=until_ts, + source_kind=source_kind, + limit=limit, + ) @app.get("/api/fire-aircraft") diff --git a/app/ws_manager.py b/app/ws_manager.py index f91657c..9c3c59d 100644 --- a/app/ws_manager.py +++ b/app/ws_manager.py @@ -8,10 +8,18 @@ from __future__ import annotations import asyncio from typing import Any +from uuid import UUID BBox = tuple[float, float, float, float] # minlon, minlat, maxlon, maxlat +def _uuid_str(value: object) -> str | None: + try: + return str(UUID(str(value))) + except (ValueError, TypeError, AttributeError): + return None + + def point_in_bbox(lon: float, lat: float, bbox: BBox | None) -> bool: """True if (lon, lat) sits inside an axis-aligned viewport.""" if bbox is None: @@ -26,6 +34,7 @@ class ConnectionManager: def __init__(self) -> None: self._queues: dict[str, asyncio.Queue] = {} self._viewports: dict[str, BBox] = {} + self._watched: dict[str, set[str]] = {} def register(self, client_id: str, maxsize: int = 256) -> asyncio.Queue: q: asyncio.Queue = asyncio.Queue(maxsize=maxsize) @@ -35,6 +44,21 @@ class ConnectionManager: def unregister(self, client_id: str) -> None: self._queues.pop(client_id, None) self._viewports.pop(client_id, None) + self._watched.pop(client_id, None) + + def set_watched_geofences(self, client_id: str, ids: list[str]) -> None: + """Watch these fence UUIDs so geofence_alert delivers off-viewport. + + Invalid UUIDs are ignored. Empty list = watch none (viewport-only). + """ + if client_id not in self._queues: + return + watched: set[str] = set() + for raw in ids: + uid = _uuid_str(raw) + if uid is not None: + watched.add(uid) + self._watched[client_id] = watched def set_viewport(self, client_id: str, bbox: BBox) -> None: if client_id in self._queues: @@ -59,13 +83,21 @@ class ConnectionManager: ) -> int: """Enqueue `{type, payload}` for clients whose viewport contains the point. - Drops the oldest queued message if a client's buffer is full so a slow - tab cannot stall ingest. Returns the number of clients that got a copy. + kind=geofence_alert also delivers when payload.geofence_id is in the + client's watch set (even if the point is off-viewport). Other kinds + stay viewport-only. Drops the oldest queued message if a client's + buffer is full. Returns the number of clients that got a copy. """ msg = {"type": kind, "payload": payload} sent = 0 + gid = _uuid_str(payload.get("geofence_id")) if kind == "geofence_alert" else None for client_id, queue in list(self._queues.items()): - if not point_in_bbox(lon, lat, self._viewports.get(client_id)): + in_view = point_in_bbox(lon, lat, self._viewports.get(client_id)) + if kind == "geofence_alert": + watching = gid is not None and gid in self._watched.get(client_id, set()) + if not in_view and not watching: + continue + elif not in_view: continue if queue.full(): try: diff --git a/tests/test_geofence.py b/tests/test_geofence.py index df1d59d..10f533a 100644 --- a/tests/test_geofence.py +++ b/tests/test_geofence.py @@ -51,23 +51,33 @@ def test_matching_geofences_only_active_hits(): assert matching_geofences(-122.4, 37.7, fences) == [] +FENCE_ID = "11111111-1111-1111-1111-111111111111" +NC_VIEW = (-80.0, 35.0, -78.0, 36.0) +SF_VIEW = (-123.0, 37.0, -121.0, 38.0) + + +def _alert_payload(gid=FENCE_ID): + return { + "geofence_id": gid, + "geofence_name": "NC", + "source_kind": "ais", + "entity_id": "366123456", + "lat": 35.5, + "lon": -79.0, + } + + def test_geofence_alert_fans_out_only_to_viewport_clients(): mgr = ConnectionManager() q_nc = mgr.register("nc") q_sf = mgr.register("sf") - mgr.set_viewport("nc", (-80.0, 35.0, -78.0, 36.0)) - mgr.set_viewport("sf", (-123.0, 37.0, -121.0, 38.0)) + mgr.set_viewport("nc", NC_VIEW) + mgr.set_viewport("sf", SF_VIEW) async def run(): - payload = { - "geofence_id": "a", - "geofence_name": "NC", - "source_kind": "ais", - "entity_id": "366123456", - "lat": 35.5, - "lon": -79.0, - } - n = await mgr.publish_point("geofence_alert", payload, lat=35.5, lon=-79.0) + n = await mgr.publish_point( + "geofence_alert", _alert_payload(), lat=35.5, lon=-79.0, + ) assert n == 1 msg = q_nc.get_nowait() assert msg["type"] == "geofence_alert" @@ -77,6 +87,109 @@ def test_geofence_alert_fans_out_only_to_viewport_clients(): asyncio.run(run()) +def test_off_viewport_watch_receives_geofence_alert(): + mgr = ConnectionManager() + q_sf = mgr.register("sf") + mgr.set_viewport("sf", SF_VIEW) + mgr.set_watched_geofences("sf", [FENCE_ID]) + + async def run(): + n = await mgr.publish_point( + "geofence_alert", _alert_payload(), lat=35.5, lon=-79.0, + ) + assert n == 1 + msg = q_sf.get_nowait() + assert msg["type"] == "geofence_alert" + assert msg["payload"]["geofence_id"] == FENCE_ID + + asyncio.run(run()) + + +def test_off_viewport_without_watch_does_not_receive_geofence_alert(): + mgr = ConnectionManager() + q_sf = mgr.register("sf") + mgr.set_viewport("sf", SF_VIEW) + + async def run(): + n = await mgr.publish_point( + "geofence_alert", _alert_payload(), lat=35.5, lon=-79.0, + ) + assert n == 0 + assert q_sf.empty() + + asyncio.run(run()) + + +def test_on_viewport_receives_geofence_alert_without_watch(): + mgr = ConnectionManager() + q_nc = mgr.register("nc") + mgr.set_viewport("nc", NC_VIEW) + + async def run(): + n = await mgr.publish_point( + "geofence_alert", _alert_payload(), lat=35.5, lon=-79.0, + ) + assert n == 1 + assert q_nc.get_nowait()["type"] == "geofence_alert" + + asyncio.run(run()) + + +def test_ais_stays_viewport_only_even_when_watching(): + mgr = ConnectionManager() + q_sf = mgr.register("sf") + mgr.set_viewport("sf", SF_VIEW) + mgr.set_watched_geofences("sf", [FENCE_ID]) + + async def run(): + n = await mgr.publish_point("ais", {"id": "366123456"}, lat=35.5, lon=-79.0) + assert n == 0 + assert q_sf.empty() + + asyncio.run(run()) + + +def test_invalid_watch_uuids_ignored_empty_list_clears(): + mgr = ConnectionManager() + q = mgr.register("sf") + mgr.set_viewport("sf", SF_VIEW) + mgr.set_watched_geofences("sf", ["not-a-uuid", FENCE_ID, "also-bad"]) + + async def run(): + n = await mgr.publish_point( + "geofence_alert", _alert_payload(), lat=35.5, lon=-79.0, + ) + assert n == 1 + q.get_nowait() + mgr.set_watched_geofences("sf", []) + n2 = await mgr.publish_point( + "geofence_alert", _alert_payload(), lat=35.5, lon=-79.0, + ) + assert n2 == 0 + assert q.empty() + + asyncio.run(run()) + + +def test_unregister_clears_watched_geofences(): + mgr = ConnectionManager() + q = mgr.register("sf") + mgr.set_viewport("sf", SF_VIEW) + mgr.set_watched_geofences("sf", [FENCE_ID]) + mgr.unregister("sf") + q2 = mgr.register("sf") + mgr.set_viewport("sf", SF_VIEW) + + async def run(): + n = await mgr.publish_point( + "geofence_alert", _alert_payload(), lat=35.5, lon=-79.0, + ) + assert n == 0 + assert q2.empty() + + asyncio.run(run()) + + def test_record_and_notify_queries_postgis_when_cache_empty(monkeypatch): """FIRMS ingest in the ingester has an empty in-process cache — still ST_Intersects.""" import geofence @@ -134,3 +247,117 @@ def test_record_and_notify_queries_postgis_when_cache_empty(monkeypatch): inserts = [p for p in executed if isinstance(p, dict)] assert inserts and inserts[0]["source_kind"] == "firms" assert "commit" in executed + + +def test_list_alerts_sql_filters(monkeypatch): + captured: dict = {} + + class FakeResult: + def mappings(self): + return self + + def all(self): + return [] + + class FakeSession: + async def execute(self, stmt, params=None): + captured["sql"] = str(stmt) + captured["params"] = params + return FakeResult() + + async def __aenter__(self): + return self + + async def __aexit__(self, *a): + return False + + monkeypatch.setattr(geofence, "async_session", FakeSession) + from datetime import datetime, timezone + + since = datetime(2026, 8, 28, tzinfo=timezone.utc) + until = datetime(2026, 8, 29, tzinfo=timezone.utc) + + async def run(): + return await geofence.list_alerts( + geofence_id=FENCE_ID, since=since, until=until, + source_kind="firms", limit=5, + ) + + assert asyncio.run(run()) == [] + sql = captured["sql"].lower() + assert "geofence_id" in sql + assert "created_at >=" in sql + assert "created_at <=" in sql + assert "source_kind" in sql + assert captured["params"]["geofence_id"] == FENCE_ID + assert captured["params"]["source_kind"] == "firms" + assert captured["params"]["limit"] == 5 + + +def test_alembic_fence_created_index_exists(): + from pathlib import Path + text = Path(__file__).resolve().parent.parent.joinpath( + "alembic/versions/011_geofence_alerts_fence.py", + ).read_text() + assert "ix_geofence_alerts_fence_created" in text + assert "010_bbox_gist" in text + + +def test_snapshot_at_404_when_fence_missing(monkeypatch): + geofence._cache.clear() + + async def boom(): + raise RuntimeError("db down") + + monkeypatch.setattr(geofence, "refresh_cache", boom) + + async def run(): + from datetime import datetime, timezone + return await geofence.snapshot_at( + FENCE_ID, datetime(2026, 8, 28, 12, 4, tzinfo=timezone.utc), + ) + + assert asyncio.run(run()) is None + + +def test_snapshot_queries_st_intersects(monkeypatch): + geofence._cache[:] = [{ + "id": FENCE_ID, "name": "NC", "geojson": NC_BOX, "active": True, + }] + sqls: list[str] = [] + + class FakeResult: + def mappings(self): + return self + + def all(self): + return [] + + class FakeSession: + async def execute(self, stmt, params=None): + sqls.append(str(stmt)) + return FakeResult() + + async def __aenter__(self): + return self + + async def __aexit__(self, *a): + return False + + monkeypatch.setattr(geofence, "async_session", FakeSession) + + async def run(): + from datetime import datetime, timezone + return await geofence.snapshot_at( + FENCE_ID, datetime(2026, 8, 28, 12, 4, 30, tzinfo=timezone.utc), + ) + + body = asyncio.run(run()) + assert body["aircraft"] == [] + assert body["vessels"] == [] + assert body["fires"] == [] + blob = "\n".join(sqls).lower() + assert "st_intersects" in blob + assert "aircraft_tracks_1min" in blob + assert "vessel_tracks_1min" in blob + assert "from fires" in blob diff --git a/tests/test_phase2_api.py b/tests/test_phase2_api.py index e52548b..2afead2 100644 --- a/tests/test_phase2_api.py +++ b/tests/test_phase2_api.py @@ -17,6 +17,9 @@ async def _req(method: str, path: str, **kw) -> httpx.Response: return await client.request(method, path, **kw) +FENCE_ID = "11111111-1111-1111-1111-111111111111" + + def test_geofence_post_rejects_point(): resp = asyncio.run(_req( "POST", "/api/geofences", @@ -25,6 +28,111 @@ def test_geofence_post_rejects_point(): assert resp.status_code == 422 +def test_delete_geofence_404_when_missing(monkeypatch): + async def missing(_gid: str) -> bool: + return False + + monkeypatch.setattr("geofence.delete_geofence", missing) + resp = asyncio.run(_req("DELETE", f"/api/geofences/{FENCE_ID}")) + assert resp.status_code == 404 + + +def test_geofence_alerts_passes_filters(monkeypatch): + seen = {} + + async def fake_list(**kwargs): + seen.update(kwargs) + return [{"id": "a", "geofence_id": FENCE_ID, "source_kind": "ais"}] + + monkeypatch.setattr("geofence.list_alerts", fake_list) + resp = asyncio.run(_req( + "GET", "/api/geofence-alerts", + params={ + "geofence_id": FENCE_ID, + "since": "2026-08-28T00:00:00Z", + "until": "2026-08-29T00:00:00Z", + "source_kind": "ais", + "limit": 10, + }, + )) + assert resp.status_code == 200 + assert resp.json()[0]["source_kind"] == "ais" + assert seen["geofence_id"] == FENCE_ID + assert seen["source_kind"] == "ais" + assert seen["limit"] == 10 + assert seen["since"] is not None + assert seen["until"] is not None + + +def test_geofence_alerts_rejects_bad_source_kind(): + resp = asyncio.run(_req( + "GET", "/api/geofence-alerts", params={"source_kind": "camera"}, + )) + assert resp.status_code == 422 + + +def test_geofence_at_404_when_missing(monkeypatch): + async def no_snap(gid: str, ts): + return None + + monkeypatch.setattr("geofence.snapshot_at", no_snap) + resp = asyncio.run(_req( + "GET", f"/api/geofences/{FENCE_ID}/at", + params={"timestamp": "2026-08-28T12:04:00Z"}, + )) + assert resp.status_code == 404 + + +def test_geofence_at_empty_lists_when_db_down(monkeypatch): + async def empty_snap(gid: str, ts): + return { + "geofence_id": gid, + "timestamp": ts.isoformat(), + "aircraft": [], + "vessels": [], + "fires": [], + } + + monkeypatch.setattr("geofence.snapshot_at", empty_snap) + resp = asyncio.run(_req( + "GET", f"/api/geofences/{FENCE_ID}/at", + params={"timestamp": "2026-08-28T12:04:00Z"}, + )) + assert resp.status_code == 200 + body = resp.json() + assert body["geofence_id"] == FENCE_ID + assert body["aircraft"] == [] + assert body["vessels"] == [] + assert body["fires"] == [] + assert "timestamp" in body + + +def test_geofence_at_does_not_notify(monkeypatch): + called = {"notify": 0} + + async def empty_snap(gid: str, ts): + return { + "geofence_id": gid, + "timestamp": ts.isoformat(), + "aircraft": [], + "vessels": [], + "fires": [], + } + + async def boom(**_kw): + called["notify"] += 1 + raise AssertionError("GET /at must not record_and_notify") + + monkeypatch.setattr("geofence.snapshot_at", empty_snap) + monkeypatch.setattr("geofence.record_and_notify", boom) + resp = asyncio.run(_req( + "GET", f"/api/geofences/{FENCE_ID}/at", + params={"timestamp": "2026-08-28T12:04:00Z"}, + )) + assert resp.status_code == 200 + assert called["notify"] == 0 + + def test_geofences_list_does_not_collide_with_alerts(): resp = asyncio.run(_req("GET", "/api/geofences")) assert resp.status_code == 200 From 8c97ce50d246a97ab6edc6e231e9a2bebfe66aae Mon Sep 17 00:00:00 2001 From: Sirius DevOps Date: Tue, 1 Sep 2026 01:36:21 -0400 Subject: [PATCH 55/79] =?UTF-8?q?feat(map):=20geofence=20watch=20HUD=20?= =?UTF-8?q?=E2=80=94=20finish/cancel,=20inbox,=20fence=20DVR?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Phone can finish a polygon without double-click. List is mute/go/rename/delete. Inbox seeds from /api/geofence-alerts and appends WS hits. Watch all fence ids on /ws/live. Selected-fence DVR uses GET /api/geofences/{id}/at. --- app/static/index.html | 315 ++++++++++++++++++++++++++++++-- tests/test_geofence_frontend.py | 32 +++- 2 files changed, 328 insertions(+), 19 deletions(-) diff --git a/app/static/index.html b/app/static/index.html index e75f9bb..71619a5 100644 --- a/app/static/index.html +++ b/app/static/index.html @@ -374,11 +374,34 @@ .lp-future .lp-name { cursor: not-allowed; } .lp-error { color: var(--red); font-size: 0.66rem; } .lp-note { font-size: 0.6rem; color: var(--muted); opacity: 0.85; line-height: 1.35; } - .gf-list { display: flex; flex-direction: column; gap: 0.22rem; max-height: 8rem; overflow-y: auto; } - .gf-item { display: flex; justify-content: space-between; align-items: center; gap: 0.4rem; font-size: 0.64rem; } - .gf-item span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--text); } - .gf-del { background: transparent; border: 1px solid var(--magenta); color: var(--magenta); font-family: 'Share Tech Mono', monospace; font-size: 0.58rem; letter-spacing: 0.08em; text-transform: uppercase; padding: 0.12rem 0.35rem; border-radius: 3px; cursor: pointer; } + .gf-list { display: flex; flex-direction: column; gap: 0.22rem; max-height: 9.5rem; overflow-y: auto; } + .gf-item { display: flex; justify-content: space-between; align-items: center; gap: 0.35rem; font-size: 0.64rem; flex-wrap: wrap; } + .gf-item.selected { outline: 1px solid var(--cyan); background: rgba(53,224,255,0.08); border-radius: 3px; } + .gf-item .gf-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--text); background: none; border: 0; font: inherit; cursor: pointer; text-align: left; flex: 1 1 6rem; min-width: 0; padding: 0.12rem 0; } + .gf-item .gf-name:hover { color: var(--cyan); } + .gf-item .gf-actions { display: flex; align-items: center; gap: 0.28rem; flex: 0 0 auto; } + .gf-item input.gf-active { accent-color: var(--cyan); cursor: pointer; width: 14px; height: 14px; } + .gf-del, .gf-go, .gf-ren { background: transparent; border: 1px solid var(--magenta); color: var(--magenta); font-family: 'Share Tech Mono', monospace; font-size: 0.58rem; letter-spacing: 0.08em; text-transform: uppercase; padding: 0.12rem 0.35rem; border-radius: 3px; cursor: pointer; } + .gf-go, .gf-ren { border-color: var(--cyan); color: var(--cyan); } .gf-del:hover { background: rgba(255,46,151,0.16); } + .gf-go:hover, .gf-ren:hover { background: rgba(53,224,255,0.14); } + .gf-draw-row { flex-wrap: wrap; gap: 0.35rem; } + #gf-finish, #gf-cancel { min-height: 32px; } + #gf-draw-bar { + position: absolute; left: 12px; bottom: 52px; z-index: 530; + display: flex; gap: 0.4rem; align-items: center; + background: rgba(6,11,20,0.86); border: 1px solid var(--line-hi); + border-radius: 4px; padding: 0.22rem 0.4rem; + } + #gf-draw-bar[hidden] { display: none !important; } + .gf-inbox { display: flex; flex-direction: column; gap: 0.18rem; max-height: 8rem; overflow-y: auto; margin-top: 0.28rem; } + .gf-hit { + cursor: pointer; font-size: 0.58rem; line-height: 1.35; color: var(--text); + padding: 0.22rem 0.28rem; border: 1px solid var(--line); border-radius: 3px; + font-family: 'Share Tech Mono', monospace; + } + .gf-hit:hover, .gf-hit:focus { border-color: var(--cyan); outline: none; background: rgba(53,224,255,0.08); } + .gf-hit .gf-hit-meta { color: var(--muted); } /* ── Keyboard cheat sheet (centered; keep off LAYERS / zoom / dock) ── */ .cheat-sheet { @@ -787,6 +810,13 @@ min-width: 0; min-height: 32px; } + #gf-draw-bar { + left: 8px; + bottom: 56px; + } + #gf-finish, #gf-cancel, #gf-draw-bar .btn, .gf-go, .gf-del, .gf-ren { + min-height: 32px; + } .leaflet-control-attribution { display: none !important; } .leaflet-top.leaflet-right .leaflet-control-zoom { margin-top: 8px; @@ -1029,11 +1059,14 @@
Two feeds: AISStream (US live) and VesselAPI (Hormuz, 5×/day). Paste both keys on the Keys page. Magenta = military · gold = law/gov · teal = underway. Click for type / dest / IMO.
-
+
+ +
-
Click vertices, double-click to close. Delete a saved fence from the list or its popup.
+
+
Tap vertices, then Finish (or double-click). Inbox keeps hits after the toast fades.
@@ -1095,6 +1128,10 @@ live
+
@@ -2242,6 +2279,8 @@ let firefighterHex = new Set(); let dvrTs = null; let dvrMinMs = 0, dvrMaxMs = 0; let gfDrawOn = false, gfVerts = [], gfLayer = null, gfSaved = null; +let gfWatchIds = [], gfSelectedId = null, gfLayerById = {}, gfNameById = {}; +let gfAtReq = 0, dvrRangeFromTracks = false, gfAtOk = true; function liveWsUrl() { const proto = location.protocol === 'https:' ? 'wss:' : 'ws:'; return proto + '//' + location.host + '/ws/live'; @@ -2249,6 +2288,11 @@ function liveWsUrl() { function sendLiveViewport() { if (!liveWs || liveWs.readyState !== 1 || !map) return; liveWs.send(JSON.stringify({ type: 'viewport', bbox: currentBBox() })); + sendWatchGeofences(); +} +function sendWatchGeofences() { + if (!liveWs || liveWs.readyState !== 1) return; + liveWs.send(JSON.stringify({ type: 'watch_geofences', ids: gfWatchIds })); } function dropLivePoint(group, id) { if (!group || !group._osintById || id == null) return; @@ -2291,6 +2335,7 @@ function applyLiveMarker(kind, p) { acGroup = upsertLivePoint(acGroup, p, q => acColor(q), 'ac'); } else if (kind === 'geofence_alert') { showGeofenceToast(p); + pushGfInbox(p); } else if (kind === 'fire_aircraft') { firefighterHex.add(String(p.aircraft_hex || '')); if (acOn && p.aircraft_lat != null) { @@ -2338,7 +2383,7 @@ function connectLiveWs() { setTimeout(connectLiveWs, delay); return; } - liveWs.onopen = () => { wsRetryMs = 1000; sendLiveViewport(); }; + liveWs.onopen = () => { wsRetryMs = 1000; sendLiveViewport(); sendWatchGeofences(); }; liveWs.onmessage = (ev) => { try { const msg = JSON.parse(ev.data); @@ -2881,6 +2926,7 @@ function setFiresSince() { } async function loadFires() { if (!map) return; + if (fenceDvrOn()) return; const req = ++fireReq; try { let url = `${API}/api/fires?bbox=${currentBBox()}&limit=2000&format=heat`; @@ -3704,8 +3750,9 @@ function toggleAircraftMil() { acMilOn = document.getElementById('lp-ac-mil-on').checked; if (acOn) loadAircraft(); } -async function loadAircraft() { +async function loadAircraft(force) { if (!map) return; + if (!force && fenceDvrOn()) return; if (map.getZoom() <= 3) { setLayerCount('lp-ac-count', 'zoom'); return; @@ -3729,6 +3776,7 @@ async function loadAircraft() { } addExtraAttrib('ADSB.lol ODbL'); addExtraAttrib('Photo © planespotters.net'); + refreshDvrRangeOnce(); } catch (e) { if (isAbort(e)) return; console.error('Aircraft load failed', e); @@ -3767,8 +3815,9 @@ async function toggleVessels() { clearTimeout(vesselRefollowTimer); } } -async function loadVessels() { +async function loadVessels(force) { if (!map) return; + if (!force && fenceDvrOn()) return; if (map.getZoom() <= 3) { setLayerCount('lp-vessels-count', 'zoom'); return; @@ -3808,6 +3857,7 @@ async function loadVessels() { }, true, 'vessel'); setLayerCount('lp-vessels-count', (pts.length || 0).toLocaleString()); addExtraAttrib('AISStream'); + refreshDvrRangeOnce(); // First positions for a new zone arrive ~1-3s after the retune. if (retuned) { clearTimeout(vesselRefollowTimer); @@ -4110,6 +4160,12 @@ setInterval(pollSwpc, SWPC_POLL_MS); /* Phase 2: DVR slider + geofence draw (no Leaflet.Draw) + fire/aircraft hits */ function dvrQs() { return dvrTs ? `×tamp=${encodeURIComponent(dvrTs)}` : ''; } +function fenceDvrOn() { return !!(gfSelectedId && dvrTs && gfAtOk); } +function refreshDvrRangeOnce() { + if (dvrRangeFromTracks) return; + dvrRangeFromTracks = true; + initDvrRange(); +} function dvrGoLive() { dvrTs = null; const bar = document.getElementById('dvr-bar'); @@ -4130,6 +4186,15 @@ function dvrScrub(v) { if (Number(v) >= 359) { dvrGoLive(); return; } const lab = document.getElementById('dvr-label'); if (lab) lab.textContent = dvrTs.slice(11, 16) + 'Z'; + if (gfSelectedId) { + dvrScrubFence().then(ok => { + if (!ok) { + if (acOn) loadAircraft(true); + if (vesselsOn) loadVessels(true); + } + }); + return; + } if (acOn) loadAircraft(); if (vesselsOn) loadVessels(); } @@ -4148,6 +4213,59 @@ async function initDvrRange() { dvrMinMs = dvrMaxMs - 6 * 3600 * 1000; } } +function applyFenceSnapshot(body) { + const ac = Array.isArray(body && body.aircraft) ? body.aircraft : []; + const vs = Array.isArray(body && body.vessels) ? body.vessels : []; + const fires = Array.isArray(body && body.fires) ? body.fires : []; + if (acOn) { + lastAircraft = ac; + acGroup = renderPoints(acGroup, ac, p => acColor(p), true, 'ac'); + setLayerCount('lp-ac-count', ac.length.toLocaleString()); + } + if (vesselsOn) { + lastVessels = vs; + vesselsGroup = renderPoints(vesselsGroup, vs, p => { + const extra = p.extra || {}; + if (extra.role === 'military') return '#f472b6'; + if (extra.role === 'government') return '#facc15'; + const sog = Number((p.speed) || 0); + return sog > 0.5 ? '#2dd4bf' : '#64748b'; + }, true, 'vessel'); + setLayerCount('lp-vessels-count', vs.length.toLocaleString()); + } + if (typeof firesOn !== 'undefined' && firesOn && map) { + if (firesHeat) map.removeLayer(firesHeat); + const pts = fires.map(f => [f.lat ?? f.latitude, f.lon ?? f.longitude, firesIntensity(f)]) + .filter(p => p[0] != null && p[1] != null); + lastFires = fires; + firesHeat = L.heatLayer(pts, { + radius: 22, blur: 20, maxZoom: 9, max: 1.0, minOpacity: 0.2, + gradient: firesGradient(), + }).addTo(map); + if (firesHeat._canvas) firesHeat._canvas.style.opacity = firesOpacity; + setLayerCount('lp-fires-count', fires.length.toLocaleString()); + } +} +async function dvrScrubFence() { + if (!gfSelectedId || !dvrTs) return false; + const req = ++gfAtReq; + try { + const r = await overlayFetch( + `${API}/api/geofences/${encodeURIComponent(gfSelectedId)}/at?timestamp=${encodeURIComponent(dvrTs)}` + ); + if (req !== gfAtReq) return true; + if (r.status === 404) { gfAtOk = false; return false; } + if (!r.ok) return false; + const body = await r.json(); + if (req !== gfAtReq) return true; + gfAtOk = true; + applyFenceSnapshot(body); + return true; + } catch (e) { + if (isAbort(e) || req !== gfAtReq) return true; + return false; + } +} function showGeofenceToast(p) { const box = document.getElementById('dvr-toast'); if (!box) return; @@ -4157,12 +4275,70 @@ function showGeofenceToast(p) { box.prepend(el); setTimeout(() => el.remove(), 8000); } +function gfHitTime(p) { + const raw = p && (p.created_at || (p.payload && p.payload.created_at)); + if (!raw) return 'now'; + const d = new Date(raw); + if (Number.isNaN(d.getTime())) return String(raw).slice(11, 19) || '—'; + return d.toISOString().slice(11, 19) + 'Z'; +} +function pushGfInbox(p) { + if (!p) return; + const box = document.getElementById('gf-inbox'); + if (!box) return; + const gid = p.geofence_id || ''; + const name = p.geofence_name || gfNameById[gid] || 'Fence'; + const el = document.createElement('button'); + el.type = 'button'; + el.className = 'gf-hit'; + el.dataset.gid = gid; + if (p.lat != null) el.dataset.lat = String(p.lat); + if (p.lon != null) el.dataset.lon = String(p.lon); + el.innerHTML = `${newsEsc(gfHitTime(p))} · ${newsEsc(name)}` + + ` · ${newsEsc(p.source_kind || '')} · ${newsEsc(p.entity_id || '')}`; + el.onclick = () => onGfHitClick(el); + box.prepend(el); + while (box.children.length > 50) box.removeChild(box.lastChild); +} +function onGfHitClick(el) { + const lat = parseFloat(el.dataset.lat); + const lon = parseFloat(el.dataset.lon); + const gid = el.dataset.gid; + if (map && Number.isFinite(lat) && Number.isFinite(lon)) { + map.setView([lat, lon], Math.max(map.getZoom() || 0, 10)); + } + if (gid) selectGeofence(gid, false); +} +async function loadGfInbox() { + try { + const r = await fetch(`${API}/api/geofence-alerts?limit=50`); + if (!r.ok) return; + const rows = await r.json(); + const box = document.getElementById('gf-inbox'); + if (!box) return; + box.innerHTML = ''; + (Array.isArray(rows) ? rows : []).slice().reverse().forEach(pushGfInbox); + } catch (e) { /* route may not be on this backend yet */ } +} +function syncGfDrawUi() { + const fin = document.getElementById('gf-finish'); + const can = document.getElementById('gf-cancel'); + if (fin) fin.hidden = !gfDrawOn; + if (can) can.hidden = !gfDrawOn; + const btn = document.getElementById('gf-draw'); + if (btn) btn.textContent = gfDrawOn ? 'Drawing…' : 'Draw geofence'; + const bar = document.getElementById('gf-draw-bar'); + if (bar) bar.hidden = !gfDrawOn; +} +function cancelGeofenceDraw() { + if (!gfDrawOn) return; + toggleGeofenceDraw(); +} function toggleGeofenceDraw() { gfDrawOn = !gfDrawOn; gfVerts = []; if (gfLayer && map) { map.removeLayer(gfLayer); gfLayer = null; } - const btn = document.getElementById('gf-draw'); - if (btn) btn.textContent = gfDrawOn ? 'Click map… (dbl-click close)' : 'Draw geofence'; + syncGfDrawUi(); if (!map) return; if (gfDrawOn) { map.getContainer().style.cursor = 'crosshair'; @@ -4185,21 +4361,99 @@ function onGfClick(e) { } async function onGfClose(e) { if (!gfDrawOn) return; - L.DomEvent.stop(e); + if (e) L.DomEvent.stop(e); if (gfVerts.length < 3) return; const ring = gfVerts.concat([gfVerts[0]]); const geojson = { type: 'Polygon', coordinates: [ring] }; + const fallback = 'Fence ' + new Date().toISOString().slice(11, 19); + let created = null; try { - await fetch(`${API}/api/geofences`, { + const r = await fetch(`${API}/api/geofences`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ name: 'Fence ' + new Date().toISOString().slice(11, 19), geojson }), + body: JSON.stringify({ name: fallback, geojson }), }); + if (r.ok) created = await r.json(); } catch (err) { console.error('geofence save failed', err); } toggleGeofenceDraw(); + if (created && created.id) { + const typed = window.prompt('Name this watch', created.name || fallback); + const name = (typed == null ? '' : String(typed).trim()) || (created.name || fallback); + if (name && name !== created.name) { + try { + await fetch(`${API}/api/geofences/${encodeURIComponent(created.id)}`, { + method: 'PATCH', headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ name }), + }); + } catch (err) { console.error('geofence rename failed', err); } + } + } loadGeofences(); } +async function patchGeofence(id, body) { + if (!id) return; + try { + await fetch(`${API}/api/geofences/${encodeURIComponent(id)}`, { + method: 'PATCH', headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(body), + }); + } catch (err) { console.error('geofence patch failed', err); } + loadGeofences(); +} +function patchGfActive(id, on) { + patchGeofence(id, { active: !!on }); +} +async function renameGeofence(id) { + const cur = gfNameById[id] || 'Fence'; + const typed = window.prompt('Rename watch', cur); + if (typed == null) return; + const name = String(typed).trim() || cur; + await patchGeofence(id, { name }); +} +function goGeofence(id) { + selectGeofence(id, true); +} +function onGfNameClick(id) { + if (gfSelectedId === id) { deselectGeofence(); return; } + selectGeofence(id, true); +} +function deselectGeofence() { + gfSelectedId = null; + document.querySelectorAll('.gf-item.selected').forEach(el => el.classList.remove('selected')); + if (gfSaved && gfSaved.setStyle) gfSaved.setStyle({ weight: 2, fillOpacity: 0.08 }); + if (dvrTs) { + if (acOn) loadAircraft(); + if (vesselsOn) loadVessels(); + } +} +function selectGeofence(id, fly) { + if (!id) return; + gfSelectedId = id; + gfAtOk = true; + document.querySelectorAll('.gf-item').forEach(el => { + el.classList.toggle('selected', el.dataset.id === id); + }); + const layer = gfLayerById[id]; + if (gfSaved && gfSaved.eachLayer) { + gfSaved.eachLayer(ly => { + const fid = ly.feature && ly.feature.properties && ly.feature.properties.id; + ly.setStyle({ + color: '#ff2e97', + weight: fid === id ? 4 : 2, + fillOpacity: fid === id ? 0.18 : 0.08, + }); + }); + } + if (layer && map) { + if (fly !== false && layer.getBounds) { + try { map.fitBounds(layer.getBounds(), { padding: [28, 28], maxZoom: 12 }); } catch (e) { /* empty */ } + } + if (layer.openPopup) layer.openPopup(); + } + if (fenceDvrOn()) dvrScrubFence(); +} async function deleteGeofence(id) { if (!id) return; + if (gfSelectedId === id) gfSelectedId = null; try { const r = await fetch(`${API}/api/geofences/${encodeURIComponent(id)}`, { method: 'DELETE' }); if (!r.ok && r.status !== 204) throw new Error('delete failed'); @@ -4212,31 +4466,55 @@ async function loadGeofences() { const r = await overlayFetch(`${API}/api/geofences`); const rows = await r.json(); const list = Array.isArray(rows) ? rows : []; + gfWatchIds = list.map(f => f.id).filter(Boolean); + gfNameById = {}; + list.forEach(f => { if (f.id) gfNameById[f.id] = f.name || 'Fence'; }); + if (gfSelectedId && !gfNameById[gfSelectedId]) gfSelectedId = null; const box = document.getElementById('gf-list'); if (box) { box.innerHTML = list.map(f => { const id = newsEsc(f.id || ''); const name = newsEsc(f.name || 'Fence'); - return `
${name}` + - `
`; + const on = f.active === false ? '' : ' checked'; + const sel = f.id === gfSelectedId ? ' selected' : ''; + return `
` + + `` + + `` + + `` + + `` + + `` + + `` + + `
`; }).join(''); } if (gfSaved && map.hasLayer(gfSaved)) map.removeLayer(gfSaved); + gfLayerById = {}; const feats = list.map(f => ({ - type: 'Feature', properties: { name: f.name, id: f.id }, geometry: f.geojson, + type: 'Feature', + properties: { name: f.name, id: f.id, active: f.active !== false }, + geometry: f.geojson, })); gfSaved = L.geoJSON({ type: 'FeatureCollection', features: feats }, { - style: { color: '#ff2e97', weight: 2, fillOpacity: 0.08 }, + style: feat => { + const on = feat.properties && feat.properties.id === gfSelectedId; + return { color: '#ff2e97', weight: on ? 4 : 2, fillOpacity: on ? 0.18 : 0.08 }; + }, onEachFeature: (feat, layer) => { const id = feat.properties && feat.properties.id; const name = newsEsc((feat.properties && feat.properties.name) || 'Fence'); + const active = feat.properties && feat.properties.active; if (!id) return; + gfLayerById[id] = layer; + const chk = active ? ' checked' : ''; layer.bindPopup( `
${name}
` + + `
` + `
` ); }, }).addTo(map); + sendWatchGeofences(); } catch (e) { if (!isAbort(e)) console.error('geofences load failed', e); } } async function loadFireAircraftHits() { @@ -4249,6 +4527,7 @@ async function loadFireAircraftHits() { } catch (e) { /* empty without table */ } } initDvrRange(); +loadGfInbox(); diff --git a/tests/test_geofence_frontend.py b/tests/test_geofence_frontend.py index 50ee03e..994c02d 100644 --- a/tests/test_geofence_frontend.py +++ b/tests/test_geofence_frontend.py @@ -1,4 +1,4 @@ -"""Geofence layer panel: draw + delete (DELETE /api/geofences/{id}).""" +"""Geofence layer panel: draw, watch, inbox, delete (HTML contract).""" from __future__ import annotations @@ -24,3 +24,33 @@ def test_load_geofences_renders_delete_controls(): assert "deleteGeofence" in js assert "onEachFeature" in js assert "bindPopup" in js + + +def test_finish_cancel_draw_controls(): + assert 'id="gf-finish"' in HTML + assert 'id="gf-cancel"' in HTML + assert "function cancelGeofenceDraw" in HTML + assert "function onGfClose" in HTML + + +def test_watch_geofences_ws_payload(): + assert "watch_geofences" in HTML + assert "function sendWatchGeofences" in HTML + + +def test_geofence_alert_inbox(): + assert 'id="gf-inbox"' in HTML + assert "/api/geofence-alerts" in HTML + assert "function loadGfInbox" in HTML + assert "function pushGfInbox" in HTML + + +def test_delete_geofence_still_present(): + assert "function deleteGeofence" in HTML + assert "method: 'DELETE'" in HTML or 'method: "DELETE"' in HTML + + +def test_fence_dvr_at_endpoint(): + assert "/at?timestamp=" in HTML or "/at?timestamp=${" in HTML + assert "function dvrScrubFence" in HTML + assert "gfSelectedId" in HTML From beb457c3820f0c8099f04dcbd2cdd0080c051f84 Mon Sep 17 00:00:00 2001 From: Sirius DevOps Date: Tue, 1 Sep 2026 01:50:24 -0400 Subject: [PATCH 56/79] =?UTF-8?q?feat(map):=20quiet=20HUD=20chrome=20?= =?UTF-8?q?=E2=80=94=20VIIRS=20default,=20collapsed=20rail?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Satellite-first chrome: daily VIIRS preferred, layer rail collapsed on load, geofence after basemap, FIRMS-only default overlays, hide MKT standby ticker, Strait select instead of buttons, IBM Plex instead of Orbitron, news as 6px circleMarkers. --- app/static/index.html | 354 ++++++++++++++++++++------------------- tests/test_hud_chrome.py | 105 ++++++++++++ 2 files changed, 289 insertions(+), 170 deletions(-) create mode 100644 tests/test_hud_chrome.py diff --git a/app/static/index.html b/app/static/index.html index 71619a5..da65fbf 100644 --- a/app/static/index.html +++ b/app/static/index.html @@ -3,10 +3,10 @@ - OSINT//DASHBOARD — Global Situational Awareness Terminal + OSINT// - + @@ -35,12 +35,12 @@ --text: #c8e6f2; --muted: #5f7d95; --topbar-h: 46px; - --dock-h: 62px; + --dock-h: 32px; /* one NEWS ticker; MKT hidden until live */ } * { margin: 0; padding: 0; box-sizing: border-box; } html, body { height: 100%; } body { - font-family: 'Rajdhani', 'Segoe UI', system-ui, sans-serif; + font-family: 'IBM Plex Sans', 'Segoe UI', system-ui, sans-serif; background: var(--bg-0); color: var(--text); overflow: hidden; font-size: 15px; letter-spacing: 0.01em; @@ -48,12 +48,12 @@ ::selection { background: var(--cyan-dim); color: #eafcff; } :focus-visible { outline: 2px solid var(--cyan); outline-offset: 2px; } a { color: var(--cyan); } - .mono, code, kbd { font-family: 'Share Tech Mono', ui-monospace, SFMono-Regular, Menlo, monospace; } + .mono, code, kbd { font-family: 'IBM Plex Mono', ui-monospace, SFMono-Regular, Menlo, monospace; font-variant-numeric: tabular-nums; } .btn { background: linear-gradient(180deg, var(--bg-3), var(--bg-2)); border: 1px solid var(--line); color: var(--text); border-radius: 4px; padding: 0.35rem 0.9rem; cursor: pointer; - font-family: 'Rajdhani', sans-serif; font-weight: 600; + font-family: 'IBM Plex Sans', sans-serif; font-weight: 600; font-size: 0.8rem; letter-spacing: 0.06em; text-transform: uppercase; transition: border-color .15s, box-shadow .15s, color .15s; } @@ -84,18 +84,18 @@ } .brand { display: flex; align-items: center; gap: 0.65rem; min-width: 0; } .brand-mark { - font-family: 'Orbitron', sans-serif; color: var(--cyan); + font-family: 'IBM Plex Sans', sans-serif; color: var(--cyan); font-size: 1.05rem; text-shadow: 0 0 12px var(--cyan-glow); border: 1px solid var(--line-hi); padding: 0.1rem 0.34rem; border-radius: 3px; background: rgba(53,224,255,0.06); } .brand-name { - font-family: 'Orbitron', sans-serif; font-weight: 700; font-size: 0.95rem; + font-family: 'IBM Plex Sans', sans-serif; font-weight: 700; font-size: 0.95rem; color: #eafcff; letter-spacing: 0.14em; white-space: nowrap; } .brand-name .accent { color: var(--cyan); text-shadow: 0 0 10px var(--cyan-glow); } .brand-sub { - font-family: 'Share Tech Mono', monospace; font-size: 0.58rem; + font-family: 'IBM Plex Mono', monospace; font-size: 0.58rem; color: var(--muted); letter-spacing: 0.22em; text-transform: uppercase; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } @@ -103,7 +103,7 @@ .topbar-right { display: flex; align-items: center; gap: 1rem; } .sys-status { display: flex; align-items: center; gap: 0.5rem; - font-family: 'Share Tech Mono', monospace; font-size: 0.72rem; + font-family: 'IBM Plex Mono', monospace; font-size: 0.72rem; color: var(--muted); white-space: nowrap; } .sys-status .sep { opacity: 0.35; } @@ -112,6 +112,10 @@ .dot.bad { background: var(--red); box-shadow: 0 0 8px var(--red); } .dot.dim { background: var(--muted); box-shadow: none; animation: none; } @keyframes pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.35; } } + .clock, .lp-count, .hud-chip b, #utc-clock, #dvr-label { + font-variant-numeric: tabular-nums; + font-family: 'IBM Plex Mono', ui-monospace, monospace; + } .clock { color: var(--cyan); } @media (max-width: 720px) { .sys-status .hide-sm { display: none; } } @@ -121,7 +125,7 @@ display: flex; align-items: center; gap: 0.5rem; background: linear-gradient(180deg, var(--bg-3), var(--bg-2)); border: 1px solid var(--line-hi); color: var(--text); - font-family: 'Orbitron', sans-serif; font-size: 0.72rem; font-weight: 700; + font-family: 'IBM Plex Sans', sans-serif; font-size: 0.72rem; font-weight: 700; letter-spacing: 0.16em; padding: 0.42rem 0.85rem; border-radius: 4px; cursor: pointer; transition: border-color .15s, box-shadow .15s; } @@ -143,7 +147,7 @@ .nav-item { display: flex; align-items: center; gap: 0.6rem; width: 100%; background: none; border: none; color: var(--text); text-align: left; - font-family: 'Rajdhani', sans-serif; font-weight: 600; font-size: 0.88rem; + font-family: 'IBM Plex Sans', sans-serif; font-weight: 600; font-size: 0.88rem; letter-spacing: 0.09em; text-transform: uppercase; padding: 0.55rem 0.7rem; border-radius: 4px; cursor: pointer; border-left: 2px solid transparent; @@ -177,17 +181,12 @@ max-width: calc(100% - 300px); /* keep off LAYERS (left) and zoom (right) */ justify-content: center; } - .chokepoint-btns { display: flex; flex-wrap: wrap; align-items: center; gap: 0.25rem; } - .chokepoint-btns .btn { padding: 0.22rem 0.42rem; font-size: 0.66rem; letter-spacing: 0.04em; } - .chokepoint-btns .btn.is-on { - border-color: var(--cyan); color: var(--cyan); - box-shadow: 0 0 8px var(--cyan-glow); background: rgba(53,224,255,0.10); - } - #chokepoint-select { display: none; } + .chokepoint-btns { display: none; } + #chokepoint-select { display: inline-block; min-width: 8rem; } .map-toolbar select, .map-toolbar input[type="date"], .map-toolbar input[type="datetime-local"] { background: var(--bg-1); color: var(--text); border: 1px solid var(--line); border-radius: 4px; padding: 0.3rem 0.45rem; font-size: 0.76rem; - font-family: 'Share Tech Mono', monospace; color-scheme: dark; + font-family: 'IBM Plex Mono', monospace; color-scheme: dark; } .map-toolbar select:focus, .map-toolbar input:focus { outline: none; border-color: var(--cyan); box-shadow: 0 0 8px var(--cyan-glow); } .map-toolbar .btn { padding: 0.3rem 0.6rem; font-size: 0.72rem; } @@ -206,7 +205,7 @@ .leaflet-control-zoom a:hover { background: var(--bg-3) !important; color: var(--cyan) !important; } .leaflet-control-attribution { background: rgba(3,6,9,0.78) !important; color: #8fa8bd !important; - font-family: 'Share Tech Mono', monospace !important; font-size: 10px !important; + font-family: 'IBM Plex Mono', monospace !important; font-size: 10px !important; } .leaflet-control-attribution a { color: var(--cyan) !important; } .leaflet-popup-content-wrapper, .leaflet-popup-tip { @@ -264,7 +263,7 @@ /* ── Map hint + HUD chips ── */ .map-hint { position: absolute; left: 12px; bottom: 12px; z-index: 500; - font-family: 'Share Tech Mono', monospace; font-size: 0.68rem; color: var(--muted); + font-family: 'IBM Plex Mono', monospace; font-size: 0.68rem; color: var(--muted); background: rgba(6,11,20,0.72); border: 1px solid var(--line); border-radius: 4px; padding: 0.3rem 0.6rem; max-width: 60%; text-shadow: 0 0 6px rgba(0,0,0,0.8); @@ -275,7 +274,7 @@ } .hud-chip { display: flex; align-items: center; gap: 0.45rem; - font-family: 'Share Tech Mono', monospace; font-size: 0.66rem; color: var(--muted); + font-family: 'IBM Plex Mono', monospace; font-size: 0.66rem; color: var(--muted); background: rgba(6,11,20,0.78); border: 1px solid var(--line); border-radius: 4px; padding: 0.26rem 0.55rem; letter-spacing: 0.06em; backdrop-filter: blur(4px); @@ -292,7 +291,7 @@ z-index: 520; display: flex; align-items: center; gap: 0.55rem; background: rgba(6,11,20,0.86); border: 1px solid var(--line-hi); border-radius: 4px; padding: 0.28rem 0.7rem; - font-family: 'Share Tech Mono', monospace; font-size: 0.66rem; color: var(--muted); + font-family: 'IBM Plex Mono', monospace; font-size: 0.66rem; color: var(--muted); min-width: 280px; max-width: 52%; } #dvr-bar input[type=range] { flex: 1; accent-color: var(--cyan); } @@ -303,7 +302,7 @@ } #dvr-toast .gf-alert { background: rgba(255,46,151,0.16); border: 1px solid var(--magenta); - color: var(--text); font-family: 'Share Tech Mono', monospace; + color: var(--text); font-family: 'IBM Plex Mono', monospace; font-size: 0.68rem; padding: 0.4rem 0.6rem; margin-bottom: 0.35rem; border-radius: 4px; } @@ -311,17 +310,19 @@ /* ── Layer control panel (dark HUD) ── */ #layer-panel { position: absolute; top: 58px; left: 12px; z-index: 600; - width: 268px; max-height: calc(100% - 74px); overflow: hidden; + width: min(320px, calc(100% - 24px)); max-width: 320px; + max-height: calc(100% - 74px); overflow: hidden; background: rgba(6,11,20,0.86); backdrop-filter: blur(8px); border: 1px solid var(--line-hi); border-radius: 6px; box-shadow: 0 0 22px rgba(53,224,255,0.14), 0 0 2px rgba(53,224,255,0.4); color: var(--text); font-size: 0.78rem; display: flex; flex-direction: column; clip-path: polygon(0 8px, 8px 0, calc(100% - 8px) 0, 100% 8px, 100% calc(100% - 8px), calc(100% - 8px) 100%, 8px 100%, 0 calc(100% - 8px)); } + #layer-panel.collapsed { width: auto; max-width: 320px; } .lp-head { display: flex; justify-content: space-between; align-items: center; padding: 0.55rem 0.75rem; border-bottom: 1px solid var(--line); - font-family: 'Orbitron', sans-serif; font-size: 0.68rem; font-weight: 700; + font-family: 'IBM Plex Sans', sans-serif; font-size: 0.68rem; font-weight: 700; letter-spacing: 0.14em; text-transform: uppercase; color: var(--cyan); text-shadow: 0 0 10px rgba(53,224,255,0.55); cursor: pointer; user-select: none; background: linear-gradient(180deg, rgba(53,224,255,0.07), transparent); @@ -341,7 +342,7 @@ .lp-dot.fires { background: #fb923c; box-shadow: 0 0 7px #fb923c; } .lp-dot.cams { background: #4ade80; box-shadow: 0 0 7px #4ade80; } .lp-dot.blips { background: var(--magenta); box-shadow: 0 0 7px var(--magenta); } - .lp-dot.news { background: var(--magenta); box-shadow: 0 0 7px var(--magenta); border-radius: 1px; transform: rotate(45deg); } + .lp-dot.news { background: var(--cyan); box-shadow: 0 0 7px var(--cyan); } .lp-dot.weather { background: var(--amber); box-shadow: 0 0 7px var(--amber); } .lp-dot.flights { background: #7dd3fc; box-shadow: 0 0 7px #7dd3fc; } .lp-dot.mil { background: #f472b6; box-shadow: 0 0 7px #f472b6; } @@ -357,15 +358,16 @@ box-shadow: 0 0 7px #64748b; } .lp-dot.conflicts { background: #ff2a6d; box-shadow: 0 0 7px #ff2a6d; } - .lp-count { font-family: 'Share Tech Mono', monospace; font-size: 0.7rem; color: var(--cyan); } + .lp-count { font-family: 'IBM Plex Mono', monospace; font-size: 0.7rem; color: var(--cyan); } .lp-sub { display: flex; justify-content: space-between; align-items: center; gap: 0.5rem; } - .lp-opacity { display: flex; align-items: center; gap: 0.4rem; font-size: 0.62rem; color: var(--muted); text-transform: uppercase; letter-spacing: 0.05em; } + .lp-opacity { display: none; align-items: center; gap: 0.4rem; font-size: 0.62rem; color: var(--muted); text-transform: uppercase; letter-spacing: 0.05em; } + .lp-layer:has(.lp-name input[type="checkbox"]:checked) .lp-opacity { display: flex; } .lp-opacity input[type="range"] { flex: 1; accent-color: var(--cyan); height: 4px; cursor: pointer; } - .lp-opacity b { color: var(--text); font-family: 'Share Tech Mono', monospace; font-weight: 400; min-width: 2.4em; text-align: right; } - .lp-select { background: var(--bg-1); color: var(--text); border: 1px solid var(--line); border-radius: 4px; padding: 0.22rem 0.35rem; font-size: 0.68rem; font-family: 'Share Tech Mono', monospace; color-scheme: dark; } + .lp-opacity b { color: var(--text); font-family: 'IBM Plex Mono', monospace; font-weight: 400; min-width: 2.4em; text-align: right; } + .lp-select { background: var(--bg-1); color: var(--text); border: 1px solid var(--line); border-radius: 4px; padding: 0.22rem 0.35rem; font-size: 0.68rem; font-family: 'IBM Plex Mono', monospace; color-scheme: dark; } .lp-select:focus { outline: none; border-color: var(--cyan); box-shadow: 0 0 8px var(--cyan-glow); } .lp-legend { border-top: 1px solid var(--line); padding-top: 0.5rem; display: flex; flex-direction: column; gap: 0.35rem; } - .lp-legend h4 { font-size: 0.58rem; text-transform: uppercase; letter-spacing: 0.1em; color: var(--muted); margin: 0; font-family: 'Rajdhani', sans-serif; font-weight: 600; } + .lp-legend h4 { font-size: 0.58rem; text-transform: uppercase; letter-spacing: 0.1em; color: var(--muted); margin: 0; font-family: 'IBM Plex Sans', sans-serif; font-weight: 600; } .lp-ramp { height: 8px; border-radius: 4px; background: linear-gradient(90deg, #2563eb, #38bdf8, #f59e0b, #ef4444, #fde047); box-shadow: 0 0 8px rgba(251,146,60,0.35) inset; } .lp-ramp-scale { display: flex; justify-content: space-between; font-size: 0.58rem; color: var(--muted); } .lp-heat-legend { display: flex; align-items: center; justify-content: space-between; font-size: 0.64rem; color: var(--muted); gap: 0.5rem; } @@ -381,7 +383,7 @@ .gf-item .gf-name:hover { color: var(--cyan); } .gf-item .gf-actions { display: flex; align-items: center; gap: 0.28rem; flex: 0 0 auto; } .gf-item input.gf-active { accent-color: var(--cyan); cursor: pointer; width: 14px; height: 14px; } - .gf-del, .gf-go, .gf-ren { background: transparent; border: 1px solid var(--magenta); color: var(--magenta); font-family: 'Share Tech Mono', monospace; font-size: 0.58rem; letter-spacing: 0.08em; text-transform: uppercase; padding: 0.12rem 0.35rem; border-radius: 3px; cursor: pointer; } + .gf-del, .gf-go, .gf-ren { background: transparent; border: 1px solid var(--magenta); color: var(--magenta); font-family: 'IBM Plex Mono', monospace; font-size: 0.58rem; letter-spacing: 0.08em; text-transform: uppercase; padding: 0.12rem 0.35rem; border-radius: 3px; cursor: pointer; } .gf-go, .gf-ren { border-color: var(--cyan); color: var(--cyan); } .gf-del:hover { background: rgba(255,46,151,0.16); } .gf-go:hover, .gf-ren:hover { background: rgba(53,224,255,0.14); } @@ -398,7 +400,7 @@ .gf-hit { cursor: pointer; font-size: 0.58rem; line-height: 1.35; color: var(--text); padding: 0.22rem 0.28rem; border: 1px solid var(--line); border-radius: 3px; - font-family: 'Share Tech Mono', monospace; + font-family: 'IBM Plex Mono', monospace; } .gf-hit:hover, .gf-hit:focus { border-color: var(--cyan); outline: none; background: rgba(53,224,255,0.08); } .gf-hit .gf-hit-meta { color: var(--muted); } @@ -419,7 +421,7 @@ } .cheat-sheet[hidden] { display: none !important; } .cheat-sheet h3 { - font-family: 'Orbitron', sans-serif; font-size: 0.72rem; letter-spacing: 0.16em; + font-family: 'IBM Plex Sans', sans-serif; font-size: 0.72rem; letter-spacing: 0.16em; color: var(--cyan); margin: 0 0 0.65rem; text-transform: uppercase; } .cheat-sheet dl { display: grid; grid-template-columns: auto 1fr; gap: 0.35rem 0.85rem; margin: 0; } @@ -445,26 +447,26 @@ .pd-head { display: flex; justify-content: space-between; align-items: center; padding: 0.55rem 0.95rem 0.55rem 0.85rem; border-bottom: 1px solid var(--line); - font-family: 'Orbitron', sans-serif; font-size: 0.68rem; font-weight: 700; + font-family: 'IBM Plex Sans', sans-serif; font-size: 0.68rem; font-weight: 700; letter-spacing: 0.14em; text-transform: uppercase; color: var(--cyan); text-shadow: 0 0 10px rgba(53,224,255,0.55); background: linear-gradient(180deg, rgba(53,224,255,0.07), transparent); } .pd-close { background: transparent; border: 1px solid var(--line); color: var(--muted); - font-family: 'Share Tech Mono', monospace; font-size: 0.78rem; + font-family: 'IBM Plex Mono', monospace; font-size: 0.78rem; width: 28px; height: 28px; border-radius: 4px; cursor: pointer; line-height: 1; flex-shrink: 0; margin-right: 2px; } .pd-close:hover { border-color: var(--cyan); color: var(--cyan); } .pd-body { padding: 0.55rem 0.75rem 0.7rem; overflow-y: auto; display: flex; flex-direction: column; gap: 0.55rem; min-height: 0; flex: 1; } - .pd-status { font-family: 'Share Tech Mono', monospace; font-size: 0.66rem; color: var(--muted); } + .pd-status { font-family: 'IBM Plex Mono', monospace; font-size: 0.66rem; color: var(--muted); } .pd-status.err { color: var(--red); } - .pd-coords { font-family: 'Share Tech Mono', monospace; font-size: 0.66rem; color: var(--cyan); letter-spacing: 0.04em; } - .pd-name { font-family: 'Rajdhani', sans-serif; font-weight: 700; font-size: 0.92rem; color: var(--text); line-height: 1.25; } + .pd-coords { font-family: 'IBM Plex Mono', monospace; font-size: 0.66rem; color: var(--cyan); letter-spacing: 0.04em; } + .pd-name { font-family: 'IBM Plex Sans', sans-serif; font-weight: 700; font-size: 0.92rem; color: var(--text); line-height: 1.25; } .pd-addr { font-size: 0.72rem; color: var(--muted); line-height: 1.4; } .pd-sec { - font-family: 'Orbitron', sans-serif; font-size: 0.58rem; letter-spacing: 0.12em; + font-family: 'IBM Plex Sans', sans-serif; font-size: 0.58rem; letter-spacing: 0.12em; text-transform: uppercase; color: var(--muted); margin-top: 0.15rem; } .pd-list { display: flex; flex-direction: column; gap: 0.18rem; } @@ -472,11 +474,11 @@ display: flex; justify-content: space-between; align-items: baseline; gap: 0.5rem; background: transparent; border: 0; border-left: 2px solid var(--line); color: var(--text); text-align: left; cursor: pointer; padding: 0.22rem 0.35rem; - font-family: 'Rajdhani', sans-serif; font-size: 0.78rem; font-weight: 600; + font-family: 'IBM Plex Sans', sans-serif; font-size: 0.78rem; font-weight: 600; } .pd-item:hover, .pd-item:focus-visible { border-left-color: var(--cyan); color: var(--cyan); background: rgba(53,224,255,0.06); } - .pd-item .k { text-transform: uppercase; letter-spacing: 0.06em; font-size: 0.58rem; color: var(--muted); font-family: 'Share Tech Mono', monospace; flex-shrink: 0; } - .pd-item .d { font-family: 'Share Tech Mono', monospace; font-size: 0.62rem; color: var(--cyan); white-space: nowrap; } + .pd-item .k { text-transform: uppercase; letter-spacing: 0.06em; font-size: 0.58rem; color: var(--muted); font-family: 'IBM Plex Mono', monospace; flex-shrink: 0; } + .pd-item .d { font-family: 'IBM Plex Mono', monospace; font-size: 0.62rem; color: var(--cyan); white-space: nowrap; } .pd-empty { font-size: 0.72rem; color: var(--muted); font-style: italic; } .pd-note { font-size: 0.6rem; color: var(--muted); opacity: 0.85; line-height: 1.35; } @@ -487,7 +489,7 @@ .cam-pop .thumb.placeholder { display: flex; align-items: center; justify-content: center; color: var(--muted); font-size: 0.7rem; height: 80px; } .cam-pop table { width: 100%; font-size: 0.72rem; border-collapse: collapse; } .cam-pop td { padding: 0.12rem 0.2rem; vertical-align: top; } - .cam-pop td.k { color: var(--muted); text-transform: uppercase; font-size: 0.6rem; letter-spacing: 0.05em; white-space: nowrap; width: 34%; font-family: 'Share Tech Mono', monospace; } + .cam-pop td.k { color: var(--muted); text-transform: uppercase; font-size: 0.6rem; letter-spacing: 0.05em; white-space: nowrap; width: 34%; font-family: 'IBM Plex Mono', monospace; } .cam-pop a { color: var(--cyan); word-break: break-all; } .cam-pop .ps-photo { margin-top: 0.45rem; } .cam-pop .ps-photo a.ps-link { display: block; } @@ -500,7 +502,7 @@ .cam-pop .ps-credit a { color: var(--cyan); } .cam-pop .ps-loading { font-size: 0.68rem; color: var(--muted); margin-top: 0.35rem; } .role-badge { - display: inline-block; font-family: 'Share Tech Mono', monospace; + display: inline-block; font-family: 'IBM Plex Mono', monospace; font-size: 0.58rem; font-weight: 700; letter-spacing: 0.12em; padding: 0.08rem 0.4rem; border-radius: 3px; margin-left: 0.4rem; vertical-align: middle; @@ -514,8 +516,8 @@ animation: emerg-pulse 1.4s ease-in-out infinite; } .blip-pop { min-width: 200px; max-width: 260px; } - .blip-pop .blip-src { font-family: 'Share Tech Mono', monospace; font-size: 0.62rem; color: var(--cyan); text-transform: uppercase; letter-spacing: 0.08em; } - .blip-pop .blip-time { font-size: 0.7rem; color: var(--muted); font-family: 'Share Tech Mono', monospace; margin: 0.2rem 0 0.3rem; } + .blip-pop .blip-src { font-family: 'IBM Plex Mono', monospace; font-size: 0.62rem; color: var(--cyan); text-transform: uppercase; letter-spacing: 0.08em; } + .blip-pop .blip-time { font-size: 0.7rem; color: var(--muted); font-family: 'IBM Plex Mono', monospace; margin: 0.2rem 0 0.3rem; } .blip-pop .blip-desc { font-size: 0.72rem; color: var(--text); line-height: 1.35; margin-top: 0.15rem; } /* ── Sub-views (News / Events / Alerts / ... ) ── */ @@ -524,7 +526,7 @@ max-width: 1280px; margin: 0 auto; } .subview > h2 { - font-family: 'Orbitron', sans-serif; font-size: 0.95rem; font-weight: 700; + font-family: 'IBM Plex Sans', sans-serif; font-size: 0.95rem; font-weight: 700; letter-spacing: 0.16em; text-transform: uppercase; color: var(--text); display: flex; align-items: center; gap: 0.6rem; margin-bottom: 0.35rem; } @@ -536,13 +538,13 @@ box-shadow: 0 0 18px rgba(53,224,255,0.05); } .panel h3 { - font-size: 0.68rem; font-family: 'Orbitron', sans-serif; font-weight: 700; + font-size: 0.68rem; font-family: 'IBM Plex Sans', sans-serif; font-weight: 700; text-transform: uppercase; letter-spacing: 0.16em; color: var(--muted); margin-bottom: 0.6rem; } table { width: 100%; border-collapse: collapse; font-size: 0.86rem; } th, td { text-align: left; padding: 0.5rem 0.65rem; border-bottom: 1px solid var(--line); } - th { color: var(--muted); font-weight: 600; font-size: 0.68rem; text-transform: uppercase; letter-spacing: 0.1em; font-family: 'Rajdhani', sans-serif; } + th { color: var(--muted); font-weight: 600; font-size: 0.68rem; text-transform: uppercase; letter-spacing: 0.1em; font-family: 'IBM Plex Sans', sans-serif; } tr:hover td { background: rgba(53,224,255,0.04); } .badge { display: inline-block; padding: 0.12rem 0.5rem; border-radius: 3px; font-size: 0.7rem; font-weight: 600; letter-spacing: 0.05em; text-transform: uppercase; } .badge-positive { background: rgba(83,240,165,0.12); color: var(--green); border: 1px solid rgba(83,240,165,0.35); } @@ -555,7 +557,7 @@ /* ── Stats strip (Events view) ── */ .stat-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 0.8rem; margin-bottom: 1.1rem; } .stat-card { position: relative; overflow: hidden; } - .stat-card .value { font-family: 'Orbitron', sans-serif; font-size: 1.5rem; font-weight: 700; color: var(--text); letter-spacing: 0.04em; } + .stat-card .value { font-family: 'IBM Plex Sans', sans-serif; font-size: 1.5rem; font-weight: 700; color: var(--text); letter-spacing: 0.04em; } .stat-card .value.cyan { color: var(--cyan); text-shadow: 0 0 14px var(--cyan-glow); } .stat-card .value.red { color: var(--red); text-shadow: 0 0 14px rgba(255,93,93,0.4); } .stat-card::after { @@ -568,14 +570,14 @@ .search-box input { flex: 1; background: var(--bg-1); border: 1px solid var(--line); border-radius: 4px; padding: 0.55rem 0.9rem; color: var(--text); - font-size: 0.88rem; font-family: 'Rajdhani', sans-serif; + font-size: 0.88rem; font-family: 'IBM Plex Sans', sans-serif; } .search-box input:focus { outline: none; border-color: var(--cyan); box-shadow: 0 0 10px var(--cyan-glow); } /* ── News view ── */ .news-head { display: flex; justify-content: space-between; align-items: flex-end; gap: 1rem; margin-bottom: 0.9rem; flex-wrap: wrap; } .news-refresh { display: flex; align-items: center; gap: 0.6rem; } - .news-updated { font-size: 0.7rem; color: var(--muted); font-family: 'Share Tech Mono', monospace; } + .news-updated { font-size: 0.7rem; color: var(--muted); font-family: 'IBM Plex Mono', monospace; } .news-summary { position: relative; background: linear-gradient(160deg, rgba(53,224,255,0.10), rgba(10,19,34,0.7) 45%); border: 1px solid rgba(53,224,255,0.35); border-radius: 8px; padding: 1rem 1.25rem 1.1rem; @@ -586,19 +588,19 @@ content: ''; position: absolute; inset: 0; pointer-events: none; background: radial-gradient(140px 70px at 85% -10%, rgba(53,224,255,0.18), transparent 70%); } - .ns-kicker { font-family: 'Orbitron', sans-serif; font-size: 0.7rem; font-weight: 700; letter-spacing: 0.16em; text-transform: uppercase; color: var(--cyan); text-shadow: 0 0 12px rgba(53,224,255,0.6); display: flex; align-items: center; gap: 0.5rem; } - .ns-badge { font-size: 0.58rem; font-weight: 700; background: rgba(53,224,255,0.14); border: 1px solid rgba(53,224,255,0.4); border-radius: 3px; padding: 0.1rem 0.45rem; color: var(--cyan); letter-spacing: 0.1em; font-family: 'Share Tech Mono', monospace; } - .ns-time { font-size: 0.68rem; color: var(--muted); font-family: 'Share Tech Mono', monospace; margin: 0.35rem 0 0.6rem; } + .ns-kicker { font-family: 'IBM Plex Sans', sans-serif; font-size: 0.7rem; font-weight: 700; letter-spacing: 0.16em; text-transform: uppercase; color: var(--cyan); text-shadow: 0 0 12px rgba(53,224,255,0.6); display: flex; align-items: center; gap: 0.5rem; } + .ns-badge { font-size: 0.58rem; font-weight: 700; background: rgba(53,224,255,0.14); border: 1px solid rgba(53,224,255,0.4); border-radius: 3px; padding: 0.1rem 0.45rem; color: var(--cyan); letter-spacing: 0.1em; font-family: 'IBM Plex Mono', monospace; } + .ns-time { font-size: 0.68rem; color: var(--muted); font-family: 'IBM Plex Mono', monospace; margin: 0.35rem 0 0.6rem; } .ns-body { font-size: 0.9rem; line-height: 1.62; color: var(--text); white-space: pre-wrap; position: relative; z-index: 1; } - .ns-body h1, .ns-body h2, .ns-body h3, .ns-body h4 { font-size: 0.98rem; margin: 0.5rem 0 0.25rem; color: var(--cyan); font-family: 'Rajdhani', sans-serif; } + .ns-body h1, .ns-body h2, .ns-body h3, .ns-body h4 { font-size: 0.98rem; margin: 0.5rem 0 0.25rem; color: var(--cyan); font-family: 'IBM Plex Sans', sans-serif; } .ns-body ul, .ns-body ol { margin: 0.35rem 0 0.35rem 1.2rem; } .ns-body li { margin-bottom: 0.2rem; } - .ns-body code { background: rgba(3,6,9,0.6); border: 1px solid var(--line); border-radius: 3px; padding: 0.05rem 0.3rem; font-size: 0.85em; font-family: 'Share Tech Mono', monospace; } + .ns-body code { background: rgba(3,6,9,0.6); border: 1px solid var(--line); border-radius: 3px; padding: 0.05rem 0.3rem; font-size: 0.85em; font-family: 'IBM Plex Mono', monospace; } .ns-empty { color: var(--muted); font-size: 0.85rem; font-style: italic; } .ns-loading { color: var(--muted); font-size: 0.85rem; } .ns-error { color: var(--red); font-size: 0.85rem; } - .news-list-head { display: flex; justify-content: space-between; align-items: center; font-family: 'Orbitron', sans-serif; font-size: 0.68rem; letter-spacing: 0.14em; text-transform: uppercase; color: var(--muted); margin-bottom: 0.4rem; } - .news-count { font-size: 0.66rem; color: var(--cyan); font-family: 'Share Tech Mono', monospace; } + .news-list-head { display: flex; justify-content: space-between; align-items: center; font-family: 'IBM Plex Sans', sans-serif; font-size: 0.68rem; letter-spacing: 0.14em; text-transform: uppercase; color: var(--muted); margin-bottom: 0.4rem; } + .news-count { font-size: 0.66rem; color: var(--cyan); font-family: 'IBM Plex Mono', monospace; } .news-list { max-height: 52vh; min-height: 120px; overflow-y: auto; border: 1px solid var(--line); border-radius: 6px; background: rgba(6,11,20,0.4); } .news-list::-webkit-scrollbar { width: 8px; } .news-list::-webkit-scrollbar-track { background: rgba(14,26,46,0.4); border-radius: 8px; } @@ -607,10 +609,10 @@ .news-item { display: flex; align-items: center; gap: 0.75rem; padding: 0.55rem 0.9rem; border-bottom: 1px solid rgba(20,50,74,0.5); text-decoration: none; color: var(--text); transition: background .15s, box-shadow .15s; } .news-item:last-child { border-bottom: none; } .news-item:hover { background: rgba(53,224,255,0.06); box-shadow: inset 2px 0 0 var(--cyan); } - .news-dom { font-size: 0.62rem; font-family: 'Share Tech Mono', monospace; color: var(--cyan); background: rgba(53,224,255,0.08); border: 1px solid rgba(53,224,255,0.25); border-radius: 3px; padding: 0.1rem 0.45rem; white-space: nowrap; flex-shrink: 0; max-width: 30%; overflow: hidden; text-overflow: ellipsis; } + .news-dom { font-size: 0.62rem; font-family: 'IBM Plex Mono', monospace; color: var(--cyan); background: rgba(53,224,255,0.08); border: 1px solid rgba(53,224,255,0.25); border-radius: 3px; padding: 0.1rem 0.45rem; white-space: nowrap; flex-shrink: 0; max-width: 30%; overflow: hidden; text-overflow: ellipsis; } .news-title { flex: 1; font-size: 0.86rem; line-height: 1.35; color: var(--text); word-break: break-word; } .news-item:hover .news-title { color: var(--cyan); } - .news-time { font-size: 0.68rem; color: var(--muted); font-family: 'Share Tech Mono', monospace; white-space: nowrap; flex-shrink: 0; } + .news-time { font-size: 0.68rem; color: var(--muted); font-family: 'IBM Plex Mono', monospace; white-space: nowrap; flex-shrink: 0; } .news-geo { color: var(--green); font-size: 0.8rem; flex-shrink: 0; text-shadow: 0 0 8px rgba(83,240,165,0.6); } .news-loading, .news-error { padding: 1rem 0.9rem; color: var(--muted); font-size: 0.85rem; } .news-error { color: var(--red); } @@ -622,14 +624,14 @@ .key-card:hover { box-shadow: 0 0 22px rgba(53,224,255,0.12); } .key-card.set { border-color: rgba(83,240,165,0.45); box-shadow: 0 0 16px rgba(83,240,165,0.12); } .key-head { display: flex; justify-content: space-between; align-items: center; gap: 0.5rem; margin-bottom: 0.35rem; } - .key-name { font-family: 'Share Tech Mono', monospace; font-size: 0.86rem; font-weight: 600; color: var(--cyan); word-break: break-all; } - .key-status { font-size: 0.68rem; font-family: 'Share Tech Mono', monospace; padding: 0.18rem 0.55rem; border-radius: 3px; white-space: nowrap; } + .key-name { font-family: 'IBM Plex Mono', monospace; font-size: 0.86rem; font-weight: 600; color: var(--cyan); word-break: break-all; } + .key-status { font-size: 0.68rem; font-family: 'IBM Plex Mono', monospace; padding: 0.18rem 0.55rem; border-radius: 3px; white-space: nowrap; } .key-status.set { background: rgba(83,240,165,0.1); color: var(--green); box-shadow: 0 0 10px rgba(83,240,165,0.3); } .key-status.missing { background: rgba(255,93,93,0.1); color: var(--red); box-shadow: 0 0 10px rgba(255,93,93,0.2); } .key-desc { font-size: 0.8rem; color: var(--muted); margin-bottom: 0.7rem; overflow-wrap: anywhere; } - .key-hint { font-size: 0.7rem; color: var(--muted); opacity: 0.8; margin-top: 0.15rem; font-family: 'Share Tech Mono', monospace; } + .key-hint { font-size: 0.7rem; color: var(--muted); opacity: 0.8; margin-top: 0.15rem; font-family: 'IBM Plex Mono', monospace; } .key-form { display: flex; gap: 0.5rem; } - .key-form input { flex: 1; background: var(--bg-0); border: 1px solid var(--line); border-radius: 4px; padding: 0.5rem 0.6rem; color: var(--text); font-size: 0.82rem; font-family: 'Share Tech Mono', monospace; } + .key-form input { flex: 1; background: var(--bg-0); border: 1px solid var(--line); border-radius: 4px; padding: 0.5rem 0.6rem; color: var(--text); font-size: 0.82rem; font-family: 'IBM Plex Mono', monospace; } .key-form input:focus { outline: none; border-color: var(--cyan); box-shadow: 0 0 8px var(--cyan-glow); } .key-form .btn { white-space: nowrap; } .key-form .btn-danger { border-color: rgba(255,93,93,0.5); color: var(--red); } @@ -645,17 +647,17 @@ .set-row textarea, .set-row input[type="text"], .set-row select { background: var(--bg-0); color: var(--text); border: 1px solid var(--line); border-radius: 4px; padding: 0.5rem 0.6rem; font-size: 0.85rem; - font-family: 'Share Tech Mono', monospace; color-scheme: dark; + font-family: 'IBM Plex Mono', monospace; color-scheme: dark; } .set-row textarea:focus, .set-row input:focus, .set-row select:focus { outline: none; border-color: var(--cyan); box-shadow: 0 0 8px var(--cyan-glow); } .set-note { font-size: 0.72rem; color: var(--muted); line-height: 1.5; } .set-note code { background: rgba(3,6,9,0.7); border: 1px solid var(--line); border-radius: 3px; padding: 0.05rem 0.35rem; font-size: 0.82em; } .set-actions { display: flex; gap: 0.6rem; margin-top: 0.4rem; } - .set-saved { color: var(--green); font-size: 0.75rem; font-family: 'Share Tech Mono', monospace; min-height: 1.1rem; } + .set-saved { color: var(--green); font-size: 0.75rem; font-family: 'IBM Plex Mono', monospace; min-height: 1.1rem; } .sys-row { display: flex; justify-content: space-between; padding: 0.32rem 0; border-bottom: 1px dashed var(--line); font-size: 0.8rem; } .sys-row:last-child { border-bottom: none; } .sys-row .k { color: var(--muted); text-transform: uppercase; letter-spacing: 0.08em; font-size: 0.68rem; } - .sys-row .v { font-family: 'Share Tech Mono', monospace; } + .sys-row .v { font-family: 'IBM Plex Mono', monospace; } /* ═══════════════ BOTTOM DOCK: tickers ═══════════════ */ .dock { @@ -672,12 +674,14 @@ .tick-label { display: flex; align-items: center; justify-content: center; gap: 0.4rem; min-width: 74px; padding: 0 0.7rem; flex-shrink: 0; - font-family: 'Orbitron', sans-serif; font-size: 0.62rem; font-weight: 700; + font-family: 'IBM Plex Sans', sans-serif; font-size: 0.62rem; font-weight: 700; letter-spacing: 0.2em; color: #02131c; background: var(--cyan); text-shadow: none; position: relative; clip-path: polygon(0 0, calc(100% - 8px) 0, 100% 100%, 0 100%); } - .ticker.news .tick-label { background: var(--magenta); color: #1c0311; } + .ticker.news .tick-label { background: var(--cyan); color: #02131c; } + .ticker.market[hidden] { display: none !important; } + .dock.news-only { height: 32px; } .tick-label .st { animation: pulse 1.6s infinite; } .tick-wrap { flex: 1; overflow: hidden; position: relative; display: flex; align-items: center; mask-image: linear-gradient(90deg, transparent 0, #000 26px, #000 calc(100% - 26px), transparent 100%); @@ -693,20 +697,20 @@ font-size: 0.82rem; padding: 0 1rem; color: var(--text); text-decoration: none; font-weight: 500; } - .tick-item .sym { font-family: 'Share Tech Mono', monospace; color: var(--cyan); font-size: 0.74rem; } - .tick-item .price { font-family: 'Share Tech Mono', monospace; color: var(--text); } + .tick-item .sym { font-family: 'IBM Plex Mono', monospace; color: var(--cyan); font-size: 0.74rem; } + .tick-item .price { font-family: 'IBM Plex Mono', monospace; color: var(--text); } .tick-item .chg.up { color: var(--green); } .tick-item .chg.down { color: var(--red); } .tick-item .chg.flat { color: var(--muted); } - .tick-item .dom { font-family: 'Share Tech Mono', monospace; font-size: 0.64rem; color: var(--cyan); background: rgba(53,224,255,0.08); border: 1px solid rgba(53,224,255,0.22); border-radius: 3px; padding: 0.05rem 0.4rem; } - .tick-item .tt { font-family: 'Share Tech Mono', monospace; font-size: 0.66rem; color: var(--muted); } + .tick-item .dom { font-family: 'IBM Plex Mono', monospace; font-size: 0.64rem; color: var(--cyan); background: rgba(53,224,255,0.08); border: 1px solid rgba(53,224,255,0.22); border-radius: 3px; padding: 0.05rem 0.4rem; } + .tick-item .tt { font-family: 'IBM Plex Mono', monospace; font-size: 0.66rem; color: var(--muted); } .tick-item .sep { color: var(--line-hi); } button.tick-item { cursor: pointer; background: transparent; border: 0; font: inherit; color: inherit; } .tick-item.brief { cursor: pointer; background: linear-gradient(90deg, rgba(255,46,151,0.12), transparent 70%); border-left: 2px solid var(--magenta); font-weight: 600; } - .tick-item .b-tag { font-family: 'Share Tech Mono', monospace; font-size: 0.6rem; color: #1c0311; background: var(--magenta); border-radius: 2px; padding: 0.08rem 0.4rem; letter-spacing: 0.1em; } + .tick-item .b-tag { font-family: 'IBM Plex Mono', monospace; font-size: 0.6rem; color: #1c0311; background: var(--magenta); border-radius: 2px; padding: 0.08rem 0.4rem; letter-spacing: 0.1em; } .tick-item .b-tag.critical { background: var(--red); } .tick-item .b-tag.high { background: var(--amber); } .tick-item .b-tag.medium { background: var(--cyan); color: #041018; } @@ -717,7 +721,7 @@ .tick-sep { color: var(--line-hi); } .tick-tag { display: flex; align-items: center; flex-shrink: 0; padding: 0 0.8rem; - font-family: 'Share Tech Mono', monospace; font-size: 0.62rem; + font-family: 'IBM Plex Mono', monospace; font-size: 0.62rem; letter-spacing: 0.12em; text-transform: uppercase; color: var(--muted); border-left: 1px solid var(--line); } @@ -733,16 +737,16 @@ } .boot.gone { opacity: 0; pointer-events: none; } .boot-inner { text-align: center; } - .boot-mark { font-family: 'Orbitron', sans-serif; font-size: 2.2rem; color: var(--cyan); text-shadow: 0 0 24px var(--cyan-glow); margin-bottom: 0.6rem; } - .boot-title { font-family: 'Orbitron', sans-serif; font-size: 1.3rem; font-weight: 900; letter-spacing: 0.3em; color: #eafcff; } + .boot-mark { font-family: 'IBM Plex Sans', sans-serif; font-size: 2.2rem; color: var(--cyan); text-shadow: 0 0 24px var(--cyan-glow); margin-bottom: 0.6rem; } + .boot-title { font-family: 'IBM Plex Sans', sans-serif; font-size: 1.3rem; font-weight: 900; letter-spacing: 0.3em; color: #eafcff; } .boot-title span { color: var(--cyan); } - .boot-sub { font-family: 'Share Tech Mono', monospace; font-size: 0.66rem; color: var(--muted); letter-spacing: 0.3em; margin-top: 0.5rem; } + .boot-sub { font-family: 'IBM Plex Mono', monospace; font-size: 0.66rem; color: var(--muted); letter-spacing: 0.3em; margin-top: 0.5rem; } .boot-bar { width: 220px; height: 3px; margin: 1.1rem auto 0; background: var(--bg-2); border-radius: 2px; overflow: hidden; } .boot-bar i { display: block; height: 100%; width: 40%; background: linear-gradient(90deg, transparent, var(--cyan), transparent); animation: bootSweep 0.9s linear infinite; } @keyframes bootSweep { from { transform: translateX(-100%); } to { transform: translateX(350%); } } @media (max-width: 820px) { - :root { --topbar-h: 42px; --dock-h: 56px; } + :root { --topbar-h: 42px; --dock-h: 32px; } .tick-label { min-width: 56px; padding: 0 0.5rem; } .tick-tag { display: none; } .hud-chips { display: none; } @@ -856,8 +860,7 @@
◢◤
-
OSINT//DASHBOARD
-
GLOBAL SITUATIONAL AWARENESS TERMINAL
+
OSINT//
@@ -906,7 +909,7 @@ Strait -
+ @@ -915,8 +918,8 @@
-
-
+ @@ -928,12 +931,20 @@
Opacity 100%
+
+
+ + + +
+
+
+
- + off
-
Sun terminator overlay. Default off. No API.
@@ -962,14 +973,14 @@
- + 0
Opacity 100%
- + 0
@@ -983,27 +994,24 @@
-
Geolocated events from the ingest pipeline. Color = source type.
- + 0
-
LLM-estimated locations from the 15-min brief. Pins only for critical/high.
- + IEM
Opacity 70%
-
IEM NEXRAD over CONUS, RainViewer elsewhere. Tiles load in the browser.
- + 0
@@ -1015,15 +1023,14 @@
- + 7d
Opacity 80%
-
Cloud-penetrating C-band. Last 7 days, viewport bbox. Tiles from same-origin TiTiler — not fetched on load.
- + 0
@@ -1035,51 +1042,37 @@
- + 0
-
Magenta = military · orange = firefighting · red = emergency (7700/7600/7500) · else altitude. Click a plane for type / squawk / operator.
- + 0
-
Amtraker · ODC-By
- + 0
-
Two feeds: AISStream (US live) and VesselAPI (Hormuz, 5×/day). Paste both keys on the Keys page. Magenta = military · gold = law/gov · teal = underway. Click for type / dest / IMO.
-
-
-
- - - -
-
-
-
Tap vertices, then Finish (or double-click). Inbox keeps hits after the toast fades.
- + 0
- + 0
-
Curated theatres · color by severity · news counts, not LiveUAMap.
@@ -1121,7 +1114,7 @@
R
Reset map view
Esc
Close panels
-

Camera / HLS thumbs at zoom 12+. F and S are left unbound.

+

Camera / HLS thumbs at zoom 12+. F and S are left unbound.

@@ -1355,8 +1348,8 @@
- - + +
@@ -1387,8 +1380,8 @@ -
-
+
+ ", 1)[0] + assert 'aria-expanded="false"' in head + assert 'id="layer-panel" class="collapsed"' in HTML + + +def test_market_ticker_hidden_no_poll(): + mkt = HTML.split('class="ticker market"', 1)[1].split(">", 1)[0] + assert "hidden" in mkt + assert "setInterval(probeMarket" not in HTML + assert "setInterval(loadMarket" not in HTML + init = HTML.split("function initMarketTicker", 1)[1].split("function ", 1)[0] + assert "/api/market" in init or "404-poll" in init + assert "setInterval" not in init + + +def test_news_pins_are_circle_markers(): + js = HTML.split("async function loadNewsPins", 1)[1].split("function refreshLiveOverlays", 1)[0] + assert "L.circleMarker" in js + assert "fillOpacity: 0.7" in js or "fillOpacity:0.7" in js + assert "rotate(45deg)" not in js + assert "L.divIcon" not in js + + +def test_chokepoint_buttons_not_in_toolbar_flow(): + assert 'id="chokepoint-select"' in HTML + css = HTML.split("", 1)[0] + assert ".chokepoint-btns { display: none; }" in css or ".chokepoint-btns{display:none" in css.replace( + " ", "" + ) + + +def test_brand_is_osint_slash(): + assert "GLOBAL SITUATIONAL AWARENESS TERMINAL" not in HTML + assert "OSINT" in HTML + assert 'class="accent">//' in HTML From 0fa49b840772af89eb9b17fd76925422bfe06432 Mon Sep 17 00:00:00 2001 From: Sirius DevOps Date: Tue, 1 Sep 2026 01:55:12 -0400 Subject: [PATCH 57/79] fix(map): NEWS ticker fills 32px news-only dock .ticker stayed at height:50% after MKT was hidden, leaving an empty half-bar. .dock.news-only .ticker is now 100% of the 32px dock. --- app/static/index.html | 1 + tests/test_hud_chrome.py | 8 ++++++++ 2 files changed, 9 insertions(+) diff --git a/app/static/index.html b/app/static/index.html index da65fbf..fdc1588 100644 --- a/app/static/index.html +++ b/app/static/index.html @@ -682,6 +682,7 @@ .ticker.news .tick-label { background: var(--cyan); color: #02131c; } .ticker.market[hidden] { display: none !important; } .dock.news-only { height: 32px; } + .dock.news-only .ticker { height: 100%; } .tick-label .st { animation: pulse 1.6s infinite; } .tick-wrap { flex: 1; overflow: hidden; position: relative; display: flex; align-items: center; mask-image: linear-gradient(90deg, transparent 0, #000 26px, #000 calc(100% - 26px), transparent 100%); diff --git a/tests/test_hud_chrome.py b/tests/test_hud_chrome.py index 210cdbc..9be2d5d 100644 --- a/tests/test_hud_chrome.py +++ b/tests/test_hud_chrome.py @@ -83,6 +83,14 @@ def test_market_ticker_hidden_no_poll(): assert "setInterval" not in init +def test_news_ticker_fills_news_only_dock(): + css = HTML.split("", 1)[0] + compact = css.replace(" ", "").replace("\n", "") + assert ".dock.news-only{height:32px;}" in compact + assert ".dock.news-only.ticker{height:100%;}" in compact + assert ".ticker{display:flex;align-items:stretch;height:50%;" in compact + + def test_news_pins_are_circle_markers(): js = HTML.split("async function loadNewsPins", 1)[1].split("function refreshLiveOverlays", 1)[0] assert "L.circleMarker" in js From c0a2454fddbd5488584a5f4da01bca459c4a9a87 Mon Sep 17 00:00:00 2001 From: Sirius DevOps Date: Fri, 13 Nov 2026 20:56:07 -0500 Subject: [PATCH 58/79] feat(auth): public read-only HUD, admin-only API keys and mutations Adds single-admin authentication to the dashboard. Anonymous visitors get a read-only site (map + news); the one admin unlocks everything else. - app/auth.py: deny-by-default ASGI middleware on /api/* with an explicit public read allowlist; /login page; /api/auth/{login,logout,me}; PBKDF2 password hashing; HMAC-signed HttpOnly SameSite=Lax session cookie (7d, Secure behind X-Forwarded-Proto: https); 5-fail/15-min per-IP login limit; Origin/Referer host check on state-changing admin requests. - Fails closed: missing ADMIN_PASSWORD_HASH or ADMIN_SESSION_SECRET -> admin routes 403 'admin auth not configured', public site unaffected. - app/main.py: mounts the middleware + router (6 lines, no per-route decorators). - app/static/index.html: hides Ingest/API Keys/Settings, the summarizer panel and geofence write controls until /api/auth/me says admin; adds a discreet SIGN IN link to /login. CSS gates fail closed without JS. - tests/test_auth.py: 42 tests (anonymous 401s, login/logout, tampered and expired cookies, fail-closed, rate limit, CSRF, HUD markup). - Existing API tests now send an admin session cookie for admin routes. Public allowlist extends the spec's list with the remaining read-only GETs the HUD calls (/api/stats, /api/conflicts, /api/place, /api/satellites, /api/infrastructure, /api/map/gpsjam, /api/map/times, /api/fire-incidents, /api/fire-perimeters, /api/weather-alerts, /api/storms, /api/geofences/{id}/at) so an anonymous HUD is not half-broken. --- .env.example | 10 + app/auth.py | 574 ++++++++++++++++++++++++++ app/main.py | 6 + app/static/index.html | 78 +++- docs/auth.md | 79 ++++ tests/conftest.py | 27 ++ tests/test_api_live_layers.py | 4 + tests/test_api_settings.py | 3 +- tests/test_auth.py | 510 +++++++++++++++++++++++ tests/test_ingest_ssrf_and_sources.py | 3 + tests/test_phase2_api.py | 3 + 11 files changed, 1283 insertions(+), 14 deletions(-) create mode 100644 app/auth.py create mode 100644 docs/auth.md create mode 100644 tests/test_auth.py diff --git a/.env.example b/.env.example index 7d194f6..7e582dc 100644 --- a/.env.example +++ b/.env.example @@ -69,6 +69,16 @@ VESSELAPI_IN_INGEST=0 # (GET/POST/DELETE /api/keys/{name}) — see app/keystore.py. The FIRMS ingestor # currently reads FIRMS_MAP_KEY from .env (above); wiring the Keys-UI store as # its lookup/fallback is a planned follow-up. +# +# Key management is ADMIN-ONLY (single admin, no user table). Visitors get a +# read-only map + news. Configure the three vars below or admin endpoints +# answer 403 {"detail": "admin auth not configured"} (fail closed — the public +# site keeps working). In the cluster they come from Secret `osint-admin`. +# Generate the hash: python app/auth.py hash 'your password' +# Generate the secret: python -c 'import secrets; print(secrets.token_urlsafe(48))' +ADMIN_USER= +ADMIN_PASSWORD_HASH= +ADMIN_SESSION_SECRET= # ── News pipeline (scraper + summarizer, profile `ingest`) ──────────────── # Scraper crawls urls.txt continuously (default 10s between crawls). diff --git a/app/auth.py b/app/auth.py new file mode 100644 index 0000000..cfdb074 --- /dev/null +++ b/app/auth.py @@ -0,0 +1,574 @@ +"""Single-admin authentication for the OSINT dashboard. + +The public site stays read-only for anonymous visitors; the one admin (the +operator) unlocks API-key management, settings and every state-changing route. + +Design notes +------------ +* **Deny by default.** :class:`AdminAuthMiddleware` inspects every ``/api/*`` + request. Only the explicit read allowlist below is reachable without a + session; everything else needs a valid signed cookie. ``/api/auth/*`` is the + bootstrap surface and handles its own checks. +* **Fail closed.** With ``ADMIN_PASSWORD_HASH`` or ``ADMIN_SESSION_SECRET`` + unset/empty, admin endpoints answer ``403 {"detail": "admin auth not + configured"}``. There is no default password and no bypass; public reads and + the HUD keep working. +* **No new dependencies.** Password hashing is stdlib ``hashlib.pbkdf2_hmac`` + and the session token is an HMAC-SHA256 signature over a base64url JSON + payload. Cookies are HttpOnly, SameSite=Lax, Path=/, 7-day lifetime, and + ``Secure`` when the request arrived over https (``X-Forwarded-Proto``). +* **CSRF.** State-changing admin requests that carry an ``Origin``/``Referer`` + are rejected when the origin host differs from the request host. Requests + without either header (curl, server-to-server) are allowed — the signed, + SameSite=Lax session cookie is what authenticates them. + +Environment (exact names, supplied by the ``osint-admin`` Secret): + +``ADMIN_USER`` + Admin username. +``ADMIN_PASSWORD_HASH`` + ``pbkdf2_sha256$$$``. Generate with:: + + python app/auth.py hash 'your password' + +``ADMIN_SESSION_SECRET`` + HMAC key for session tokens. Generate with:: + + python -c 'import secrets; print(secrets.token_urlsafe(48))' +""" + +from __future__ import annotations + +import base64 +import hashlib +import hmac +import json +import os +import re +import secrets +import time +from collections import deque +from urllib.parse import parse_qs, urlparse + +from fastapi import APIRouter, Request +from fastapi.responses import HTMLResponse, JSONResponse + +# ── Constants ──────────────────────────────────────────────────────────────── + +COOKIE_NAME = "osint_session" +SESSION_TTL_SECONDS = 7 * 24 * 60 * 60 +PBKDF2_ALGORITHM = "pbkdf2_sha256" +PBKDF2_ITERATIONS = 260_000 +_ITERATIONS_FLOOR, _ITERATIONS_CEIL = 1_000, 5_000_000 + +LOGIN_WINDOW_SECONDS = 15 * 60 +LOGIN_MAX_FAILURES = 5 + +_STATE_CHANGING = frozenset({"POST", "PUT", "PATCH", "DELETE"}) + +# ── Public read allowlist ──────────────────────────────────────────────────── +# Anonymous visitors get the map + news HUD. Every path here was audited as a +# pure read (no writes, no spend of a stored API key). Anything absent requires +# the admin session. + +PUBLIC_GET_EXACT = frozenset({ + # core + "/api/health", + "/api/ready", + "/api/stats", + # events / sources / entities / alerts / documents + "/api/sources", + "/api/events", + "/api/fires", + "/api/entities", + "/api/alerts", + "/api/documents", + # analytics + "/api/analytics/summary", + "/api/analytics/timeline", + "/api/analytics/sentiment/by-source", + # cameras + "/api/cameras", + # news + "/api/news", + "/api/news/summaries", + "/api/news/ticker", + "/api/news/map", + # map / live layers + "/api/map/layers", + "/api/map/chokepoints", + "/api/map/radar", + "/api/map/sentinel1", + "/api/map/gpsjam", + "/api/map/times", + "/api/conflicts", + "/api/aircraft", + "/api/aircraft/photo", + "/api/trains", + "/api/vessels", + "/api/tracks/range", + "/api/satellites", + "/api/infrastructure", + "/api/place", + # geofences (reads only — create/patch/delete stay admin) + "/api/geofences", + "/api/geofence-alerts", + # fire / weather overlays + "/api/fire-aircraft", + "/api/fire-incidents", + "/api/fire-perimeters", + "/api/weather-alerts", + "/api/storms", +}) + +PUBLIC_GET_PATTERNS = tuple(re.compile(p) for p in ( + r"^/api/events/[^/]+$", + r"^/api/entities/[^/]+$", + r"^/api/entities/[^/]+/events$", + r"^/api/cameras/[^/]+$", + r"^/api/cameras/[^/]+/(?:snapshot|stream|hls\.m3u8|hlsseg)$", + r"^/api/geofences/[^/]+/at$", +)) + +# POST is only public for the read-only query endpoint. +PUBLIC_POST_EXACT = frozenset({"/api/search"}) + + +def is_public(path: str, method: str) -> bool: + """True when ``method path`` may be served without an admin session.""" + if not path.startswith("/api/"): + return True + if path.startswith("/api/auth/"): + return True + norm = path.rstrip("/") or "/" + if method in ("GET", "HEAD"): + if norm in PUBLIC_GET_EXACT: + return True + return any(p.match(norm) for p in PUBLIC_GET_PATTERNS) + if method == "POST": + return norm in PUBLIC_POST_EXACT + return False + + +# ── Config (read per call so tests and reloads pick up env changes) ───────── + +def _env(name: str) -> str: + return (os.environ.get(name) or "").strip() + + +def admin_user() -> str: + return _env("ADMIN_USER") + + +def admin_password_hash() -> str: + return _env("ADMIN_PASSWORD_HASH") + + +def session_secret() -> str: + return _env("ADMIN_SESSION_SECRET") + + +def auth_configured() -> bool: + """Fail closed: both the password hash and the signing key must be set.""" + return bool(admin_password_hash() and session_secret()) + + +# ── Password hashing (stdlib PBKDF2-SHA256) ───────────────────────────────── + +def _b64e(raw: bytes) -> str: + return base64.urlsafe_b64encode(raw).rstrip(b"=").decode("ascii") + + +def _b64d(text: str) -> bytes: + pad = "=" * (-len(text) % 4) + return base64.urlsafe_b64decode(text + pad) + + +def hash_password(password: str, *, iterations: int = PBKDF2_ITERATIONS, + salt: bytes | None = None) -> str: + """Return ``pbkdf2_sha256$$$``.""" + salt = salt if salt is not None else secrets.token_bytes(16) + dk = hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), salt, iterations) + return f"{PBKDF2_ALGORITHM}${iterations}${_b64e(salt)}${_b64e(dk)}" + + +def verify_password(password: str, stored: str) -> bool: + """Constant-time check of ``password`` against a stored PBKDF2 string.""" + if not stored: + return False + try: + algorithm, iterations_s, salt_b64, hash_b64 = stored.split("$", 3) + iterations = int(iterations_s) + salt = _b64d(salt_b64) + expected = _b64d(hash_b64) + except (ValueError, TypeError): + return False + if algorithm != PBKDF2_ALGORITHM: + return False + if not (_ITERATIONS_FLOOR <= iterations <= _ITERATIONS_CEIL): + return False + dk = hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), salt, iterations) + return hmac.compare_digest(dk, expected) + + +def _const_eq(a: str, b: str) -> bool: + return hmac.compare_digest(a.encode("utf-8"), b.encode("utf-8")) + + +# ── Session tokens ─────────────────────────────────────────────────────────── + +def _sign(body: str, secret: str) -> str: + digest = hmac.new(secret.encode("utf-8"), body.encode("ascii"), hashlib.sha256).digest() + return _b64e(digest) + + +def create_session_token(user: str, *, now: float | None = None) -> str: + secret = session_secret() + if not secret: + raise RuntimeError("ADMIN_SESSION_SECRET is not configured") + issued = int(now if now is not None else time.time()) + payload = {"v": 1, "sub": user, "iat": issued, "exp": issued + SESSION_TTL_SECONDS} + body = _b64e(json.dumps(payload, separators=(",", ":"), sort_keys=True).encode("utf-8")) + return f"{body}.{_sign(body, secret)}" + + +def verify_session_token(token: str | None, *, now: float | None = None) -> str | None: + """Return the username for a valid token, else ``None``. Never raises.""" + if not token or "." not in token: + return None + secret = session_secret() + if not secret: + return None + body, signature = token.rsplit(".", 1) + try: + expected = _sign(body, secret) + if not hmac.compare_digest(signature.encode("utf-8"), expected.encode("utf-8")): + return None + except (UnicodeEncodeError, ValueError, TypeError): + return None + try: + payload = json.loads(_b64d(body)) + version = payload["v"] + subject = str(payload["sub"]) + issued = int(payload["iat"]) + expires = int(payload["exp"]) + except (ValueError, KeyError, TypeError): + return None + now_s = int(now if now is not None else time.time()) + if version != 1: + return None + if expires <= now_s or issued > now_s + 300: + return None + expected = admin_user() + if not expected or not _const_eq(subject, expected): + return None + return subject + + +def current_user(request: Request) -> str | None: + """The authenticated admin username for this request, else ``None``.""" + if not auth_configured(): + return None + return verify_session_token(request.cookies.get(COOKIE_NAME)) + + +# ── Cookie helpers ─────────────────────────────────────────────────────────── + +def _is_https(request: Request) -> bool: + proto = (request.headers.get("x-forwarded-proto") or "").split(",")[0].strip().lower() + if proto: + return proto == "https" + return request.url.scheme == "https" + + +def set_session_cookie(response, request: Request, token: str) -> None: + response.set_cookie( + COOKIE_NAME, + token, + max_age=SESSION_TTL_SECONDS, + httponly=True, + samesite="lax", + secure=_is_https(request), + path="/", + ) + + +def clear_session_cookie(response) -> None: + response.delete_cookie(COOKIE_NAME, path="/", httponly=True, samesite="lax") + + +# ── Login rate limiting (in-memory; single replica) ───────────────────────── + +_failures: dict[str, deque[float]] = {} + + +def client_ip(request: Request) -> str: + forwarded = request.headers.get("x-forwarded-for") or "" + first = forwarded.split(",")[0].strip() + if first: + return first + return request.client.host if request.client else "unknown" + + +def _prune(bucket: deque[float], now: float) -> None: + while bucket and now - bucket[0] > LOGIN_WINDOW_SECONDS: + bucket.popleft() + + +def rate_limited(ip: str, *, now: float | None = None) -> bool: + now_s = time.time() if now is None else now + bucket = _failures.get(ip) + if not bucket: + return False + _prune(bucket, now_s) + return len(bucket) >= LOGIN_MAX_FAILURES + + +def record_failure(ip: str, *, now: float | None = None) -> None: + now_s = time.time() if now is None else now + if len(_failures) > 10_000: # bound memory against IP spraying + for key in [k for k, v in _failures.items() if not v or now_s - v[-1] > LOGIN_WINDOW_SECONDS]: + _failures.pop(key, None) + bucket = _failures.setdefault(ip, deque()) + _prune(bucket, now_s) + bucket.append(now_s) + + +def reset_failures(ip: str | None = None) -> None: + """Clear the limiter (used by logout success and tests).""" + if ip is None: + _failures.clear() + else: + _failures.pop(ip, None) + + +# ── CSRF (origin host must match the request host when supplied) ──────────── + +def origin_allowed(request: Request) -> bool: + if request.method.upper() not in _STATE_CHANGING: + return True + origin = request.headers.get("origin") or request.headers.get("referer") + if not origin: + return True # no browser context: session cookie is the credential + host = (request.headers.get("x-forwarded-host") or request.headers.get("host") or "") + host = host.split(",")[0].strip().lower() + try: + origin_host = urlparse(origin).netloc.strip().lower() + except ValueError: + return False + if not host or not origin_host: + return False + return origin_host == host + + +# ── Middleware ─────────────────────────────────────────────────────────────── + +def _json_response(status: int, detail: str) -> JSONResponse: + return JSONResponse({"detail": detail}, status_code=status) + + +class AdminAuthMiddleware: + """Deny-by-default gate for ``/api/*`` (pure ASGI; keeps streaming intact).""" + + def __init__(self, app): + self.app = app + + async def __call__(self, scope, receive, send): + if scope.get("type") != "http": + return await self.app(scope, receive, send) + path = scope.get("path") or "" + method = (scope.get("method") or "GET").upper() + if not path.startswith("/api/") or is_public(path, method): + return await self.app(scope, receive, send) + + request = Request(scope) + if not auth_configured(): + return await _json_response(403, "admin auth not configured")(scope, receive, send) + if current_user(request) is None: + return await _json_response(401, "admin authentication required")(scope, receive, send) + if not origin_allowed(request): + return await _json_response(403, "cross-origin admin request blocked")(scope, receive, send) + return await self.app(scope, receive, send) + + +# ── Auth routes ───────────────────────────────────────────────────────────── + +router = APIRouter() + + +@router.get("/api/auth/me") +async def auth_me(request: Request): + """Always 200 — the HUD uses this to show/hide admin UI.""" + user = current_user(request) + return {"authenticated": user is not None, "admin": user is not None} + + +async def _read_credentials(request: Request) -> dict: + """Accept form-encoded or JSON bodies (never trust the claimed type).""" + raw = await request.body() + if not raw: + return {} + ctype = (request.headers.get("content-type") or "").lower() + if "json" in ctype: + try: + payload = json.loads(raw) + except (ValueError, TypeError): + return {} + return payload if isinstance(payload, dict) else {} + if "form" in ctype or "urlencoded" in ctype: + try: + parsed = parse_qs(raw.decode("utf-8", "replace")) + except (ValueError, TypeError): + return {} + return {k: v[0] for k, v in parsed.items() if v} + # Unknown content type: try JSON, then form. + try: + payload = json.loads(raw) + if isinstance(payload, dict): + return payload + except (ValueError, TypeError): + pass + try: + parsed = parse_qs(raw.decode("utf-8", "replace")) + except (ValueError, TypeError): + return {} + return {k: v[0] for k, v in parsed.items() if v} + + +@router.post("/api/auth/login") +async def auth_login(request: Request): + ip = client_ip(request) + if not auth_configured(): + return _json_response(403, "admin auth not configured") + if rate_limited(ip): + return _json_response(429, "too many failed login attempts") + + data = await _read_credentials(request) + username = str(data.get("username") or data.get("user") or "") + password = str(data.get("password") or "") + + user_ok = bool(username) and bool(admin_user()) and _const_eq(username, admin_user()) + pass_ok = verify_password(password, admin_password_hash()) + if not (user_ok and pass_ok): + record_failure(ip) + return _json_response(401, "invalid credentials") + + reset_failures(ip) + response = JSONResponse({"authenticated": True, "admin": True}) + set_session_cookie(response, request, create_session_token(admin_user())) + return response + + +@router.post("/api/auth/logout") +async def auth_logout(request: Request): + # NOTE: never clear the login limiter here — logout is unauthenticated and + # would otherwise let an attacker reset the rate limit between guesses. + response = JSONResponse({"authenticated": False, "admin": False}) + clear_session_cookie(response) + return response + + +_LOGIN_PAGE = """ + + + + + +Admin sign-in · OSINT// + + + +
+
OSINT// ADMIN
+

Sign in

+ + + + + + + +
+ + + +""" + +_NOT_CONFIGURED = ('
Admin auth is not configured on this server. ' + 'Set ADMIN_PASSWORD_HASH and ADMIN_SESSION_SECRET.
') + + +@router.get("/login", response_class=HTMLResponse) +async def login_page(): + html = _LOGIN_PAGE + if not auth_configured(): + html = html.replace('', + _NOT_CONFIGURED.replace('class="msg"', 'class="msg" id="msg" role="alert"')) + response = HTMLResponse(html) + response.headers["Cache-Control"] = "no-store" + return response + + +# ── CLI: generate a password hash ──────────────────────────────────────────── + +def _main(argv: list[str]) -> int: + if len(argv) != 2 or argv[0] != "hash": + print("usage: python app/auth.py hash ''") + return 2 + print(hash_password(argv[1])) + return 0 + + +if __name__ == "__main__": + import sys + + raise SystemExit(_main(sys.argv[1:])) diff --git a/app/main.py b/app/main.py index 049d96c..2d7a3f6 100644 --- a/app/main.py +++ b/app/main.py @@ -34,6 +34,7 @@ from sqlalchemy import and_, func, or_, select, text from sqlalchemy.ext.asyncio import AsyncSession from database import async_session, init_extensions +from auth import AdminAuthMiddleware, router as auth_router from models import ( alerts, documents, entities, entity_events, events, feed_sources, fires, articles, article_summaries, news_items, @@ -116,6 +117,11 @@ app = FastAPI( ) app.add_middleware(GZipMiddleware, minimum_size=1024) +# Single-admin auth: deny-by-default on /api/* with an explicit public read +# allowlist (app/auth.py), plus /login, /api/auth/{login,logout,me}. +app.add_middleware(AdminAuthMiddleware) +app.include_router(auth_router) + STATIC_DIR = Path(__file__).parent / "static" diff --git a/app/static/index.html b/app/static/index.html index fdc1588..acca754 100644 --- a/app/static/index.html +++ b/app/static/index.html @@ -157,6 +157,20 @@ .nav-item.primary .ico { color: var(--magenta); } .nav-sep { height: 1px; background: var(--line); margin: 0.35rem 0.3rem; } + /* ═══════════════ ADMIN GATE (UX only — the API is the real gate) ═══ + Elements marked data-admin stay hidden until /api/auth/me reports a + valid admin session (body.is-admin). Fails closed: no JS => hidden. */ + body:not(.is-admin) [data-admin] { display: none !important; } + .admin-link { + font-size: 0.62rem; letter-spacing: 0.16em; text-transform: uppercase; + color: var(--muted); text-decoration: none; border: 1px solid var(--line); + border-radius: 3px; padding: 0.28rem 0.5rem; white-space: nowrap; + transition: color .15s, border-color .15s; + } + .admin-link:hover, .admin-link:focus-visible { color: var(--cyan); border-color: var(--cyan); } + body.is-admin .admin-link { color: var(--magenta); border-color: var(--magenta); } + + /* ═══════════════ STAGE / VIEWS ═══════════════ */ .stage { /* 100vh first for old browsers; 100dvh shrinks with mobile URL chrome */ @@ -875,6 +889,7 @@
+ SIGN IN
@@ -933,7 +948,7 @@
Opacity 100%
-
+
@@ -1238,7 +1253,7 @@ -
+

⇪ Data Ingestion

Manually trigger feed pulls & NATS processing

@@ -1271,7 +1286,7 @@
-
+

⚿ API Keys

Keys used by ingest services (FIRMS, Nous Portal, Telegram, AIS, …). Stored in Postgres, never shown again — only status + last 4 chars.

@@ -1298,7 +1313,7 @@
-
+

News Summarizer

Takes effect on the next 15-min run. No container restart.

@@ -1626,6 +1641,40 @@ function initHudKeys() { }); } +/* ═══════════════ ADMIN SESSION (UX gate — the API is the real gate) ═══════ + Anonymous visitors get the read-only map + news. Admin-only chrome is + marked data-admin and revealed only when /api/auth/me reports a session. */ +let IS_ADMIN = false; +let AUTH_READY = false; +const ADMIN_VIEWS = ['keys', 'ingest', 'settings']; + +async function initAuth() { + try { + const r = await fetch(`${API}/api/auth/me`, {cache: 'no-store', credentials: 'same-origin'}); + const d = r.ok ? await r.json() : {}; + IS_ADMIN = !!(d && d.admin); + } catch (e) { + IS_ADMIN = false; + } + AUTH_READY = true; + document.body.classList.toggle('is-admin', IS_ADMIN); + const link = document.getElementById('admin-link'); + if (link) { + link.textContent = IS_ADMIN ? 'SIGN OUT' : (link.dataset.anonLabel || 'SIGN IN'); + link.title = IS_ADMIN ? 'End admin session' : 'Admin sign-in'; + link.setAttribute('aria-label', IS_ADMIN ? 'Sign out of admin session' : 'Admin sign-in'); + } +} + +async function onAdminLink(ev) { + if (!IS_ADMIN) return; // anonymous: plain link to /login + ev.preventDefault(); + try { + await fetch(`${API}/api/auth/logout`, {method: 'POST', credentials: 'same-origin'}); + } catch (e) { /* cookie expires anyway */ } + window.location.reload(); +} + /* ═══════════════ NAV (dropdown) ═══════════════ */ const VIEWS = ['map', 'news', 'events', 'alerts', 'entities', 'ingest', 'keys', 'settings']; @@ -1672,6 +1721,7 @@ function initNav() { function showView(name) { if (!VIEWS.includes(name)) name = 'map'; + if (AUTH_READY && !IS_ADMIN && ADMIN_VIEWS.includes(name)) name = 'map'; VIEWS.forEach(v => { document.getElementById('view-' + v).classList.toggle('active', v === name); }); @@ -4154,6 +4204,8 @@ async function loadConflicts(paint) { } /* ═══════════════ INITIAL LOAD ═══════════════ */ +document.getElementById('admin-link').addEventListener('click', onAdminLink); +initAuth(); initNav(); initHudKeys(); initSettings(); @@ -4493,13 +4545,13 @@ async function loadGeofences() { const on = f.active === false ? '' : ' checked'; const sel = f.id === gfSelectedId ? ' selected' : ''; return `
` + - `` + `` + `` + `` + - `` + - `` + + `` + + `` + `
`; }).join(''); } @@ -4524,8 +4576,8 @@ async function loadGeofences() { const chk = active ? ' checked' : ''; layer.bindPopup( `
${name}
` + - `
` + - `
` + `
` + + `
` ); }, }).addTo(map); diff --git a/docs/auth.md b/docs/auth.md new file mode 100644 index 0000000..8a7bef9 --- /dev/null +++ b/docs/auth.md @@ -0,0 +1,79 @@ +# Admin authentication + +The dashboard is **public read-only**: anyone can open the map and the news +brief. One admin (the operator) additionally gets API-key management, settings +and every state-changing route. There is no user table, no RBAC and no OAuth — +one admin, one signed cookie (`app/auth.py`). + +## Surface + +| Route | Anonymous | Admin | +| --- | --- | --- | +| `GET /`, `GET /login`, `GET /static/*`, `WS /ws/live` | ✅ | ✅ | +| Read allowlist (`GET /api/news`, `/api/map/*`, feeds, analytics, cameras, `POST /api/search`, …) | ✅ | ✅ | +| `GET/POST/DELETE /api/keys*` | 401 | ✅ | +| `GET/PUT /api/settings`, `GET /api/news/models` | 401 | ✅ | +| Every other `POST/PUT/PATCH/DELETE` (`/api/ingest/*`, `/api/sources`, events, entities, alerts, geofences, `/api/vessels/subscribe`) | 401 | ✅ | +| `GET /api/auth/me` | 200 `{"authenticated": false, "admin": false}` | 200, both `true` | +| `POST /api/auth/login` | — | 200 + `Set-Cookie` | +| `POST /api/auth/logout` | 200 (clears cookie) | 200 | + +Enforcement is **deny-by-default on `/api/*`** in `AdminAuthMiddleware` +(`app/auth.py`); the public list is an explicit allowlist (`PUBLIC_GET_EXACT`, +`PUBLIC_GET_PATTERNS`, `PUBLIC_POST_EXACT`). Naming a path there is the only way +to make it public — never a per-route decorator in `app/main.py`. + +## Configuration + +Three environment variables (cluster: Secret `osint-admin`): + +| Variable | Meaning | +| --- | --- | +| `ADMIN_USER` | Admin username. | +| `ADMIN_PASSWORD_HASH` | `pbkdf2_sha256$$$`. | +| `ADMIN_SESSION_SECRET` | HMAC-SHA256 key for the session token. | + +```bash +python app/auth.py hash 'your password' # password hash +python -c 'import secrets; print(secrets.token_urlsafe(48))' # session secret +``` + +Put the values into a Secret and reference them from the deployment; never +commit them. + +### Fail closed + +If `ADMIN_PASSWORD_HASH` **or** `ADMIN_SESSION_SECRET` is unset/empty: + +* every admin endpoint answers `403 {"detail": "admin auth not configured"}`, +* `/login` renders that message instead of the form, +* `/api/auth/login` also answers 403, +* public pages and the read allowlist still work. + +There is no default password and no bypass. + +## Session cookie + +`osint_session`, HMAC-SHA256 signed base64url JSON payload `{v,sub,iat,exp}`, +`HttpOnly`, `SameSite=Lax`, `Path=/`, 7-day lifetime, `Secure` when the request +arrived over https (`X-Forwarded-Proto`, i.e. behind Cloudflare). Signature and +expiry are checked with `hmac.compare_digest`; a token for another username, or +one signed with a different secret, is rejected. + +## Abuse controls + +* **Login rate limit:** 5 failed attempts per client IP (first hop of + `X-Forwarded-For`, else the socket peer) per 15 minutes, then `429`. + In-memory — fine for the single replica. +* **CSRF:** state-changing admin requests that carry `Origin`/`Referer` must + match the request host, else `403`. Header-less clients (curl, + service-to-service) rely on the signed SameSite=Lax cookie. + +## HUD + +`app/static/index.html` hides admin chrome with `body:not(.is-admin) +[data-admin]` and adds the class only when `GET /api/auth/me` reports +`admin: true`. The menu's Ingest / API Keys / Settings entries, the summarizer +panel and the geofence draw/rename/delete controls are admin-only; anonymous +visitors see a discreet `SIGN IN` link to `/login`. This is UX only — the API +gate is what actually protects the data. diff --git a/tests/conftest.py b/tests/conftest.py index 74a1d9c..770107b 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -30,11 +30,38 @@ os.environ.setdefault("DB_NAME", "osint_data") # reused across loops, so force a NullPool (new connection per session). os.environ.setdefault("DB_NULL_POOL", "1") +# ── Single-admin auth test configuration ──────────────────────────────────── +# Admin routes are denied unless a signed session cookie is present, so the +# suite needs known credentials + a signing key. Tests that exercise the +# "auth not configured" path monkeypatch these away. +ADMIN_TEST_USER = "admin" +ADMIN_TEST_PASSWORD = "test-admin-password" +ADMIN_TEST_SECRET = "test-admin-session-secret-not-for-production" + +from auth import COOKIE_NAME, create_session_token, hash_password, reset_failures # noqa: E402 + +os.environ.setdefault("ADMIN_USER", ADMIN_TEST_USER) +os.environ.setdefault("ADMIN_PASSWORD_HASH", hash_password(ADMIN_TEST_PASSWORD)) +os.environ.setdefault("ADMIN_SESSION_SECRET", ADMIN_TEST_SECRET) + import asyncpg # noqa: E402 pytestmark = [] +def admin_cookies() -> dict[str, str]: + """A valid admin session cookie value for in-process API calls.""" + return {COOKIE_NAME: create_session_token(os.environ["ADMIN_USER"])} + + +@pytest.fixture(autouse=True) +def _clear_login_limiter(): + """The login limiter is process-global; never leak failures between tests.""" + reset_failures() + yield + reset_failures() + + def _db_reachable() -> bool: try: import asyncio diff --git a/tests/test_api_live_layers.py b/tests/test_api_live_layers.py index 7349fd8..2efe445 100644 --- a/tests/test_api_live_layers.py +++ b/tests/test_api_live_layers.py @@ -7,18 +7,22 @@ import httpx from live_layers import overlay_catalog from main import app +from conftest import admin_cookies + BASE = "http://test" async def _get(path: str) -> httpx.Response: transport = httpx.ASGITransport(app=app) async with httpx.AsyncClient(transport=transport, base_url=BASE) as client: + client.cookies.update(admin_cookies()) return await client.get(path) async def _post(path: str, payload: dict | None) -> httpx.Response: transport = httpx.ASGITransport(app=app) async with httpx.AsyncClient(transport=transport, base_url=BASE) as client: + client.cookies.update(admin_cookies()) return await client.post(path, json=payload) diff --git a/tests/test_api_settings.py b/tests/test_api_settings.py index 6dad2f5..05a5b1d 100644 --- a/tests/test_api_settings.py +++ b/tests/test_api_settings.py @@ -9,7 +9,7 @@ import asyncpg import httpx import pytest -from conftest import requires_db +from conftest import admin_cookies, requires_db from main import app @@ -51,6 +51,7 @@ def _request(method: str, path: str, json: dict | None = None) -> httpx.Response async def _run() -> httpx.Response: transport = httpx.ASGITransport(app=app) async with httpx.AsyncClient(transport=transport, base_url=BASE) as client: + client.cookies.update(admin_cookies()) return await client.request(method, path, json=json) return asyncio.run(_run()) diff --git a/tests/test_auth.py b/tests/test_auth.py new file mode 100644 index 0000000..54d00bb --- /dev/null +++ b/tests/test_auth.py @@ -0,0 +1,510 @@ +"""Single-admin auth tests: public read-only site, admin-only everything else. + +Driven in-process through ``httpx.ASGITransport`` exactly like the other API +tests. No database is required: the few routes under test that would query +Postgres are stubbed with a no-row fake session, so this file runs on a bare +checkout. +""" + +from __future__ import annotations + +import asyncio +import time + +import httpx +import pytest + +from conftest import ADMIN_TEST_PASSWORD, ADMIN_TEST_USER, admin_cookies + +import auth +from main import app + +BASE = "http://test" +NOUS_KEY_PATH = "/api/keys/NOUS_API_KEY" + + +# ── Helpers ───────────────────────────────────────────────────────────────── + +class _FakeResult: + def mappings(self): + return self + + def all(self): + return [] + + def scalar(self): + return 0 + + def scalars(self): + return self + + def unique(self): + return self + + def one_or_none(self): + return None + + def scalar_one_or_none(self): + return None + + def __iter__(self): + return iter(()) + + +class _FakeSession: + async def __aenter__(self): + return self + + async def __aexit__(self, *exc): + return False + + async def execute(self, *args, **kwargs): + return _FakeResult() + + async def commit(self): + return None + + +def _fake_session(*args, **kwargs): + return _FakeSession() + + +@pytest.fixture() +def no_db(monkeypatch): + """Stub the DB session + key/settings stores so reads succeed offline.""" + import main + + monkeypatch.setattr(main, "async_session", _fake_session) + + async def _empty_keys(): + return [] + + async def _settings(): + return {"summary_model": "Hermes-4.3-36B", + "nous_base_url": "https://inference-api.nousresearch.com/v1"} + + async def _set_model(model: str): + return {"summary_model": model, + "nous_base_url": "https://inference-api.nousresearch.com/v1"} + + monkeypatch.setattr(main, "list_keys", _empty_keys) + monkeypatch.setattr(main, "get_app_settings", _settings) + monkeypatch.setattr(main, "set_summary_model", _set_model) + + +def _request(method: str, path: str, *, cookies=None, json=None, headers=None, + data=None) -> httpx.Response: + async def _run() -> httpx.Response: + transport = httpx.ASGITransport(app=app) + async with httpx.AsyncClient(transport=transport, base_url=BASE) as client: + if cookies: + client.cookies.update(cookies) + return await client.request( + method, path, json=json, headers=headers, data=data, + ) + + return asyncio.run(_run()) + + +def _login(password: str = ADMIN_TEST_PASSWORD, username: str = ADMIN_TEST_USER, + headers=None, form: bool = True) -> httpx.Response: + if form: + return _request( + "POST", "/api/auth/login", + data={"username": username, "password": password}, headers=headers, + ) + return _request( + "POST", "/api/auth/login", json={"username": username, "password": password}, + headers=headers, + ) + + +# ── Anonymous: public reads ───────────────────────────────────────────────── + +def test_anonymous_can_read_news(no_db): + resp = _request("GET", "/api/news") + assert resp.status_code == 200 + assert resp.json() == [] + + +def test_anonymous_can_read_public_allowlist(no_db): + # Every documented public read must pass the gate (handler errors from the + # stubbed DB are irrelevant here — 401/403/redirects are the failure modes). + async def _run() -> dict[str, int]: + # raise_app_exceptions=False: handler errors from the stubbed DB are + # irrelevant here — 401/403/redirects are the failure modes. + transport = httpx.ASGITransport(app=app, raise_app_exceptions=False) + + out: dict[str, int] = {} + async with httpx.AsyncClient(transport=transport, base_url=BASE) as client: + for path in ( + "/api/health", + "/api/map/layers", + "/api/map/chokepoints", + "/api/news", + "/api/news/ticker", + "/api/news/map", + "/api/geofences", + "/api/geofence-alerts", + "/api/analytics/summary", + "/api/tracks/range", + "/api/fire-aircraft", + ): + out[path] = (await client.get(path)).status_code + return out + + statuses = asyncio.run(_run()) + for path, status in statuses.items(): + assert status not in (401, 403, 307), f"{path} -> {status}" + + # DB-free reads answer for real. + for path in ("/api/news", "/api/map/layers", "/api/map/chokepoints"): + assert _request("GET", path).status_code == 200, path + + +SPEC_PUBLIC_READS = ( + "/api/health", "/api/ready", "/api/events", "/api/fires", "/api/sources", + "/api/entities", "/api/alerts", "/api/documents", + "/api/analytics/summary", "/api/analytics/timeline", + "/api/analytics/sentiment/by-source", "/api/cameras", + "/api/news", "/api/news/summaries", "/api/news/ticker", "/api/news/map", + "/api/map/layers", "/api/map/chokepoints", "/api/map/radar", + "/api/map/sentinel1", "/api/aircraft", "/api/aircraft/photo", + "/api/trains", "/api/vessels", "/api/tracks/range", "/api/geofences", + "/api/geofence-alerts", "/api/fire-aircraft", + "/api/events/11111111-1111-1111-1111-111111111111", + "/api/entities/11111111-1111-1111-1111-111111111111", + "/api/entities/11111111-1111-1111-1111-111111111111/events", + "/api/cameras/abc", "/api/cameras/abc/snapshot", + "/api/cameras/abc/stream", "/api/cameras/abc/hls.m3u8", + "/api/cameras/abc/hlsseg", +) + + +def test_public_allowlist_covers_the_spec(): + for path in SPEC_PUBLIC_READS: + assert auth.is_public(path, "GET"), path + + +def test_public_post_search_is_read_only(no_db): + resp = _request("POST", "/api/search", json={"q": "fire", "limit": 5}) + assert resp.status_code not in (401, 403) + + +def test_anonymous_can_load_hud(): + resp = _request("GET", "/") + assert resp.status_code == 200 + assert "text/html" in resp.headers["content-type"] + assert "OSINT" in resp.text + assert 'id="view-map"' in resp.text + + +def test_login_page_is_public(): + resp = _request("GET", "/login") + assert resp.status_code == 200 + assert "Sign in" in resp.text + assert resp.headers.get("cache-control") == "no-store" + assert 'name="username"' in resp.text and 'name="password"' in resp.text + assert "/api/auth/login" in resp.text + + +def test_hud_gates_admin_chrome_client_side(): + """Spec item 5: UX hiding is markup-driven and fails closed.""" + html = _request("GET", "/").text + # Fails closed without JS: data-admin is hidden unless body.is-admin. + assert "body:not(.is-admin) [data-admin]" in html + # Admin nav entries (API Keys is the headline requirement) are marked. + for view in ("keys", "ingest", "settings"): + assert f'data-view="{view}" data-admin' in html, view + # Keys view, ingest view and the summarizer panel are gated too. + assert 'id="view-keys" aria-label="API keys" data-admin' in html + assert 'id="view-ingest" aria-label="Ingest" data-admin' in html + # Discreet sign-in link + the /api/auth/me probe that reveals admin chrome. + assert 'id="admin-link"' in html and 'href="/login"' in html + assert "/api/auth/me" in html + + +def test_static_assets_are_public(): + assert _request("GET", "/static/index.html").status_code == 200 + + +# ── Anonymous: admin surface is closed ────────────────────────────────────── + +def test_anonymous_keys_read_is_401(): + resp = _request("GET", "/api/keys") + assert resp.status_code == 401 + assert resp.headers["content-type"].startswith("application/json") + assert "detail" in resp.json() + + +def test_anonymous_keys_write_is_401(): + resp = _request("POST", NOUS_KEY_PATH, json={"value": "sk-nope-1234567890"}) + assert resp.status_code == 401 + + +def test_anonymous_keys_delete_is_401(): + assert _request("DELETE", NOUS_KEY_PATH).status_code == 401 + + +def test_anonymous_settings_write_is_401(): + resp = _request("PUT", "/api/settings", json={"summary_model": "x/y-z"}) + assert resp.status_code == 401 + + +def test_anonymous_settings_read_is_401(): + assert _request("GET", "/api/settings").status_code == 401 + + +def test_anonymous_news_models_is_401(): + # /api/news/models spends the stored Nous key — never public. + assert _request("GET", "/api/news/models").status_code == 401 + + +def test_anonymous_state_changing_routes_are_401(): + cases = [ + ("POST", "/api/sources", {"name": "x", "url": "https://example.com/feed", "source_type": "rss"}), + ("POST", "/api/events", {"source_type": "rss", "title": "x"}), + ("POST", "/api/entities", {"name": "x", "entity_type": "person"}), + ("POST", "/api/alerts", {"alert_type": "keyword", "severity": "low", "title": "x"}), + ("POST", "/api/geofences", {"name": "x", "geojson": {"type": "Point", "coordinates": [0, 0]}}), + ("PATCH", "/api/geofences/abc", {"name": "y"}), + ("DELETE", "/api/geofences/abc", None), + ("POST", "/api/vessels/subscribe", {"bbox": "-70,40,-60,45"}), + ("POST", "/api/ingest/rss", None), + ("POST", "/api/ingest/earthquakes", None), + ("POST", "/api/ingest/process", None), + ] + for method, path, body in cases: + resp = _request(method, path, json=body) + assert resp.status_code == 401, f"{method} {path} -> {resp.status_code}" + + +def test_unknown_api_path_is_denied_anonymously(): + assert _request("GET", "/api/does-not-exist").status_code == 401 + + +# ── /api/auth/me ──────────────────────────────────────────────────────────── + +def test_auth_me_anonymous(): + resp = _request("GET", "/api/auth/me") + assert resp.status_code == 200 + assert resp.json() == {"authenticated": False, "admin": False} + + +def test_auth_me_with_session(): + resp = _request("GET", "/api/auth/me", cookies=admin_cookies()) + assert resp.status_code == 200 + assert resp.json() == {"authenticated": True, "admin": True} + + +# ── Login / logout ────────────────────────────────────────────────────────── + +def test_login_wrong_password_is_401(): + resp = _login(password="wrong-password") + assert resp.status_code == 401 + assert "invalid credentials" in resp.json()["detail"] + assert auth.COOKIE_NAME not in resp.cookies + + +def test_login_wrong_username_is_401(): + resp = _login(username="root") + assert resp.status_code == 401 + # Generic message: never reveal which half was wrong / that the user exists. + assert "root" not in resp.text + + +def test_login_missing_fields_is_401_not_500(): + resp = _request("POST", "/api/auth/login", data={}) + assert resp.status_code == 401 + + +def test_login_success_sets_httponly_cookie(): + resp = _login() + assert resp.status_code == 200 + assert resp.json() == {"authenticated": True, "admin": True} + raw = resp.headers.get("set-cookie", "") + assert auth.COOKIE_NAME in raw + assert "HttpOnly" in raw + assert "SameSite=lax" in raw.replace("samesite=lax", "SameSite=lax") + assert "Path=/" in raw + assert "Secure" not in raw # plain http in tests + assert resp.cookies.get(auth.COOKIE_NAME) + + +def test_login_accepts_json_body(): + resp = _login(form=False) + assert resp.status_code == 200 + assert resp.json()["authenticated"] is True + + +def test_login_cookie_marks_secure_behind_https_proxy(): + resp = _login(headers={"X-Forwarded-Proto": "https"}) + assert resp.status_code == 200 + assert "Secure" in resp.headers.get("set-cookie", "") + + +def test_session_cookie_unlocks_admin_routes(no_db): + login = _login() + cookie = {auth.COOKIE_NAME: login.cookies.get(auth.COOKIE_NAME)} + assert _request("GET", "/api/keys", cookies=cookie).status_code == 200 + assert _request("PUT", "/api/settings", + json={"summary_model": "m"}, cookies=cookie).status_code == 200 + assert _request("GET", "/api/settings", cookies=cookie).status_code == 200 + + +def test_logout_clears_session(no_db): + login = _login() + cookie = {auth.COOKIE_NAME: login.cookies.get(auth.COOKIE_NAME)} + out = _request("POST", "/api/auth/logout", cookies=cookie) + assert out.status_code == 200 + assert out.json() == {"authenticated": False, "admin": False} + assert "Max-Age=0" in out.headers.get("set-cookie", "") or "expires" in \ + out.headers.get("set-cookie", "").lower() + # A cleared cookie no longer authenticates (simulate the browser dropping it). + assert _request("GET", "/api/keys", cookies={}).status_code == 401 + + +def test_tampered_cookie_is_401(): + login = _login() + token = login.cookies.get(auth.COOKIE_NAME) + body, signature = token.rsplit(".", 1) + tampered = f"{body}.{'A' * len(signature)}" + assert _request("GET", "/api/keys", cookies={auth.COOKIE_NAME: tampered}).status_code == 401 + + +def test_cookie_for_another_user_is_401(monkeypatch): + forged = auth.create_session_token("intruder") + assert _request("GET", "/api/keys", + cookies={auth.COOKIE_NAME: forged}).status_code == 401 + + +def test_expired_token_is_rejected(): + token = auth.create_session_token(ADMIN_TEST_USER, now=time.time() - auth.SESSION_TTL_SECONDS - 5) + assert auth.verify_session_token(token) is None + + +# ── Fail closed ───────────────────────────────────────────────────────────── + +def test_admin_env_unset_fails_closed(monkeypatch, no_db): + monkeypatch.delenv("ADMIN_PASSWORD_HASH", raising=False) + monkeypatch.delenv("ADMIN_SESSION_SECRET", raising=False) + + resp = _request("GET", "/api/keys") + assert resp.status_code == 403 + assert resp.json() == {"detail": "admin auth not configured"} + + # Public site keeps working, and /login explains the situation. + assert _request("GET", "/api/news").status_code == 200 + page = _request("GET", "/login") + assert page.status_code == 200 + assert "not configured" in page.text + + +def test_login_without_password_hash_is_403(monkeypatch): + monkeypatch.delenv("ADMIN_PASSWORD_HASH", raising=False) + resp = _login() + assert resp.status_code == 403 + assert resp.json() == {"detail": "admin auth not configured"} + + +def test_session_secret_unset_invalidates_existing_cookie(monkeypatch): + cookie = admin_cookies() + monkeypatch.delenv("ADMIN_SESSION_SECRET", raising=False) + resp = _request("GET", "/api/keys", cookies=cookie) + assert resp.status_code == 403 + assert resp.json() == {"detail": "admin auth not configured"} + + +# ── Rate limiting ─────────────────────────────────────────────────────────── + +def test_rate_limit_after_five_failures(): + for attempt in range(5): + assert _login(password="nope").status_code == 401, f"attempt {attempt}" + assert _login(password="nope").status_code == 429 + # Correct credentials are refused too while the window is open. + assert _login().status_code == 429 + + +def test_rate_limit_is_per_client_ip(): + for _ in range(5): + _login(password="nope", headers={"X-Forwarded-For": "203.0.113.9"}) + assert _login(password="nope", headers={"X-Forwarded-For": "203.0.113.9"}).status_code == 429 + # A different client is unaffected. + assert _login(password="nope", headers={"X-Forwarded-For": "203.0.113.10"}).status_code == 401 + + +def test_logout_does_not_reset_the_login_limiter(): + """Regression: logout is unauthenticated — it must not clear lockouts.""" + for _ in range(5): + assert _login(password="nope").status_code == 401 + assert _request("POST", "/api/auth/logout").status_code == 200 + assert _login().status_code == 429 + + +def test_non_ascii_garbage_cookie_is_rejected_not_500(): + assert auth.verify_session_token("abc.\u00e9\u00e9\u00e9") is None + assert auth.verify_session_token("\u00e9\u00e9\u00e9") is None + resp = _request("GET", "/api/keys", cookies={auth.COOKIE_NAME: "garbage"}) + assert resp.status_code == 401 + + +# ── CSRF ──────────────────────────────────────────────────────────────────── + +def test_cross_origin_admin_write_is_403(no_db): + cookies = admin_cookies() + resp = _request("PUT", "/api/settings", json={"summary_model": "m"}, + cookies=cookies, headers={"Origin": "https://evil.example"}) + assert resp.status_code == 403 + assert "cross-origin" in resp.json()["detail"] + + +def test_same_origin_admin_write_is_allowed(no_db): + cookies = admin_cookies() + resp = _request("PUT", "/api/settings", json={"summary_model": "m"}, + cookies=cookies, headers={"Origin": BASE}) + assert resp.status_code == 200 + + +def test_same_host_referer_admin_write_is_allowed(no_db): + cookies = admin_cookies() + resp = _request("PUT", "/api/settings", json={"summary_model": "m"}, + cookies=cookies, headers={"Referer": f"{BASE}/login"}) + assert resp.status_code == 200 + + +# ── Unit: hashing + token helpers ─────────────────────────────────────────── + +def test_password_hash_round_trip(): + stored = auth.hash_password("s3cret-pw", iterations=2000) + assert stored.startswith("pbkdf2_sha256$") + assert auth.verify_password("s3cret-pw", stored) + assert not auth.verify_password("s3cret-pW", stored) + assert not auth.verify_password("", stored) + + +def test_password_hash_rejects_malformed_values(): + for bad in ("", "plain", "pbkdf2_sha256$abc$x$y", "md5$1$a$b", + "pbkdf2_sha256$0$AAAA$AAAA"): + assert not auth.verify_password("x", bad) + + +def test_session_token_round_trip(): + token = auth.create_session_token(ADMIN_TEST_USER) + assert auth.verify_session_token(token) == ADMIN_TEST_USER + assert auth.verify_session_token(token + "x") is None + assert auth.verify_session_token(None) is None + + +def test_public_allowlist_classification(): + assert auth.is_public("/api/news", "GET") + assert auth.is_public("/api/news/", "GET") + assert auth.is_public("/api/events/abc-123", "GET") + assert auth.is_public("/api/cameras/abc/hls.m3u8", "GET") + assert auth.is_public("/api/search", "POST") + assert not auth.is_public("/api/news/models", "GET") + assert not auth.is_public("/api/keys", "GET") + assert not auth.is_public("/api/settings", "GET") + assert not auth.is_public("/api/ingest/rss", "POST") + assert not auth.is_public("/api/vessels/subscribe", "POST") + assert not auth.is_public("/api/geofences", "POST") + assert auth.is_public("/ws/live", "GET") diff --git a/tests/test_ingest_ssrf_and_sources.py b/tests/test_ingest_ssrf_and_sources.py index 21c85b2..16683a1 100644 --- a/tests/test_ingest_ssrf_and_sources.py +++ b/tests/test_ingest_ssrf_and_sources.py @@ -10,6 +10,8 @@ from pydantic import ValidationError from main import app +from conftest import admin_cookies + BASE = "http://test" LINK_LOCAL_META = "http://169.254.169.254/latest/meta-data/" LOOPBACK = "http://127.0.0.1/secret" @@ -18,6 +20,7 @@ LOOPBACK = "http://127.0.0.1/secret" async def _req(method: str, path: str, **kw) -> httpx.Response: transport = httpx.ASGITransport(app=app) async with httpx.AsyncClient(transport=transport, base_url=BASE) as client: + client.cookies.update(admin_cookies()) return await client.request(method, path, **kw) diff --git a/tests/test_phase2_api.py b/tests/test_phase2_api.py index 2afead2..b7e7157 100644 --- a/tests/test_phase2_api.py +++ b/tests/test_phase2_api.py @@ -8,12 +8,15 @@ import httpx from main import app +from conftest import admin_cookies + BASE = "http://test" async def _req(method: str, path: str, **kw) -> httpx.Response: transport = httpx.ASGITransport(app=app) async with httpx.AsyncClient(transport=transport, base_url=BASE) as client: + client.cookies.update(admin_cookies()) return await client.request(method, path, **kw) From 72757e7c51a363bb377284662e8dc85a598b6dbf Mon Sep 17 00:00:00 2001 From: Hermes Backend Date: Fri, 13 Nov 2026 21:15:05 -0500 Subject: [PATCH 59/79] feat(auth): ADMIN_COOKIE_SECURE forces the session cookie Secure Behind the cluster's HTTP origin listener Envoy normalizes X-Forwarded-Proto to http, so _is_https() never fires and the session cookie was issued without Secure. Add an explicit deploy-time flag: set_session_cookie() now marks the cookie Secure when the env var is 1/true/yes (case-insensitive, stripped) or the header inference says https. clear_session_cookie() is unchanged, SameSite stays Lax. Tests cover flag-over-http, header-without-flag, and the local-dev path; docs/auth.md and .env.example document the variable. --- .env.example | 5 +++++ app/auth.py | 18 ++++++++++++++++-- docs/auth.md | 7 +++++++ tests/test_auth.py | 41 +++++++++++++++++++++++++++++++++++++++-- 4 files changed, 67 insertions(+), 4 deletions(-) diff --git a/.env.example b/.env.example index 7e582dc..42d5c10 100644 --- a/.env.example +++ b/.env.example @@ -79,6 +79,11 @@ VESSELAPI_IN_INGEST=0 ADMIN_USER= ADMIN_PASSWORD_HASH= ADMIN_SESSION_SECRET= +# Optional: force the session cookie's Secure flag (1/true/yes) when the app is +# reached over plain HTTP behind a TLS-terminating proxy that rewrites +# X-Forwarded-Proto to http (the cluster: Cloudflare tunnel -> Cilium Gateway). +# Leave unset locally so the cookie works over http://localhost. +ADMIN_COOKIE_SECURE= # ── News pipeline (scraper + summarizer, profile `ingest`) ──────────────── # Scraper crawls urls.txt continuously (default 10s between crawls). diff --git a/app/auth.py b/app/auth.py index cfdb074..58cc47a 100644 --- a/app/auth.py +++ b/app/auth.py @@ -16,7 +16,9 @@ Design notes * **No new dependencies.** Password hashing is stdlib ``hashlib.pbkdf2_hmac`` and the session token is an HMAC-SHA256 signature over a base64url JSON payload. Cookies are HttpOnly, SameSite=Lax, Path=/, 7-day lifetime, and - ``Secure`` when the request arrived over https (``X-Forwarded-Proto``). + ``Secure`` when the request arrived over https (``X-Forwarded-Proto``) or + when ``ADMIN_COOKIE_SECURE`` is truthy (TLS-only deployments behind an + HTTP origin listener, where Envoy normalizes the header to ``http``). * **CSRF.** State-changing admin requests that carry an ``Origin``/``Referer`` are rejected when the origin host differs from the request host. Requests without either header (curl, server-to-server) are allowed — the signed, @@ -281,6 +283,18 @@ def _is_https(request: Request) -> bool: return request.url.scheme == "https" +_TRUTHY = {"1", "true", "yes"} + + +def cookie_secure_forced() -> bool: + """``ADMIN_COOKIE_SECURE`` marks the deployment TLS-only. + + Read on every call so tests and restarts pick up env changes; the header + inference in :func:`_is_https` stays as the fallback. + """ + return (os.getenv("ADMIN_COOKIE_SECURE") or "").strip().lower() in _TRUTHY + + def set_session_cookie(response, request: Request, token: str) -> None: response.set_cookie( COOKIE_NAME, @@ -288,7 +302,7 @@ def set_session_cookie(response, request: Request, token: str) -> None: max_age=SESSION_TTL_SECONDS, httponly=True, samesite="lax", - secure=_is_https(request), + secure=cookie_secure_forced() or _is_https(request), path="/", ) diff --git a/docs/auth.md b/docs/auth.md index 8a7bef9..0e6d57f 100644 --- a/docs/auth.md +++ b/docs/auth.md @@ -60,6 +60,13 @@ arrived over https (`X-Forwarded-Proto`, i.e. behind Cloudflare). Signature and expiry are checked with `hmac.compare_digest`; a token for another username, or one signed with a different secret, is rejected. +Set `ADMIN_COOKIE_SECURE=1` (`true`/`yes` also work) whenever the deployment is +TLS-only but the app itself is reached over plain HTTP. In the cluster the +Cloudflare tunnel originates at the Cilium Gateway on plain HTTP and Envoy +normalizes `X-Forwarded-Proto` to `http`, so the header inference never fires +there — the flag is what makes the cookie `Secure` in the cluster. Leave it +unset for local development, where the cookie has to work over `http://localhost`. + ## Abuse controls * **Login rate limit:** 5 failed attempts per client IP (first hop of diff --git a/tests/test_auth.py b/tests/test_auth.py index 54d00bb..85f369b 100644 --- a/tests/test_auth.py +++ b/tests/test_auth.py @@ -318,7 +318,8 @@ def test_login_missing_fields_is_401_not_500(): assert resp.status_code == 401 -def test_login_success_sets_httponly_cookie(): +def test_login_success_sets_httponly_cookie(monkeypatch): + monkeypatch.delenv("ADMIN_COOKIE_SECURE", raising=False) resp = _login() assert resp.status_code == 200 assert resp.json() == {"authenticated": True, "admin": True} @@ -337,12 +338,48 @@ def test_login_accepts_json_body(): assert resp.json()["authenticated"] is True -def test_login_cookie_marks_secure_behind_https_proxy(): +def test_login_cookie_marks_secure_behind_https_proxy(monkeypatch): + monkeypatch.delenv("ADMIN_COOKIE_SECURE", raising=False) resp = _login(headers={"X-Forwarded-Proto": "https"}) assert resp.status_code == 200 assert "Secure" in resp.headers.get("set-cookie", "") +def test_login_cookie_secure_via_env_flag_over_http_origin(monkeypatch): + """ADMIN_COOKIE_SECURE is what makes the cookie Secure in the cluster: + the header arrives as ``http`` from the Cilium Gateway.""" + monkeypatch.setenv("ADMIN_COOKIE_SECURE", "1") + resp = _login(headers={"X-Forwarded-Proto": "http"}) + assert resp.status_code == 200 + raw = resp.headers.get("set-cookie", "") + assert "Secure" in raw + assert "SameSite=lax" in raw.replace("samesite=lax", "SameSite=lax") + assert "HttpOnly" in raw + + +@pytest.mark.parametrize("value", ["true", "TRUE", " Yes ", "yes"]) +def test_login_cookie_env_flag_accepts_truthy_spellings(monkeypatch, value): + monkeypatch.setenv("ADMIN_COOKIE_SECURE", value) + resp = _login() + assert resp.status_code == 200 + assert "Secure" in resp.headers.get("set-cookie", "") + + +@pytest.mark.parametrize("value", ["", "0", "false", "no", "off"]) +def test_login_cookie_env_flag_ignores_falsey_spellings(monkeypatch, value): + monkeypatch.setenv("ADMIN_COOKIE_SECURE", value) + resp = _login(headers={"X-Forwarded-Proto": "http"}) + assert resp.status_code == 200 + assert "Secure" not in resp.headers.get("set-cookie", "") + + +def test_login_cookie_without_header_or_flag_is_not_secure_locally(monkeypatch): + monkeypatch.delenv("ADMIN_COOKIE_SECURE", raising=False) + resp = _login() + assert resp.status_code == 200 + assert "Secure" not in resp.headers.get("set-cookie", "") + + def test_session_cookie_unlocks_admin_routes(no_db): login = _login() cookie = {auth.COOKIE_NAME: login.cookies.get(auth.COOKIE_NAME)} From c42d375d6ce3416232c09e4918c47701c2b0ac79 Mon Sep 17 00:00:00 2001 From: backend Date: Fri, 13 Nov 2026 21:41:44 -0500 Subject: [PATCH 60/79] fix(news): drop future-dated items at ingest, hide them in /api/news wiseye.org public-affairs event listings carry pubDate 3-6 days ahead; with ORDER BY timestamp DESC they pinned the top of the feed for a week and made the news list look frozen. - PostgresPipeline drops items whose parsed publish date is >2h in the future, counts future_dated_dropped (stats + one INFO line per run). Unparseable dates keep the old behaviour (kept, timestamped now()). - GET /api/news filters timestamp > now() in the query while still returning timestamp IS NULL rows; limit/offset/domain/since unchanged. - docs/news.md documents the guard. - tests: pipeline drop/keep unit tests, API future-row exclusion + limit. --- app/main.py | 7 +- docs/news.md | 5 +- news/scraper/newsScraper/pipelines.py | 52 +++++++++++++++ tests/test_api_news.py | 22 ++++++- tests/test_news_scraper.py | 93 +++++++++++++++++++++++++++ 5 files changed, 176 insertions(+), 3 deletions(-) diff --git a/app/main.py b/app/main.py index dd799d7..4f466ba 100644 --- a/app/main.py +++ b/app/main.py @@ -1207,7 +1207,12 @@ async def list_news( ): """Most recent scraped news articles (newest first).""" async with async_session() as session: - stmt = select(articles).order_by( + stmt = select(articles).where( + or_( + articles.c.timestamp.is_(None), + articles.c.timestamp <= func.now(), + ) + ).order_by( articles.c.timestamp.desc().nullslast() ) if domain: diff --git a/docs/news.md b/docs/news.md index d94d29f..79d6c6f 100644 --- a/docs/news.md +++ b/docs/news.md @@ -43,7 +43,10 @@ feeds (`GET /api/news` exact key set is unchanged on purpose). URLs from `urls.txt` (homepages autodiscover RSS; feed URLs are parsed directly), follows each `` link, extracts the main article body, and the `PostgresPipeline` writes to `articles` with URL-based dedup - (`ON CONFLICT (url) DO NOTHING`). + (`ON CONFLICT (url) DO NOTHING`). Items whose parsed publish date is more + than 2 hours in the future are dropped at ingest (`future_dated_dropped`) + and never surface via `/api/news`, which additionally hides any + `articles.timestamp > now()` row until its date arrives. 2. **Summarizer** — `news/summerizer/run_news_summarizer.py` runs `summarizer.py` every `NEWS_SUMMARIZE_INTERVAL_S` (default 900) over the last `SUMMARY_WINDOW_MINUTES` (default 15), and again at 23:00 diff --git a/news/scraper/newsScraper/pipelines.py b/news/scraper/newsScraper/pipelines.py index 68cad97..2629372 100644 --- a/news/scraper/newsScraper/pipelines.py +++ b/news/scraper/newsScraper/pipelines.py @@ -3,10 +3,49 @@ # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html +import datetime import logging import psycopg2 import os from scrapy.exceptions import DropItem + +log = logging.getLogger(__name__) + +# Feed items dated further ahead than this are event listings (or clock skew +# from the source), not news. Dropping them keeps `ORDER BY timestamp DESC` +# from pinning the top of /api/news for days. See docs/news.md. +FUTURE_TOLERANCE = datetime.timedelta(hours=2) + + +def _parsed_timestamp(value): + """Return an aware UTC datetime for an item timestamp, or None. + + None means "could not parse" — callers must keep such items, exactly as + before this guard existed (undated items currently get now() upstream). + """ + if isinstance(value, datetime.datetime): + ts = value + elif isinstance(value, str) and value.strip(): + try: + ts = datetime.datetime.fromisoformat(value.strip().replace("Z", "+00:00")) + except ValueError: + return None + else: + return None + if ts.tzinfo is None: + ts = ts.replace(tzinfo=datetime.timezone.utc) + return ts.astimezone(datetime.timezone.utc) + + +def is_future_dated(value, now=None, tolerance=FUTURE_TOLERANCE): + """True when a parsed publish timestamp is more than `tolerance` ahead.""" + ts = _parsed_timestamp(value) + if ts is None: + return False + now = now or datetime.datetime.now(datetime.timezone.utc) + return ts > now + tolerance + + class PostgresPipeline: def __init__(self, db_config): @@ -14,6 +53,8 @@ class PostgresPipeline: self.db_config = db_config # 2. Initialize the set here so it exists when process_item is called self.seen_urls = set() + # 3. Future-dated drops, reported once per run in close_spider() + self.future_dated_dropped = 0 @classmethod def from_crawler(cls, crawler): @@ -54,6 +95,12 @@ class PostgresPipeline: def process_item(self, item, spider): url = item['url'] + if is_future_dated(item.get('timestamp')): + self.future_dated_dropped += 1 + stats = getattr(getattr(spider, 'crawler', None), 'stats', None) + if stats is not None: + stats.inc_value('future_dated_dropped') + raise DropItem(f"Future-dated item: {url}") if url in self.seen_urls: raise DropItem(f"Duplicate URL (in-memory): {url}") self.seen_urls.add(url) @@ -82,6 +129,11 @@ class PostgresPipeline: raise def close_spider(self, spider): + if self.future_dated_dropped: + spider.logger.info( + "Dropped %d future-dated item(s) (>%s ahead)", + self.future_dated_dropped, FUTURE_TOLERANCE, + ) self.cur.close() self.connection.close() diff --git a/tests/test_api_news.py b/tests/test_api_news.py index 0ba569d..d71c853 100644 --- a/tests/test_api_news.py +++ b/tests/test_api_news.py @@ -10,7 +10,7 @@ from __future__ import annotations import asyncio import os -from datetime import datetime, timezone +from datetime import datetime, timedelta, timezone import asyncpg import httpx @@ -157,6 +157,26 @@ def test_api_news_since_filter(clean_news): assert body[0]["title"] == "after" +@requires_db +def test_api_news_excludes_future_dated_rows(clean_news): + """Future-dated event listings must not pin the top of the feed.""" + now = datetime.now(timezone.utc) + future = now + timedelta(days=5) + recent = now - timedelta(hours=1) + _seed_article("recent", "https://a.example/recent", "a.example", recent.isoformat()) + _seed_article("future", "https://a.example/future", "a.example", future.isoformat()) + + body = _get("/api/news").json() + assert [a["title"] for a in body] == ["recent"] + + # limit still caps the (post-filter) result set + _seed_article("recent2", "https://a.example/recent2", "a.example", (now - timedelta(hours=2)).isoformat()) + _seed_article("recent3", "https://a.example/recent3", "a.example", (now - timedelta(hours=3)).isoformat()) + limited = _get("/api/news?limit=2").json() + assert [a["title"] for a in limited] == ["recent", "recent2"] + + + @requires_db def test_api_news_summaries_contract(clean_news): _seed_summary("master summary markdown…", "2026-08-24T18:05:00+00:00") diff --git a/tests/test_news_scraper.py b/tests/test_news_scraper.py index b2b3817..ac335c2 100644 --- a/tests/test_news_scraper.py +++ b/tests/test_news_scraper.py @@ -2,9 +2,12 @@ from __future__ import annotations +import datetime as _dt import sys from pathlib import Path +import pytest + ROOT = Path(__file__).resolve().parent.parent _SCRAPER = ROOT / "news/scraper" if str(_SCRAPER) not in sys.path: @@ -40,3 +43,93 @@ def test_spider_skips_audio_before_request(): assert "is_audio_url" in src assert "article_timestamp" in src assert "datetime.datetime.now()" not in src + + +# ── future-dated guard (ingest) ─────────────────────────────────────────── + +class _FakeCursor: + rowcount = 1 + + def __init__(self): + self.executed = [] + + def execute(self, sql, params=None): + self.executed.append((sql, params)) + + +class _FakeConnection: + def commit(self): + pass + + def rollback(self): + pass + + +class _FakeStats: + def __init__(self): + self.values = {} + + def inc_value(self, key, count=1): + self.values[key] = self.values.get(key, 0) + count + + +class _FakeSpider: + class _Logger: + def info(self, *a, **kw): + pass + + def error(self, *a, **kw): + pass + + def __init__(self): + self.logger = self._Logger() + self.crawler = type("C", (), {"stats": _FakeStats()})() + + +def _pipeline(): + from newsScraper.pipelines import PostgresPipeline + + pipe = PostgresPipeline(db_config={}) + pipe.cur = _FakeCursor() + pipe.connection = _FakeConnection() + return pipe + + +def _item(ts: _dt.datetime) -> dict: + return { + "title": "t", + "url": f"https://a.example/{ts.isoformat()}", + "text": "body", + "domain": "a.example", + "timestamp": ts.isoformat(), + } + + +def test_pipeline_drops_future_dated_item(): + from scrapy.exceptions import DropItem + + pipe = _pipeline() + spider = _FakeSpider() + future = _dt.datetime.now(_dt.timezone.utc) + _dt.timedelta(days=5) + with pytest.raises(DropItem): + pipe.process_item(_item(future), spider) + assert pipe.future_dated_dropped == 1 + assert spider.crawler.stats.values["future_dated_dropped"] == 1 + assert pipe.cur.executed == [] # never reached the INSERT + + +def test_pipeline_keeps_recent_item(): + pipe = _pipeline() + spider = _FakeSpider() + recent = _dt.datetime.now(_dt.timezone.utc) - _dt.timedelta(days=1) + assert pipe.process_item(_item(recent), spider)["domain"] == "a.example" + assert pipe.future_dated_dropped == 0 + assert len(pipe.cur.executed) == 1 + + +def test_pipeline_keeps_unparseable_timestamp(): + from newsScraper.pipelines import is_future_dated + + assert is_future_dated("not a date") is False + assert is_future_dated(None) is False + From 853e87b7c5c1bb86c36e1149a96dd6fe3bc18bac Mon Sep 17 00:00:00 2001 From: hermes-backend Date: Fri, 13 Nov 2026 21:47:30 -0500 Subject: [PATCH 61/79] feat(summarizer): score articles in the map phase, brief only the important ones The map prompt now grades every article 0-100 against an explicit rubric as the first line of its block; the summarizer parses Score:, falls back to the Importance: label when the line is missing, ranks blocks best-first and passes only score >= SUMMARY_MIN_SCORE (capped at SUMMARY_TOP_N) to the reduce phase. - new pure helpers in intel.py: parse_map_scores(), select_graded(), join_blocks() - reduce prompts drop the 'fill the brief with minor incidents and crime' filler instructions and the 'fill ticker with medium then low' clause - new article_scores table (ensure_tables + alembic 012) persists every grade with selected/summary_id/model so thresholds can be tuned from data - SUMMARY_MIN_SCORE (60), SUMMARY_TOP_N (12), SUMMARY_FALLBACK_TOP (3) env knobs --- .env.example | 7 + alembic/versions/012_article_scores.py | 39 ++++ docs/news.md | 28 ++- news/summerizer/intel.py | 132 +++++++++++- news/summerizer/summarizer.py | 192 ++++++++++++++--- news/summerizer/tests/test_grading.py | 174 +++++++++++++++ .../summerizer/tests/test_grading_pipeline.py | 202 ++++++++++++++++++ news/summerizer/tests/test_prompts.py | 38 +++- 8 files changed, 775 insertions(+), 37 deletions(-) create mode 100644 alembic/versions/012_article_scores.py create mode 100644 news/summerizer/tests/test_grading.py create mode 100644 news/summerizer/tests/test_grading_pipeline.py diff --git a/.env.example b/.env.example index 42d5c10..fe913fd 100644 --- a/.env.example +++ b/.env.example @@ -98,6 +98,13 @@ NOUS_BASE_URL=https://inference-api.nousresearch.com/v1 # Hermes-4.3-36B remains after a Postgres miss. Env wins when set. # SUMMARY_MODEL= NEWS_BATCH_SIZE=50 +# Map-phase grading: the map model scores each article 0-100, and only blocks +# with score >= SUMMARY_MIN_SCORE reach the reduce brief (best first). +# If nothing clears the bar, the top SUMMARY_FALLBACK_TOP blocks are used +# (0 = honour the threshold and pass an empty DATA section instead). +SUMMARY_MIN_SCORE=60 +SUMMARY_TOP_N=12 +SUMMARY_FALLBACK_TOP=3 SUMMARY_WINDOW_MINUTES=15 # Futures/markets coupling from the upstream pipeline is OFF by default # (irrelevant to OSINT). Set INCLUDE_FUTURES=1 + install yfinance to enable. diff --git a/alembic/versions/012_article_scores.py b/alembic/versions/012_article_scores.py new file mode 100644 index 0000000..853ded7 --- /dev/null +++ b/alembic/versions/012_article_scores.py @@ -0,0 +1,39 @@ +"""article_scores: per-article map-phase grades for threshold tuning + +Revision ID: 012_article_scores +Revises: 011_geofence_alerts_fence +Create Date: 2026-11-13 +""" + +from alembic import op + +revision = "012_article_scores" +down_revision = "011_geofence_alerts_fence" +branch_labels = None +depends_on = None + + +def upgrade() -> None: + op.execute( + """ + CREATE TABLE IF NOT EXISTS article_scores ( + article_id INTEGER NOT NULL, + summary_id INTEGER, + score INTEGER NOT NULL, + category TEXT, + selected BOOLEAN NOT NULL, + model TEXT, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + PRIMARY KEY (article_id, created_at) + ) + """ + ) + op.execute( + "CREATE INDEX IF NOT EXISTS ix_article_scores_summary " + "ON article_scores (summary_id)" + ) + + +def downgrade() -> None: + op.execute("DROP INDEX IF EXISTS ix_article_scores_summary") + op.execute("DROP TABLE IF EXISTS article_scores") diff --git a/docs/news.md b/docs/news.md index d64b31d..d5e00bb 100644 --- a/docs/news.md +++ b/docs/news.md @@ -60,8 +60,29 @@ if `article_summaries` already has a row in the last interval, the summarizer The `articles` and `article_summaries` tables are created by the idempotent alembic migration `003_news` (also created by the scraper's own -`CREATE TABLE IF NOT EXISTS`). `news_items` is alembic `005_news_items`. -Container startup order doesn't matter. +`CREATE TABLE IF NOT EXISTS`). `news_items` is alembic `005_news_items` and +`article_scores` is `012_article_scores` (also created by the summarizer's own +`ensure_tables()`). Container startup order doesn't matter. + +## Grading and selection + +The map phase grades every article 0-100 against the rubric in the map prompt +(90-100 breaking geopolitical/military/security or major disaster, 70-89 +significant national/international news, 40-69 notable regional/economic/tech/ +health, 10-39 routine crime and local interest, 0-9 noise: sport, celebrity, +entertainment, market tape, promotional and event-calendar listings). The +summarizer parses the first `Score:` line in each `Article :` block, clamps +it to 0-100, and falls back to the `Importance:` label (critical 95, high 78, +medium 50, low 22, none 5) when the line is missing or unparsable — a block is +never dropped and the fallback count is logged per batch. Only blocks scoring +`>= SUMMARY_MIN_SCORE` (default 60) reach the reduce prompt, best first, capped +at `SUMMARY_TOP_N` (default 12). If nothing clears the bar the top +`SUMMARY_FALLBACK_TOP` blocks (default 3) are used so the HUD is not blank; +`SUMMARY_FALLBACK_TOP=0` passes an empty DATA section instead. The reduce prompt +no longer asks for filler: it leads with the highest-scoring stories and never +promotes an item above its score. Every graded article is persisted to +`article_scores` (score, category, selected, model, summary_id) so the operator +can tune the thresholds against real data. ## Keys and Settings @@ -240,6 +261,9 @@ map. `summary_en` lands in `article_summaries.summary_text`. | `NOUS_BASE_URL` | `https://inference-api.nousresearch.com/v1` | Read-only in Settings. | | `SUMMARY_MODEL` | `Hermes-4.3-36B` | Compose default. Operator-facing choice is Settings → `app_settings.SUMMARY_MODEL`. | | `NEWS_BATCH_SIZE` | `50` | Articles per map-phase batch (compose maps to container `BATCH_SIZE`). | +| `SUMMARY_MIN_SCORE` | `60` | Map-phase score a block must reach to enter the reduce brief. | +| `SUMMARY_TOP_N` | `12` | Max blocks passed to the reduce phase (best score first). | +| `SUMMARY_FALLBACK_TOP` | `3` | Blocks used when nothing clears `SUMMARY_MIN_SCORE`; `0` = empty DATA. | | `SUMMARY_WINDOW_MINUTES` | `15` | How far back the summarizer looks for new articles. | | `NEWS_SCRAPE_INTERVAL_S` | `10` | Pause after each crawl before the next (scraper is otherwise continuous). | | `NEWS_SUMMARIZE_INTERVAL_S` | `900` | Seconds between analyst runs (default 15 min). | diff --git a/news/summerizer/intel.py b/news/summerizer/intel.py index 1f9874c..d99b258 100644 --- a/news/summerizer/intel.py +++ b/news/summerizer/intel.py @@ -1,4 +1,4 @@ -"""Pure parser for the news-summarizer reduce JSON / geo / importance contract.""" +"""Pure parser for the news-summarizer map grading / reduce JSON / geo contract.""" from __future__ import annotations @@ -16,6 +16,16 @@ MAP_HEADLINE_MAX = 160 TICKER_CAP = 12 MAP_CAP = 20 +# ── Map-phase grading (score parsing + selection, pure) ──────────────────── +# Importance label → stand-in score, used when the map model omits Score:. +IMPORTANCE_SCORE = {"critical": 95, "high": 78, "medium": 50, "low": 22, "none": 5} +NEUTRAL_SCORE = 50 + +_ARTICLE_RE = re.compile(r"^[ \t>*_#\-]*Article[ \t]+(\d{1,3})[ \t]*:", re.IGNORECASE | re.MULTILINE) +_SCORE_RE = re.compile(r"Score:\s*(\d{1,3})", re.IGNORECASE) +_IMPORTANCE_RE = re.compile(r"Importance:\s*(critical|high|medium|low|none)", re.IGNORECASE) +_CATEGORY_RE = re.compile(r"Category:\s*(.+)", re.IGNORECASE) + def parse_reduce_json(raw: str) -> dict: try: @@ -102,3 +112,123 @@ def select_map(items: list) -> list: if len(out) >= MAP_CAP: break return out + + +# ── Map grading ──────────────────────────────────────────────────────────── + +def _clamp_score(value: int) -> int: + return max(0, min(100, int(value))) + + +def _score_from_block(text: str) -> tuple[int, bool]: + """Score for one article block. Second element True when a fallback was used.""" + match = _SCORE_RE.search(text) + if match: + try: + return _clamp_score(int(match.group(1))), False + except (TypeError, ValueError): + pass + match = _IMPORTANCE_RE.search(text) + if match: + return IMPORTANCE_SCORE.get(match.group(1).lower(), NEUTRAL_SCORE), True + return NEUTRAL_SCORE, True + + +def _category_from_block(text: str) -> str | None: + match = _CATEGORY_RE.search(text) + if not match: + return None + value = match.group(1).strip().strip("*_` ").rstrip(".").strip() + return value[:40] or None + + +def parse_map_scores( + raw: str, *, articles: list[dict], batch_index: int = 0, batch_size: int = 1 +) -> tuple[list[dict], dict]: + """Split one map response into scored per-article blocks. + + Pure: no DB, no logging. Block ``n`` of batch ``b`` is attributed to + ``articles[b * batch_size + n - 1]``. Blocks whose ``Article `` number does + not land inside this batch (model omitted/reordered articles) are counted in + ``stats["unattributed"]`` and dropped — there is no article row to attribute + them to. Never raises. + + Returns ``(blocks, stats)`` where each block is:: + + {"n", "article", "article_id", "score", "importance", "category", + "text", "position"} + """ + text = raw or "" + matches = list(_ARTICLE_RE.finditer(text)) + blocks: list[dict] = [] + seen: set[int] = set() + fallback = 0 + unattributed = 0 + size = max(1, int(batch_size)) + for pos, match in enumerate(matches): + try: + n = int(match.group(1)) + except (TypeError, ValueError): + unattributed += 1 + continue + if n in seen: + unattributed += 1 + continue + seen.add(n) + end = matches[pos + 1].start() if pos + 1 < len(matches) else len(text) + block_text = text[match.start():end].strip() + offset = int(batch_index) * size + n - 1 + article = articles[offset] if 0 <= offset < len(articles) else None + if article is None or not block_text: + unattributed += 1 + continue + score, used_fallback = _score_from_block(block_text) + fallback += 1 if used_fallback else 0 + importance = None + imp_match = _IMPORTANCE_RE.search(block_text) + if imp_match: + importance = imp_match.group(1).lower() + blocks.append( + { + "n": n, + "article": article, + "article_id": article.get("id"), + "score": score, + "importance": importance, + "category": _category_from_block(block_text), + "text": block_text, + "position": offset, + } + ) + stats = { + "blocks": len(matches), + "graded": len(blocks), + "fallback": fallback, + "unattributed": unattributed, + } + return blocks, stats + + +def select_graded( + blocks: list[dict], *, min_score: int, top_n: int, fallback_top: int +) -> tuple[list[dict], bool]: + """Rank blocks best-first and return the ones the reduce phase should see. + + Keeps ``score >= min_score`` capped at ``top_n`` (stable on ties: original + order). When nothing clears the bar, returns the top ``fallback_top`` blocks + and True; ``fallback_top == 0`` yields an empty selection. + """ + ordered = sorted(blocks, key=lambda b: -int(b.get("score") or 0)) + limit = max(0, int(top_n)) + clearing = [b for b in ordered if int(b.get("score") or 0) >= int(min_score)] + if clearing: + return clearing[:limit], False + fallback_limit = max(0, int(fallback_top)) + if fallback_limit <= 0: + return [], False + return ordered[:fallback_limit], bool(ordered) + + +def join_blocks(blocks: list[dict]) -> str: + """Reduce-phase DATA text: only these blocks, original text, best-first.""" + return "\n\n".join(b["text"] for b in blocks) diff --git a/news/summerizer/summarizer.py b/news/summerizer/summarizer.py index acc1262..2ddd023 100644 --- a/news/summerizer/summarizer.py +++ b/news/summerizer/summarizer.py @@ -31,7 +31,7 @@ from zoneinfo import ZoneInfo import psycopg2 -from intel import parse_reduce_json, select_map, select_ticker +from intel import join_blocks, parse_map_scores, parse_reduce_json, select_graded, select_map, select_ticker from nous_client import chat logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s") @@ -50,6 +50,30 @@ DEFAULT_NOUS_BASE_URL = "https://inference-api.nousresearch.com/v1" DEFAULT_SUMMARY_MODEL = "Hermes-4.3-36B" BATCH_SIZE = int(os.getenv("BATCH_SIZE", "50")) +# Map-phase grading knobs (operator sets them in the cluster ConfigMap). +DEFAULT_SUMMARY_MIN_SCORE = 60 +DEFAULT_SUMMARY_TOP_N = 12 +DEFAULT_SUMMARY_FALLBACK_TOP = 3 + + +def _env_int(name: str, default: int) -> int: + raw = (os.getenv(name) or "").strip() + if not raw: + return default + try: + return int(raw) + except ValueError: + logger.warning("Invalid %s=%r — using default %s", name, raw, default) + return default + + +def selection_config() -> tuple[int, int, int]: + """(min_score, top_n, fallback_top) from env, read per run.""" + min_score = max(0, min(100, _env_int("SUMMARY_MIN_SCORE", DEFAULT_SUMMARY_MIN_SCORE))) + top_n = max(0, _env_int("SUMMARY_TOP_N", DEFAULT_SUMMARY_TOP_N)) + fallback_top = max(0, _env_int("SUMMARY_FALLBACK_TOP", DEFAULT_SUMMARY_FALLBACK_TOP)) + return min_score, top_n, fallback_top + def _summary_window_minutes() -> int: hours = (os.getenv("SUMMARY_WINDOW_HOURS") or "").strip() @@ -94,30 +118,40 @@ FUTURES_TICKERS = { MAP_PROMPT_DEFAULT = """\ You are a precise, factual OSINT news processor. Your ONLY source of information is the articles provided below. Do NOT add external knowledge, assumptions, training data, or invented facts. -Focus on breaking important news (geopolitical, military/conflict, security, disasters, major political developments). Ignore futures prices, commodity tape, ticker chatter, and routine market moves unless they themselves are the breaking event. If the batch has no critical/high stories, still extract minor incidents and crime reports. +Focus on breaking important news (geopolitical, military/conflict, security, disasters, major political developments). Ignore futures prices, commodity tape, ticker chatter, and routine market moves unless they themselves are the breaking event. Extract every article; the Score below decides what reaches the operator brief. Write every field in English. Translate if the article is not English. +Grade every article with this rubric before writing anything else in its block: + +- 90–100 — breaking geopolitical/military/security event or major disaster, immediate consequence +- 70–89 — significant national/international politics, conflict, security, infrastructure or disaster news +- 40–69 — notable regional/economic/tech/health story with real consequences +- 10–39 — routine, minor or single-incident crime; local interest +- 0–9 — noise: sport, celebrity, entertainment, market/commodity tape, promotional or event-calendar/schedule listings + For EACH article in the batch: -1. Extract 2-4 key factual bullet points (who, what, when, where, numbers, quotes — stay very close to the text). -2. Location: country/city/region or Unknown. If you can estimate coordinates, emit them as numbers; otherwise omit. -3. Entities: list the key people, organizations, or governments mentioned (comma-separated, only names present in the text), else "None". -4. Category: pick one — politics, military/conflict, economy, technology, environment/disaster, health, crime, society, sport, other. -5. 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. Importance: critical (breaking geopolitical/military/disaster with immediate impact), high, medium, low, none. +1. Score: the integer 0-100 from the rubric above, first line of the block. +2. Extract 2-4 key factual bullet points (who, what, when, where, numbers, quotes — stay very close to the text). +3. Location: country/city/region or Unknown. If you can estimate coordinates, emit them as numbers; otherwise omit. +4. Entities: list the key people, organizations, or governments mentioned (comma-separated, only names present in the text), else "None". +5. Category: pick one — politics, military/conflict, economy, technology, environment/disaster, health, crime, society, sport, other. +6. OSINT signal: if the article describes a breaking event with geopolitical, security, military, or disaster significance, say so in one short sentence. Otherwise write: "No notable OSINT signal." +7. Importance: critical (breaking geopolitical/military/disaster with immediate impact), high, medium, low, none. Keep it consistent with the Score. If several articles cover the same story, add one short batch-level note at the end: "Batch theme: [one sentence]". -Output format — strictly one block per article: +Output format — strictly one block per article, Score and Importance first: Article 1: +- Score: <0-100> +- Importance: critical|high|medium|low|none - Fact bullet 1 - Fact bullet 2 - Location: ... - Entities: ... - Category: ... - OSINT signal: ... -- Importance: ... - Lat: ... - Lon: ... @@ -133,9 +167,11 @@ You are writing an English operator HUD brief from the article facts in DATA bel Always write a real summary_en that recaps the most important stories present in DATA. Rank geopolitics, military/conflict, security, disasters, and major political developments first. Ignore futures prices, commodity tape, ticker chatter, and routine market data — do not treat price ticks as news. -Lead with critical and high breaking events. If DATA has no critical/high stories, fill the brief with minor incidents and crime reports rather than writing an empty or unfinished brief. Never truncate mid-sentence; finish every sentence. If you run out of room, drop the lowest-priority item instead of cutting a line short. +DATA is pre-filtered by score and ordered best-first. Lead with the highest-scoring breaking stories and rank them honestly by importance — never promote an item above its score. Never truncate mid-sentence; finish every sentence. If you run out of room, drop the lowest-priority item instead of cutting a line short. -ticker: prefer critical and high. If nothing is critical or high, fill ticker with medium then low incidents and crime so the HUD is not blank. +If DATA is empty, return exactly {"summary_en": "No significant developments in this window.", "ticker": [], "map_items": []}. + +ticker: only stories present in DATA, highest score first. map_items may be empty if no located critical/high event is explicit in the data. @@ -160,9 +196,11 @@ You are writing a daily recap of the last 24 hours of news for an OSINT operator Always write a real summary_en daily recap of the most important stories in DATA. Rank geopolitics, military/conflict, security, disasters, and major political developments first. Ignore futures prices, commodity tape, ticker chatter, and routine market data — do not treat price ticks as news. -Lead with critical and high breaking events. If DATA has no critical/high stories, fill the recap with minor incidents and crime reports rather than writing an empty or unfinished recap. Never truncate mid-sentence; finish every sentence. +DATA is pre-filtered by score and ordered best-first. Lead with the highest-scoring breaking stories of the day and rank them honestly by importance — never promote an item above its score. Never truncate mid-sentence; finish every sentence. -ticker: prefer critical and high. If nothing is critical or high, fill ticker with medium then low incidents and crime so the HUD is not blank. +If DATA is empty, return exactly {"summary_en": "No significant developments in this window.", "ticker": [], "map_items": []}. + +ticker: only stories present in DATA, highest score first. Demand a single JSON object (no markdown fences) with this exact shape: @@ -326,6 +364,18 @@ def ensure_tables() -> None: CREATE INDEX IF NOT EXISTS ix_news_items_map_bbox ON news_items (lon, lat) WHERE kind = 'map' AND lat IS NOT NULL AND lon IS NOT NULL; + CREATE TABLE IF NOT EXISTS article_scores ( + article_id INTEGER NOT NULL, + summary_id INTEGER, + score INTEGER NOT NULL, + category TEXT, + selected BOOLEAN NOT NULL, + model TEXT, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + PRIMARY KEY (article_id, created_at) + ); + CREATE INDEX IF NOT EXISTS ix_article_scores_summary + ON article_scores (summary_id); """ try: conn = psycopg2.connect(**DB_CONFIG) @@ -342,7 +392,7 @@ def get_recent_news(window_minutes: int | None = None) -> list[dict]: """Fetch articles from the look-back window (content > 100 chars).""" mins = window_minutes if window_minutes is not None else effective_window_minutes() query = """ - SELECT title, content, url, domain + SELECT id, title, content, url, domain FROM articles WHERE timestamp > NOW() - make_interval(mins => %s) AND content IS NOT NULL AND length(content) > 100 @@ -356,7 +406,7 @@ def get_recent_news(window_minutes: int | None = None) -> list[dict]: cur.close() conn.close() return [ - {"title": r[0], "content": r[1], "url": r[2], "domain": r[3]} + {"id": r[0], "title": r[1], "content": r[2], "url": r[3], "domain": r[4]} for r in rows ] except Exception as exc: # noqa: BLE001 @@ -412,14 +462,14 @@ def _already_recapped_today() -> bool: def save_batch( summary_en: str, model: str, ticker: list, map_items: list, *, kind: str = "interval" -) -> None: - """Insert the master brief plus flagged ticker/map rows.""" +) -> int | None: + """Insert the master brief plus flagged ticker/map rows. Returns the new summary id.""" ticker_rows = select_ticker(ticker or []) map_rows = select_map(map_items or []) text = (summary_en or "").strip() if len(text) < 10 and not ticker_rows and not map_rows: logger.info("Summary too short or empty. Skipping save.") - return + return None insert_item = """ INSERT INTO news_items ( summary_id, kind, headline, importance, location_name, @@ -473,8 +523,54 @@ def save_batch( ) cur.close() conn.close() + return summary_id except Exception as exc: # noqa: BLE001 logger.error("Error saving batch to DB: %s", exc) + return None + + +def persist_article_scores( + graded: list[dict], *, summary_id: int | None, model: str +) -> None: + """Insert one article_scores row per graded article (selected true/false). + + Best-effort: a failure here is logged and never aborts the run. + """ + rows = [] + for block in graded or []: + article_id = block.get("article_id") + if article_id is None: + continue + rows.append( + ( + article_id, + summary_id, + int(block.get("score") or 0), + block.get("category"), + bool(block.get("selected")), + model, + ) + ) + if not rows: + return + try: + conn = psycopg2.connect(**DB_CONFIG) + cur = conn.cursor() + cur.executemany( + "INSERT INTO article_scores " + "(article_id, summary_id, score, category, selected, model) " + "VALUES (%s, %s, %s, %s, %s, %s)", + rows, + ) + conn.commit() + cur.close() + conn.close() + logger.info( + "article_scores persisted rows=%d selected=%d summary_id=%s", + len(rows), sum(1 for r in rows if r[4]), summary_id, + ) + except Exception as exc: # noqa: BLE001 + logger.error("Error persisting article_scores (run continues): %s", exc) # ── Orchestration ────────────────────────────────────────────────────────── @@ -533,34 +629,69 @@ def summarize_news() -> None: logger.info("No new articles found in the last %s min.", window) return + min_score, top_n, fallback_top = selection_config() logger.info( - "Processing %d articles with %s (batch_size=%d, recap=%s, window_min=%s)...", + "Processing %d articles with %s (batch_size=%d, recap=%s, window_min=%s, " + "min_score=%d, top_n=%d, fallback_top=%d)...", len(articles), model, BATCH_SIZE, recap, window, + min_score, top_n, fallback_top, ) - partial_summaries: list[str] = [] + graded: list[dict] = [] for i in range(0, len(articles), BATCH_SIZE): batch = articles[i : i + BATCH_SIZE] + batch_index = i // BATCH_SIZE logger.info( "map batch %d/%d (%d articles)", - i // BATCH_SIZE + 1, -(-len(articles) // BATCH_SIZE), len(batch), + batch_index + 1, -(-len(articles) // BATCH_SIZE), len(batch), ) - summary = call_llm( + response = call_llm( build_map_prompt(batch), api_key=api_key, model=model, base_url=base_url, json_mode=False, ) - if summary: - partial_summaries.append(summary) + if not response: + continue + blocks, stats = parse_map_scores( + response, articles=articles, batch_index=batch_index, batch_size=BATCH_SIZE + ) + logger.info( + "map batch %d graded %d/%d (score fallback=%d, unattributed=%d)", + batch_index + 1, stats["graded"], len(batch), + stats["fallback"], stats["unattributed"], + ) + graded.extend(blocks) - final_input = "\n\n".join(partial_summaries) - if not final_input.strip(): - logger.warning("No partial summaries produced — nothing to reduce.") + if not graded: + logger.warning("No article blocks parsed from the map phase — nothing to reduce.") return - logger.info("reduce phase over %d partial summaries", len(partial_summaries)) + selected, used_fallback = select_graded( + graded, min_score=min_score, top_n=top_n, fallback_top=fallback_top + ) + selected_positions = {block["position"] for block in selected} + for block in graded: + block["selected"] = block["position"] in selected_positions + if used_fallback: + logger.warning( + "No article cleared SUMMARY_MIN_SCORE=%d — fallback to top %d " + "(max score %d)", + min_score, len(selected), max(b["score"] for b in graded), + ) + logger.info( + "selected %d/%d graded articles for reduce (scores=%s)", + len(selected), len(graded), [b["score"] for b in selected], + ) + + final_input = join_blocks(selected) + if not final_input.strip(): + logger.warning( + "Selection is empty (min_score=%d, fallback_top=%d) — reduce gets empty DATA.", + min_score, fallback_top, + ) + master_raw = call_llm( build_master_prompt(final_input, recap=recap), api_key=api_key, @@ -572,13 +703,14 @@ def summarize_news() -> None: logger.warning("Reduce phase returned empty — nothing to persist.") return parsed = parse_reduce_json(master_raw) - save_batch( + summary_id = save_batch( parsed["summary_en"], model, parsed["ticker"], parsed["map_items"], kind="daily_recap" if recap else "interval", ) + persist_article_scores(graded, summary_id=summary_id, model=model) if __name__ == "__main__": diff --git a/news/summerizer/tests/test_grading.py b/news/summerizer/tests/test_grading.py new file mode 100644 index 0000000..811f3d0 --- /dev/null +++ b/news/summerizer/tests/test_grading.py @@ -0,0 +1,174 @@ +"""Map-phase grading: score parsing, batch attribution, selection, reduce input.""" + +from __future__ import annotations + +import pytest + +from intel import join_blocks, parse_map_scores, select_graded + + +def _articles(n: int, 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, score=None, importance=None, marker="Article") -> str: + lines = [f"{marker} {n}:"] + if score is not None: + lines.append(f"- Score: {score}") + if importance is not None: + lines.append(f"- Importance: {importance}") + lines.append("- Some fact bullet") + lines.append("- Category: politics") + return "\n".join(lines) + + +def test_parses_score_line(): + raw = _block(1, score=84) + blocks, stats = parse_map_scores(raw, articles=_articles(1)) + assert len(blocks) == 1 + assert blocks[0]["score"] == 84 + assert blocks[0]["importance"] is None + assert stats == {"blocks": 1, "graded": 1, "fallback": 0, "unattributed": 0} + + +def test_parses_category_and_article_id(): + blocks, _ = parse_map_scores(_block(1, score=70), articles=_articles(1)) + assert blocks[0]["category"] == "politics" + assert blocks[0]["article_id"] == 100 + assert "Score: 70" in blocks[0]["text"] + + +@pytest.mark.parametrize( + "importance,expected", + [("critical", 95), ("high", 78), ("medium", 50), ("low", 22), ("none", 5)], +) +def test_missing_score_falls_back_to_importance_label(importance, expected): + blocks, stats = parse_map_scores( + _block(1, importance=importance), articles=_articles(1) + ) + assert blocks[0]["score"] == expected + assert stats["fallback"] == 1 + + +def test_missing_score_and_missing_importance_defaults_to_50(): + blocks, stats = parse_map_scores("Article 1:\n- Some fact bullet", articles=_articles(1)) + assert blocks[0]["score"] == 50 + assert stats["fallback"] == 1 + + +@pytest.mark.parametrize("line", ["- Score: high", "- Score: n/a", "- Score:"]) +def test_garbage_score_line_falls_back(line): + blocks, stats = parse_map_scores( + f"{_block(1, importance='high').replace('- Importance: high', line + chr(10) + '- Importance: high')}", + articles=_articles(1), + ) + assert blocks[0]["score"] == 78 + assert stats["fallback"] == 1 + + +def test_score_is_clamped(): + blocks, stats = parse_map_scores(_block(1, score=150), articles=_articles(1)) + assert blocks[0]["score"] == 100 + assert stats["fallback"] == 0 + blocks, _ = parse_map_scores(_block(1, score=0), articles=_articles(1)) + assert blocks[0]["score"] == 0 + + +def test_split_is_case_insensitive_and_markdown_tolerant(): + raw = "**article 1:**\n- score: 77\n- Importance: high\n\n ARTICLE 2:\n- Score: 12" + blocks, stats = parse_map_scores(raw, articles=_articles(2)) + assert [b["score"] for b in blocks] == [77, 12] + assert stats["graded"] == 2 + + +def test_batch_index_attribution(): + articles = _articles(8) + raw = _block(1, score=90) + "\n\n" + _block(2, score=10) + blocks, _ = parse_map_scores(raw, articles=articles, batch_index=1, batch_size=4) + assert [b["article_id"] for b in blocks] == [104, 105] + assert [b["position"] for b in blocks] == [4, 5] + + +def test_omitted_and_reordered_articles_attribute_by_number(): + articles = _articles(4) + raw = "\n\n".join([_block(3, score=30), _block(1, score=88), _block(4, score=61)]) + blocks, stats = parse_map_scores(raw, articles=articles, batch_size=4) + assert [b["article_id"] for b in blocks] == [102, 100, 103] + assert stats["graded"] == 3 + assert stats["blocks"] == 3 + + +def test_out_of_range_and_duplicate_blocks_are_counted_not_raised(): + articles = _articles(2) + raw = "\n\n".join([_block(1, score=90), _block(1, score=20), _block(9, score=80)]) + blocks, stats = parse_map_scores(raw, articles=articles, batch_size=2) + assert [b["article_id"] for b in blocks] == [100] + assert stats["unattributed"] == 2 + assert stats["blocks"] == 3 + + +@pytest.mark.parametrize("raw", ["", "no article blocks at all", None]) +def test_never_raises_on_junk(raw): + blocks, stats = parse_map_scores(raw, articles=_articles(3)) + assert blocks == [] + assert stats["graded"] == 0 + + +# ── selection ───────────────────────────────────────────────────────────── + +def _scored(pairs): + return [ + {"position": i, "score": score, "text": f"block {i}"} for i, score in enumerate(pairs) + ] + + +def test_threshold_and_cap_selection_best_first(): + blocks = _scored([55, 90, 61, 88, 40, 70]) + selected, fallback = select_graded(blocks, min_score=60, top_n=3, fallback_top=3) + assert [b["score"] for b in selected] == [90, 88, 70] + assert [b["text"] for b in selected] == ["block 1", "block 3", "block 5"] + assert fallback is False + + +def test_ties_keep_original_order(): + blocks = _scored([70, 90, 70, 90]) + selected, _ = select_graded(blocks, min_score=60, top_n=4, fallback_top=3) + assert [b["text"] for b in selected] == ["block 1", "block 3", "block 0", "block 2"] + + +def test_nothing_clears_the_bar_uses_fallback_top(): + blocks = _scored([40, 12, 55, 3]) + selected, fallback = select_graded(blocks, min_score=60, top_n=12, fallback_top=3) + assert [b["score"] for b in selected] == [55, 40, 12] + assert fallback is True + + +def test_fallback_top_zero_yields_empty_selection(): + blocks = _scored([40, 12, 55]) + selected, fallback = select_graded(blocks, min_score=60, top_n=12, fallback_top=0) + assert selected == [] + assert fallback is False + assert join_blocks(selected) == "" + + +def test_empty_blocks_select_nothing(): + assert select_graded([], min_score=60, top_n=12, fallback_top=3) == ([], False) + + +def test_reduce_input_contains_only_selected_blocks(): + raw = "\n\n".join([_block(n, score=s) for n, s in [(1, 12), (2, 95), (3, 5)]]) + blocks, _ = parse_map_scores(raw, articles=_articles(3), batch_size=3) + selected, _ = select_graded(blocks, min_score=60, top_n=12, fallback_top=3) + data = join_blocks(selected) + assert "Article 2:" in data + assert "Article 1:" not in data + assert "Article 3:" not in data diff --git a/news/summerizer/tests/test_grading_pipeline.py b/news/summerizer/tests/test_grading_pipeline.py new file mode 100644 index 0000000..b78bf80 --- /dev/null +++ b/news/summerizer/tests/test_grading_pipeline.py @@ -0,0 +1,202 @@ +"""Offline end-to-end: map grading feeds a thresholded subset to the reduce phase.""" + +from __future__ import annotations + +import json + +import pytest + +import summarizer + + +class _FakeCursor: + def __init__(self, log: list): + self.log = log + self._sql = "" + + def execute(self, sql, params=None): + self._sql = " ".join(sql.split()) + self.log.append(("execute", self._sql, params)) + + def executemany(self, sql, rows): + self.log.append(("executemany", " ".join(sql.split()), list(rows))) + + def fetchone(self): + if "article_summaries" in self._sql: + return (42,) + return None + + def fetchall(self): + return [] + + def close(self): + pass + + +class _FakeConn: + def __init__(self, log: list): + self.log = log + + def cursor(self): + return _FakeCursor(self.log) + + def commit(self): + self.log.append(("commit",)) + + def close(self): + pass + + +def _articles(n: int = 6) -> list[dict]: + return [ + { + "id": i + 1, + "title": f"Story {i + 1}", + "content": f"Body of story {i + 1} " + "x" * 120, + "url": f"https://ex.com/{i + 1}", + "domain": "ex.com", + } + for i in range(n) + ] + + +def _block(n: int, score=None, importance=None) -> str: + lines = [f"Article {n}:", "- Fact bullet one"] + if score is not None: + lines.append(f"- Score: {score}") + if importance is not None: + lines.append(f"- Importance: {importance}") + lines += ["- Location: Kyiv", "- Entities: None", "- Category: politics", + "- OSINT signal: No notable OSINT signal.", "- Lat: 50.45", "- Lon: 30.52"] + return "\n".join(lines) + + +MAP_REPLIES = [ + # batch 0 → articles 1..3 + "\n\n".join([_block(1, score=92), _block(2, score=34), _block(3, score=81)]), + # batch 1 → articles 4..6 (numbering restarts; article 6 loses its Score line) + "\n\n".join([_block(1, score=12), _block(2, score=66), _block(3, importance="low")]), +] + +REDUCE_REPLY = json.dumps( + { + "summary_en": "Lead: strike in Kyiv. Also: minister resigns.", + "ticker": [ + {"headline": "Strike in Kyiv", "importance": "critical", "url": "https://ex.com/1"}, + ], + "map_items": [ + { + "headline": "Strike in Kyiv", + "importance": "critical", + "location_name": "Kyiv", + "lat": 50.45, + "lon": 30.52, + "location_confidence": "city", + "category": "military/conflict", + "url": "https://ex.com/1", + } + ], + } +) + + +@pytest.fixture +def harness(monkeypatch): + """Run summarize_news offline: fake DB, fake LLM, 6 articles, BATCH_SIZE=3.""" + calls: list[tuple[str, str]] = [] + db_log: list = [] + + def fake_call_llm(prompt, *, api_key, model, base_url, json_mode=False): + calls.append(("json" if json_mode else "text", prompt)) + return REDUCE_REPLY if json_mode else MAP_REPLIES[len(calls) - 1] + + monkeypatch.setenv("NOUS_API_KEY", "test-key") + monkeypatch.setenv("SUMMARY_MODEL", "test-model") + monkeypatch.setattr(summarizer, "BATCH_SIZE", 3) + monkeypatch.setattr(summarizer, "call_llm", fake_call_llm) + monkeypatch.setattr(summarizer, "get_recent_news", lambda *a, **k: _articles()) + monkeypatch.setattr(summarizer, "_already_summarized_this_interval", lambda: False) + monkeypatch.setattr(summarizer, "_already_recapped_today", lambda: False) + monkeypatch.setattr( + summarizer.psycopg2, "connect", lambda **kwargs: _FakeConn(db_log) + ) + return calls, db_log + + +def _score_rows(db_log: list) -> list[tuple]: + rows = [entry[2] for entry in db_log if entry[0] == "executemany"] + assert rows, f"no executemany in db log: {db_log}" + return rows[-1] + + +def test_reduce_sees_only_articles_above_the_threshold(harness): + calls, db_log = harness + summarizer.summarize_news() + + reduce_prompt = [prompt for kind, prompt in calls if kind == "json"][0] + # Selected: 92 (article 1), 81 (article 3), 66 (article 5) — best first. + assert reduce_prompt.index("Score: 92") < reduce_prompt.index("Score: 81") + assert reduce_prompt.index("Score: 81") < reduce_prompt.index("Score: 66") + for leaked in ("Score: 34", "Score: 12", "Importance: low"): + assert leaked not in reduce_prompt + + rows = _score_rows(db_log) + assert len(rows) == 6 + by_article = {row[0]: row for row in rows} + assert by_article[6][2] == 22 # Importance: low fallback + assert sorted(aid for aid, row in by_article.items() if row[4]) == [1, 3, 5] + assert {row[1] for row in rows} == {42} # summary_id from save_batch + assert {row[5] for row in rows} == {"test-model"} + assert by_article[1][3] == "politics" + + +def test_all_low_scores_fall_back_to_top_three(harness, monkeypatch): + calls, db_log = harness + monkeypatch.setenv("SUMMARY_MIN_SCORE", "95") + monkeypatch.setenv("SUMMARY_FALLBACK_TOP", "3") + summarizer.summarize_news() + + reduce_prompt = [prompt for kind, prompt in calls if kind == "json"][0] + # Top three by score: 92 (article 1), 81 (article 3), 66 (article 5). + for kept in ("Score: 92", "Score: 81", "Score: 66"): + assert kept in reduce_prompt + for dropped in ("Score: 34", "Score: 12", "Importance: low"): + assert dropped not in reduce_prompt + assert sorted(row[0] for row in _score_rows(db_log) if row[4]) == [1, 3, 5] + + +def test_fallback_top_zero_sends_empty_data(harness, monkeypatch): + calls, db_log = harness + monkeypatch.setenv("SUMMARY_MIN_SCORE", "95") + monkeypatch.setenv("SUMMARY_FALLBACK_TOP", "0") + summarizer.summarize_news() + + reduce_prompt = [prompt for kind, prompt in calls if kind == "json"][0] + assert "Score: 92" not in reduce_prompt + assert reduce_prompt.rstrip().endswith("DATA:") + assert not any(row[4] for row in _score_rows(db_log)) + + +def test_score_insert_failure_does_not_abort_the_run(harness, monkeypatch): + calls, db_log = harness + + class _BoomConn(_FakeConn): + def cursor(self): + raise RuntimeError("article_scores unavailable") + + real_connect = summarizer.psycopg2.connect + state = {"n": 0} + + def flaky_connect(**kwargs): + # First connect = ensure_tables, second = save_batch, third = scores. + state["n"] += 1 + if state["n"] >= 3: + return _BoomConn(db_log) + return real_connect(**kwargs) + + monkeypatch.setattr(summarizer.psycopg2, "connect", flaky_connect) + summarizer.summarize_news() # must not raise + + kinds = [kind for kind, _ in calls] + assert kinds.count("json") == 1 # reduce still ran + assert any(entry[0] == "execute" and "article_summaries" in entry[1] for entry in db_log) diff --git a/news/summerizer/tests/test_prompts.py b/news/summerizer/tests/test_prompts.py index 954e5b3..048e472 100644 --- a/news/summerizer/tests/test_prompts.py +++ b/news/summerizer/tests/test_prompts.py @@ -22,12 +22,42 @@ def test_summary_prompt_focuses_on_breaking_news_not_futures(): assert "commodity" in p or "market" in p -def test_summary_prompt_covers_critical_then_incidents(): +def test_map_prompt_has_the_grading_rubric_and_score_first_block(): + p = MAP_PROMPT_DEFAULT + assert "- Score: <0-100>" in p + assert "Importance: critical|high|medium|low|none" in p + for band in ( + "90–100", + "70–89", + "40–69", + "10–39", + "0–9", + "event-calendar/schedule listings", + ): + assert band in p + # Score must be the first line of the per-article output block. + block = p.split("Article 1:", 1)[1] + first_lines = [line.strip() for line in block.splitlines() if line.strip()] + assert first_lines[0].startswith("- Score:") + + +def test_reduce_prompts_do_not_demand_filler(): + for prompt in (SUMMARY_PROMPT_DEFAULT, RECAP_PROMPT_DEFAULT): + p = prompt.lower() + assert "fill the brief with minor incidents" not in p + assert "fill the recap with minor incidents" not in p + assert "fill ticker with medium then low" not in p + assert "pre-filtered by score" in p + assert "never promote an item above its score" in p + assert "No significant developments in this window." in prompt + + +def test_summary_prompt_ranks_by_score_and_stays_complete(): p = SUMMARY_PROMPT_DEFAULT.lower() assert "critical" in p - assert "crime" in p - assert "incident" in p - assert "complete" in p or "truncat" in p or "unfinished" in p or "mid-sentence" in p + assert "highest-scoring" in p + assert "pre-filtered" in p + assert "complete" in p or "truncat" in p or "mid-sentence" in p def test_summary_prompt_does_not_bail_out_with_canned_empty_brief(): From 57c0444a69265c86344160b9f42558dae1baa802 Mon Sep 17 00:00:00 2001 From: backend Date: Fri, 13 Nov 2026 21:56:46 -0500 Subject: [PATCH 62/79] fix(summarizer): ignore future-dated rows; require a score floor for the fallback Two leaks let low-value items reach the operator brief: - get_recent_news() only bounded the window from below, so event listings dated days ahead (wiseye.org, +3d/+6d) were re-fetched, re-graded and re-billed every interval for a week. The window is now (now - N, now]; NULL timestamps stay excluded as before. - select_graded() returned ordered[:fallback_top] with no floor, so a 15/100 event listing entered the brief as 'low'. New SUMMARY_FALLBACK_MIN_SCORE (default 40, clamped 0-100) filters the fallback set; when nothing clears it the reduce phase gets empty DATA and writes the empty-brief response. The fallback WARNING now logs the floor. Docs: .env.example and docs/news.md document the new knob and window. --- .env.example | 6 +- docs/news.md | 11 +- news/summerizer/intel.py | 19 +- news/summerizer/summarizer.py | 40 ++-- news/summerizer/tests/test_grading.py | 57 ++++++ .../summerizer/tests/test_grading_pipeline.py | 29 +++ news/summerizer/tests/test_summarizer.py | 172 +++++++++++++++++- 7 files changed, 311 insertions(+), 23 deletions(-) diff --git a/.env.example b/.env.example index fe913fd..def97d4 100644 --- a/.env.example +++ b/.env.example @@ -100,11 +100,13 @@ NOUS_BASE_URL=https://inference-api.nousresearch.com/v1 NEWS_BATCH_SIZE=50 # Map-phase grading: the map model scores each article 0-100, and only blocks # with score >= SUMMARY_MIN_SCORE reach the reduce brief (best first). -# If nothing clears the bar, the top SUMMARY_FALLBACK_TOP blocks are used -# (0 = honour the threshold and pass an empty DATA section instead). +# If nothing clears the bar, up to SUMMARY_FALLBACK_TOP blocks scoring at least +# SUMMARY_FALLBACK_MIN_SCORE are used; if none do, the reduce phase gets an +# empty DATA section (SUMMARY_FALLBACK_TOP=0 does the same unconditionally). SUMMARY_MIN_SCORE=60 SUMMARY_TOP_N=12 SUMMARY_FALLBACK_TOP=3 +SUMMARY_FALLBACK_MIN_SCORE=40 SUMMARY_WINDOW_MINUTES=15 # Futures/markets coupling from the upstream pipeline is OFF by default # (irrelevant to OSINT). Set INCLUDE_FUTURES=1 + install yfinance to enable. diff --git a/docs/news.md b/docs/news.md index 92d5342..9f0a9d2 100644 --- a/docs/news.md +++ b/docs/news.md @@ -79,9 +79,11 @@ it to 0-100, and falls back to the `Importance:` label (critical 95, high 78, medium 50, low 22, none 5) when the line is missing or unparsable — a block is never dropped and the fallback count is logged per batch. Only blocks scoring `>= SUMMARY_MIN_SCORE` (default 60) reach the reduce prompt, best first, capped -at `SUMMARY_TOP_N` (default 12). If nothing clears the bar the top -`SUMMARY_FALLBACK_TOP` blocks (default 3) are used so the HUD is not blank; -`SUMMARY_FALLBACK_TOP=0` passes an empty DATA section instead. The reduce prompt +at `SUMMARY_TOP_N` (default 12). If nothing clears the bar, up to +`SUMMARY_FALLBACK_TOP` blocks (default 3) scoring at least +`SUMMARY_FALLBACK_MIN_SCORE` (default 40) are used; when none does, or when +`SUMMARY_FALLBACK_TOP=0`, the reduce phase receives an empty DATA section and +writes the empty-brief response instead of promoting noise. The reduce prompt no longer asks for filler: it leads with the highest-scoring stories and never promotes an item above its score. Every graded article is persisted to `article_scores` (score, category, selected, model, summary_id) so the operator @@ -267,7 +269,8 @@ map. `summary_en` lands in `article_summaries.summary_text`. | `SUMMARY_MIN_SCORE` | `60` | Map-phase score a block must reach to enter the reduce brief. | | `SUMMARY_TOP_N` | `12` | Max blocks passed to the reduce phase (best score first). | | `SUMMARY_FALLBACK_TOP` | `3` | Blocks used when nothing clears `SUMMARY_MIN_SCORE`; `0` = empty DATA. | -| `SUMMARY_WINDOW_MINUTES` | `15` | How far back the summarizer looks for new articles. | +| `SUMMARY_FALLBACK_MIN_SCORE` | `40` | Score floor for the fallback set; below it the reduce phase gets empty DATA. | +| `SUMMARY_WINDOW_MINUTES` | `15` | How far back the summarizer looks for new articles (window is `(now - N, now]`; future-dated rows are ignored). | | `NEWS_SCRAPE_INTERVAL_S` | `10` | Pause after each crawl before the next (scraper is otherwise continuous). | | `NEWS_SUMMARIZE_INTERVAL_S` | `900` | Seconds between analyst runs (default 15 min). | | `TZ` | `America/New_York` | Timezone for the 23:00 daily recap. | diff --git a/news/summerizer/intel.py b/news/summerizer/intel.py index d99b258..7d3dc15 100644 --- a/news/summerizer/intel.py +++ b/news/summerizer/intel.py @@ -210,13 +210,20 @@ def parse_map_scores( def select_graded( - blocks: list[dict], *, min_score: int, top_n: int, fallback_top: int + blocks: list[dict], + *, + min_score: int, + top_n: int, + fallback_top: int, + fallback_min_score: int = 0, ) -> tuple[list[dict], bool]: """Rank blocks best-first and return the ones the reduce phase should see. Keeps ``score >= min_score`` capped at ``top_n`` (stable on ties: original - order). When nothing clears the bar, returns the top ``fallback_top`` blocks - and True; ``fallback_top == 0`` yields an empty selection. + order). When nothing clears the bar, returns up to ``fallback_top`` blocks + that also clear ``fallback_min_score`` and True; ``fallback_top == 0``, a + floor that excludes every block, or no blocks at all yield an empty + selection and False. """ ordered = sorted(blocks, key=lambda b: -int(b.get("score") or 0)) limit = max(0, int(top_n)) @@ -226,7 +233,11 @@ def select_graded( fallback_limit = max(0, int(fallback_top)) if fallback_limit <= 0: return [], False - return ordered[:fallback_limit], bool(ordered) + floor = int(fallback_min_score) + floor_clearing = [b for b in ordered if int(b.get("score") or 0) >= floor] + if not floor_clearing: + return [], False + return floor_clearing[:fallback_limit], True def join_blocks(blocks: list[dict]) -> str: diff --git a/news/summerizer/summarizer.py b/news/summerizer/summarizer.py index 2ddd023..c1daeae 100644 --- a/news/summerizer/summarizer.py +++ b/news/summerizer/summarizer.py @@ -54,6 +54,7 @@ BATCH_SIZE = int(os.getenv("BATCH_SIZE", "50")) DEFAULT_SUMMARY_MIN_SCORE = 60 DEFAULT_SUMMARY_TOP_N = 12 DEFAULT_SUMMARY_FALLBACK_TOP = 3 +DEFAULT_SUMMARY_FALLBACK_MIN_SCORE = 40 def _env_int(name: str, default: int) -> int: @@ -67,12 +68,15 @@ def _env_int(name: str, default: int) -> int: return default -def selection_config() -> tuple[int, int, int]: - """(min_score, top_n, fallback_top) from env, read per run.""" +def selection_config() -> tuple[int, int, int, int]: + """(min_score, top_n, fallback_top, fallback_min_score) from env, per run.""" min_score = max(0, min(100, _env_int("SUMMARY_MIN_SCORE", DEFAULT_SUMMARY_MIN_SCORE))) top_n = max(0, _env_int("SUMMARY_TOP_N", DEFAULT_SUMMARY_TOP_N)) fallback_top = max(0, _env_int("SUMMARY_FALLBACK_TOP", DEFAULT_SUMMARY_FALLBACK_TOP)) - return min_score, top_n, fallback_top + fallback_min_score = max( + 0, min(100, _env_int("SUMMARY_FALLBACK_MIN_SCORE", DEFAULT_SUMMARY_FALLBACK_MIN_SCORE)) + ) + return min_score, top_n, fallback_top, fallback_min_score def _summary_window_minutes() -> int: @@ -389,12 +393,18 @@ def ensure_tables() -> None: def get_recent_news(window_minutes: int | None = None) -> list[dict]: - """Fetch articles from the look-back window (content > 100 chars).""" + """Fetch articles from the look-back window ``(now - window, now]``. + + The upper bound is deliberate: future-dated rows (event listings, bad + scrape timestamps) must not be re-graded every interval. Rows with a NULL + timestamp have never matched the lower bound and still do not. + """ mins = window_minutes if window_minutes is not None else effective_window_minutes() query = """ SELECT id, title, content, url, domain FROM articles WHERE timestamp > NOW() - make_interval(mins => %s) + AND timestamp <= NOW() AND content IS NOT NULL AND length(content) > 100 ORDER BY timestamp DESC; """ @@ -629,12 +639,12 @@ def summarize_news() -> None: logger.info("No new articles found in the last %s min.", window) return - min_score, top_n, fallback_top = selection_config() + min_score, top_n, fallback_top, fallback_min_score = selection_config() logger.info( "Processing %d articles with %s (batch_size=%d, recap=%s, window_min=%s, " - "min_score=%d, top_n=%d, fallback_top=%d)...", + "min_score=%d, top_n=%d, fallback_top=%d, fallback_min_score=%d)...", len(articles), model, BATCH_SIZE, recap, window, - min_score, top_n, fallback_top, + min_score, top_n, fallback_top, fallback_min_score, ) graded: list[dict] = [] @@ -669,7 +679,11 @@ def summarize_news() -> None: return selected, used_fallback = select_graded( - graded, min_score=min_score, top_n=top_n, fallback_top=fallback_top + graded, + min_score=min_score, + top_n=top_n, + fallback_top=fallback_top, + fallback_min_score=fallback_min_score, ) selected_positions = {block["position"] for block in selected} for block in graded: @@ -677,8 +691,9 @@ def summarize_news() -> None: if used_fallback: logger.warning( "No article cleared SUMMARY_MIN_SCORE=%d — fallback to top %d " - "(max score %d)", - min_score, len(selected), max(b["score"] for b in graded), + "with score >= %d (max score %d)", + min_score, len(selected), fallback_min_score, + max(b["score"] for b in graded), ) logger.info( "selected %d/%d graded articles for reduce (scores=%s)", @@ -688,8 +703,9 @@ def summarize_news() -> None: final_input = join_blocks(selected) if not final_input.strip(): logger.warning( - "Selection is empty (min_score=%d, fallback_top=%d) — reduce gets empty DATA.", - min_score, fallback_top, + "Selection is empty (min_score=%d, fallback_top=%d, " + "fallback_min_score=%d) — reduce gets empty DATA.", + min_score, fallback_top, fallback_min_score, ) master_raw = call_llm( diff --git a/news/summerizer/tests/test_grading.py b/news/summerizer/tests/test_grading.py index 811f3d0..4de4d92 100644 --- a/news/summerizer/tests/test_grading.py +++ b/news/summerizer/tests/test_grading.py @@ -152,6 +152,63 @@ def test_nothing_clears_the_bar_uses_fallback_top(): assert fallback is True +def test_fallback_respects_the_score_floor(): + blocks = _scored([45, 30, 15]) + selected, fallback = select_graded( + blocks, min_score=60, top_n=12, fallback_top=3, fallback_min_score=40 + ) + assert [b["score"] for b in selected] == [45] + assert fallback is True + + +def test_fallback_floor_drops_everything_below_it(): + blocks = _scored([30, 15, 12]) + selected, fallback = select_graded( + blocks, min_score=60, top_n=12, fallback_top=3, fallback_min_score=40 + ) + assert selected == [] + assert fallback is False + assert join_blocks(selected) == "" + + +def test_fallback_floor_zero_keeps_old_behaviour(): + blocks = _scored([40, 12, 55]) + selected, fallback = select_graded( + blocks, min_score=60, top_n=12, fallback_top=3, fallback_min_score=0 + ) + assert [b["score"] for b in selected] == [55, 40, 12] + assert fallback is True + + +def test_fallback_floor_does_not_affect_the_threshold_path(): + blocks = _scored([95, 45, 30]) + selected, fallback = select_graded( + blocks, min_score=60, top_n=12, fallback_top=3, fallback_min_score=90 + ) + assert [b["score"] for b in selected] == [95] + assert fallback is False + + +def test_replay_of_the_observed_run_keeps_only_the_45(): + """Master run #4: scores [45, 30, 15], min_score=60, fallback_top=3.""" + blocks = _scored([45, 30, 15]) + blocks[0]["text"] = "Article 1:\n- Score: 45\n- Importance: medium\n- Budget fight" + blocks[1]["text"] = "Article 2:\n- Score: 30\n- Importance: low\n- Council meeting" + blocks[2]["text"] = ( + "Article 3:\n- Score: 15\n- Importance: low\n" + "- UW-Madison Elections Research Center to host 2026 midterm election symposium" + ) + selected, fallback = select_graded( + blocks, min_score=60, top_n=12, fallback_top=3, fallback_min_score=40 + ) + assert [b["score"] for b in selected] == [45] + assert fallback is True + data = join_blocks(selected) + assert "Score: 45" in data + assert "symposium" not in data + assert "Council meeting" not in data + + def test_fallback_top_zero_yields_empty_selection(): blocks = _scored([40, 12, 55]) selected, fallback = select_graded(blocks, min_score=60, top_n=12, fallback_top=0) diff --git a/news/summerizer/tests/test_grading_pipeline.py b/news/summerizer/tests/test_grading_pipeline.py index b78bf80..3b6f021 100644 --- a/news/summerizer/tests/test_grading_pipeline.py +++ b/news/summerizer/tests/test_grading_pipeline.py @@ -177,6 +177,35 @@ def test_fallback_top_zero_sends_empty_data(harness, monkeypatch): assert not any(row[4] for row in _score_rows(db_log)) +def test_fallback_below_the_floor_sends_empty_data(harness, monkeypatch, caplog): + """Every block scores under the floor (max 92 < 93): no fallback at all.""" + calls, db_log = harness + monkeypatch.setenv("SUMMARY_MIN_SCORE", "95") + monkeypatch.setenv("SUMMARY_FALLBACK_MIN_SCORE", "93") + with caplog.at_level("WARNING"): + summarizer.summarize_news() + + reduce_prompt = [prompt for kind, prompt in calls if kind == "json"][0] + assert "Score: 92" not in reduce_prompt + assert reduce_prompt.rstrip().endswith("DATA:") + assert not any(row[4] for row in _score_rows(db_log)) + assert any("fallback_min_score=93" in rec.message for rec in caplog.records) + + +def test_fallback_floor_is_logged_in_the_warning(harness, monkeypatch, caplog): + calls, _ = harness + monkeypatch.setenv("SUMMARY_MIN_SCORE", "95") + monkeypatch.setenv("SUMMARY_FALLBACK_TOP", "3") + monkeypatch.setenv("SUMMARY_FALLBACK_MIN_SCORE", "40") + with caplog.at_level("WARNING"): + summarizer.summarize_news() + + warnings = [rec.message for rec in caplog.records if rec.levelname == "WARNING"] + assert any( + "fallback to top 3 with score >= 40 (max score 92)" in msg for msg in warnings + ), warnings + + def test_score_insert_failure_does_not_abort_the_run(harness, monkeypatch): calls, db_log = harness diff --git a/news/summerizer/tests/test_summarizer.py b/news/summerizer/tests/test_summarizer.py index 117044f..708a3f5 100644 --- a/news/summerizer/tests/test_summarizer.py +++ b/news/summerizer/tests/test_summarizer.py @@ -1,10 +1,19 @@ -"""Summarizer window, recap flag, and no futures injection into prompts.""" +"""Summarizer window, recap flag, no futures injection, and grading env knobs.""" +from __future__ import annotations + +from datetime import datetime, timedelta, timezone + +import pytest + +import summarizer from summarizer import ( build_map_prompt, build_master_prompt, effective_window_minutes, + get_recent_news, is_recap_run, + selection_config, ) @@ -43,3 +52,164 @@ def test_build_master_prompt_recap_uses_daily_template(): assert "partial facts" in prompt assert "daily recap" in prompt.lower() assert "24" in prompt + + +# ── get_recent_news window: (now - window, now] ─────────────────────────── + + +class _WindowCursor: + """Cursor double that applies the (now-window, now] window to a fixed table. + + It emulates PostgreSQL's ``NOW()`` semantics for the window bounds the query + declares, so a query missing the upper bound returns future-dated rows + exactly as the live table did. Rows with a NULL timestamp never satisfy a + range comparison, matching the pre-existing live behaviour. + """ + + def __init__(self, rows): + self.rows = rows + self.sql = "" + self.params = None + + def execute(self, sql, params=None): + self.sql = " ".join(sql.split()) + self.params = params + + def fetchall(self): + mins = self.params[0] + now = datetime.now(timezone.utc) + start = now - timedelta(minutes=mins) + has_upper = "timestamp <= NOW()" in self.sql + out = [] + for row in self.rows: + ts = row[5] + if ts is None or ts <= start: + continue + if has_upper and ts > now: + continue + out.append(row) + return out + + def close(self): + pass + + +class _WindowConn: + def __init__(self, rows): + self.rows = rows + + def cursor(self): + return _WindowCursor(self.rows) + + def close(self): + pass + + +def _row(row_id: int, ts, domain: str = "ex.com") -> tuple: + return (row_id, "title", "x" * 120, f"https://ex.com/{row_id}", domain, ts) + + +def _patch_articles(monkeypatch, rows): + monkeypatch.setattr(summarizer.psycopg2, "connect", lambda **kwargs: _WindowConn(rows)) + + +def test_recent_news_excludes_future_dated_rows(monkeypatch): + now = datetime.now(timezone.utc) + rows = [ + _row(1, now - timedelta(minutes=2), "fresh.example"), + _row(2, now + timedelta(days=3), "wiseye.org"), + _row(3, now + timedelta(days=6), "wiseye.org"), + ] + _patch_articles(monkeypatch, rows) + + news = get_recent_news(15) + + assert [n["id"] for n in news] == [1] + assert {n["domain"] for n in news} == {"fresh.example"} + + +def test_recent_news_window_is_closed_at_now_and_open_at_the_start(monkeypatch): + now = datetime.now(timezone.utc) + rows = [ + _row(1, now), # exactly now → inside (now - window, now] + _row(2, now - timedelta(minutes=20)), # older than the 15 min window + ] + _patch_articles(monkeypatch, rows) + + assert [n["id"] for n in get_recent_news(15)] == [1] + + +def test_recent_news_still_excludes_null_timestamps(monkeypatch): + now = datetime.now(timezone.utc) + _patch_articles(monkeypatch, [_row(1, None), _row(2, now - timedelta(minutes=1))]) + + assert [n["id"] for n in get_recent_news(15)] == [2] + + +def test_recent_news_query_keeps_content_filter_and_ordering(monkeypatch): + captured = {} + + class _CaptureCursor(_WindowCursor): + def execute(self, sql, params=None): + super().execute(sql, params) + captured["sql"] = self.sql + + class _CaptureConn(_WindowConn): + def cursor(self): + return _CaptureCursor([]) + + monkeypatch.setattr(summarizer.psycopg2, "connect", lambda **kwargs: _CaptureConn([])) + get_recent_news(15) + + sql = captured["sql"] + assert "timestamp > NOW() - make_interval(mins => %s)" in sql + assert "timestamp <= NOW()" in sql + assert "content IS NOT NULL AND length(content) > 100" in sql + assert "ORDER BY timestamp DESC" in sql + assert "IS NULL OR" not in sql + assert "COALESCE(timestamp" not in sql + + +# ── selection_config: SUMMARY_FALLBACK_MIN_SCORE ────────────────────────── + + +def _clear_selection_env(monkeypatch): + for name in ( + "SUMMARY_MIN_SCORE", + "SUMMARY_TOP_N", + "SUMMARY_FALLBACK_TOP", + "SUMMARY_FALLBACK_MIN_SCORE", + ): + monkeypatch.delenv(name, raising=False) + + +def test_selection_config_defaults(monkeypatch): + _clear_selection_env(monkeypatch) + assert selection_config() == (60, 12, 3, 40) + + +def test_selection_config_reads_the_floor(monkeypatch): + _clear_selection_env(monkeypatch) + monkeypatch.setenv("SUMMARY_FALLBACK_MIN_SCORE", "55") + assert selection_config()[3] == 55 + + +def test_selection_config_floor_zero_is_honoured(monkeypatch): + _clear_selection_env(monkeypatch) + monkeypatch.setenv("SUMMARY_FALLBACK_MIN_SCORE", "0") + assert selection_config()[3] == 0 + + +def test_selection_config_garbage_floor_warns_and_defaults(monkeypatch, caplog): + _clear_selection_env(monkeypatch) + monkeypatch.setenv("SUMMARY_FALLBACK_MIN_SCORE", "not-a-number") + with caplog.at_level("WARNING"): + assert selection_config()[3] == 40 + assert any("SUMMARY_FALLBACK_MIN_SCORE" in rec.message for rec in caplog.records) + + +@pytest.mark.parametrize("raw,expected", [("100", 100), ("101", 100), ("-5", 0)]) +def test_selection_config_floor_is_clamped(monkeypatch, raw, expected): + _clear_selection_env(monkeypatch) + monkeypatch.setenv("SUMMARY_FALLBACK_MIN_SCORE", raw) + assert selection_config()[3] == expected From d40244900e61171dc929eae3a919de95c312f174 Mon Sep 17 00:00:00 2001 From: Sirius DevOps Date: Fri, 13 Nov 2026 22:14:44 -0500 Subject: [PATCH 63/79] feat(summarizer): collapse syndicated wire copies before selection MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The map phase grades every article, but a single wire story arrives from many station domains with an identical headline (the measured run selected 12 blocks that were only two stories, then produced a ticker with five summit rows and one FAA row). Dedupe now runs before the threshold/cap, so SUMMARY_TOP_N buys distinct stories. - intel.py: pure `dedupe_blocks(blocks, *, similarity, enabled)` plus `normalize_title` / `title_similarity`. Titles are lowercased, punctuation flattened and a short digit-free trailing source suffix (" - KCCI", " | CNN", " — AP") dropped; blocks match on equal normalised titles or word-set Jaccard / word-sequence difflib ratio >= similarity (default 0.85). Best score wins the group (ties -> earliest), matching is against the representative only (no transitive chaining), and differing categories or differing numbers never merge. Blocks now carry their article title. - summarizer.py: dedupe graded blocks before select_graded() and log `dedupe 21 -> 9 (kept 9, duplicates 12)`; SUMMARY_DEDUPE=0 skips it, SUMMARY_DEDUPE_SIMILARITY tunes it. persist_article_scores() still writes one row per graded article, with duplicates selected=false and duplicate_of pointing at the surviving article id. - article_scores.duplicate_of INTEGER NULL in ensure_tables() and alembic 013 (upgrade/downgrade verified against Postgres 16). - docs/news.md + .env.example document both knobs. Replaying the observed summary id=6 (21 graded, 9 distinct titles) now keeps 9 and, at min_score=60/top_n=12, selects 2 — the 11 dropped copies that scored >= 60 are stored selected=false with a duplicate_of pointer. --- .env.example | 10 + .../013_article_scores_duplicate_of.py | 23 + docs/news.md | 17 + news/summerizer/intel.py | 197 ++++++++ news/summerizer/summarizer.py | 89 +++- news/summerizer/tests/test_dedupe.py | 432 ++++++++++++++++++ 6 files changed, 757 insertions(+), 11 deletions(-) create mode 100644 alembic/versions/013_article_scores_duplicate_of.py create mode 100644 news/summerizer/tests/test_dedupe.py diff --git a/.env.example b/.env.example index def97d4..b23921c 100644 --- a/.env.example +++ b/.env.example @@ -107,6 +107,16 @@ SUMMARY_MIN_SCORE=60 SUMMARY_TOP_N=12 SUMMARY_FALLBACK_TOP=3 SUMMARY_FALLBACK_MIN_SCORE=40 +# Syndication dedupe: the same wire story arrives from many station domains +# (kcci.com, wtae.com, …) with an identical headline. Copies are collapsed +# before the threshold/cap, so SUMMARY_TOP_N buys distinct stories: normalised +# titles (lowercase, trailing " - KCCI"/" | CNN"/" — AP" source suffix dropped) +# count as one story when they are equal or >= SUMMARY_DEDUPE_SIMILARITY alike. +# The highest-scoring copy represents the story; the rest are still written to +# article_scores with selected=false and duplicate_of = the surviving article id. +# Set SUMMARY_DEDUPE=0 to skip dedupe entirely (old behaviour). +SUMMARY_DEDUPE=1 +SUMMARY_DEDUPE_SIMILARITY=0.85 SUMMARY_WINDOW_MINUTES=15 # Futures/markets coupling from the upstream pipeline is OFF by default # (irrelevant to OSINT). Set INCLUDE_FUTURES=1 + install yfinance to enable. diff --git a/alembic/versions/013_article_scores_duplicate_of.py b/alembic/versions/013_article_scores_duplicate_of.py new file mode 100644 index 0000000..2fcfb8b --- /dev/null +++ b/alembic/versions/013_article_scores_duplicate_of.py @@ -0,0 +1,23 @@ +"""article_scores.duplicate_of: link a syndicated copy to its representative + +Revision ID: 013_article_scores_duplicate_of +Revises: 012_article_scores +Create Date: 2026-11-13 +""" + +from alembic import op + +revision = "013_article_scores_duplicate_of" +down_revision = "012_article_scores" +branch_labels = None +depends_on = None + + +def upgrade() -> None: + op.execute( + "ALTER TABLE article_scores ADD COLUMN IF NOT EXISTS duplicate_of INTEGER" + ) + + +def downgrade() -> None: + op.execute("ALTER TABLE article_scores DROP COLUMN IF EXISTS duplicate_of") diff --git a/docs/news.md b/docs/news.md index 9f0a9d2..4d4c545 100644 --- a/docs/news.md +++ b/docs/news.md @@ -89,6 +89,21 @@ promotes an item above its score. Every graded article is persisted to `article_scores` (score, category, selected, model, summary_id) so the operator can tune the thresholds against real data. +Syndicated wire copy is collapsed **before** the threshold and cap, so +`SUMMARY_TOP_N` counts distinct stories instead of stations: the same headline +carried by seven Hearst domains is one story, not seven. Titles are normalised +first (lowercase, punctuation flattened, a trailing ` - KCCI` / ` | CNN` / +` — AP` source suffix dropped when it is short and digit-free), then two blocks +are the same story when the normalised titles are equal or at least +`SUMMARY_DEDUPE_SIMILARITY` similar (default 0.85; word-set Jaccard or +word-sequence `difflib` ratio). The highest-scoring copy represents the story +(ties → earliest); differing `category` values and titles that disagree on any +number are never merged. Duplicates are still written to `article_scores` with +`selected=false` and `duplicate_of` = the surviving `article_id`, so nothing is +lost for tuning. `SUMMARY_DEDUPE=0` disables dedupe entirely; raising +`SUMMARY_DEDUPE_SIMILARITY` toward 0.95 makes it stricter. Dedupe is pure string +work — no extra LLM call. + ## Keys and Settings - **`NOUS_API_KEY`** — paste in the dashboard **Keys** UI (`api_keys` / @@ -270,6 +285,8 @@ map. `summary_en` lands in `article_summaries.summary_text`. | `SUMMARY_TOP_N` | `12` | Max blocks passed to the reduce phase (best score first). | | `SUMMARY_FALLBACK_TOP` | `3` | Blocks used when nothing clears `SUMMARY_MIN_SCORE`; `0` = empty DATA. | | `SUMMARY_FALLBACK_MIN_SCORE` | `40` | Score floor for the fallback set; below it the reduce phase gets empty DATA. | +| `SUMMARY_DEDUPE` | `1` | Collapse syndicated wire copies before selection; `0` skips dedupe entirely. | +| `SUMMARY_DEDUPE_SIMILARITY` | `0.85` | Normalised-title similarity at which two blocks count as the same story (1.0 = verbatim only). | | `SUMMARY_WINDOW_MINUTES` | `15` | How far back the summarizer looks for new articles (window is `(now - N, now]`; future-dated rows are ignored). | | `NEWS_SCRAPE_INTERVAL_S` | `10` | Pause after each crawl before the next (scraper is otherwise continuous). | | `NEWS_SUMMARIZE_INTERVAL_S` | `900` | Seconds between analyst runs (default 15 min). | diff --git a/news/summerizer/intel.py b/news/summerizer/intel.py index 7d3dc15..5cdf13c 100644 --- a/news/summerizer/intel.py +++ b/news/summerizer/intel.py @@ -2,6 +2,7 @@ from __future__ import annotations +import difflib import json import re @@ -193,6 +194,7 @@ def parse_map_scores( "n": n, "article": article, "article_id": article.get("id"), + "title": article.get("title"), "score": score, "importance": importance, "category": _category_from_block(block_text), @@ -243,3 +245,198 @@ def select_graded( def join_blocks(blocks: list[dict]) -> str: """Reduce-phase DATA text: only these blocks, original text, best-first.""" return "\n\n".join(b["text"] for b in blocks) + + +# ── Syndication dedupe (pure string work — no LLM, no DB) ────────────────── + +DEFAULT_DEDUPE_SIMILARITY = 0.85 + +# Wire copy carries the station at the end of the headline: " - KCCI", " | CNN". +_SOURCE_SEPARATORS = (" - ", " | ", " — ", " – ") +_MAX_SUFFIX_CHARS = 40 +_MAX_SUFFIX_WORDS = 4 +_NON_ALNUM_RE = re.compile(r"[^a-z0-9]+") +_DIGIT_RE = re.compile(r"\d") + + +def normalize_title(title) -> str: + """Comparable headline form: lowercase, source suffix stripped, words only. + + A trailing `` - KCCI`` / `` | CNN`` / `` — AP`` marker is removed when the + tail is short (<= 40 chars and <= 4 words) **and carries no digits**, so + ``Story - KCCI`` and ``Story | WTAE`` land on the same key while serial + titles (``… – Part 1`` / ``… – Part 2``, ``… — Day 5``) stay distinct. + Titles that are None, empty or non-string normalise to ``""`` and never + match anything. + """ + if title is None: + return "" + if not isinstance(title, str): + title = str(title) + text = title.strip().lower() + cut = -1 + for separator in _SOURCE_SEPARATORS: + idx = text.rfind(separator) + if idx <= 0: + continue + tail = text[idx + len(separator):].strip() + if ( + len(tail) <= _MAX_SUFFIX_CHARS + and 0 < len(tail.split()) <= _MAX_SUFFIX_WORDS + and not _DIGIT_RE.search(tail) + ): + cut = max(cut, idx) + if cut > 0: + text = text[:cut] + return " ".join(_NON_ALNUM_RE.sub(" ", text).split()) + + +def title_similarity(normalised_left: str, normalised_right: str) -> float: + """0..1 story-similarity of two already-normalised titles. + + Max of word-set Jaccard (word order and repetition do not matter) and the + ``difflib`` ratio over the *word sequence* (so near-verbatim rewrites + score high, while short headlines differing only in a name — "story 1" vs + "story 2", "storm hits Texas" vs "storm hits Tennessee" — stay low). + """ + if not normalised_left or not normalised_right: + return 0.0 + if normalised_left == normalised_right: + return 1.0 + words_left = normalised_left.split() + words_right = normalised_right.split() + set_left, set_right = set(words_left), set(words_right) + union = set_left | set_right + jaccard = len(set_left & set_right) / len(union) if union else 0.0 + ratio = difflib.SequenceMatcher(None, words_left, words_right).ratio() + return max(jaccard, ratio) + + +def _block_title(block: dict): + """Title of a graded block: the parsed key, else the nested article row.""" + title = block.get("title") + if title is None: + article = block.get("article") + if isinstance(article, dict): + title = article.get("title") + return title + + +def _block_score(block: dict) -> int: + try: + return int(block.get("score") or 0) + except (TypeError, ValueError): + return 0 + + +def _block_position(block: dict, fallback: int) -> int: + position = block.get("position") + return position if isinstance(position, int) else fallback + + +def _categories_conflict(left: dict, right: dict) -> bool: + """True when both blocks carry a category and the two differ.""" + cat_left = str(left.get("category") or "").strip().lower() + cat_right = str(right.get("category") or "").strip().lower() + return bool(cat_left) and bool(cat_right) and cat_left != cat_right + + +def _numbers_conflict(left: str, right: str) -> bool: + """True when the two titles disagree on any number. + + Syndicated wire copy is verbatim, so a differing figure ("… – Part 1" vs + "… – Part 2", "12 dead" vs "21 dead", horoscope date boilerplate) means a + different story — never collapse it on string similarity alone. + """ + digits_left = {word for word in left.split() if _DIGIT_RE.search(word)} + digits_right = {word for word in right.split() if _DIGIT_RE.search(word)} + return digits_left != digits_right + + +def dedupe_blocks( + blocks: list[dict], + *, + similarity: float = DEFAULT_DEDUPE_SIMILARITY, + enabled: bool = True, +) -> tuple[list[dict], dict]: + """Collapse syndicated copies of one story into a single representative block. + + Blocks are visited best-score-first (ties -> earliest position), so each + cluster's representative is its highest-scoring block and a dropped block + never survives. Matching is against the representative only (star + clustering, no transitive chaining); two titles match when their normalised + forms are equal or ``title_similarity`` clears ``similarity``. Blocks whose + categories are both set and different are never merged, and neither are + titles that disagree on any number (wire copy is verbatim; a different + figure is a different story). Blocks without a usable title stay unique. + Never raises: empty/None input and malformed blocks are tolerated. + + Returns ``(kept_blocks, stats)``; kept blocks keep their original order. + ``stats["duplicate_blocks"]`` holds one record per dropped block:: + + {"index", "article_id", "position", "score", "title", + "duplicate_of", "duplicate_of_position", "similarity", "block"} + """ + items = [block for block in (blocks or []) if isinstance(block, dict)] + try: + threshold = float(similarity) + except (TypeError, ValueError): + threshold = DEFAULT_DEDUPE_SIMILARITY + threshold = min(1.0, max(0.0, threshold)) + stats = { + "input": len(items), + "kept": len(items), + "duplicates": 0, + "threshold": threshold, + "duplicate_blocks": [], + } + if not enabled or len(items) < 2: + return list(items), stats + + ranked = sorted( + range(len(items)), + key=lambda i: (-_block_score(items[i]), _block_position(items[i], i), i), + ) + # groups: representative index -> normalised representative title + groups: list[dict] = [] + for index in ranked: + block = items[index] + norm = normalize_title(_block_title(block)) + match: tuple[dict, float] | None = None + if norm: + for group in groups: + rep_norm = group["norm"] + if ( + not rep_norm + or _categories_conflict(block, items[group["index"]]) + or _numbers_conflict(norm, rep_norm) + ): + continue + score = 1.0 if norm == rep_norm else title_similarity(norm, rep_norm) + if score >= threshold: + match = (group, score) + break + if match is None: + groups.append({"index": index, "norm": norm}) + continue + group, score = match + rep = items[group["index"]] + stats["duplicate_blocks"].append( + { + "index": index, + "article_id": block.get("article_id"), + "position": _block_position(block, index), + "score": _block_score(block), + "title": _block_title(block), + "duplicate_of": rep.get("article_id"), + "duplicate_of_position": _block_position(rep, group["index"]), + "similarity": round(score, 4), + "block": block, + } + ) + + dropped = {record["index"] for record in stats["duplicate_blocks"]} + kept = [block for index, block in enumerate(items) if index not in dropped] + stats["kept"] = len(kept) + stats["duplicates"] = len(stats["duplicate_blocks"]) + return kept, stats diff --git a/news/summerizer/summarizer.py b/news/summerizer/summarizer.py index c1daeae..b1d9c85 100644 --- a/news/summerizer/summarizer.py +++ b/news/summerizer/summarizer.py @@ -14,6 +14,12 @@ of each summarize_news() — env wins, else api_keys / app_settings: NOUS_API_KEY Nous Portal key (else api_keys.name='NOUS_API_KEY') NOUS_BASE_URL default https://inference-api.nousresearch.com/v1 SUMMARY_MODEL default Hermes-4.3-36B (else app_settings) + SUMMARY_MIN_SCORE map-score a block needs to reach the reduce brief (60) + SUMMARY_TOP_N max distinct blocks passed to reduce (12) + SUMMARY_FALLBACK_TOP blocks used when nothing clears MIN_SCORE (3) + SUMMARY_FALLBACK_MIN_SCORE score floor for that fallback set (40) + SUMMARY_DEDUPE "0" disables syndication dedupe (default on) + SUMMARY_DEDUPE_SIMILARITY normalised-title similarity for one story (0.85) BATCH_SIZE articles per map-phase batch (default 50) SUMMARY_WINDOW_MINUTES look-back window (default 15; SUMMARY_WINDOW_HOURS wins if set) NEWS_RECAP "1" for the 23:00 daily recap (24h window, recap prompt) @@ -31,7 +37,15 @@ from zoneinfo import ZoneInfo import psycopg2 -from intel import join_blocks, parse_map_scores, parse_reduce_json, select_graded, select_map, select_ticker +from intel import ( + dedupe_blocks, + join_blocks, + parse_map_scores, + parse_reduce_json, + select_graded, + select_map, + select_ticker, +) from nous_client import chat logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s") @@ -56,6 +70,10 @@ DEFAULT_SUMMARY_TOP_N = 12 DEFAULT_SUMMARY_FALLBACK_TOP = 3 DEFAULT_SUMMARY_FALLBACK_MIN_SCORE = 40 +# Syndication dedupe (pure string work, runs before the threshold/cap). +DEFAULT_SUMMARY_DEDUPE_SIMILARITY = 0.85 +_FALSY = ("0", "false", "no", "off") + def _env_int(name: str, default: int) -> int: raw = (os.getenv(name) or "").strip() @@ -68,6 +86,26 @@ def _env_int(name: str, default: int) -> int: return default +def _env_float(name: str, default: float) -> float: + raw = (os.getenv(name) or "").strip() + if not raw: + return default + try: + return float(raw) + except ValueError: + logger.warning("Invalid %s=%r — using default %s", name, raw, default) + return default + + +def dedupe_config() -> tuple[bool, float]: + """(enabled, similarity) from env. SUMMARY_DEDUPE=0 skips dedupe entirely.""" + enabled = (os.getenv("SUMMARY_DEDUPE") or "1").strip().lower() not in _FALSY + similarity = _env_float( + "SUMMARY_DEDUPE_SIMILARITY", DEFAULT_SUMMARY_DEDUPE_SIMILARITY + ) + return enabled, min(1.0, max(0.0, similarity)) + + def selection_config() -> tuple[int, int, int, int]: """(min_score, top_n, fallback_top, fallback_min_score) from env, per run.""" min_score = max(0, min(100, _env_int("SUMMARY_MIN_SCORE", DEFAULT_SUMMARY_MIN_SCORE))) @@ -375,9 +413,11 @@ def ensure_tables() -> None: category TEXT, selected BOOLEAN NOT NULL, model TEXT, + duplicate_of INTEGER, created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), PRIMARY KEY (article_id, created_at) ); + ALTER TABLE article_scores ADD COLUMN IF NOT EXISTS duplicate_of INTEGER; CREATE INDEX IF NOT EXISTS ix_article_scores_summary ON article_scores (summary_id); """ @@ -544,6 +584,9 @@ def persist_article_scores( ) -> None: """Insert one article_scores row per graded article (selected true/false). + Syndication duplicates are written too, with ``selected=false`` and + ``duplicate_of`` pointing at the surviving article id — the representative + carries the selection even when the copy itself scores above the bar. Best-effort: a failure here is logged and never aborts the run. """ rows = [] @@ -551,14 +594,18 @@ def persist_article_scores( article_id = block.get("article_id") if article_id is None: continue + duplicate_of = block.get("duplicate_of") + if not isinstance(duplicate_of, int): + duplicate_of = None rows.append( ( article_id, summary_id, int(block.get("score") or 0), block.get("category"), - bool(block.get("selected")), + bool(block.get("selected")) and duplicate_of is None, model, + duplicate_of, ) ) if not rows: @@ -568,16 +615,17 @@ def persist_article_scores( cur = conn.cursor() cur.executemany( "INSERT INTO article_scores " - "(article_id, summary_id, score, category, selected, model) " - "VALUES (%s, %s, %s, %s, %s, %s)", + "(article_id, summary_id, score, category, selected, model, duplicate_of) " + "VALUES (%s, %s, %s, %s, %s, %s, %s)", rows, ) conn.commit() cur.close() conn.close() logger.info( - "article_scores persisted rows=%d selected=%d summary_id=%s", - len(rows), sum(1 for r in rows if r[4]), summary_id, + "article_scores persisted rows=%d selected=%d duplicates=%d summary_id=%s", + len(rows), sum(1 for r in rows if r[4]), + sum(1 for r in rows if r[6] is not None), summary_id, ) except Exception as exc: # noqa: BLE001 logger.error("Error persisting article_scores (run continues): %s", exc) @@ -678,16 +726,35 @@ def summarize_news() -> None: logger.warning("No article blocks parsed from the map phase — nothing to reduce.") return + dedupe_enabled, dedupe_similarity = dedupe_config() + distinct, dedupe_stats = dedupe_blocks( + graded, similarity=dedupe_similarity, enabled=dedupe_enabled + ) + duplicate_blocks = [record["block"] for record in dedupe_stats["duplicate_blocks"]] + for record in dedupe_stats["duplicate_blocks"]: + record["block"]["duplicate_of"] = record["duplicate_of"] + if dedupe_enabled: + logger.info( + "dedupe %d -> %d (kept %d, duplicates %d)", + dedupe_stats["input"], dedupe_stats["kept"], + dedupe_stats["kept"], dedupe_stats["duplicates"], + ) + else: + logger.info("dedupe skipped (SUMMARY_DEDUPE=0)") + selected, used_fallback = select_graded( - graded, + distinct, min_score=min_score, top_n=top_n, fallback_top=fallback_top, fallback_min_score=fallback_min_score, ) selected_positions = {block["position"] for block in selected} - for block in graded: + for block in distinct: block["selected"] = block["position"] in selected_positions + for block in duplicate_blocks: + # The representative carries the selection; a wire copy never does. + block["selected"] = False if used_fallback: logger.warning( "No article cleared SUMMARY_MIN_SCORE=%d — fallback to top %d " @@ -696,8 +763,8 @@ def summarize_news() -> None: max(b["score"] for b in graded), ) logger.info( - "selected %d/%d graded articles for reduce (scores=%s)", - len(selected), len(graded), [b["score"] for b in selected], + "selected %d/%d distinct articles for reduce (scores=%s)", + len(selected), len(distinct), [b["score"] for b in selected], ) final_input = join_blocks(selected) @@ -726,7 +793,7 @@ def summarize_news() -> None: parsed["map_items"], kind="daily_recap" if recap else "interval", ) - persist_article_scores(graded, summary_id=summary_id, model=model) + persist_article_scores(distinct + duplicate_blocks, summary_id=summary_id, model=model) if __name__ == "__main__": diff --git a/news/summerizer/tests/test_dedupe.py b/news/summerizer/tests/test_dedupe.py new file mode 100644 index 0000000..1f2ae87 --- /dev/null +++ b/news/summerizer/tests/test_dedupe.py @@ -0,0 +1,432 @@ +"""Syndication dedupe: collapse wire copies before the threshold/cap runs.""" + +from __future__ import annotations + +import json + +import pytest + +import summarizer +from intel import ( + DEFAULT_DEDUPE_SIMILARITY, + dedupe_blocks, + normalize_title, + select_graded, + title_similarity, +) + +# Real titles/scores/categories/ids from summary_id=6 (the measured defect): +# 21 graded articles, 9 distinct titles, 12 of them two wire stories. +OBSERVED_RUN = [ + (95, "www.kcci.com", "politics", 17263, + "Trump, Xi and Putin plan an unprecedented joint meeting on the sidelines of APEC, White House says"), + (95, "www.wyff4.com", "politics", 18546, + "Trump, Xi and Putin plan an unprecedented joint meeting on the sidelines of APEC, White House says"), + (95, "www.wtae.com", "politics", 18550, + "Trump, Xi and Putin plan an unprecedented joint meeting on the sidelines of APEC, White House says"), + (92, "www.koat.com", "politics", 17272, + "Trump, Xi and Putin plan an unprecedented joint meeting on the sidelines of APEC, White House says"), + (92, "www.ketv.com", "politics", 17291, + "Trump, Xi and Putin plan an unprecedented joint meeting on the sidelines of APEC, White House says"), + (92, "www.wlky.com", "politics", 18205, + "Trump, Xi and Putin plan an unprecedented joint meeting on the sidelines of APEC, White House says"), + (92, "www.wbaltv.com", "politics", 18297, + "Trump, Xi and Putin plan an unprecedented joint meeting on the sidelines of APEC, White House says"), + (75, "www.wlky.com", "other", 23748, + "Interactive graphic shows the dramatic impact of Friday's FAA ground stop"), + (75, "www.wtae.com", "other", 24029, + "Interactive graphic shows the dramatic impact of Friday's FAA ground stop"), + (60, "www.kcci.com", "other", 22643, + "Interactive graphic shows the dramatic impact of Friday's FAA ground stop"), + (60, "www.ketv.com", "other", 22664, + "Interactive graphic shows the dramatic impact of Friday's FAA ground stop"), + (60, "www.koat.com", "other", 22683, + "Interactive graphic shows the dramatic impact of Friday's FAA ground stop"), + (60, "www.wbaltv.com", "other", 23708, + "Interactive graphic shows the dramatic impact of Friday's FAA ground stop"), + (55, "www.wlky.com", "environment/disaster", 23943, + "Wild video shows the moment a tanker struck a docked cruise ship in New Orleans"), + (55, "www.wyff4.com", "other", 24087, + "Interactive graphic shows the dramatic impact of Friday's FAA ground stop"), + (45, "www.straitstimes.com", "other", 21227, + "Over 600 personnel take part in multi-agency exercise at RTS Link Woodlands North station"), + (30, "nypost.com", "crime", 16888, + "Monster ex-cop sentenced to chemical castration for raping young kids: “We will take his manhood!”"), + (5, "www.excelsior.com.mx", "other", 17414, + ""), + (5, "nypost.com", "sport", 22376, + "Rangers’ Dylan Garand gets full-circle moment in return to British Columbia"), + (5, "nypost.com", "sport", 22427, + "Chargers get harsh reality check from edge rusher as frustration builds: ‘Walk upstairs and ask them’"), + (5, "www.channelnewsasia.com", "sport", 23026, + "Svitolina says daughter remains priority after split from Monfils"), +] + + +def _blocks(rows) -> list[dict]: + return [ + { + "position": index, + "article_id": article_id, + "score": score, + "category": category, + "domain": domain, + "title": title, + "text": f"Article {index + 1}:\n- Score: {score}\n- Title: {title}", + } + for index, (score, domain, category, article_id, title) in enumerate(rows) + ] + + +def _story(title, *, score=90, article_id=None, category="politics", domain="ex.com", position=0): + return { + "position": position, + "article_id": article_id, + "score": score, + "category": category, + "domain": domain, + "title": title, + "text": f"Article {position + 1}:\n- Score: {score}", + } + + +# ── title normalisation ─────────────────────────────────────────────────── + +@pytest.mark.parametrize( + "title,expected", + [ + ("Big story - KCCI", "big story"), + ("Big story | CNN", "big story"), + ("Big story — AP", "big story"), + ("Big story – AP", "big story"), + (" Big STORY!! ", "big story"), + ("Trump–Xi–Putin summit", "trump xi putin summit"), + ], +) +def test_normalize_title(title, expected): + assert normalize_title(title) == expected + + +@pytest.mark.parametrize("title", [None, "", " ", 12345, ["not", "a", "title"]]) +def test_normalize_title_never_raises(title): + assert isinstance(normalize_title(title), str) + + +def test_serial_titles_are_not_treated_as_a_source_suffix(): + assert normalize_title("Governor's Board – Part 1") != normalize_title( + "Governor's Board – Part 2" + ) + + +# ── grouping ────────────────────────────────────────────────────────────── + +def test_exact_title_duplicates_collapse_to_the_best_scoring_copy(): + blocks = _blocks( + [ + (70, "a.com", "politics", 1, "Storm hits the coast"), + (95, "b.com", "politics", 2, "Storm hits the coast - KCCI"), + (80, "c.com", "politics", 3, "Storm hits the coast"), + ] + ) + kept, stats = dedupe_blocks(blocks) + assert len(kept) == 1 + assert kept[0]["article_id"] == 2 # highest score wins, not the earliest + assert stats["input"] == 3 and stats["kept"] == 1 and stats["duplicates"] == 2 + assert {record["article_id"] for record in stats["duplicate_blocks"]} == {1, 3} + assert all( + record["duplicate_of"] == 2 for record in stats["duplicate_blocks"] + ) + assert all( + record["duplicate_of_position"] == 1 for record in stats["duplicate_blocks"] + ) + + +def test_hearst_style_syndication_set_collapses_to_one(): + domains = [ + "www.kcci.com", "www.wtae.com", "www.wyff4.com", "www.wbaltv.com", + "www.koat.com", "www.ketv.com", "www.wlky.com", + ] + headline = "Flights halted at airports across US due to air traffic control problems" + blocks = [ + _story(headline, score=90 - i, article_id=100 + i, domain=domain, position=i) + for i, domain in enumerate(domains) + ] + kept, stats = dedupe_blocks(blocks) + assert len(kept) == 1 + assert kept[0]["article_id"] == 100 + assert stats["duplicates"] == 6 + assert len({record["duplicate_of"] for record in stats["duplicate_blocks"]}) == 1 + + +def test_rewrites_above_the_threshold_merge_and_below_do_not(): + original = "Flights halted at airports across US due to air traffic control communications problems" + u_s_variant = "Flights halted at airports across U.S. due to air traffic control communications problems" + other_story = "Flights halted at airports across US as a snowstorm closes runways" + + assert title_similarity(normalize_title(original), normalize_title(u_s_variant)) >= 0.85 + assert title_similarity(normalize_title(original), normalize_title(other_story)) < 0.85 + + kept, stats = dedupe_blocks( + [_story(original, article_id=1), _story(u_s_variant, article_id=2, score=80)] + ) + assert [block["article_id"] for block in kept] == [1] + assert stats["duplicates"] == 1 + assert stats["duplicate_blocks"][0]["similarity"] >= 0.85 + + kept, stats = dedupe_blocks( + [_story(original, article_id=1), _story(other_story, article_id=2, score=80)] + ) + assert len(kept) == 2 + assert stats["duplicates"] == 0 + + +def test_threshold_is_tunable(): + left = "Storm batters the coast with heavy rain and wind" + right = "Storm batters the coast with heavy rain, flooding and wind" + assert len(dedupe_blocks([_story(left), _story(right, score=80)], similarity=0.75)[0]) == 1 + assert len(dedupe_blocks([_story(left), _story(right, score=80)], similarity=0.99)[0]) == 2 + + +def test_different_categories_are_never_merged(): + headline = "Officials announce the election result" + blocks = [ + _story(headline, article_id=1, category="politics"), + _story(headline, article_id=2, score=80, category="military/conflict"), + _story(headline, article_id=3, score=70, category=None), + ] + kept, stats = dedupe_blocks(blocks) + # politics != military/conflict -> kept apart; NULL category may join politics. + assert [block["article_id"] for block in kept] == [1, 2] + assert stats["duplicates"] == 1 + assert stats["duplicate_blocks"][0]["article_id"] == 3 + + +def test_titles_disagreeing_on_a_number_stay_separate(): + blocks = [ + _story("Governor's Commutation Advisory Board – Part 1", article_id=1), + _story("Governor's Commutation Advisory Board – Part 2", article_id=2, score=80), + _story("Quake kills 12 in the northern province", article_id=3, score=70), + _story("Quake kills 21 in the northern province", article_id=4, score=60), + ] + kept, stats = dedupe_blocks(blocks) + assert len(kept) == 4 + assert stats["duplicates"] == 0 + + +def test_ties_keep_the_earliest_position(): + blocks = _blocks( + [ + (90, "a.com", "politics", 11, "Identical headline"), + (90, "b.com", "politics", 12, "Identical headline"), + ] + ) + kept, stats = dedupe_blocks(blocks) + assert [block["article_id"] for block in kept] == [11] + assert stats["duplicate_blocks"][0]["duplicate_of"] == 11 + + +def test_kept_blocks_stay_in_original_order(): + blocks = _blocks( + [ + (10, "a.com", "sport", 1, "Rangers beat the Chargers"), + (95, "b.com", "politics", 2, "Summit announced"), + (20, "c.com", "sport", 3, "Svitolina wins in straight sets"), + ] + ) + kept, _ = dedupe_blocks(blocks) + assert [block["article_id"] for block in kept] == [1, 2, 3] + + +# ── robustness ──────────────────────────────────────────────────────────── + +@pytest.mark.parametrize("blocks", [[], None]) +def test_empty_input_is_returned_untouched(blocks): + kept, stats = dedupe_blocks(blocks) + assert kept == [] + assert stats["input"] == 0 and stats["kept"] == 0 and stats["duplicates"] == 0 + + +def test_missing_and_null_titles_are_kept_and_never_merged(): + blocks = [ + {"position": 0, "score": 90, "text": "a"}, # no title key + {"position": 1, "score": 80, "title": None, "text": "b"}, + {"position": 2, "score": 70, "title": "", "text": "c"}, + {"position": 3, "score": 60, "title": " ", "text": "d"}, + {"position": 4, "score": 50, "title": "Real headline", "text": "e"}, + ] + kept, stats = dedupe_blocks(blocks) + assert len(kept) == 5 + assert stats["duplicates"] == 0 + + +def test_malformed_blocks_do_not_raise(): + kept, stats = dedupe_blocks( + [ + "not a dict", + {"position": 0, "score": "high", "title": "Headline", "text": "a"}, + {"position": 1, "score": None, "title": 42, "text": "b"}, + ] + ) + assert len(kept) == 2 + assert stats["input"] == 2 + + +def test_kill_switch_bypasses_everything(): + blocks = _blocks( + [ + (95, "a.com", "politics", 1, "Same headline"), + (94, "b.com", "politics", 2, "Same headline"), + ] + ) + kept, stats = dedupe_blocks(blocks, enabled=False) + assert [block["article_id"] for block in kept] == [1, 2] + assert stats["duplicates"] == 0 + assert stats["kept"] == 2 + + +def test_dedupe_config_reads_the_environment(monkeypatch): + monkeypatch.delenv("SUMMARY_DEDUPE", raising=False) + monkeypatch.delenv("SUMMARY_DEDUPE_SIMILARITY", raising=False) + assert summarizer.dedupe_config() == (True, DEFAULT_DEDUPE_SIMILARITY) + + monkeypatch.setenv("SUMMARY_DEDUPE", "0") + assert summarizer.dedupe_config()[0] is False + monkeypatch.setenv("SUMMARY_DEDUPE", "off") + assert summarizer.dedupe_config()[0] is False + + monkeypatch.setenv("SUMMARY_DEDUPE_SIMILARITY", "0.95") + assert summarizer.dedupe_config() == (False, 0.95) + monkeypatch.setenv("SUMMARY_DEDUPE_SIMILARITY", "nonsense") + assert summarizer.dedupe_config()[1] == DEFAULT_DEDUPE_SIMILARITY + monkeypatch.setenv("SUMMARY_DEDUPE_SIMILARITY", "7") + assert summarizer.dedupe_config()[1] == 1.0 + + +# ── replay of the measured run (summary id=6) ───────────────────────────── + +def test_replay_of_summary_6_collapses_21_to_9_and_selects_2(): + blocks = _blocks(OBSERVED_RUN) + assert len(blocks) == 21 + assert len({normalize_title(block["title"]) for block in blocks}) == 9 + + kept, stats = dedupe_blocks(blocks) + assert stats["input"] == 21 + assert stats["kept"] == 9 + assert stats["duplicates"] == 12 + assert len(kept) == 9 + + selected, fallback = select_graded(kept, min_score=60, top_n=12, fallback_top=3) + assert fallback is False + assert [block["score"] for block in selected] == [95, 75] + assert [block["article_id"] for block in selected] == [17263, 23748] + + # Every one of the 12 dropped copies points at one of the two survivors. + survivors = {record["duplicate_of"] for record in stats["duplicate_blocks"]} + assert survivors == {17263, 23748} + # 11 dropped copies still score above SUMMARY_MIN_SCORE; none is selected. + dropped_above = [ + record for record in stats["duplicate_blocks"] if record["score"] >= 60 + ] + assert len(dropped_above) == 11 + + +# ── wiring: one article_scores row per graded article ───────────────────── + +class _FakeCursor: + def __init__(self, log: list): + self.log = log + self._sql = "" + + def execute(self, sql, params=None): + self._sql = " ".join(sql.split()) + self.log.append(("execute", self._sql, params)) + + def executemany(self, sql, rows): + self.log.append(("executemany", " ".join(sql.split()), list(rows))) + + def fetchone(self): + if "article_summaries" in self._sql: + return (77,) + return None + + def fetchall(self): + return [] + + def close(self): + pass + + +class _FakeConn: + def __init__(self, log: list): + self.log = log + + def cursor(self): + return _FakeCursor(self.log) + + def commit(self): + pass + + def close(self): + pass + + +def _map_block(n: int, score: int) -> str: + return "\n".join( + [ + f"Article {n}:", + f"- Score: {score}", + "- Fact bullet", + "- Category: politics", + "- Importance: high", + ] + ) + + +def test_duplicates_are_persisted_unselected_with_duplicate_of(monkeypatch): + """Full summarize_news flow: 4 graded articles, 2 of them the same story.""" + summerizer_articles = [ + {"id": 1, "title": "Summit announced in the region", "content": "x" * 120, + "url": "https://a.com/1", "domain": "a.com"}, + {"id": 2, "title": "Summit announced in the region - KCCI", "content": "x" * 120, + "url": "https://b.com/2", "domain": "b.com"}, + {"id": 3, "title": "Tanker strikes a docked cruise ship", "content": "x" * 120, + "url": "https://c.com/3", "domain": "c.com"}, + {"id": 4, "title": "Rangers win in overtime", "content": "x" * 120, + "url": "https://d.com/4", "domain": "d.com"}, + ] + map_reply = "\n\n".join( + [_map_block(1, 95), _map_block(2, 92), _map_block(3, 55), _map_block(4, 5)] + ) + reduce_reply = json.dumps({"summary_en": "Brief.", "ticker": [], "map_items": []}) + db_log: list = [] + prompts: list[str] = [] + + def fake_chat(prompt, *, api_key, model, base_url, json_mode=False): + prompts.append(prompt) + return reduce_reply if json_mode else map_reply + + monkeypatch.setenv("NOUS_API_KEY", "test-key") + monkeypatch.setenv("SUMMARY_MODEL", "test-model") + monkeypatch.delenv("SUMMARY_DEDUPE", raising=False) + monkeypatch.delenv("SUMMARY_DEDUPE_SIMILARITY", raising=False) + monkeypatch.setattr(summarizer, "BATCH_SIZE", 10) + monkeypatch.setattr(summarizer, "call_llm", fake_chat) + monkeypatch.setattr(summarizer, "get_recent_news", lambda *a, **k: summerizer_articles) + monkeypatch.setattr(summarizer, "_already_summarized_this_interval", lambda: False) + monkeypatch.setattr(summarizer, "ensure_tables", lambda: None) + monkeypatch.setattr(summarizer.psycopg2, "connect", lambda **kwargs: _FakeConn(db_log)) + + summarizer.summarize_news() + + reduce_prompt = prompts[-1] + assert "Score: 95" in reduce_prompt + assert "Score: 92" not in reduce_prompt # wire copy never reaches reduce + + rows = [entry[2] for entry in db_log if entry[0] == "executemany"] + assert rows, db_log + by_article = {row[0]: row for row in rows[-1]} + assert sorted(by_article) == [1, 2, 3, 4] # one row per graded article + assert by_article[1][4] is True and by_article[1][6] is None + assert by_article[2][4] is False and by_article[2][6] == 1 # duplicate_of + assert by_article[3][4] is False and by_article[3][6] is None + assert by_article[4][4] is False and by_article[4][6] is None From c572f0ee608e6cc152d8f2962ff17eb6af23fd39 Mon Sep 17 00:00:00 2001 From: Sirius DevOps Date: Sat, 14 Nov 2026 00:30:04 -0500 Subject: [PATCH 64/79] fix(hud): hide vessel and FIRMS rows when those feeds are unset Read feeds.vessels.configured and feeds.fires.configured from /api/stats. A missing feeds object leaves both rows visible. WFIGS and trains stay. --- app/static/index.html | 18 +++++ tests/test_feed_rail.py | 152 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 170 insertions(+) create mode 100644 tests/test_feed_rail.py diff --git a/app/static/index.html b/app/static/index.html index acca754..956f4d5 100644 --- a/app/static/index.html +++ b/app/static/index.html @@ -1508,6 +1508,23 @@ function setLayerCount(id, value) { } } +function applyFeedConfig(s) { + // Hide only when /api/stats says the key is unset. Missing feeds (old image) + // leaves both rows visible. Never infer from a zero count. Never touch WFIGS or trains. + const feeds = (s && typeof s.feeds === 'object' && s.feeds) ? s.feeds : null; + setFeedRow('lp-vessels-on', feeds && feeds.vessels); + setFeedRow('lp-fires-on', feeds && feeds.fires); +} +function setFeedRow(id, flag) { + const el = document.getElementById(id); + const row = el && el.closest ? el.closest('.lp-layer') : null; + if (!row) return; + const hide = !!(flag && flag.configured === false); + row.hidden = hide; + // .lp-layer { display:flex } beats the UA [hidden] rule — inline display is what hides it. + row.style.display = hide ? 'none' : ''; +} + async function pollLayerStats() { if (statsPollDisabled) return; try { @@ -1516,6 +1533,7 @@ async function pollLayerStats() { if (!r.ok) return; const s = await r.json(); if (!s || typeof s !== 'object') return; + applyFeedConfig(s); statsRailActive = true; const skipIfOn = { fires: firesOn, diff --git a/tests/test_feed_rail.py b/tests/test_feed_rail.py new file mode 100644 index 0000000..cde7d53 --- /dev/null +++ b/tests/test_feed_rail.py @@ -0,0 +1,152 @@ +"""Layer rail hides Vessels and FIRMS only when /api/stats says the key is unset.""" + +from __future__ import annotations + +import json +import subprocess +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +HTML = (ROOT / "app/static/index.html").read_text() + + +def _between(start: str, end: str) -> str: + return HTML.split(start, 1)[1].split(end, 1)[0] + + +def _feed_fns() -> str: + return _between("function applyFeedConfig", "async function pollLayerStats") + + +def _layer_chunk(elem_id: str) -> str: + idx = HTML.index(f'id="{elem_id}"') + start = HTML.rfind('
+
+
+ + 0 +
+
@@ -1121,6 +1144,7 @@
CAMS —
BLIPS —
NEWS —
+
ARTICLES —